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
/* * Virtual Raw MIDI client on Sequencer * * Copyright (c) 2000 by Takashi Iwai <[email protected]>, * Jaroslav Kysela <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* * Virtual Raw MIDI client * * The virtual rawmidi client is a sequencer client which associate * a rawmidi device file. The created rawmidi device file can be * accessed as a normal raw midi, but its MIDI source and destination * are arbitrary. For example, a user-client software synth connected * to this port can be used as a normal midi device as well. * * The virtual rawmidi device accepts also multiple opens. Each file * has its own input buffer, so that no conflict would occur. The drain * of input/output buffer acts only to the local buffer. * */ #include <linux/init.h> #include <linux/wait.h> #include <linux/module.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/rawmidi.h> #include <sound/info.h> #include <sound/control.h> #include <sound/minors.h> #include <sound/seq_kernel.h> #include <sound/seq_midi_event.h> #include <sound/seq_virmidi.h> MODULE_AUTHOR("Takashi Iwai <[email protected]>"); MODULE_DESCRIPTION("Virtual Raw MIDI client on Sequencer"); MODULE_LICENSE("GPL"); /* * initialize an event record */ static void snd_virmidi_init_event(struct snd_virmidi *vmidi, struct snd_seq_event *ev) { memset(ev, 0, sizeof(*ev)); ev->source.port = vmidi->port; switch (vmidi->seq_mode) { case SNDRV_VIRMIDI_SEQ_DISPATCH: ev->dest.client = SNDRV_SEQ_ADDRESS_SUBSCRIBERS; break; case SNDRV_VIRMIDI_SEQ_ATTACH: /* FIXME: source and destination are same - not good.. */ ev->dest.client = vmidi->client; ev->dest.port = vmidi->port; break; } ev->type = SNDRV_SEQ_EVENT_NONE; } /* * decode input event and put to read buffer of each opened file */ static int snd_virmidi_dev_receive_event(struct snd_virmidi_dev *rdev, struct snd_seq_event *ev) { struct snd_virmidi *vmidi; unsigned char msg[4]; int len; read_lock(&rdev->filelist_lock); list_for_each_entry(vmidi, &rdev->filelist, list) { if (!vmidi->trigger) continue; if (ev->type == SNDRV_SEQ_EVENT_SYSEX) { if ((ev->flags & SNDRV_SEQ_EVENT_LENGTH_MASK) != SNDRV_SEQ_EVENT_LENGTH_VARIABLE) continue; snd_seq_dump_var_event(ev, (snd_seq_dump_func_t)snd_rawmidi_receive, vmidi->substream); } else { len = snd_midi_event_decode(vmidi->parser, msg, sizeof(msg), ev); if (len > 0) snd_rawmidi_receive(vmidi->substream, msg, len); } } read_unlock(&rdev->filelist_lock); return 0; } /* * receive an event from the remote virmidi port * * for rawmidi inputs, you can call this function from the event * handler of a remote port which is attached to the virmidi via * SNDRV_VIRMIDI_SEQ_ATTACH. */ #if 0 int snd_virmidi_receive(struct snd_rawmidi *rmidi, struct snd_seq_event *ev) { struct snd_virmidi_dev *rdev; rdev = rmidi->private_data; return snd_virmidi_dev_receive_event(rdev, ev); } #endif /* 0 */ /* * event handler of virmidi port */ static int snd_virmidi_event_input(struct snd_seq_event *ev, int direct, void *private_data, int atomic, int hop) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!(rdev->flags & SNDRV_VIRMIDI_USE)) return 0; /* ignored */ return snd_virmidi_dev_receive_event(rdev, ev); } /* * trigger rawmidi stream for input */ static void snd_virmidi_input_trigger(struct snd_rawmidi_substream *substream, int up) { struct snd_virmidi *vmidi = substream->runtime->private_data; if (up) { vmidi->trigger = 1; } else { vmidi->trigger = 0; } } /* * trigger rawmidi stream for output */ static void snd_virmidi_output_trigger(struct snd_rawmidi_substream *substream, int up) { struct snd_virmidi *vmidi = substream->runtime->private_data; int count, res; unsigned char buf[32], *pbuf; if (up) { vmidi->trigger = 1; if (vmidi->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH && !(vmidi->rdev->flags & SNDRV_VIRMIDI_SUBSCRIBE)) { snd_rawmidi_transmit_ack(substream, substream->runtime->buffer_size - substream->runtime->avail); return; /* ignored */ } if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) { if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0) return; vmidi->event.type = SNDRV_SEQ_EVENT_NONE; } while (1) { count = snd_rawmidi_transmit_peek(substream, buf, sizeof(buf)); if (count <= 0) break; pbuf = buf; while (count > 0) { res = snd_midi_event_encode(vmidi->parser, pbuf, count, &vmidi->event); if (res < 0) { snd_midi_event_reset_encode(vmidi->parser); continue; } snd_rawmidi_transmit_ack(substream, res); pbuf += res; count -= res; if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) { if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0) return; vmidi->event.type = SNDRV_SEQ_EVENT_NONE; } } } } else { vmidi->trigger = 0; } } /* * open rawmidi handle for input */ static int snd_virmidi_input_open(struct snd_rawmidi_substream *substream) { struct snd_virmidi_dev *rdev = substream->rmidi->private_data; struct snd_rawmidi_runtime *runtime = substream->runtime; struct snd_virmidi *vmidi; unsigned long flags; vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL); if (vmidi == NULL) return -ENOMEM; vmidi->substream = substream; if (snd_midi_event_new(0, &vmidi->parser) < 0) { kfree(vmidi); return -ENOMEM; } vmidi->seq_mode = rdev->seq_mode; vmidi->client = rdev->client; vmidi->port = rdev->port; runtime->private_data = vmidi; write_lock_irqsave(&rdev->filelist_lock, flags); list_add_tail(&vmidi->list, &rdev->filelist); write_unlock_irqrestore(&rdev->filelist_lock, flags); vmidi->rdev = rdev; return 0; } /* * open rawmidi handle for output */ static int snd_virmidi_output_open(struct snd_rawmidi_substream *substream) { struct snd_virmidi_dev *rdev = substream->rmidi->private_data; struct snd_rawmidi_runtime *runtime = substream->runtime; struct snd_virmidi *vmidi; vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL); if (vmidi == NULL) return -ENOMEM; vmidi->substream = substream; if (snd_midi_event_new(MAX_MIDI_EVENT_BUF, &vmidi->parser) < 0) { kfree(vmidi); return -ENOMEM; } vmidi->seq_mode = rdev->seq_mode; vmidi->client = rdev->client; vmidi->port = rdev->port; snd_virmidi_init_event(vmidi, &vmidi->event); vmidi->rdev = rdev; runtime->private_data = vmidi; return 0; } /* * close rawmidi handle for input */ static int snd_virmidi_input_close(struct snd_rawmidi_substream *substream) { struct snd_virmidi *vmidi = substream->runtime->private_data; snd_midi_event_free(vmidi->parser); list_del(&vmidi->list); substream->runtime->private_data = NULL; kfree(vmidi); return 0; } /* * close rawmidi handle for output */ static int snd_virmidi_output_close(struct snd_rawmidi_substream *substream) { struct snd_virmidi *vmidi = substream->runtime->private_data; snd_midi_event_free(vmidi->parser); substream->runtime->private_data = NULL; kfree(vmidi); return 0; } /* * subscribe callback - allow output to rawmidi device */ static int snd_virmidi_subscribe(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!try_module_get(rdev->card->module)) return -EFAULT; rdev->flags |= SNDRV_VIRMIDI_SUBSCRIBE; return 0; } /* * unsubscribe callback - disallow output to rawmidi device */ static int snd_virmidi_unsubscribe(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; rdev->flags &= ~SNDRV_VIRMIDI_SUBSCRIBE; module_put(rdev->card->module); return 0; } /* * use callback - allow input to rawmidi device */ static int snd_virmidi_use(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!try_module_get(rdev->card->module)) return -EFAULT; rdev->flags |= SNDRV_VIRMIDI_USE; return 0; } /* * unuse callback - disallow input to rawmidi device */ static int snd_virmidi_unuse(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; rdev->flags &= ~SNDRV_VIRMIDI_USE; module_put(rdev->card->module); return 0; } /* * Register functions */ static struct snd_rawmidi_ops snd_virmidi_input_ops = { .open = snd_virmidi_input_open, .close = snd_virmidi_input_close, .trigger = snd_virmidi_input_trigger, }; static struct snd_rawmidi_ops snd_virmidi_output_ops = { .open = snd_virmidi_output_open, .close = snd_virmidi_output_close, .trigger = snd_virmidi_output_trigger, }; /* * create a sequencer client and a port */ static int snd_virmidi_dev_attach_seq(struct snd_virmidi_dev *rdev) { int client; struct snd_seq_port_callback pcallbacks; struct snd_seq_port_info *pinfo; int err; if (rdev->client >= 0) return 0; pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL); if (!pinfo) { err = -ENOMEM; goto __error; } client = snd_seq_create_kernel_client(rdev->card, rdev->device, "%s %d-%d", rdev->rmidi->name, rdev->card->number, rdev->device); if (client < 0) { err = client; goto __error; } rdev->client = client; /* create a port */ pinfo->addr.client = client; sprintf(pinfo->name, "VirMIDI %d-%d", rdev->card->number, rdev->device); /* set all capabilities */ pinfo->capability |= SNDRV_SEQ_PORT_CAP_WRITE | SNDRV_SEQ_PORT_CAP_SYNC_WRITE | SNDRV_SEQ_PORT_CAP_SUBS_WRITE; pinfo->capability |= SNDRV_SEQ_PORT_CAP_READ | SNDRV_SEQ_PORT_CAP_SYNC_READ | SNDRV_SEQ_PORT_CAP_SUBS_READ; pinfo->capability |= SNDRV_SEQ_PORT_CAP_DUPLEX; pinfo->type = SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | SNDRV_SEQ_PORT_TYPE_SOFTWARE | SNDRV_SEQ_PORT_TYPE_PORT; pinfo->midi_channels = 16; memset(&pcallbacks, 0, sizeof(pcallbacks)); pcallbacks.owner = THIS_MODULE; pcallbacks.private_data = rdev; pcallbacks.subscribe = snd_virmidi_subscribe; pcallbacks.unsubscribe = snd_virmidi_unsubscribe; pcallbacks.use = snd_virmidi_use; pcallbacks.unuse = snd_virmidi_unuse; pcallbacks.event_input = snd_virmidi_event_input; pinfo->kernel = &pcallbacks; err = snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_CREATE_PORT, pinfo); if (err < 0) { snd_seq_delete_kernel_client(client); rdev->client = -1; goto __error; } rdev->port = pinfo->addr.port; err = 0; /* success */ __error: kfree(pinfo); return err; } /* * release the sequencer client */ static void snd_virmidi_dev_detach_seq(struct snd_virmidi_dev *rdev) { if (rdev->client >= 0) { snd_seq_delete_kernel_client(rdev->client); rdev->client = -1; } } /* * register the device */ static int snd_virmidi_dev_register(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; int err; switch (rdev->seq_mode) { case SNDRV_VIRMIDI_SEQ_DISPATCH: err = snd_virmidi_dev_attach_seq(rdev); if (err < 0) return err; break; case SNDRV_VIRMIDI_SEQ_ATTACH: if (rdev->client == 0) return -EINVAL; /* should check presence of port more strictly.. */ break; default: snd_printk(KERN_ERR "seq_mode is not set: %d\n", rdev->seq_mode); return -EINVAL; } return 0; } /* * unregister the device */ static int snd_virmidi_dev_unregister(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; if (rdev->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH) snd_virmidi_dev_detach_seq(rdev); return 0; } /* * */ static struct snd_rawmidi_global_ops snd_virmidi_global_ops = { .dev_register = snd_virmidi_dev_register, .dev_unregister = snd_virmidi_dev_unregister, }; /* * free device */ static void snd_virmidi_free(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; kfree(rdev); } /* * create a new device * */ /* exported */ int snd_virmidi_new(struct snd_card *card, int device, struct snd_rawmidi **rrmidi) { struct snd_rawmidi *rmidi; struct snd_virmidi_dev *rdev; int err; *rrmidi = NULL; if ((err = snd_rawmidi_new(card, "VirMidi", device, 16, /* may be configurable */ 16, /* may be configurable */ &rmidi)) < 0) return err; strcpy(rmidi->name, rmidi->id); rdev = kzalloc(sizeof(*rdev), GFP_KERNEL); if (rdev == NULL) { snd_device_free(card, rmidi); return -ENOMEM; } rdev->card = card; rdev->rmidi = rmidi; rdev->device = device; rdev->client = -1; rwlock_init(&rdev->filelist_lock); INIT_LIST_HEAD(&rdev->filelist); rdev->seq_mode = SNDRV_VIRMIDI_SEQ_DISPATCH; rmidi->private_data = rdev; rmidi->private_free = snd_virmidi_free; rmidi->ops = &snd_virmidi_global_ops; snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_virmidi_input_ops); snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_virmidi_output_ops); rmidi->info_flags = SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_DUPLEX; *rrmidi = rmidi; return 0; } /* * ENTRY functions */ static int __init alsa_virmidi_init(void) { return 0; } static void __exit alsa_virmidi_exit(void) { } module_init(alsa_virmidi_init) module_exit(alsa_virmidi_exit) EXPORT_SYMBOL(snd_virmidi_new);
Jackeagle/android_kernel_sony_c2305
sound/core/seq/seq_virmidi.c
C
gpl-2.0
14,463
@echo off taskkill /f /im paraengineclient.exe taskkill /f /im cmd.exe
NPLPackages/TableDB
setup/stopNPL.bat
Batchfile
gpl-2.0
70
// External imports import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.FileInputStream; import java.io.BufferedInputStream; import javax.imageio.ImageIO; import javax.swing.*; // Local imports import org.j3d.renderer.aviatrix3d.texture.TextureCreateUtils; /** * Example application that demonstrates how to use the loader interface * to load a file into the scene graph. * <p> * * @author Justin Couch * @version $Revision: 1.1 $ */ public class NormalMapDemo extends JFrame implements ActionListener { private JFileChooser openDialog; /** Renderer for the basic image */ private ImageIcon srcIcon; private JLabel srcLabel; /** Renderer for the normal map version */ private ImageIcon mapIcon; private JLabel mapLabel; /** Utility for munging textures to power of 2 size */ private TextureCreateUtils textureUtils; public NormalMapDemo() { super("Normal map conversion demo"); setSize(1280, 1024); setLocation(0, 0); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textureUtils = new TextureCreateUtils(); JPanel p1 = new JPanel(new BorderLayout()); srcIcon = new ImageIcon(); srcLabel = new JLabel(); srcLabel.setVerticalTextPosition(SwingConstants.BOTTOM); srcLabel.setText("Source Image"); mapIcon = new ImageIcon(); mapLabel = new JLabel(); mapLabel.setVerticalTextPosition(SwingConstants.BOTTOM); mapLabel.setText("NormalMap Image"); JButton b = new JButton("Open A file"); b.addActionListener(this); p1.add(b, BorderLayout.SOUTH); p1.add(srcLabel, BorderLayout.WEST); p1.add(mapLabel, BorderLayout.EAST); getContentPane().add(p1); } //--------------------------------------------------------------- // Methods defined by WindowListener //--------------------------------------------------------------- /** * Process the action event from the open button */ public void actionPerformed(ActionEvent evt) { if(openDialog == null) openDialog = new JFileChooser(); int ret_val = openDialog.showOpenDialog(this); if(ret_val != JFileChooser.APPROVE_OPTION) return; File file = openDialog.getSelectedFile(); try { System.out.println("Loading external file: " + file); FileInputStream is = new FileInputStream(file); BufferedInputStream stream = new BufferedInputStream(is); BufferedImage img = ImageIO.read(stream); if(img == null) { System.out.println("Image load barfed"); return; } srcIcon.setImage(img); srcLabel.setIcon(srcIcon); BufferedImage map_img = textureUtils.createNormalMap(img, null); mapIcon.setImage(map_img); mapLabel.setIcon(mapIcon); } catch(IOException ioe) { System.out.println("crashed " + ioe.getMessage()); ioe.printStackTrace(); } } //--------------------------------------------------------------- // Local methods //--------------------------------------------------------------- public static void main(String[] args) { NormalMapDemo demo = new NormalMapDemo(); demo.setVisible(true); } }
Norkart/NK-VirtualGlobe
aviatrix3d/examples/texture/NormalMapDemo.java
Java
gpl-2.0
3,599
# tps23861 Linux driver for TPS23861 IEEE 802.3at Quad Port Power-over-Ethernet PSE Controller. Tested with kernel version 3.19.0 Bindings example: tps23861: tps23861@20 { compatible = "ti,tps23861"; reg = <0x20>; irq-gpio = <84>; port0@0 { enable = <1>; mode = "auto"; power = <1>; }; port1@1 { enable = <1>; mode = "manual"; power = <0>; }; port2@2 { enable = <0>; }; port3@3 { enable = <0>; }; };
cbuilder/tps23861-linux-driver
README.md
Markdown
gpl-2.0
618
<?php get_header() ?> archive <!--/nav--> <?php $banner_image = get_field('banner_image'); $bannerUrl = wp_get_attachment_image_src($banner_image, 'large'); $bannerImg = aq_resize($bannerUrl[0], 974, 312, true); if ($bannerImg == '') { $bannerImg = get_template_directory_uri() . '/images/the-authors-banner.jpg'; } ?> <section id="banner"> <div class="container" style="background-image:url('<?php echo $bannerImg; ?>');"> </div> </section> <!--main--> <div id="main" role="main"> <div class="container"> <section id="archive-news"> <header class="section-header left"><h1>Latest News</h1></header> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <?php $feat_image = get_post_thumbnail_id($post->ID); $featureUrl = wp_get_attachment_image_src($feat_image, 'large'); $featureImage = aq_resize($featureUrl[0], 309, 206, true); ?> <article class="has-feature"> <div class="wrap"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <div class="alpha"> <small><time datetime="2014-11-21"><?php echo get_the_date(); ?></time></small> <?php the_content(); ?> </div> <div class="beta"><figure><a href="<?php the_permalink(); ?>"><img src="<?php echo $featureImage; ?>" /></a></figure></div> </div> <div class="divide"><div></div></div> </article> <?php endwhile; endif; ?> </section> </div> <!-- /container --> </div> <!-- testimonials slider --> <!-- /testimonials slider --> <?php get_footer() ?>
digital-one/fastforward
wp-content/themes/fast_forward/archive.php
PHP
gpl-2.0
1,953
/* * The TiLib: wavelet based lossy image compression library * Copyright (C) 1998-2004 Alexander Simakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * QuikInfo: * * Top-level compression & decompression functions. * */ #ifndef TILIB_H #define TILIB_H #ifdef __cplusplus extern "C" { #endif #define GRAYSCALE (0) #define TRUECOLOR (1) #define BUTTERWORTH (0) #define DAUB97 (1) int TiCompress(unsigned char *image, unsigned char *stream, int img_width, int img_height, int wavelet, int img_type, int desired_size, int *actual_size, int lum_ratio, int cb_ratio, int cr_ratio, int scales); int TiCheckHeader(unsigned char *stream, int *img_width, int *img_height, int *img_type, int stream_size); int TiDecompress(unsigned char *stream, unsigned char *image, int img_width, int img_height, int img_type, int stream_size); #ifdef __cplusplus } #endif #endif /* TILIB_H */
Upliner/tilib
include/tilib.h
C
gpl-2.0
1,872
<?php /** * Created by PhpStorm. * User: Anh Tuan * Date: 4/22/14 * Time: 12:26 AM */ ////////////////////////////////////////////////////////////////// // Dropcap shortcode ////////////////////////////////////////////////////////////////// add_shortcode( 'dropcap', 'shortcode_dropcap' ); function shortcode_dropcap( $atts, $content = null ) { extract( shortcode_atts( array( 'text' => '', 'el_class' => '' ), $atts ) ); return '<span class="dropcap '.$el_class.'">' . $content . '</span>'; }
yogaValdlabs/shopingchart
wp-content/themes/aloxo/inc/shortcodes/dropcap/dropcap.php
PHP
gpl-2.0
515
/* * $RCSfile: OrCRIF.java,v $ * * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. * * Use is subject to license terms. * * $Revision: 1.1 $ * $Date: 2005/02/11 04:56:38 $ * $State: Exp $ */ package com.sun.media.jai.opimage; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.ParameterBlock; import java.awt.image.renderable.RenderableImage; import javax.media.jai.CRIFImpl; import javax.media.jai.ImageLayout; import java.util.Map; /** * A <code>CRIF</code> supporting the "Or" operation in the * rendered and renderable image layers. * * @since EA2 * @see javax.media.jai.operator.OrDescriptor * @see OrOpImage * */ public class OrCRIF extends CRIFImpl { /** Constructor. */ public OrCRIF() { super("or"); } /** * Creates a new instance of <code>OrOpImage</code> in the * rendered layer. This method satisifies the implementation of RIF. * * @param paramBlock The two source images to be "Ored" together. * @param renderHints Optionally contains destination image layout. */ public RenderedImage create(ParameterBlock paramBlock, RenderingHints renderHints) { // Get ImageLayout from renderHints if any. ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints); return new OrOpImage(paramBlock.getRenderedSource(0), paramBlock.getRenderedSource(1), renderHints, layout); } }
RoProducts/rastertheque
JAILibrary/src/com/sun/media/jai/opimage/OrCRIF.java
Java
gpl-2.0
1,740
using BlueBit.CarsEvidence.Commons.Templates; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.Contracts; namespace BlueBit.CarsEvidence.BL.Entities { public class Person : EntityBase, IObjectWithGetCode, IObjectWithGetInfo { [Required] [MaxLength(Configuration.Consts.LengthCode)] public virtual string Code { get; set; } [MaxLength(Configuration.Consts.LengthInfo)] public virtual string Info { get; set; } [Required] [MaxLength(Configuration.Consts.LengthText)] public virtual string FirstName { get; set; } [Required] [MaxLength(Configuration.Consts.LengthText)] public virtual string LastName { get; set; } public virtual ISet<PeriodRouteEntry> PeriodRouteEntries { get; set; } public virtual ISet<PeriodFuelEntry> PeriodFuelEntries { get; set; } public override void Init() { PeriodRouteEntries = PeriodRouteEntries ?? new HashSet<PeriodRouteEntry>(); PeriodFuelEntries = PeriodFuelEntries ?? new HashSet<PeriodFuelEntry>(); } } public static class PersonExtensions { public static PeriodRouteEntry AddPeriodRouteEntry(this Person @this, PeriodRouteEntry entry) { Contract.Assert(@this != null); Contract.Assert(entry != null); Contract.Assert(entry.Person == null); entry.Person = @this; @this.PeriodRouteEntries.Add(entry); return entry; } public static PeriodFuelEntry AddPeriodFuelEntry(this Person @this, PeriodFuelEntry entry) { Contract.Assert(@this != null); Contract.Assert(entry != null); Contract.Assert(entry.Person == null); entry.Person = @this; @this.PeriodFuelEntries.Add(entry); return entry; } } }
tomasz-orynski/BlueBit.CarsEvidence
BlueBit.CarsEvidence.BL/Entities/Person.cs
C#
gpl-2.0
1,979
/* * Created by Rolando Abarca 2012. * Copyright (c) 2012 Rolando Abarca. All rights reserved. * Copyright (c) 2013 Zynga Inc. All rights reserved. * Copyright (c) 2013-2014 Chukong Technologies Inc. * * Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.h * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef __FAKE_XMLHTTPREQUEST_H__ #define __FAKE_XMLHTTPREQUEST_H__ #include "jsapi.h" #include "jsfriendapi.h" #include "network/HttpClient.h" #include "js_bindings_config.h" #include "ScriptingCore.h" #include "jsb_helper.h" class MinXmlHttpRequest : public cocos2d::Ref { public: enum class ResponseType { STRING, ARRAY_BUFFER, BLOB, DOCUMENT, JSON }; // Ready States (http://www.w3.org/TR/XMLHttpRequest/#interface-xmlhttprequest) static const unsigned short UNSENT = 0; static const unsigned short OPENED = 1; static const unsigned short HEADERS_RECEIVED = 2; static const unsigned short LOADING = 3; static const unsigned short DONE = 4; MinXmlHttpRequest(); ~MinXmlHttpRequest(); JS_BINDED_CLASS_GLUE(MinXmlHttpRequest); JS_BINDED_CONSTRUCTOR(MinXmlHttpRequest); JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, onreadystatechange); JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, responseType); JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, withCredentials); JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, upload); JS_BINDED_PROP_ACCESSOR(MinXmlHttpRequest, timeout); JS_BINDED_PROP_GET(MinXmlHttpRequest, readyState); JS_BINDED_PROP_GET(MinXmlHttpRequest, status); JS_BINDED_PROP_GET(MinXmlHttpRequest, statusText); JS_BINDED_PROP_GET(MinXmlHttpRequest, responseText); JS_BINDED_PROP_GET(MinXmlHttpRequest, response); JS_BINDED_PROP_GET(MinXmlHttpRequest, responseXML); JS_BINDED_FUNC(MinXmlHttpRequest, open); JS_BINDED_FUNC(MinXmlHttpRequest, send); JS_BINDED_FUNC(MinXmlHttpRequest, abort); JS_BINDED_FUNC(MinXmlHttpRequest, getAllResponseHeaders); JS_BINDED_FUNC(MinXmlHttpRequest, getResponseHeader); JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader); JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType); void handle_requestResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); private: void _gotHeader(std::string header); void _setRequestHeader(const char* field, const char* value); void _setHttpRequestHeader(); void _sendRequest(JSContext *cx); std::string _url; JSContext* _cx; std::string _meth; std::string _type; char* _data; uint32_t _dataSize; JSObject* _onreadystateCallback; int _readyState; int _status; std::string _statusText; ResponseType _responseType; unsigned _timeout; bool _isAsync; cocos2d::network::HttpRequest* _httpRequest; bool _isNetwork; bool _withCredentialsValue; bool _errorFlag; std::unordered_map<std::string, std::string> _httpHeader; std::unordered_map<std::string, std::string> _requestHeader; }; #endif
csyeung/Othello
frameworks/js-bindings/bindings/manual/network/XMLHTTPRequest.h
C
gpl-2.0
4,575
<?php /** Admin Page Framework v3.5.6 by Michael Uno Generated by PHP Class Files Script Generator <https://github.com/michaeluno/PHP-Class-Files-Script-Generator> <http://en.michaeluno.jp/admin-page-framework> Copyright (c) 2013-2015, Michael Uno; Licensed under MIT <http://opensource.org/licenses/MIT> */ abstract class SeamlessDonationsAdminPageFramework_TaxonomyField_View extends SeamlessDonationsAdminPageFramework_TaxonomyField_Model { public function _replyToPrintFieldsWOTableRows($oTerm) { echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, false); } public function _replyToPrintFieldsWithTableRows($oTerm) { echo $this->_getFieldsOutput(isset($oTerm->term_id) ? $oTerm->term_id : null, true); } private function _getFieldsOutput($iTermID, $bRenderTableRow) { $_aOutput = array(); $_aOutput[] = wp_nonce_field($this->oProp->sClassHash, $this->oProp->sClassHash, true, false); $this->_setOptionArray($iTermID, $this->oProp->sOptionKey); $this->oForm->format(); $_oFieldsTable = new SeamlessDonationsAdminPageFramework_FormTable($this->oProp->aFieldTypeDefinitions, $this->_getFieldErrors(), $this->oMsg); $_aOutput[] = $bRenderTableRow ? $_oFieldsTable->getFieldRows($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput')) : $_oFieldsTable->getFields($this->oForm->aFields['_default'], array($this, '_replyToGetFieldOutput')); $_sOutput = $this->oUtil->addAndApplyFilters($this, 'content_' . $this->oProp->sClassName, implode(PHP_EOL, $_aOutput)); $this->oUtil->addAndDoActions($this, 'do_' . $this->oProp->sClassName, $this); return $_sOutput; } public function _replyToPrintColumnCell($vValue, $sColumnSlug, $sTermID) { $_sCellHTML = ''; if (isset($_GET['taxonomy']) && $_GET['taxonomy']) { $_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$_GET['taxonomy']}", $vValue, $sColumnSlug, $sTermID); } $_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}", $_sCellHTML, $sColumnSlug, $sTermID); $_sCellHTML = $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sClassName}_{$sColumnSlug}", $_sCellHTML, $sTermID); echo $_sCellHTML; } }
johnmanlove/NoOn1
wp-content/plugins/seamless-donations/library/apf/factory/AdminPageFramework_TaxonomyField/AdminPageFramework_TaxonomyField_View.php
PHP
gpl-2.0
2,360
<?php /** * Created by PhpStorm. * User: udit * Date: 12/9/14 * Time: 10:43 AM */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! class_exists( 'WM_Revision' ) ) { /** * Class WM_Revision * * Handles all the functionality to track custom fields * * @since 0.4 */ class WM_Revision { /** * @since 0.4 */ function __construct() { /** * This hook filters the number of revisions to keep for a specific post. */ add_filter( 'wp_revisions_to_keep', array( $this, 'filter_revisions_to_keep' ), 999, 2 ); /** * This hooks gets fired once a revision is stored in WP_Post table in DB. * * This gives us $revision_id. So we can make use of that and store our stuff into post meta for that particular revision. * E.g., Taxonomy diff, meta diff., featured image diff, etc. * */ add_action( '_wp_put_post_revision', array( $this, 'post_revision_process' ), 10, 1 ); /** * Filter whether the post has changed since the last revision. * * By default a revision is saved only if one of the revisioned fields has changed. * This filter can override that so a revision is saved even if nothing has changed. * * We will take care of our own fields and pass on the flag. */ add_filter( 'wp_save_post_revision_post_has_changed', array( $this, 'check_for_changes' ), 10, 3 ); /** * We may have to call this dynamically within a for loop. depending upon how many custom fields that we are supporting. */ foreach ( array_keys( $this->get_custom_revision_fields() ) as $field ) { add_filter( '_wp_post_revision_field_'.$field, array( $this, 'revision_field_content' ), 10, 4 ); } /** * This adds custom diff ui for custom revision fields */ add_filter( 'wp_get_revision_ui_diff', array( $this, 'revision_ui_diff' ), 10, 3 ); } /** * @param $num * @param $post * * @return int * @since 0.1 */ function filter_revisions_to_keep( $num, $post ) { // Check individual Post Limit $revision_limit = get_post_meta( $post->ID, WM_Admin::$wm_revision_limit_meta_key, true ); if ( '' !== $revision_limit ) { if ( ! is_numeric( $revision_limit ) ) { $num = - 1; } else { $num = intval( $revision_limit ); } } else { $post_type = get_post_type( $post ); $revision_limit = get_option( WM_Settings::$revision_limit_key . $post_type, false ); if ( '' === $revision_limit || ! is_numeric( $revision_limit ) ) { $num = - 1; } else { $num = intval( $revision_limit ); } } return $num; } /** * @return array $revision_fields * @since 0.5 */ function get_custom_revision_fields() { $revision_fields = array( 'post_author' => array( 'label' => __( 'Post Author', WM_TEXT_DOMAIN ), 'meta_key' => '_wm_post_author', 'meta_value' => function( $post ) { $author = new WP_User( $post->post_author ); return $author->display_name . ' (' . $post->post_author . ')'; }, ), 'post_status' => array( 'label' => __( 'Post Status', WM_TEXT_DOMAIN ), 'meta_key' => '_wm_post_status', 'meta_value' => function( $post ) { $post_status = get_post_status_object( $post->post_status ); return $post_status->label; }, ), 'post_date' => array( 'label' => __( 'Post Date', WM_TEXT_DOMAIN ), 'meta_key' => '_wm_post_date', 'meta_value' => function( $post ) { $datef = 'M j, Y @ H:i'; return date_i18n( $datef, strtotime( $post->post_date ) ); }, ), ); return $revision_fields; } /** * @param $revision_id * @since 0.4 */ function post_revision_process( $revision_id ) { $revision = get_post( $revision_id ); $post = get_post( $revision->post_parent ); foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) { update_post_meta( $post->ID, $fieldmeta['meta_key'] . '_' . $revision_id , call_user_func( $fieldmeta['meta_value'], $post ) ); } } /** * @param $post_has_changed * @param $last_revision * @param $post * * @return mixed * @since 0.4 */ function check_for_changes( $post_has_changed, $last_revision, $post ) { foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) { $post_value = normalize_whitespace( call_user_func( $fieldmeta['meta_value'], $post ) ); $revision_value = normalize_whitespace( apply_filters( "_wp_post_revision_field_$field", $last_revision->$field, $field, $last_revision, 'from' ) ); if ( $post_value != $revision_value ) { $post_has_changed = true; break; } } return $post_has_changed; } /** * Contextually filter a post revision field. * * The dynamic portion of the hook name, $field, corresponds to each of the post * fields of the revision object being iterated over in a foreach statement. * * @param string $value The current revision field to compare to or from. * @param string $field The current revision field. * @param WP_Post $post The revision post object to compare to or from. * @param string $context The context of whether the current revision is the old or the new one. Values are 'to' or 'from'. * * @return string $value * @since 0.4 */ function revision_field_content( $value, $field, $post, $context ) { $revision_fields = $this->get_custom_revision_fields(); if ( array_key_exists( $field, $revision_fields ) ) { $value = get_post_meta( $post->post_parent, $revision_fields[ $field ]['meta_key'] . '_' . $post->ID, true ); } return $value; } /** * Filter the fields displayed in the post revision diff UI. * * @since 4.1.0 * * @param array $return Revision UI fields. Each item is an array of id, name and diff. * @param WP_Post $compare_from The revision post to compare from. * @param WP_Post $compare_to The revision post to compare to. * * @return array $return * @since 0.5 */ function revision_ui_diff( $return, $compare_from, $compare_to ) { foreach ( $this->get_custom_revision_fields() as $field => $fieldmeta ) { /** * Contextually filter a post revision field. * * The dynamic portion of the hook name, `$field`, corresponds to each of the post * fields of the revision object being iterated over in a foreach statement. * * @since 3.6.0 * * @param string $compare_from->$field The current revision field to compare to or from. * @param string $field The current revision field. * @param WP_Post $compare_from The revision post object to compare to or from. * @param string null The context of whether the current revision is the old * or the new one. Values are 'to' or 'from'. */ $content_from = $compare_from ? apply_filters( "_wp_post_revision_field_$field", $compare_from->$field, $field, $compare_from, 'from' ) : ''; /** This filter is documented in wp-admin/includes/revision.php */ $content_to = apply_filters( "_wp_post_revision_field_$field", $compare_to->$field, $field, $compare_to, 'to' ); $args = array( 'show_split_view' => true, ); /** * Filter revisions text diff options. * * Filter the options passed to {@see wp_text_diff()} when viewing a post revision. * * @since 4.1.0 * * @param array $args { * Associative array of options to pass to {@see wp_text_diff()}. * * @type bool $show_split_view True for split view (two columns), false for * un-split view (single column). Default true. * } * @param string $field The current revision field. * @param WP_Post $compare_from The revision post to compare from. * @param WP_Post $compare_to The revision post to compare to. */ $args = apply_filters( 'revision_text_diff_options', $args, $field, $compare_from, $compare_to ); $diff = wp_text_diff( $content_from, $content_to, $args ); if ( $diff ) { $return[] = array( 'id' => $field, 'name' => $fieldmeta['label'], 'diff' => $diff, ); } } return $return; } } }
desaiuditd/watchman
revision/class-wm-revision.php
PHP
gpl-2.0
8,344
<?php /** * The main template file. * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package morrisseys_catering */ get_header(); ?> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php morrisseys_catering_content_nav( 'nav-below' ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> <div id="food-content"> <h1>image</h1> <div id="inner-box"> <p>Fresh. Local. Family Owned.</p> <a class="button" href="#"> <h1>Icon menu </h1> <p>Browse Menus</p> </a> </div> </div> <div class="wrapper"> <blockquote id="feedback"> <p> Thank you for providing us each delicious food and service for the St. Mary's 50th Anniversary Celebration! The food was excellent and you are all the best to work with! We are grateful for you, thank you.<br> <span>-Siobhan </span> </p> <div class="splitter"> </div> <br> <br> <p>Many thanks for your kindness during such a sad time for us - you were so helpful. Everyone enjoyed your wonderful food at the church reception. <br> <span>-Mrs. Showalter</span></p> </blockquote> <div id="contact-info"> <div id="contact-box"> <img src="wp-content/themes/morrisseys_catering/images/icon_phone.png" alt="phone.icon"> <p> (804) 592-2188</p> </div> <br> <br> <div class="address-info"> <p> 8901 Three Chopt Road, Suite A, Richmond, Va 23229 </p> <p> Located in the Westbury Pharmacy Center</p> </div> <!--address-info --> </div> <!-- contact-info" --> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
nickdtaylor1993/morrisseys_catering
wp-content/themes/morrisseys_catering/index.php
PHP
gpl-2.0
2,289
<?php /* -------------------------------------------------------------- $Id: customer_memo.php 10395 2016-11-07 13:18:38Z GTB $ modified eCommerce Shopsoftware http://www.modified-shop.org Copyright (c) 2009 - 2013 [www.modified-shop.org] -------------------------------------------------------------- Released under the GNU General Public License -------------------------------------------------------------- Third Party contribution: (c) 2003 XT-Commerce (c) 2003 nextcommerce (customer_memo.php,v 1.6 2003/08/18); www.nextcommerce.org --------------------------------------------------------------*/ defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' ); ?> <td class="dataTableConfig col-left" style="vertical-align:top;"><?php echo ENTRY_MEMO; ?></td> <td class="dataTableConfig col-single-right"> <?php $memo_query = xtc_db_query("SELECT * FROM " . TABLE_CUSTOMERS_MEMO . " WHERE customers_id = '" . (int)$_GET['cID'] . "' ORDER BY memo_date DESC"); if (xtc_db_num_rows($memo_query) > 0) { while ($memo_values = xtc_db_fetch_array($memo_query)) { $poster_query = xtc_db_query("SELECT customers_firstname, customers_lastname FROM " . TABLE_CUSTOMERS . " WHERE customers_id = '" . $memo_values['poster_id'] . "'"); $poster_values = xtc_db_fetch_array($poster_query); ?> <div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;"> <table style="width:100%"> <tr> <td class="main" style="width:120px; border:none; padding:2px;"><strong><?php echo TEXT_DATE; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo xtc_date_short($memo_values['memo_date']); ?></td> </tr> <tr> <td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_title']; ?></td> </tr> <tr> <td class="main" style="border:none; padding:2px;"><strong><?php echo TEXT_POSTER; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo $poster_values['customers_lastname'] . ' ' . $poster_values['customers_firstname']; ?></td> </tr> <tr> <td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo $memo_values['memo_text']; ?></td> </tr> <tr> <td class="txta-r" colspan="2" style="border:none; padding:2px;"><a style="text-decoration:none;" href="<?php echo xtc_href_link(basename($PHP_SELF), 'cID=' . (int)$_GET['cID'] . '&action=edit&special=remove_memo&mID=' . $memo_values['memo_id']); ?>" class="button" onclick="return confirmLink('<?php echo DELETE_ENTRY; ?>', '', this)"><?php echo BUTTON_DELETE; ?></a></td> </tr> </table> </div> <?php } echo '<br/>'; } ?> <div style="margin:2px; padding:2px; border: 1px solid; border-color: #cccccc;"> <table style="width:100%"> <tr> <td class="main" style="width:80px; border:none; padding:2px;"><strong><?php echo TEXT_TITLE; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_input_field('memo_title', ((isset($cInfo->memo_title)) ? $cInfo->memo_title : ''), 'style="width:100%; max-width:676px;"'); ?></td> </tr> <tr> <td class="main" style="border:none; padding:2px; vertical-align:top;"><strong><?php echo ENTRY_MEMO; ?></strong>:</td> <td class="main" style="border:none; padding:2px;"><?php echo xtc_draw_textarea_field('memo_text', 'soft', '80', '8', ((isset($cInfo->memo_text)) ? $cInfo->memo_text : ''), 'style="width:99%; max-width:676px;"'); ?></td> </tr> <tr> <td class="txta-r" colspan="2" style="border:none; padding:2px;"><input type="submit" class="button" value="<?php echo BUTTON_INSERT; ?>"></td> </tr> </table> </div> </td>
dsiekiera/modified-bs4
admin/includes/modules/customer_memo.php
PHP
gpl-2.0
4,322
<?php /* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */ use Icinga\Web\Controller; use Icinga\Web\Url; use Icinga\Web\Widget\Tabextension\DashboardAction; use Icinga\Web\Widget\Tabextension\OutputFormat; use Icinga\Application\Config; use Icinga\Application\Logger; use Icinga\Data\ConfigObject; use Icinga\Protocol\File\FileReader; use \Zend_Controller_Action_Exception as ActionError; /** * Class ListController * * Application wide controller for various listing actions */ class ListController extends Controller { /** * Add title tab * * @param string $action */ protected function addTitleTab($action) { $this->getTabs()->add($action, array( 'label' => ucfirst($action), 'url' => Url::fromPath( 'list/' . str_replace(' ', '', $action) ) ))->extend(new OutputFormat())->extend(new DashboardAction())->activate($action); } /** * Display the application log */ public function applicationlogAction() { if (! Logger::writesToFile()) { throw new ActionError('Site not found', 404); } $this->addTitleTab('application log'); $resource = new FileReader(new ConfigObject(array( 'filename' => Config::app()->get('logging', 'file'), 'fields' => '/(?<!.)(?<datetime>[0-9]{4}(?:-[0-9]{2}){2}' // date . 'T[0-9]{2}(?::[0-9]{2}){2}(?:[\+\-][0-9]{2}:[0-9]{2})?)' // time . ' - (?<loglevel>[A-Za-z]+) - (?<message>.*)(?!.)/msS' // loglevel, message ))); $this->view->logData = $resource->select()->order('DESC'); $this->setupLimitControl(); $this->setupPaginationControl($this->view->logData); } }
hsanjuan/icingaweb2
application/controllers/ListController.php
PHP
gpl-2.0
1,817
SHELL = /bin/sh # V=0 quiet, V=1 verbose. other values don't work. V = 0 Q1 = $(V:1=) Q = $(Q1:0=@) ECHO1 = $(V:1=@ :) ECHO = $(ECHO1:0=@ echo) NULLCMD = : #### Start of system configuration section. #### srcdir = . topdir = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0 hdrdir = $(topdir) arch_hdrdir = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/universal-darwin19 PATH_SEPARATOR = : VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby prefix = $(DESTDIR)/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr rubysitearchprefix = $(rubylibprefix)/$(sitearch) rubyarchprefix = $(rubylibprefix)/$(arch) rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) exec_prefix = $(prefix) vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) sitearchhdrdir = $(sitehdrdir)/$(sitearch) rubyarchhdrdir = $(rubyhdrdir)/$(arch) vendorhdrdir = $(rubyhdrdir)/vendor_ruby sitehdrdir = $(rubyhdrdir)/site_ruby rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) vendorarchdir = $(vendorlibdir)/$(sitearch) vendorlibdir = $(vendordir)/$(ruby_version) vendordir = $(rubylibprefix)/vendor_ruby sitearchdir = $(DESTDIR)./.gem.20200512-39687-o0q90e sitelibdir = $(DESTDIR)./.gem.20200512-39687-o0q90e sitedir = $(DESTDIR)/Library/Ruby/Site rubyarchdir = $(rubylibdir)/$(arch) rubylibdir = $(rubylibprefix)/$(ruby_version) sitearchincludedir = $(includedir)/$(sitearch) archincludedir = $(includedir)/$(arch) sitearchlibdir = $(libdir)/$(sitearch) archlibdir = $(libdir)/$(arch) ridir = $(datarootdir)/$(RI_BASE_NAME) mandir = $(DESTDIR)/usr/share/man localedir = $(datarootdir)/locale libdir = $(exec_prefix)/lib psdir = $(docdir) pdfdir = $(docdir) dvidir = $(docdir) htmldir = $(docdir) infodir = $(DESTDIR)/usr/share/info docdir = $(datarootdir)/doc/$(PACKAGE) oldincludedir = $(DESTDIR)/usr/include includedir = $(DESTDIR)/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk$(prefix)/include localstatedir = $(prefix)/var sharedstatedir = $(prefix)/com sysconfdir = $(DESTDIR)/Library/Ruby/Site datadir = $(datarootdir) datarootdir = $(prefix)/share libexecdir = $(exec_prefix)/libexec sbindir = $(exec_prefix)/sbin bindir = $(exec_prefix)/bin archdir = $(rubyarchdir) CC_WRAPPER = CC = xcrun clang CXX = xcrun clang++ LIBRUBY = $(LIBRUBY_SO) LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME) LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static -framework Security -framework Foundation $(MAINLIBS) empty = OUTFLAG = -o $(empty) COUTFLAG = -o $(empty) CSRCFLAG = $(empty) RUBY_EXTCONF_H = extconf.h cflags = $(optflags) $(debugflags) $(warnflags) cxxflags = $(optflags) $(debugflags) $(warnflags) optflags = debugflags = -g warnflags = cppflags = CCDLFLAGS = CFLAGS = $(CCDLFLAGS) -g -Os -pipe -DHAVE_GCC_ATOMIC_BUILTINS $(ARCH_FLAG) INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) -I/opt/local/lib/libffi-3.2.1/include DEFS = CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT $(DEFS) $(cppflags) CXXFLAGS = $(CCDLFLAGS) -g -Os -pipe $(ARCH_FLAG) ldflags = -L. -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.Internal.sdk/usr/local/lib -L/opt/local/lib dldflags = -arch x86_64 -undefined dynamic_lookup -multiply_defined suppress ARCH_FLAG = -arch x86_64 DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) LDSHARED = $(CC) -dynamic -bundle LDSHAREDXX = $(CXX) -dynamic -bundle AR = libtool -static EXEEXT = RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) RUBY_SO_NAME = ruby.2.6 RUBYW_INSTALL_NAME = RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) RUBYW_BASE_NAME = rubyw RUBY_BASE_NAME = ruby arch = universal-darwin19 sitearch = $(arch) ruby_version = 2.6.0 ruby = $(bindir)/$(RUBY_BASE_NAME) RUBY = $(ruby) ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H) RM = rm -f RM_RF = $(RUBY) -run -e rm -- -rf RMDIRS = rmdir -p MAKEDIRS = mkdir -p INSTALL = /usr/bin/install -c INSTALL_PROG = $(INSTALL) -m 0755 INSTALL_DATA = $(INSTALL) -m 644 COPY = cp TOUCH = exit > #### End of system configuration section. #### preload = libpath = . $(libdir) LIBPATH = -L. -L$(libdir) DEFFILE = CLEANFILES = mkmf.log DISTCLEANFILES = DISTCLEANDIRS = extout = extout_prefix = target_prefix = LOCAL_LIBS = LIBS = $(LIBRUBYARG_SHARED) -lffi -lffi ORIG_SRCS = AbstractMemory.c ArrayType.c Buffer.c Call.c ClosurePool.c DynamicLibrary.c Function.c FunctionInfo.c LastError.c LongDouble.c MappedType.c MemoryPointer.c MethodHandle.c Platform.c Pointer.c Struct.c StructByValue.c StructLayout.c Thread.c Type.c Types.c Variadic.c ffi.c SRCS = $(ORIG_SRCS) OBJS = AbstractMemory.o ArrayType.o Buffer.o Call.o ClosurePool.o DynamicLibrary.o Function.o FunctionInfo.o LastError.o LongDouble.o MappedType.o MemoryPointer.o MethodHandle.o Platform.o Pointer.o Struct.o StructByValue.o StructLayout.o Thread.o Type.o Types.o Variadic.o ffi.o HDRS = $(srcdir)/Type.h $(srcdir)/rbffi_endian.h $(srcdir)/MappedType.h $(srcdir)/Types.h $(srcdir)/LastError.h $(srcdir)/ArrayType.h $(srcdir)/extconf.h $(srcdir)/StructByValue.h $(srcdir)/AbstractMemory.h $(srcdir)/ClosurePool.h $(srcdir)/Call.h $(srcdir)/MethodHandle.h $(srcdir)/Struct.h $(srcdir)/rbffi.h $(srcdir)/Thread.h $(srcdir)/compat.h $(srcdir)/DynamicLibrary.h $(srcdir)/Platform.h $(srcdir)/Function.h $(srcdir)/LongDouble.h $(srcdir)/MemoryPointer.h $(srcdir)/Pointer.h LOCAL_HDRS = TARGET = ffi_c TARGET_NAME = ffi_c TARGET_ENTRY = Init_$(TARGET_NAME) DLLIB = $(TARGET).bundle EXTSTATIC = STATIC_LIB = TIMESTAMP_DIR = . BINDIR = $(bindir) RUBYCOMMONDIR = $(sitedir)$(target_prefix) RUBYLIBDIR = $(sitelibdir)$(target_prefix) RUBYARCHDIR = $(sitearchdir)$(target_prefix) HDRDIR = $(rubyhdrdir)/ruby$(target_prefix) ARCHHDRDIR = $(rubyhdrdir)/$(arch)/ruby$(target_prefix) TARGET_SO_DIR = TARGET_SO = $(TARGET_SO_DIR)$(DLLIB) CLEANLIBS = $(TARGET_SO) CLEANOBJS = *.o *.bak all: $(DLLIB) static: $(STATIC_LIB) .PHONY: all install static install-so install-rb .PHONY: clean clean-so clean-static clean-rb clean-static:: clean-rb-default:: clean-rb:: clean-so:: clean: clean-so clean-static clean-rb-default clean-rb -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time distclean-rb-default:: distclean-rb:: distclean-so:: distclean-static:: distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true realclean: distclean install: install-so install-rb install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) clean-static:: -$(Q)$(RM) $(STATIC_LIB) install-rb: pre-install-rb do-install-rb install-rb-default install-rb-default: pre-install-rb-default do-install-rb-default pre-install-rb: Makefile pre-install-rb-default: Makefile do-install-rb: do-install-rb-default: pre-install-rb-default: @$(NULLCMD) $(TIMESTAMP_DIR)/.sitearchdir.time: $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) $(Q) $(TOUCH) $@ site-install: site-install-so site-install-rb site-install-so: install-so site-install-rb: install-rb .SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S .cc.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .cc.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< .mm.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .mm.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< .cxx.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .cxx.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< .cpp.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .cpp.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< .c.o: $(ECHO) compiling $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .c.S: $(ECHO) translating $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< .m.o: $(ECHO) compiling $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< .m.S: $(ECHO) translating $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< $(TARGET_SO): $(OBJS) Makefile $(ECHO) linking shared-object $(DLLIB) -$(Q)$(RM) $(@) $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) $(Q) $(POSTLINK) $(OBJS): $(HDRS) $(ruby_headers)
yangqiju/yangqiju.github.com
vendor/bundle/ruby/2.6.0/gems/ffi-1.12.2/ext/ffi_c/Makefile
Makefile
gpl-2.0
9,332
/* neutrino bouquet editor - channel selection Copyright (C) 2001 Steffen Hehn 'McClean' Copyright (C) 2017 Sven Hoefer License: GPL This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <unistd.h> #include <global.h> #include <neutrino.h> #include <driver/fontrenderer.h> #include <driver/screen_max.h> #include <gui/widget/icons.h> #include <zapit/getservices.h> #include <zapit/zapit.h> #include "bouqueteditor_chanselect.h" extern CBouquetManager *g_bouquetManager; CBEChannelSelectWidget::CBEChannelSelectWidget(const std::string & Caption, CZapitBouquet* Bouquet, CZapitClient::channelsMode Mode) { caption = Caption; bouquet = Bouquet; mode = Mode; selected = 0; liststart = 0; channellist_sort_mode = SORT_ALPHA; bouquetChannels = NULL; int iw, ih; action_icon_width = 0; frameBuffer->getIconSize(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, &action_icon_width, &ih); status_icon_width = 0; frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_SCRAMBLED, &iw, &ih); status_icon_width = std::max(status_icon_width, iw); frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_STREAMING, &iw, &ih); status_icon_width = std::max(status_icon_width, iw); } CBEChannelSelectWidget::~CBEChannelSelectWidget() { } void CBEChannelSelectWidget::paintItem(int pos) { int ypos = y + header_height + pos*item_height; unsigned int current = liststart + pos; bool i_selected = current == selected; int i_radius = RADIUS_NONE; fb_pixel_t color; fb_pixel_t bgcolor; getItemColors(color, bgcolor, i_selected); if (i_selected) { if (current < Channels.size() || Channels.empty()) paintDetails(pos, current); i_radius = RADIUS_LARGE; } else { if (current < Channels.size() && (Channels[current]->flags & CZapitChannel::NOT_PRESENT)) color = COL_MENUCONTENTINACTIVE_TEXT; } if (i_radius) frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, COL_MENUCONTENT_PLUS_0); frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, bgcolor, i_radius); if (current < Channels.size()) { if (isChannelInBouquet(current)) frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_GREEN, x + OFFSET_INNER_MID, ypos, item_height); else frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, x + OFFSET_INNER_MID, ypos, item_height); int text_offset = 2*OFFSET_INNER_MID + action_icon_width; item_font->RenderString(x + text_offset, ypos + item_height, width - text_offset - SCROLLBAR_WIDTH - 2*OFFSET_INNER_MID - status_icon_width, Channels[current]->getName(), color); if (Channels[current]->scrambled) frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_SCRAMBLED, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height); else if (!Channels[current]->getUrl().empty()) frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_STREAMING, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height); } frameBuffer->blit(); } void CBEChannelSelectWidget::paintItems() { liststart = (selected/items_count)*items_count; for(unsigned int count = 0; count < items_count; count++) paintItem(count); int total_pages; int current_page; getScrollBarData(&total_pages, &current_page, Channels.size(), items_count, selected); paintScrollBar(x + width - SCROLLBAR_WIDTH, y + header_height, SCROLLBAR_WIDTH, body_height, total_pages, current_page); } void CBEChannelSelectWidget::paintHead() { CBEGlobals::paintHead(caption + (mode == CZapitClient::MODE_TV ? " - TV" : " - Radio"), mode == CZapitClient::MODE_TV ? NEUTRINO_ICON_VIDEO : NEUTRINO_ICON_AUDIO); } struct button_label CBEChannelSelectButtons[] = { { NEUTRINO_ICON_BUTTON_RED, LOCALE_CHANNELLIST_FOOT_SORT_ALPHA }, { NEUTRINO_ICON_BUTTON_OKAY, LOCALE_BOUQUETEDITOR_SWITCH }, { NEUTRINO_ICON_BUTTON_HOME, LOCALE_BOUQUETEDITOR_RETURN } }; void CBEChannelSelectWidget::paintFoot() { switch (channellist_sort_mode) { case SORT_FREQ: { CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_FREQ; break; } case SORT_SAT: { CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_SAT; break; } case SORT_CH_NUMBER: { CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_CHNUM; break; } case SORT_ALPHA: default: { CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_ALPHA; break; } } const short numbuttons = sizeof(CBEChannelSelectButtons)/sizeof(CBEChannelSelectButtons[0]); CBEGlobals::paintFoot(numbuttons, CBEChannelSelectButtons); } std::string CBEChannelSelectWidget::getInfoText(int index) { std::string res = ""; if (Channels.empty()) return res; std::string satname = CServiceManager::getInstance()->GetSatelliteName(Channels[index]->getSatellitePosition()); if (IS_WEBCHAN(Channels[index]->getChannelID())) satname = "Web-Channel"; // TODO split into WebTV/WebRadio transponder t; CServiceManager::getInstance()->GetTransponder(Channels[index]->getTransponderId(), t); std::string desc = t.description(); if (Channels[index]->pname) { if (desc.empty()) desc = std::string(Channels[index]->pname); else desc += " (" + std::string(Channels[index]->pname) + ")"; } if (!Channels[index]->getDesc().empty()) desc += "\n" + Channels[index]->getDesc(); res = satname + " - " + desc; return res; } void CBEChannelSelectWidget::updateSelection(unsigned int newpos) { if (newpos == selected || newpos == (unsigned int)-1) return; unsigned int prev_selected = selected; selected = newpos; unsigned int oldliststart = liststart; liststart = (selected/items_count)*items_count; if (oldliststart != liststart) { paintItems(); } else { paintItem(prev_selected - liststart); paintItem(selected - liststart); } } int CBEChannelSelectWidget::exec(CMenuTarget* parent, const std::string & /*actionKey*/) { neutrino_msg_t msg; neutrino_msg_data_t data; int res = menu_return::RETURN_REPAINT; selected = 0; if (parent) parent->hide(); bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels); Channels.clear(); if (mode == CZapitClient::MODE_RADIO) CServiceManager::getInstance()->GetAllRadioChannels(Channels); else CServiceManager::getInstance()->GetAllTvChannels(Channels); sort(Channels.begin(), Channels.end(), CmpChannelByChName()); paintHead(); paintBody(); paintFoot(); paintItems(); uint64_t timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr); channelChanged = false; bool loop = true; while (loop) { g_RCInput->getMsgAbsoluteTimeout(&msg, &data, &timeoutEnd); if (msg <= CRCInput::RC_MaxRC) timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr); if ((msg == CRCInput::RC_timeout) || (msg == CRCInput::RC_home)) { loop = false; } else if (msg == CRCInput::RC_up || msg == (neutrino_msg_t)g_settings.key_pageup || msg == CRCInput::RC_down || msg == (neutrino_msg_t)g_settings.key_pagedown) { int new_selected = UpDownKey(Channels, msg, items_count, selected); updateSelection(new_selected); } else if (msg == (neutrino_msg_t) g_settings.key_list_start || msg == (neutrino_msg_t) g_settings.key_list_end) { if (!Channels.empty()) { int new_selected = msg == (neutrino_msg_t) g_settings.key_list_start ? 0 : Channels.size() - 1; updateSelection(new_selected); } } else if (msg == CRCInput::RC_ok || msg == CRCInput::RC_green) { if (selected < Channels.size()) selectChannel(); } else if (msg == CRCInput::RC_red) { if (selected < Channels.size()) sortChannels(); } else if (CNeutrinoApp::getInstance()->listModeKey(msg)) { // do nothing } else { CNeutrinoApp::getInstance()->handleMsg(msg, data); } } hide(); return res; } void CBEChannelSelectWidget::sortChannels() { channellist_sort_mode++; if (channellist_sort_mode >= SORT_END) channellist_sort_mode = SORT_ALPHA; switch (channellist_sort_mode) { case SORT_FREQ: { sort(Channels.begin(), Channels.end(), CmpChannelByFreq()); break; } case SORT_SAT: { sort(Channels.begin(), Channels.end(), CmpChannelBySat()); break; } case SORT_CH_NUMBER: { sort(Channels.begin(), Channels.end(), CmpChannelByChNum()); break; } case SORT_ALPHA: default: { sort(Channels.begin(), Channels.end(), CmpChannelByChName()); break; } } paintFoot(); paintItems(); } void CBEChannelSelectWidget::selectChannel() { channelChanged = true; if (isChannelInBouquet(selected)) bouquet->removeService(Channels[selected]); else bouquet->addService(Channels[selected]); bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels); paintItem(selected - liststart); g_RCInput->postMsg(CRCInput::RC_down, 0); } bool CBEChannelSelectWidget::isChannelInBouquet(int index) { for (unsigned int i=0; i< bouquetChannels->size(); i++) { if ((*bouquetChannels)[i]->getChannelID() == Channels[index]->getChannelID()) return true; } return false; } bool CBEChannelSelectWidget::hasChanged() { return channelChanged; }
TangoCash/neutrino-mp-cst-next
src/gui/bedit/bouqueteditor_chanselect.cpp
C++
gpl-2.0
9,692
/* * Copyright (C) 2014 Fraunhofer ITWM * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Written by: * Phoebe Buckheister <[email protected]> */ #include <linux/err.h> #include <linux/bug.h> #include <linux/completion.h> #include <net/ieee802154.h> #include <crypto/algapi.h> #include "mac802154.h" #include "llsec.h" static void llsec_key_put(struct mac802154_llsec_key *key); static bool llsec_key_id_equal(const struct ieee802154_llsec_key_id *a, const struct ieee802154_llsec_key_id *b); static void llsec_dev_free(struct mac802154_llsec_device *dev); void mac802154_llsec_init(struct mac802154_llsec *sec) { memset(sec, 0, sizeof(*sec)); memset(&sec->params.default_key_source, 0xFF, IEEE802154_ADDR_LEN); INIT_LIST_HEAD(&sec->table.security_levels); INIT_LIST_HEAD(&sec->table.devices); INIT_LIST_HEAD(&sec->table.keys); hash_init(sec->devices_short); hash_init(sec->devices_hw); rwlock_init(&sec->lock); } void mac802154_llsec_destroy(struct mac802154_llsec *sec) { struct ieee802154_llsec_seclevel *sl, *sn; struct ieee802154_llsec_device *dev, *dn; struct ieee802154_llsec_key_entry *key, *kn; list_for_each_entry_safe(sl, sn, &sec->table.security_levels, list) { struct mac802154_llsec_seclevel *msl; msl = container_of(sl, struct mac802154_llsec_seclevel, level); list_del(&sl->list); kfree(msl); } list_for_each_entry_safe(dev, dn, &sec->table.devices, list) { struct mac802154_llsec_device *mdev; mdev = container_of(dev, struct mac802154_llsec_device, dev); list_del(&dev->list); llsec_dev_free(mdev); } list_for_each_entry_safe(key, kn, &sec->table.keys, list) { struct mac802154_llsec_key *mkey; mkey = container_of(key->key, struct mac802154_llsec_key, key); list_del(&key->list); llsec_key_put(mkey); kfree(key); } } int mac802154_llsec_get_params(struct mac802154_llsec *sec, struct ieee802154_llsec_params *params) { read_lock_bh(&sec->lock); *params = sec->params; read_unlock_bh(&sec->lock); return 0; } int mac802154_llsec_set_params(struct mac802154_llsec *sec, const struct ieee802154_llsec_params *params, int changed) { write_lock_bh(&sec->lock); if (changed & IEEE802154_LLSEC_PARAM_ENABLED) sec->params.enabled = params->enabled; if (changed & IEEE802154_LLSEC_PARAM_FRAME_COUNTER) sec->params.frame_counter = params->frame_counter; if (changed & IEEE802154_LLSEC_PARAM_OUT_LEVEL) sec->params.out_level = params->out_level; if (changed & IEEE802154_LLSEC_PARAM_OUT_KEY) sec->params.out_key = params->out_key; if (changed & IEEE802154_LLSEC_PARAM_KEY_SOURCE) sec->params.default_key_source = params->default_key_source; if (changed & IEEE802154_LLSEC_PARAM_PAN_ID) sec->params.pan_id = params->pan_id; if (changed & IEEE802154_LLSEC_PARAM_HWADDR) sec->params.hwaddr = params->hwaddr; if (changed & IEEE802154_LLSEC_PARAM_COORD_HWADDR) sec->params.coord_hwaddr = params->coord_hwaddr; if (changed & IEEE802154_LLSEC_PARAM_COORD_SHORTADDR) sec->params.coord_shortaddr = params->coord_shortaddr; write_unlock_bh(&sec->lock); return 0; } static struct mac802154_llsec_key* llsec_key_alloc(const struct ieee802154_llsec_key *template) { const int authsizes[3] = { 4, 8, 16 }; struct mac802154_llsec_key *key; int i; key = kzalloc(sizeof(*key), GFP_KERNEL); if (!key) return NULL; kref_init(&key->ref); key->key = *template; BUILD_BUG_ON(ARRAY_SIZE(authsizes) != ARRAY_SIZE(key->tfm)); for (i = 0; i < ARRAY_SIZE(key->tfm); i++) { key->tfm[i] = crypto_alloc_aead("ccm(aes)", 0, CRYPTO_ALG_ASYNC); if (!key->tfm[i]) goto err_tfm; if (crypto_aead_setkey(key->tfm[i], template->key, IEEE802154_LLSEC_KEY_SIZE)) goto err_tfm; if (crypto_aead_setauthsize(key->tfm[i], authsizes[i])) goto err_tfm; } key->tfm0 = crypto_alloc_blkcipher("ctr(aes)", 0, CRYPTO_ALG_ASYNC); if (!key->tfm0) goto err_tfm; if (crypto_blkcipher_setkey(key->tfm0, template->key, IEEE802154_LLSEC_KEY_SIZE)) goto err_tfm0; return key; err_tfm0: crypto_free_blkcipher(key->tfm0); err_tfm: for (i = 0; i < ARRAY_SIZE(key->tfm); i++) if (key->tfm[i]) crypto_free_aead(key->tfm[i]); kfree(key); return NULL; } static void llsec_key_release(struct kref *ref) { struct mac802154_llsec_key *key; int i; key = container_of(ref, struct mac802154_llsec_key, ref); for (i = 0; i < ARRAY_SIZE(key->tfm); i++) crypto_free_aead(key->tfm[i]); crypto_free_blkcipher(key->tfm0); kfree(key); } static struct mac802154_llsec_key* llsec_key_get(struct mac802154_llsec_key *key) { kref_get(&key->ref); return key; } static void llsec_key_put(struct mac802154_llsec_key *key) { kref_put(&key->ref, llsec_key_release); } static bool llsec_key_id_equal(const struct ieee802154_llsec_key_id *a, const struct ieee802154_llsec_key_id *b) { if (a->mode != b->mode) return false; if (a->mode == IEEE802154_SCF_KEY_IMPLICIT) return ieee802154_addr_equal(&a->device_addr, &b->device_addr); if (a->id != b->id) return false; switch (a->mode) { case IEEE802154_SCF_KEY_INDEX: return true; case IEEE802154_SCF_KEY_SHORT_INDEX: return a->short_source == b->short_source; case IEEE802154_SCF_KEY_HW_INDEX: return a->extended_source == b->extended_source; } return false; } int mac802154_llsec_key_add(struct mac802154_llsec *sec, const struct ieee802154_llsec_key_id *id, const struct ieee802154_llsec_key *key) { struct mac802154_llsec_key *mkey = NULL; struct ieee802154_llsec_key_entry *pos, *new; if (!(key->frame_types & (1 << IEEE802154_FC_TYPE_MAC_CMD)) && key->cmd_frame_ids) return -EINVAL; list_for_each_entry(pos, &sec->table.keys, list) { if (llsec_key_id_equal(&pos->id, id)) return -EEXIST; if (memcmp(pos->key->key, key->key, IEEE802154_LLSEC_KEY_SIZE)) continue; mkey = container_of(pos->key, struct mac802154_llsec_key, key); /* Don't allow multiple instances of the same AES key to have * different allowed frame types/command frame ids, as this is * not possible in the 802.15.4 PIB. */ if (pos->key->frame_types != key->frame_types || pos->key->cmd_frame_ids != key->cmd_frame_ids) return -EEXIST; break; } new = kzalloc(sizeof(*new), GFP_KERNEL); if (!new) return -ENOMEM; if (!mkey) mkey = llsec_key_alloc(key); else mkey = llsec_key_get(mkey); if (!mkey) goto fail; new->id = *id; new->key = &mkey->key; list_add_rcu(&new->list, &sec->table.keys); return 0; fail: kfree(new); return -ENOMEM; } int mac802154_llsec_key_del(struct mac802154_llsec *sec, const struct ieee802154_llsec_key_id *key) { struct ieee802154_llsec_key_entry *pos; list_for_each_entry(pos, &sec->table.keys, list) { struct mac802154_llsec_key *mkey; mkey = container_of(pos->key, struct mac802154_llsec_key, key); if (llsec_key_id_equal(&pos->id, key)) { list_del_rcu(&pos->list); llsec_key_put(mkey); return 0; } } return -ENOENT; } static bool llsec_dev_use_shortaddr(__le16 short_addr) { return short_addr != cpu_to_le16(IEEE802154_ADDR_UNDEF) && short_addr != cpu_to_le16(0xffff); } static u32 llsec_dev_hash_short(__le16 short_addr, __le16 pan_id) { return ((__force u16) short_addr) << 16 | (__force u16) pan_id; } static u64 llsec_dev_hash_long(__le64 hwaddr) { return (__force u64) hwaddr; } static struct mac802154_llsec_device* llsec_dev_find_short(struct mac802154_llsec *sec, __le16 short_addr, __le16 pan_id) { struct mac802154_llsec_device *dev; u32 key = llsec_dev_hash_short(short_addr, pan_id); hash_for_each_possible_rcu(sec->devices_short, dev, bucket_s, key) { if (dev->dev.short_addr == short_addr && dev->dev.pan_id == pan_id) return dev; } return NULL; } static struct mac802154_llsec_device* llsec_dev_find_long(struct mac802154_llsec *sec, __le64 hwaddr) { struct mac802154_llsec_device *dev; u64 key = llsec_dev_hash_long(hwaddr); hash_for_each_possible_rcu(sec->devices_hw, dev, bucket_hw, key) { if (dev->dev.hwaddr == hwaddr) return dev; } return NULL; } static void llsec_dev_free(struct mac802154_llsec_device *dev) { struct ieee802154_llsec_device_key *pos, *pn; struct mac802154_llsec_device_key *devkey; list_for_each_entry_safe(pos, pn, &dev->dev.keys, list) { devkey = container_of(pos, struct mac802154_llsec_device_key, devkey); list_del(&pos->list); kfree(devkey); } kfree(dev); } int mac802154_llsec_dev_add(struct mac802154_llsec *sec, const struct ieee802154_llsec_device *dev) { struct mac802154_llsec_device *entry; u32 skey = llsec_dev_hash_short(dev->short_addr, dev->pan_id); u64 hwkey = llsec_dev_hash_long(dev->hwaddr); BUILD_BUG_ON(sizeof(hwkey) != IEEE802154_ADDR_LEN); if ((llsec_dev_use_shortaddr(dev->short_addr) && llsec_dev_find_short(sec, dev->short_addr, dev->pan_id)) || llsec_dev_find_long(sec, dev->hwaddr)) return -EEXIST; entry = kmalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; entry->dev = *dev; spin_lock_init(&entry->lock); INIT_LIST_HEAD(&entry->dev.keys); if (llsec_dev_use_shortaddr(dev->short_addr)) hash_add_rcu(sec->devices_short, &entry->bucket_s, skey); else INIT_HLIST_NODE(&entry->bucket_s); hash_add_rcu(sec->devices_hw, &entry->bucket_hw, hwkey); list_add_tail_rcu(&entry->dev.list, &sec->table.devices); return 0; } static void llsec_dev_free_rcu(struct rcu_head *rcu) { llsec_dev_free(container_of(rcu, struct mac802154_llsec_device, rcu)); } int mac802154_llsec_dev_del(struct mac802154_llsec *sec, __le64 device_addr) { struct mac802154_llsec_device *pos; pos = llsec_dev_find_long(sec, device_addr); if (!pos) return -ENOENT; hash_del_rcu(&pos->bucket_s); hash_del_rcu(&pos->bucket_hw); call_rcu(&pos->rcu, llsec_dev_free_rcu); return 0; } static struct mac802154_llsec_device_key* llsec_devkey_find(struct mac802154_llsec_device *dev, const struct ieee802154_llsec_key_id *key) { struct ieee802154_llsec_device_key *devkey; list_for_each_entry_rcu(devkey, &dev->dev.keys, list) { if (!llsec_key_id_equal(key, &devkey->key_id)) continue; return container_of(devkey, struct mac802154_llsec_device_key, devkey); } return NULL; } int mac802154_llsec_devkey_add(struct mac802154_llsec *sec, __le64 dev_addr, const struct ieee802154_llsec_device_key *key) { struct mac802154_llsec_device *dev; struct mac802154_llsec_device_key *devkey; dev = llsec_dev_find_long(sec, dev_addr); if (!dev) return -ENOENT; if (llsec_devkey_find(dev, &key->key_id)) return -EEXIST; devkey = kmalloc(sizeof(*devkey), GFP_KERNEL); if (!devkey) return -ENOMEM; devkey->devkey = *key; list_add_tail_rcu(&devkey->devkey.list, &dev->dev.keys); return 0; } int mac802154_llsec_devkey_del(struct mac802154_llsec *sec, __le64 dev_addr, const struct ieee802154_llsec_device_key *key) { struct mac802154_llsec_device *dev; struct mac802154_llsec_device_key *devkey; dev = llsec_dev_find_long(sec, dev_addr); if (!dev) return -ENOENT; devkey = llsec_devkey_find(dev, &key->key_id); if (!devkey) return -ENOENT; list_del_rcu(&devkey->devkey.list); kfree_rcu(devkey, rcu); return 0; } static struct mac802154_llsec_seclevel* llsec_find_seclevel(const struct mac802154_llsec *sec, const struct ieee802154_llsec_seclevel *sl) { struct ieee802154_llsec_seclevel *pos; list_for_each_entry(pos, &sec->table.security_levels, list) { if (pos->frame_type != sl->frame_type || (pos->frame_type == IEEE802154_FC_TYPE_MAC_CMD && pos->cmd_frame_id != sl->cmd_frame_id) || pos->device_override != sl->device_override || pos->sec_levels != sl->sec_levels) continue; return container_of(pos, struct mac802154_llsec_seclevel, level); } return NULL; } int mac802154_llsec_seclevel_add(struct mac802154_llsec *sec, const struct ieee802154_llsec_seclevel *sl) { struct mac802154_llsec_seclevel *entry; if (llsec_find_seclevel(sec, sl)) return -EEXIST; entry = kmalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; entry->level = *sl; list_add_tail_rcu(&entry->level.list, &sec->table.security_levels); return 0; } int mac802154_llsec_seclevel_del(struct mac802154_llsec *sec, const struct ieee802154_llsec_seclevel *sl) { struct mac802154_llsec_seclevel *pos; pos = llsec_find_seclevel(sec, sl); if (!pos) return -ENOENT; list_del_rcu(&pos->level.list); kfree_rcu(pos, rcu); return 0; } static int llsec_recover_addr(struct mac802154_llsec *sec, struct ieee802154_addr *addr) { __le16 caddr = sec->params.coord_shortaddr; addr->pan_id = sec->params.pan_id; if (caddr == cpu_to_le16(IEEE802154_ADDR_BROADCAST)) { return -EINVAL; } else if (caddr == cpu_to_le16(IEEE802154_ADDR_UNDEF)) { addr->extended_addr = sec->params.coord_hwaddr; addr->mode = IEEE802154_ADDR_LONG; } else { addr->short_addr = sec->params.coord_shortaddr; addr->mode = IEEE802154_ADDR_SHORT; } return 0; } static struct mac802154_llsec_key* llsec_lookup_key(struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, const struct ieee802154_addr *addr, struct ieee802154_llsec_key_id *key_id) { struct ieee802154_addr devaddr = *addr; u8 key_id_mode = hdr->sec.key_id_mode; struct ieee802154_llsec_key_entry *key_entry; struct mac802154_llsec_key *key; if (key_id_mode == IEEE802154_SCF_KEY_IMPLICIT && devaddr.mode == IEEE802154_ADDR_NONE) { if (hdr->fc.type == IEEE802154_FC_TYPE_BEACON) { devaddr.extended_addr = sec->params.coord_hwaddr; devaddr.mode = IEEE802154_ADDR_LONG; } else if (llsec_recover_addr(sec, &devaddr) < 0) { return NULL; } } list_for_each_entry_rcu(key_entry, &sec->table.keys, list) { const struct ieee802154_llsec_key_id *id = &key_entry->id; if (!(key_entry->key->frame_types & BIT(hdr->fc.type))) continue; if (id->mode != key_id_mode) continue; if (key_id_mode == IEEE802154_SCF_KEY_IMPLICIT) { if (ieee802154_addr_equal(&devaddr, &id->device_addr)) goto found; } else { if (id->id != hdr->sec.key_id) continue; if ((key_id_mode == IEEE802154_SCF_KEY_INDEX) || (key_id_mode == IEEE802154_SCF_KEY_SHORT_INDEX && id->short_source == hdr->sec.short_src) || (key_id_mode == IEEE802154_SCF_KEY_HW_INDEX && id->extended_source == hdr->sec.extended_src)) goto found; } } return NULL; found: key = container_of(key_entry->key, struct mac802154_llsec_key, key); if (key_id) *key_id = key_entry->id; return llsec_key_get(key); } static void llsec_geniv(u8 iv[16], __le64 addr, const struct ieee802154_sechdr *sec) { __be64 addr_bytes = (__force __be64) swab64((__force u64) addr); __be32 frame_counter = (__force __be32) swab32((__force u32) sec->frame_counter); iv[0] = 1; /* L' = L - 1 = 1 */ memcpy(iv + 1, &addr_bytes, sizeof(addr_bytes)); memcpy(iv + 9, &frame_counter, sizeof(frame_counter)); iv[13] = sec->level; iv[14] = 0; iv[15] = 1; } static int llsec_do_encrypt_unauth(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key) { u8 iv[16]; struct scatterlist src; struct blkcipher_desc req = { .tfm = key->tfm0, .info = iv, .flags = 0, }; llsec_geniv(iv, sec->params.hwaddr, &hdr->sec); sg_init_one(&src, skb->data, skb->len); return crypto_blkcipher_encrypt_iv(&req, &src, &src, skb->len); } static struct crypto_aead* llsec_tfm_by_len(struct mac802154_llsec_key *key, int authlen) { int i; for (i = 0; i < ARRAY_SIZE(key->tfm); i++) if (crypto_aead_authsize(key->tfm[i]) == authlen) return key->tfm[i]; BUG(); } static int llsec_do_encrypt_auth(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key) { u8 iv[16]; unsigned char *data; int authlen, assoclen, datalen, rc; struct scatterlist src, assoc[2], dst[2]; struct aead_request *req; authlen = ieee802154_sechdr_authtag_len(&hdr->sec); llsec_geniv(iv, sec->params.hwaddr, &hdr->sec); req = aead_request_alloc(llsec_tfm_by_len(key, authlen), GFP_ATOMIC); if (!req) return -ENOMEM; sg_init_table(assoc, 2); sg_set_buf(&assoc[0], skb_mac_header(skb), skb->mac_len); assoclen = skb->mac_len; data = skb_mac_header(skb) + skb->mac_len; datalen = skb_tail_pointer(skb) - data; if (hdr->sec.level & IEEE802154_SCF_SECLEVEL_ENC) { sg_set_buf(&assoc[1], data, 0); } else { sg_set_buf(&assoc[1], data, datalen); assoclen += datalen; datalen = 0; } sg_init_one(&src, data, datalen); sg_init_table(dst, 2); sg_set_buf(&dst[0], data, datalen); sg_set_buf(&dst[1], skb_put(skb, authlen), authlen); aead_request_set_callback(req, 0, NULL, NULL); aead_request_set_assoc(req, assoc, assoclen); aead_request_set_crypt(req, &src, dst, datalen, iv); rc = crypto_aead_encrypt(req); kfree(req); return rc; } static int llsec_do_encrypt(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key) { if (hdr->sec.level == IEEE802154_SCF_SECLEVEL_ENC) return llsec_do_encrypt_unauth(skb, sec, hdr, key); else return llsec_do_encrypt_auth(skb, sec, hdr, key); } int mac802154_llsec_encrypt(struct mac802154_llsec *sec, struct sk_buff *skb) { struct ieee802154_hdr hdr; int rc, authlen, hlen; struct mac802154_llsec_key *key; u32 frame_ctr; hlen = ieee802154_hdr_pull(skb, &hdr); if (hlen < 0 || hdr.fc.type != IEEE802154_FC_TYPE_DATA) return -EINVAL; if (!hdr.fc.security_enabled || hdr.sec.level == 0) { skb_push(skb, hlen); return 0; } authlen = ieee802154_sechdr_authtag_len(&hdr.sec); if (skb->len + hlen + authlen + IEEE802154_MFR_SIZE > IEEE802154_MTU) return -EMSGSIZE; rcu_read_lock(); read_lock_bh(&sec->lock); if (!sec->params.enabled) { rc = -EINVAL; goto fail_read; } key = llsec_lookup_key(sec, &hdr, &hdr.dest, NULL); if (!key) { rc = -ENOKEY; goto fail_read; } read_unlock_bh(&sec->lock); write_lock_bh(&sec->lock); frame_ctr = be32_to_cpu(sec->params.frame_counter); hdr.sec.frame_counter = cpu_to_le32(frame_ctr); if (frame_ctr == 0xFFFFFFFF) { write_unlock_bh(&sec->lock); llsec_key_put(key); rc = -EOVERFLOW; goto fail; } sec->params.frame_counter = cpu_to_be32(frame_ctr + 1); write_unlock_bh(&sec->lock); rcu_read_unlock(); skb->mac_len = ieee802154_hdr_push(skb, &hdr); skb_reset_mac_header(skb); rc = llsec_do_encrypt(skb, sec, &hdr, key); llsec_key_put(key); return rc; fail_read: read_unlock_bh(&sec->lock); fail: rcu_read_unlock(); return rc; } static struct mac802154_llsec_device* llsec_lookup_dev(struct mac802154_llsec *sec, const struct ieee802154_addr *addr) { struct ieee802154_addr devaddr = *addr; struct mac802154_llsec_device *dev = NULL; if (devaddr.mode == IEEE802154_ADDR_NONE && llsec_recover_addr(sec, &devaddr) < 0) return NULL; if (devaddr.mode == IEEE802154_ADDR_SHORT) { u32 key = llsec_dev_hash_short(devaddr.short_addr, devaddr.pan_id); hash_for_each_possible_rcu(sec->devices_short, dev, bucket_s, key) { if (dev->dev.pan_id == devaddr.pan_id && dev->dev.short_addr == devaddr.short_addr) return dev; } } else { u64 key = llsec_dev_hash_long(devaddr.extended_addr); hash_for_each_possible_rcu(sec->devices_hw, dev, bucket_hw, key) { if (dev->dev.hwaddr == devaddr.extended_addr) return dev; } } return NULL; } static int llsec_lookup_seclevel(const struct mac802154_llsec *sec, u8 frame_type, u8 cmd_frame_id, struct ieee802154_llsec_seclevel *rlevel) { struct ieee802154_llsec_seclevel *level; list_for_each_entry_rcu(level, &sec->table.security_levels, list) { if (level->frame_type == frame_type && (frame_type != IEEE802154_FC_TYPE_MAC_CMD || level->cmd_frame_id == cmd_frame_id)) { *rlevel = *level; return 0; } } return -EINVAL; } static int llsec_do_decrypt_unauth(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key, __le64 dev_addr) { u8 iv[16]; unsigned char *data; int datalen; struct scatterlist src; struct blkcipher_desc req = { .tfm = key->tfm0, .info = iv, .flags = 0, }; llsec_geniv(iv, dev_addr, &hdr->sec); data = skb_mac_header(skb) + skb->mac_len; datalen = skb_tail_pointer(skb) - data; sg_init_one(&src, data, datalen); return crypto_blkcipher_decrypt_iv(&req, &src, &src, datalen); } static int llsec_do_decrypt_auth(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key, __le64 dev_addr) { u8 iv[16]; unsigned char *data; int authlen, datalen, assoclen, rc; struct scatterlist src, assoc[2]; struct aead_request *req; authlen = ieee802154_sechdr_authtag_len(&hdr->sec); llsec_geniv(iv, dev_addr, &hdr->sec); req = aead_request_alloc(llsec_tfm_by_len(key, authlen), GFP_ATOMIC); if (!req) return -ENOMEM; sg_init_table(assoc, 2); sg_set_buf(&assoc[0], skb_mac_header(skb), skb->mac_len); assoclen = skb->mac_len; data = skb_mac_header(skb) + skb->mac_len; datalen = skb_tail_pointer(skb) - data; if (hdr->sec.level & IEEE802154_SCF_SECLEVEL_ENC) { sg_set_buf(&assoc[1], data, 0); } else { sg_set_buf(&assoc[1], data, datalen - authlen); assoclen += datalen - authlen; data += datalen - authlen; datalen = authlen; } sg_init_one(&src, data, datalen); aead_request_set_callback(req, 0, NULL, NULL); aead_request_set_assoc(req, assoc, assoclen); aead_request_set_crypt(req, &src, &src, datalen, iv); rc = crypto_aead_decrypt(req); kfree(req); skb_trim(skb, skb->len - authlen); return rc; } static int llsec_do_decrypt(struct sk_buff *skb, const struct mac802154_llsec *sec, const struct ieee802154_hdr *hdr, struct mac802154_llsec_key *key, __le64 dev_addr) { if (hdr->sec.level == IEEE802154_SCF_SECLEVEL_ENC) return llsec_do_decrypt_unauth(skb, sec, hdr, key, dev_addr); else return llsec_do_decrypt_auth(skb, sec, hdr, key, dev_addr); } static int llsec_update_devkey_info(struct mac802154_llsec_device *dev, const struct ieee802154_llsec_key_id *in_key, u32 frame_counter) { struct mac802154_llsec_device_key *devkey = NULL; if (dev->dev.key_mode == IEEE802154_LLSEC_DEVKEY_RESTRICT) { devkey = llsec_devkey_find(dev, in_key); if (!devkey) return -ENOENT; } spin_lock_bh(&dev->lock); if ((!devkey && frame_counter < dev->dev.frame_counter) || (devkey && frame_counter < devkey->devkey.frame_counter)) { spin_unlock_bh(&dev->lock); return -EINVAL; } if (devkey) devkey->devkey.frame_counter = frame_counter + 1; else dev->dev.frame_counter = frame_counter + 1; spin_unlock_bh(&dev->lock); return 0; } int mac802154_llsec_decrypt(struct mac802154_llsec *sec, struct sk_buff *skb) { struct ieee802154_hdr hdr; struct mac802154_llsec_key *key; struct ieee802154_llsec_key_id key_id; struct mac802154_llsec_device *dev; struct ieee802154_llsec_seclevel seclevel; int err; __le64 dev_addr; u32 frame_ctr; if (ieee802154_hdr_peek(skb, &hdr) < 0) return -EINVAL; if (!hdr.fc.security_enabled) return 0; if (hdr.fc.version == 0) return -EINVAL; read_lock_bh(&sec->lock); if (!sec->params.enabled) { read_unlock_bh(&sec->lock); return -EINVAL; } read_unlock_bh(&sec->lock); rcu_read_lock(); key = llsec_lookup_key(sec, &hdr, &hdr.source, &key_id); if (!key) { err = -ENOKEY; goto fail; } dev = llsec_lookup_dev(sec, &hdr.source); if (!dev) { err = -EINVAL; goto fail_dev; } if (llsec_lookup_seclevel(sec, hdr.fc.type, 0, &seclevel) < 0) { err = -EINVAL; goto fail_dev; } if (!(seclevel.sec_levels & BIT(hdr.sec.level)) && (hdr.sec.level == 0 && seclevel.device_override && !dev->dev.seclevel_exempt)) { err = -EINVAL; goto fail_dev; } frame_ctr = le32_to_cpu(hdr.sec.frame_counter); if (frame_ctr == 0xffffffff) { err = -EOVERFLOW; goto fail_dev; } err = llsec_update_devkey_info(dev, &key_id, frame_ctr); if (err) goto fail_dev; dev_addr = dev->dev.hwaddr; rcu_read_unlock(); err = llsec_do_decrypt(skb, sec, &hdr, key, dev_addr); llsec_key_put(key); return err; fail_dev: llsec_key_put(key); fail: rcu_read_unlock(); return err; }
nsat/zynq-linux
net/mac802154/llsec.c
C
gpl-2.0
24,885
vti_encoding:SR|utf8-nl vti_timelastmodified:TR|08 Nov 2012 23:29:31 -0000 vti_extenderversion:SR|5.0.2.6790 vti_lineageid:SR|{44761BDF-1053-4E8B-8B42-2966A30F18D2} vti_cacheddtm:TX|08 Nov 2012 23:29:31 -0000 vti_filesize:IR|2149 vti_backlinkinfo:VX|
JustinTBayer/chapter-manager
_vti_cnf/changelog.php
PHP
gpl-2.0
258
# gonads A Go-style CSP channel implementation for Haskell Monads. Get it?
existentialmutt/gonads
README.md
Markdown
gpl-2.0
76
package org.janelia.alignment.match; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * List of {@link CanvasMatches} with associated tileIds mapped for fast lookup. * * @author Eric Trautman */ public class TileIdsWithMatches { private final Set<String> tileIds; private final List<CanvasMatches> canvasMatchesList; public TileIdsWithMatches() { this.canvasMatchesList = new ArrayList<>(); this.tileIds = new HashSet<>(); } /** * * @param canvasMatchesList list of matches for section (could include tiles not in stack). * @param stackTileIds set of tile ids in stack. * To be kept, match pair must have both tiles in stack. */ public void addMatches(final List<CanvasMatches> canvasMatchesList, final Set<String> stackTileIds) { for (final CanvasMatches canvasMatches : canvasMatchesList) { final String pId = canvasMatches.getpId(); final String qId = canvasMatches.getqId(); if (stackTileIds.contains(pId) && stackTileIds.contains(qId)) { this.canvasMatchesList.add(canvasMatches); this.tileIds.add(pId); this.tileIds.add(qId); } } } public boolean contains(final String tileId) { return tileIds.contains(tileId); } public List<CanvasMatches> getCanvasMatchesList() { return canvasMatchesList; } }
saalfeldlab/render
render-app/src/main/java/org/janelia/alignment/match/TileIdsWithMatches.java
Java
gpl-2.0
1,543
/* Pin Tool for * calculation of the Stack Reuse Distance Histogram * * (C) 2015, Josef Weidendorfer / LRR-TUM * GPLv2+ (see COPYING) */ #include "pin.H" #include <stdio.h> #include <cassert> #include <cstring> #include <cmath> #include <unistd.h> #include "dist.cpp" // Consistency checks? #define DEBUG 0 // 2: Huge amount of debug output, 1: checks, 0: silent #define VERBOSE 0 // uses INS_IsStackRead/Write: misleading with -fomit-frame-pointer #define IGNORE_STACK 1 // collect addresses in chunk buffer before? (always worse) #define MERGE_CHUNK 0 #define CHUNKSIZE 4096 // must be a power-of-two #define MEMBLOCKLEN 64 unsigned long stackAccesses; unsigned long ignoredReads, ignoredWrites; /* ===================================================================== */ /* Command line options */ /* ===================================================================== */ KNOB<int> KnobMinDist(KNOB_MODE_WRITEONCE, "pintool", "m", "4096", "minimum bucket distance"); KNOB<int> KnobDoubleSteps(KNOB_MODE_WRITEONCE, "pintool", "s", "1", "number of buckets for doubling distance"); KNOB<bool> KnobPIDPrefix(KNOB_MODE_WRITEONCE, "pintool", "p", "0", "prepend output by --PID--"); /* ===================================================================== */ /* Handle Memory block access (aligned at multiple of MEMBLOCKLEN) */ /* ===================================================================== */ #if MERGE_CHUNK void accessMerging(Addr a) { static Addr mergeBuffer[CHUNKSIZE]; static int ptr = 0; if (ptr < CHUNKSIZE) { mergeBuffer[ptr++] = a; return; } sort(mergeBuffer,mergeBuffer+CHUNKSIZE); for(ptr=0; ptr<CHUNKSIZE; ptr++) { RD_accessBlock(mergeBuffer[ptr]); } ptr = 0; } #define RD_accessBlock accessMerging #endif /* ===================================================================== */ /* Direct Callbacks */ /* ===================================================================== */ void memAccess(ADDRINT addr, UINT32 size) { Addr a1 = (void*) (addr & ~(MEMBLOCKLEN-1)); Addr a2 = (void*) ((addr+size-1) & ~(MEMBLOCKLEN-1)); if (a1 == a2) { if (VERBOSE >1) fprintf(stderr," => %p\n", a1); RD_accessBlock(a1); } else { if (VERBOSE >1) fprintf(stderr," => CROSS %p/%p\n", a1, a2); RD_accessBlock(a1); RD_accessBlock(a2); } } VOID memRead(THREADID t, ADDRINT addr, UINT32 size) { if (t > 0) { // we are NOT thread-safe, ignore access ignoredReads++; return; } if (VERBOSE >1) fprintf(stderr,"R %p/%d", (void*)addr, size); memAccess(addr, size); } VOID memWrite(THREADID t, ADDRINT addr, UINT32 size) { if (t > 0) { // we are NOT thread-safe, ignore access ignoredWrites++; return; } if (VERBOSE >1) fprintf(stderr,"W %p/%d", (void*)addr, size); memAccess(addr, size); } VOID stackAccess() { stackAccesses++; } /* ===================================================================== */ /* Instrumentation */ /* ===================================================================== */ VOID Instruction(INS ins, VOID* v) { if (IGNORE_STACK && (INS_IsStackRead(ins) || INS_IsStackWrite(ins))) { INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)stackAccess, IARG_END); return; } UINT32 memOperands = INS_MemoryOperandCount(ins); for (UINT32 memOp = 0; memOp < memOperands; memOp++) { if (INS_MemoryOperandIsRead(ins, memOp)) INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memRead, IARG_THREAD_ID, IARG_MEMORYOP_EA, memOp, IARG_UINT32, INS_MemoryOperandSize(ins, memOp), IARG_END); if (INS_MemoryOperandIsWritten(ins, memOp)) INS_InsertPredicatedCall( ins, IPOINT_BEFORE, (AFUNPTR)memWrite, IARG_THREAD_ID, IARG_MEMORYOP_EA, memOp, IARG_UINT32, INS_MemoryOperandSize(ins, memOp), IARG_END); } } /* ===================================================================== */ /* Callbacks from Pin */ /* ===================================================================== */ VOID ThreadStart(THREADID t, CONTEXT *ctxt, INT32 flags, VOID *v) { fprintf(stderr, "Thread %d started\n", t); } /* ===================================================================== */ /* Output results at exit */ /* ===================================================================== */ VOID Exit(INT32 code, VOID *v) { char pStr[20]; if (KnobPIDPrefix.Value()) sprintf(pStr, "--%5d-- ", getpid()); else pStr[0] = 0; RD_printHistogram(stderr, pStr, MEMBLOCKLEN); fprintf(stderr, "%s ignored stack accesses: %lu\n", pStr, stackAccesses); fprintf(stderr, "%s ignored accesses by thread != 0: %lu reads, %lu writes\n", pStr, ignoredReads, ignoredWrites); } /* ===================================================================== */ /* Usage/Main Function of the Pin Tool */ /* ===================================================================== */ INT32 Usage() { PIN_ERROR( "PinDist: Get the Stack Reuse Distance Histogram\n" + KNOB_BASE::StringKnobSummary() + "\n"); return -1; } int main (int argc, char *argv[]) { if (PIN_Init(argc, argv)) return Usage(); // add buckets [0-1023], [1K - 2K-1], ... [1G - ] double d = KnobMinDist.Value(); int s = KnobDoubleSteps.Value(); double f = pow(2, 1.0/s); RD_init((int)(d / MEMBLOCKLEN)); for(d*=f; d< 1024*1024*1024; d*=f) RD_addBucket((int)(d / MEMBLOCKLEN)); stackAccesses = 0; PIN_InitSymbols(); INS_AddInstrumentFunction(Instruction, 0); PIN_AddFiniFunction(Exit, 0); PIN_AddThreadStartFunction(ThreadStart, 0); PIN_StartProgram(); return 0; }
lrr-tum/reuse
pindist/pindist.cpp
C++
gpl-2.0
5,945
import { createSelector } from '@automattic/state-utils'; import { filter, orderBy } from 'lodash'; import 'calypso/state/comments/init'; function filterCommentsByStatus( comments, status ) { return 'all' === status ? filter( comments, ( comment ) => 'approved' === comment.status || 'unapproved' === comment.status ) : filter( comments, ( comment ) => status === comment.status ); } /** * Returns list of loaded comments for a given site, filtered by status * * @param {object} state Redux state * @param {number} siteId Site for whose comments to find * @param {string} [status] Status to filter comments * @param {string} [order=asc] Order in which to sort filtered comments * @returns {Array<object>} Available comments for site, filtered by status */ export const getSiteComments = createSelector( ( state, siteId, status, order = 'asc' ) => { const comments = state.comments.items ?? {}; const parsedComments = Object.keys( comments ) .filter( ( key ) => parseInt( key.split( '-', 1 ), 10 ) === siteId ) .reduce( ( list, key ) => [ ...list, ...comments[ key ] ], [] ); return status ? orderBy( filterCommentsByStatus( parsedComments, status ), 'date', order ) : orderBy( parsedComments, 'date', order ); }, ( state ) => [ state.comments.items ] );
Automattic/wp-calypso
client/state/comments/selectors/get-site-comments.js
JavaScript
gpl-2.0
1,304
(function(customer_id) { tinymce.create('tinymce.plugins.ItStream_AttachToPost', { customer_id: customer_id, init : function(editor, plugin_url) { editor.addButton('player_scheduling', { title : 'Embed ItStream Player', cmd : 'itm_scheduling', image : plugin_url + '/scheduling.gif' }); // Register a new TinyMCE command editor.addCommand('itm_scheduling', this.render_attach_to_post_interface, { editor: editor, plugin: editor.plugins.ItStream_AttachToPost }); }, createControl : function(n, cm) { return null; }, getInfo : function() { return { longname : 'ItStream Scheduling Button', author : 'It-Marketing', authorurl : 'http://www.itmarketingsrl.it/', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example', version : "0.1" }; }, wm_close_event: function() { // Restore scrolling for the main content window when the attach to post interface is closed jQuery('html,body').css('overflow', 'auto'); tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('p')[0]); tinyMCE.activeEditor.selection.collapse(0); }, render_attach_to_post_interface: function() { var attach_to_post_url = itstream_ajax.attach_to_post; if (typeof(customer_id) != 'undefined') { attach_to_post_url += "?id=" + itstream_ajax.customer_id; } var win = window; while (win.parent != null && win.parent != win) { win = win.parent; } win = jQuery(win); var winWidth = win.width(); var winHeight = win.height(); var popupWidth = 680; var popupHeight = 560; var minWidth = 320; var minHeight = 200; var maxWidth = winWidth - (winWidth * 0.05); var maxHeight = winHeight - (winHeight * 0.05); if (maxWidth < minWidth) { maxWidth = winWidth - 10; } if (maxHeight < minHeight) { maxHeight = winHeight - 10; } if (popupWidth > maxWidth) { popupWidth = maxWidth; } if (popupHeight > maxHeight) { popupHeight = maxHeight; } // Open a window this.editor.windowManager.open({ url: attach_to_post_url, id: 'its_attach_to_post_dialog', width: popupWidth, height: popupHeight, title: 'ItStream - Embed Player', inline: 1 /*buttons: [{ text: 'Close', onclick: 'close' }]*/ }); // Ensure that the window cannot be scrolled - XXX actually allow scrolling in the main window and disable it for the inner-windows/frames/elements as to create a single scrollbar jQuery('html,body').css('overflow', 'hidden'); jQuery('#its_attach_to_post_dialog_ifr').css('overflow-y', 'auto'); jQuery('#its_attach_to_post_dialog_ifr').css('overflow-x', 'hidden'); } }); // Register plugin tinymce.PluginManager.add( 'itstream', tinymce.plugins.ItStream_AttachToPost ); })(itstream_ajax.customer_id);
wp-plugins/itstream
admin/assets/js/editor.js
JavaScript
gpl-2.0
3,621
<?php /** * ExtendedEditBar extension for BlueSpice * * Provides additional buttons to the wiki edit field. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This file is part of BlueSpice for MediaWiki * For further information visit http://www.blue-spice.org * * @author Markus Glaser <[email protected]> * @author MediaWiki Extension * @version 2.22.0 stable * @package BlueSpice_Extensions * @subpackage ExtendedEditBar * @copyright Copyright (C) 2010 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later * @filesource */ /* Changelog * v1.20.0 * * v1.0.0 * - raised to stable * v0.1 * - initial release */ /** * Base class for ExtendedEditBar extension * @package BlueSpice_Extensions * @subpackage ExtendedEditBar */ class ExtendedEditBar extends BsExtensionMW { /** * Constructor of ExtendedEditBar class */ public function __construct() { wfProfileIn( 'BS::'.__METHOD__ ); // Base settings $this->mExtensionFile = __FILE__; $this->mExtensionType = EXTTYPE::OTHER; //SPECIALPAGE/OTHER/VARIABLE/PARSERHOOK $this->mInfo = array( EXTINFO::NAME => 'ExtendedEditBar', EXTINFO::DESCRIPTION => wfMessage( 'bs-extendededitbar-desc' )->escaped(), EXTINFO::AUTHOR => 'MediaWiki Extension, packaging by Markus Glaser', EXTINFO::VERSION => 'default', EXTINFO::STATUS => 'default', EXTINFO::PACKAGE => 'default', EXTINFO::URL => 'http://www.blue-spice.org', EXTINFO::DEPS => array( 'bluespice' => '2.22.0' ) ); $this->mExtensionKey = 'MW::ExtendedEditBar'; wfProfileOut('BS::'.__METHOD__ ); } /** * Initialization of ExtendedEditBar extension */ protected function initExt() { wfProfileIn( 'BS::'.__METHOD__ ); $this->setHook('EditPageBeforeEditToolbar'); wfProfileOut( 'BS::'.__METHOD__ ); } /** * * @global type $wgStylePath * @global type $wgContLang * @global type $wgLang * @global OutputPage $wgOut * @global type $wgUseTeX * @global type $wgEnableUploads * @global type $wgForeignFileRepos * @param string $toolbar * @return boolean */ public function onEditPageBeforeEditToolbar( &$toolbar ) { $this->getOutput()->addModuleStyles( 'ext.bluespice.extendeditbar.styles' ); $this->getOutput()->addModules( 'ext.bluespice.extendeditbar' ); //This is copy-code from EditPage::getEditToolbar(). Sad but neccesary //until we suppot WikiEditor and this get's obsolete. global $wgContLang, $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos; $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos ); $sNs = $this->getLanguage()->getNsText( NS_IMAGE ); $sCaption = wfMessage( 'bs-extendededitbar-gallerysamplecaption' )->plain(); $sPicture = wfMessage( 'bs-extendededitbar-gallerysamplepicture' )->plain(); $sGallery = "{$sNs}:{$sPicture}.jpg|{$sCaption}\n{$sNs}:{$sPicture}.jpg|{$sCaption}"; $sHeader = wfMessage( 'bs-extendededitbar-tablesampleheader' )->plain(); $sRow = wfMessage( 'bs-extendededitbar-tablesamplerow' )->plain(); $sCell = wfMessage( 'bs-extendededitbar-tablesamplecell' )->plain(); $sTable = "! {$sHeader} 1\n! {$sHeader} 2\n! {$sHeader} 3\n|-\n| {$sRow} 1, ". "{$sCell} 1\n| {$sRow} 1, {$sCell} 2\n| {$sRow} 1, {$sCell} 3\n|-\n|". " {$sRow} 2, {$sCell} 1\n| {$sRow} 2, {$sCell} 2\n| {$sRow} 2, {$sCell} 3"; $aMWButtonCfgs = array( 'mw-editbutton-bold' => array( 'open' => '\'\'\'', 'close' => '\'\'\'', 'sample' => wfMessage( 'bold_sample' )->text(), 'tip' => wfMessage( 'bold_tip' )->text(), 'key' => 'B' ), 'mw-editbutton-italic' => array( 'open' => '\'\'', 'close' => '\'\'', 'sample' => wfMessage( 'italic_sample' )->text(), 'tip' => wfMessage( 'italic_tip' )->text(), 'key' => 'I' ), 'mw-editbutton-link' => array( 'open' => '[[', 'close' => ']]', 'sample' => wfMessage( 'link_sample' )->text(), 'tip' => wfMessage( 'link_tip' )->text(), 'key' => 'L' ), 'mw-editbutton-extlink' => array( 'open' => '[', 'close' => ']', 'sample' => wfMessage( 'extlink_sample' )->text(), 'tip' => wfMessage( 'extlink_tip' )->text(), 'key' => 'X' ), 'mw-editbutton-headline' => array( 'open' => "\n== ", 'close' => " ==\n", 'sample' => wfMessage( 'headline_sample' )->text(), 'tip' => wfMessage( 'headline_tip' )->text(), 'key' => 'H' ), 'mw-editbutton-image' => $imagesAvailable ? array( 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':', 'close' => ']]', 'sample' => wfMessage( 'image_sample' )->text(), 'tip' => wfMessage( 'image_tip' )->text(), 'key' => 'D', ) : false, 'mw-editbutton-media' => $imagesAvailable ? array( 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':', 'close' => ']]', 'sample' => wfMessage( 'media_sample' )->text(), 'tip' => wfMessage( 'media_tip' )->text(), 'key' => 'M' ) : false, 'mw-editbutton-math' => $wgUseTeX ? array( 'open' => "<math>", 'close' => "</math>", 'sample' => wfMessage( 'math_sample' )->text(), 'tip' => wfMessage( 'math_tip' )->text(), 'key' => 'C' ) : false, 'mw-editbutton-signature' => array( 'open' => '--~~~~', 'close' => '', 'sample' => '', 'tip' => wfMessage( 'sig_tip' )->text(), 'key' => 'Y' ), ); $aBSButtonCfgs = array( 'bs-editbutton-redirect' => array( 'tip' => wfMessage('bs-extendededitbar-redirecttip')->plain(), 'open' => "#REDIRECT [[", 'close' => "]]", 'sample' => wfMessage('bs-extendededitbar-redirectsample')->plain() ), 'bs-editbutton-strike' => array( 'tip' => wfMessage('bs-extendededitbar-striketip')->plain(), 'open' => "<s>", 'close' => "</s>", 'sample' => wfMessage('bs-extendededitbar-strikesample')->plain() ), 'bs-editbutton-linebreak' => array( 'tip' => wfMessage('bs-extendededitbar-entertip')->plain(), 'open' => "<br />\n", 'close' => "", 'sample' => '' ), 'bs-editbutton-sup' => array( 'tip' => wfMessage('bs-extendededitbar-uppertip')->plain(), 'open' => "<sup>", 'close' => "</sup>", 'sample' => wfMessage('bs-extendededitbar-uppersample')->plain() ), 'bs-editbutton-sub' => array( 'tip' => wfMessage('bs-extendededitbar-lowertip')->plain(), 'open' => "<sub>", 'close' => "</sub>", 'sample' => wfMessage('bs-extendededitbar-lowersample')->plain() ), 'bs-editbutton-small' => array( 'tip' => wfMessage('bs-extendededitbar-smalltip')->plain(), 'open' => "<small>", 'close' => "</small>", 'sample' => wfMessage('bs-extendededitbar-smallsample')->plain() ), 'bs-editbutton-comment' => array( 'tip' => wfMessage('bs-extendededitbar-commenttip')->plain(), 'open' => "<!-- ", 'close' => " -->", 'sample' => wfMessage('bs-extendededitbar-commentsample')->plain() ), 'bs-editbutton-gallery' => array( 'tip' => wfMessage('bs-extendededitbar-gallerytip')->plain(), 'open' => "\n<gallery>\n", 'close' => "\n</gallery>", 'sample' => $sGallery ), 'bs-editbutton-blockquote' => array( 'tip' => wfMessage('bs-extendededitbar-quotetip')->plain(), 'open' => "\n<blockquote>\n", 'close' => "\n</blockquote>", 'sample' => wfMessage('bs-extendededitbar-quotesample')->plain() ), 'bs-editbutton-table' => array( 'tip' => wfMessage('bs-extendededitbar-tabletip')->plain(), 'open' => "{| class=\"wikitable\"\n|-\n", 'close' => "\n|}", 'sample' => $sTable ), ); $aButtonCfgs = $aMWButtonCfgs + $aBSButtonCfgs; $aRows = array( array('editing' => array(), 'dialogs' => array(), 'table' => array( 10 => 'bs-editbutton-table' )), //this is reserverd for BlueSpice dialogs array( 'formatting' => array( 10 => 'mw-editbutton-bold', 20 => 'mw-editbutton-italic', 30 => 'bs-editbutton-strike', 40 => 'mw-editbutton-headline', 50 => 'bs-editbutton-linebreak', ), 'content' => array( //10 => 'mw-editbutton-link', //20 => 'mw-editbutton-extlink', 30 => 'mw-editbutton-strike', //40 => 'mw-editbutton-image', //50 => 'mw-editbutton-media', 60 => 'bs-editbutton-gallery', ), 'misc' => array( 10 => 'mw-editbutton-signature', 20 => 'bs-editbutton-redirect', 30 => 'bs-editbutton-comment', ) ) ); wfRunHooks( 'BSExtendedEditBarBeforeEditToolbar', array( &$aRows, &$aButtonCfgs )); $aContent = array(); foreach( $aRows as $aRow ) { $sRow = Html::openElement( 'div', array( 'class' => 'row' ) ); foreach( $aRow as $sGroupId => $aButtons ) { $sGroup = Html::openElement( 'div', array( 'class' => 'group' ) ); ksort( $aButtons ); foreach ( $aButtons as $iButtonSort => $sButtonId ) { if( !isset( $aButtonCfgs[$sButtonId] ) ) continue; $aButtonCfg = $aButtonCfgs[$sButtonId]; if( !is_array( $aButtonCfg ) ) continue; $aDefaultAttributes = array( 'href' => '#', 'class' => 'bs-button-32 mw-toolbar-editbutton' ); $aAttributes = array( 'title' => $aButtonCfg['tip'], 'id' => $sButtonId ) + $aDefaultAttributes; if( isset( $aButtonCfg['open'] ) ) $aAttributes['data-open'] = $aButtonCfg['open']; if( isset( $aButtonCfg['close'] ) ) $aAttributes['data-close'] = $aButtonCfg['close']; if( isset( $aButtonCfg['sample'] ) ) $aAttributes['data-sample'] = $aButtonCfg['sample']; $sButton = Html::element( 'a', $aAttributes, $aButtonCfg['tip'] ); $sGroup .= $sButton; } $sGroup .= Html::closeElement('div'); $sRow.= $sGroup; } $sRow.= Html::closeElement('div'); $aContent[] = $sRow; } //We have to keep the old toolbar (the one with ugly icons) because //some extensions (i.e. MsUpload) rely on it to add elements to the DOM. //Unfortunately VisualEditor wil set it to visible when toggled. //Therefore we move it out of sight using CSS positioning. Some buttons //May be not visible though. //TODO: Take contents of div#toolbar as base $toolbar .= Html::rawElement( 'div', array( 'id' => 'bs-extendededitbar' ), implode( '', $aContent) ); return true; } }
scolladogsp/wiki
extensions/BlueSpiceExtensions/ExtendedEditBar/ExtendedEditBar.class.php
PHP
gpl-2.0
11,037
package org.wordpress.android.ui.notifications; import com.android.volley.VolleyError; import org.wordpress.android.models.Note; import java.util.List; public class NotificationEvents { public static class NotificationsChanged { final public boolean hasUnseenNotes; public NotificationsChanged() { this.hasUnseenNotes = false; } public NotificationsChanged(boolean hasUnseenNotes) { this.hasUnseenNotes = hasUnseenNotes; } } public static class NoteModerationFailed {} public static class NoteModerationStatusChanged { final boolean isModerating; final String noteId; public NoteModerationStatusChanged(String noteId, boolean isModerating) { this.noteId = noteId; this.isModerating = isModerating; } } public static class NoteLikeStatusChanged { final String noteId; public NoteLikeStatusChanged(String noteId) { this.noteId = noteId; } } public static class NoteVisibilityChanged { final boolean isHidden; final String noteId; public NoteVisibilityChanged(String noteId, boolean isHidden) { this.noteId = noteId; this.isHidden = isHidden; } } public static class NotificationsSettingsStatusChanged { final String mMessage; public NotificationsSettingsStatusChanged(String message) { mMessage = message; } public String getMessage() { return mMessage; } } public static class NotificationsUnseenStatus { final public boolean hasUnseenNotes; public NotificationsUnseenStatus(boolean hasUnseenNotes) { this.hasUnseenNotes = hasUnseenNotes; } } public static class NotificationsRefreshCompleted { final List<Note> notes; public NotificationsRefreshCompleted(List<Note> notes) { this.notes = notes; } } public static class NotificationsRefreshError { VolleyError error; public NotificationsRefreshError(VolleyError error) { this.error = error; } public NotificationsRefreshError() { } } }
mzorz/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationEvents.java
Java
gpl-2.0
2,258
<?php /** * @ignore */ function mysql_table_exists($database, $tableName) { global $tc_db; $tables = array(); $tablesResults = $tc_db->GetAll("SHOW TABLES FROM `$database`;"); foreach ($tablesResults AS $row) $tables[] = $row[0]; return(in_array($tableName, $tables)); } function pgsql_table_exists($database, $tableName) { global $tc_db; $tables = array(); $tablesResults = $tc_db->GetAll(" select table_name from information_schema.tables where table_schema='public' and table_type='BASE TABLE'"); foreach ($tablesResults AS $row) $tables[] = $row[0]; return(in_array($tableName, $tables)); } function sqlite_table_exists($database, $tableName) { global $tc_db; $tables = array(); $tablesResults = $tc_db->GetAll("SELECT name FROM sqlite_master WHERE type = 'table'" ); foreach ($tablesResults AS $row) $tables[] = $row[0]; return(in_array($tableName, $tables)); } function CreateSalt() { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $salt = ''; for ($i = 0; $i < 3; ++$i) { $salt .= $chars[mt_rand(0, strlen($chars) - 1)]; } return $salt; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Kusaba B Installation</title> <style type="text/css"> body { font-family: sans-serif; font-size: 75%; background: #ffe } a { text-decoration: none; color: #550 } h1,h2 { margin: 0px; background: #fca } h1 { font-size: 150% } h2 { font-size: 100%; margin-top: 1em } .hl { font-style: italic } .plus { float: right; font-size: 8px; font-weight: normal; padding: 1px 4px 2px 4px; margin: 0px 0px; background: #eb9; color: #000; border: 1px solid #da8; cursor: hand; cursor: pointer } .plus:hover { background: #da8; border: 1px solid #c97 } ul { list-style: none; padding-left: 0px; margin: 0px } li { margin: 0px } li:hover { background: #fec; } li a { display: block; width: 100%; } </style> <link rel="shortcut icon" href="/favicon.ico" /> </head> <body> <div style="text-align:center;"><h1>Kusaba B Installation</h1></div> <?php echo '<h2>Checking configuration file...</h2>'; if (file_exists('../config.php')) { require '../config.php'; require KU_ROOTDIR . 'inc/functions.php'; if (KU_RANDOMSEED!="ENTER RANDOM LETTERS/NUMBERS HERE"&&KU_RANDOMSEED!="") { echo 'Configuration appears correct.'; echo '<h2>Checking database...</h2>'; $reqiredtables = array("ads","announcements","banlist","bannedhashes","blotter","boards","board_filetypes","embeds","events","filetypes","front","loginattempts","modlog","module_settings","posts","reports","sections","staff","watchedthreads","wordfilter"); foreach ($reqiredtables as $tablename) { if (KU_DBTYPE == 'mysql' || KU_DBTYPE == 'mysqli') { if (!mysql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) { die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-mysql.php\"><strong><u>insert the mySQL dump</u></strong></a>."); } } if (KU_DBTYPE == 'postgres7' || KU_DBTYPE == 'postgres8' || KU_DBTYPE == 'postgres') { if (!pgsql_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) { die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-pgsql.php\"><strong><u>insert the PostgreSQL dump</u></strong></a>."); } } if (KU_DBTYPE == 'sqlite') { if (!sqlite_table_exists(KU_DBDATABASE,KU_DBPREFIX.$tablename)) { die("Couldn't find the table <strong>".KU_DBPREFIX.$tablename."</strong> in the database. Please <a href=\"install-sqlite.php\"><strong><u>insert the SQLite dump</u></strong></a>."); } } } echo 'Database appears correct.'; echo '<h2>Inserting default administrator account...</h2>'; $result_exists = $tc_db->GetOne("SELECT COUNT(*) FROM `".KU_DBPREFIX."staff` WHERE `username` = 'admin'"); if ($result_exists==0) { $salt = CreateSalt(); $result = $tc_db->Execute("INSERT INTO `".KU_DBPREFIX."staff` ( `username` , `salt`, `password` , `type` , `addedon` ) VALUES ( 'admin' , '".$salt."', '".md5("admin".$salt)."' , '1' , '".time()."' )"); echo 'Account inserted.'; $result = true; } else { echo 'There is already an administrator account inserted.'; $result = true; } if ($result) { require_once KU_ROOTDIR . 'inc/classes/menu.class.php'; $menu_class = new Menu(); $menu_class->Generate(); echo '<h2>Done!</h2>Installation has finished! The default administrator account is <strong>admin</strong> with the password of <strong>admin</strong>.<br /><br />Delete this and the install-mysql.php file from the server, then <a href="manage.php">add some boards</a>!'; echo '<br /><br /><br /><h1><font color="red">DELETE THIS AND install-mysql.php RIGHT NOW!</font></h1>'; } else { echo 'Error inserting SQL. Please add <strong>$tc_db->debug = true;</strong> just before ?&gt; in config.php to turn on debugging, and check the error message.'; } } else { echo 'Please enter a random string into the <strong>KU_RANDOMSEED</strong> value.'; } } else { echo 'Unable to locate config.php'; } ?> </body> </html>
314parley/Kusaba-B
INSTALL/install.php
PHP
gpl-2.0
5,390
<?php /** * @file * Teamwork15 sub theme template functions * */ /** * Implements hook_preprocess_maintenance_page(). */ function teamwork_15_subtheme_preprocess_maintenance_page(&$variables) { backdrop_add_css(backdrop_get_path('theme', 'bartik') . '/css/maintenance-page.css'); } /** * Implements hook_preprocess_layout(). */ function teamwork_15_subtheme_preprocess_layout(&$variables) { if ($variables['content']['header']) { $variables['content']['header'] = '<div class="l-header-inner">' . $variables['content']['header'] . '</div>'; } if (theme_get_setting('teamwork_15_subtheme_cdn') > 0) { backdrop_add_css('http://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css', array('type' => 'external', 'every_page' => TRUE, 'group' => CSS_DEFAULT)); } $var1 = theme_get_setting('teamwork_15_subtheme_juiced_main_background'); $var2 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background'); $var3 = theme_get_setting('teamwork_15_subtheme_juiced_main_background_blurred'); $var4 = theme_get_setting('teamwork_15_subtheme_juiced_big_statement_background_blurred'); if ($var1 && $var3 > 0) { backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if ($var1 && $var3 == 0) { backdrop_add_css("@media screen and (min-width: 769px) { .juiced-main { background: url($var1) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if ($var2 && $var4 > 0) { backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if ($var2 && $var4 == 0) { backdrop_add_css("@media screen and (min-width: 769px) { .l-big-statement { background: url($var2) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline')); } $var5 = theme_get_setting('teamwork_15_subtheme_body_main_background'); $var6 = theme_get_setting('teamwork_15_subtheme_footer_main_background'); $var7 = theme_get_setting('teamwork_15_subtheme_body_main_background_blurred'); $var8 = theme_get_setting('teamwork_15_subtheme_footer_main_background_blurred'); if ($var5 && $var7 > 0) { backdrop_add_css("@media screen and (min-width: 769px) { .layout::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if ($var5 && $var7 == 0) { backdrop_add_css("@media screen and (min-width: 769px) { .layout { background: url($var5) no-repeat; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if ($var6 && $var8 > 0) { backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer::before { content: ' '; width: 100%; height: 100%; display: block; position: absolute; z-index: -100; -webkit-filter: blur(20px); -moz-filter: blur(20px); -o-filter: blur(20px); -ms-filter: blur(20px); filter: blur(20px); opacity: 0.4; background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } footer.l-footer { background: transparent; } }", array('type' => 'inline')); } if ($var6 && $var8 == 0) { backdrop_add_css("@media screen and (min-width: 769px) { footer.l-footer { background: url($var6) no-repeat fixed; background-size: cover; background-position: center; } }", array('type' => 'inline')); } if (theme_get_setting('teamwork_15_subtheme_script1') > 0) { backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE)); } if (theme_get_setting('teamwork_15_subtheme_script2') > 0) { backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE)); } if (theme_get_setting('teamwork_15_subtheme_script3') > 0) { backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE)); } if (theme_get_setting('teamwork_15_subtheme_script4') > 0) { backdrop_add_js("https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js", array('type' => 'external', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE)); } backdrop_add_js("themes/teamwork_15_subtheme/js/scripts.js", array('type' => 'file', 'scope' => 'footer', 'every_page' => TRUE, 'preprocess' => TRUE)); backdrop_add_js("document.write('<script src=\"http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1\"></' + 'script>')", array('type' => 'inline', 'scope' => 'footer', 'weight' => 9999)); } /** * Implements theme_field__field_type(). */ function teamwork_15_subtheme_field__taxonomy_term_reference($variables) { $output = ''; // Render the label, if it's not hidden. if (!$variables['label_hidden']) { $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>'; } // Render the items. $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">'; foreach ($variables['items'] as $delta => $item) { $item_attributes = (isset($variables['item_attributes'][$delta])) ? backdrop_attributes($variables['item_attributes'][$delta]) : ''; $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $item_attributes . '>' . backdrop_render($item) . '</li>'; } $output .= '</ul>'; // Render the surrounding DIV with appropriate classes and attributes. if (!in_array('clearfix', $variables['classes'])) { $variables['classes'][] = 'clearfix'; } $output = '<div class="' . implode(' ', $variables['classes']) . '"' . backdrop_attributes($variables['attributes']) . '>' . $output . '</div>'; return $output; } /** * Implements theme_preprocess_image_style(). */ function teamwork_15_subtheme_preprocess_image_style(&$vars) { $vars['attributes']['class'][] = 'pure-img'; } function teamwork_15_subtheme_button(&$vars) { $classes = array('button-success', 'pure-button-primary', 'button-xlarge', 'pure-button'); if (!isset($vars['#attributes']['class'])) { $vars['#attributes'] = array('class' => $classes); } else { $vars['#attributes']['class'] = array_merge($vars['#attributes']['class'], $classes); } if (!isset($vars['element']['#attributes']['class'])) { $vars['element']['#attributes'] = array('class' => $classes); } else { $vars['element']['#attributes']['class'] = array_merge($vars['element']['#attributes']['class'], $classes); } return theme_button($vars); } function teamwork_15_subtheme_css_alter(&$css) { $css_to_remove = array(); if (theme_get_setting('teamwork_15_subtheme_cdn') > 0) { $css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css'; } if (theme_get_setting('teamwork_15_subtheme_sass') > 0) { $css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/style.css'; $css_to_remove[] = backdrop_get_path('theme','teamwork_15') . '/css/pure.min.css'; } foreach ($css_to_remove as $index => $css_file) { unset($css[$css_file]); } } /** * Implements hook_form_alter() */ function teamwork_15_subtheme_form_alter(&$form, &$form_state, $form_id) { $classes = array('pure-form', 'pure-form-aligned'); if (!isset($form['#attributes']['class'])) { $form['#attributes'] = array('class' => $classes); } else { $form['#attributes']['class'] = array_merge($form['#attributes']['class'], $classes); } } function teamwork_15_subtheme_menu_tree($variables) { return '<ul class="menu">' . $variables['tree'] . '</ul>'; } /** * Overrides theme_form_element_label(). */ function teamwork_15_subtheme_form_element_label(&$variables) { $element = $variables['element']; $title = filter_xss_admin($element['#title']); // If the element is required, a required marker is appended to the label. $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : ''; // // This is also used in the installer, pre-database setup. $t = get_t(); $attributes = array(); if (!empty($element['#id'])) { $attributes['for'] = $element['#id']; } $output = ''; if (isset($variables['#children'])) { if ($element['#type'] === "radio") { $output .= $variables['#children']; } if ($element['#type'] === "checkbox") { $output .= $variables['#children']; } } return ' <label' . backdrop_attributes($attributes) . '></label><div>' . $t('!title', array('!title' => $title)) . "</div> \n"; } /** * Implements theme_preprocess_menu_link(). */ function teamwork_15_subtheme_menu_link(array $variables) { $element = $variables['element']; $classes = array('pure-menu-item'); $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $classes); $sub_menu = ''; if ($element['#below']) { $sub_menu = backdrop_render($element['#below']); } $output = l($element['#title'], $element['#href'], $element['#localized_options']); return '<li' . backdrop_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n"; }
backdrop-contrib/teamwork_15
teamwork_15_subtheme/template.php
PHP
gpl-2.0
10,165
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2006, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * $Id: getinfo.c,v 1.1 2006/07/05 22:41:22 victor Exp $ ***************************************************************************/ #include "setup.h" #include <curl/curl.h> #include "urldata.h" #include "getinfo.h" #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include "memory.h" #include "sslgen.h" /* Make this the last #include */ #include "memdebug.h" /* * This is supposed to be called in the beginning of a perform() session * and should reset all session-info variables */ CURLcode Curl_initinfo(struct SessionHandle *data) { struct Progress *pro = &data->progress; struct PureInfo *info =&data->info; pro->t_nslookup = 0; pro->t_connect = 0; pro->t_pretransfer = 0; pro->t_starttransfer = 0; pro->timespent = 0; pro->t_redirect = 0; info->httpcode = 0; info->httpversion=0; info->filetime=-1; /* -1 is an illegal time and thus means unknown */ if (info->contenttype) free(info->contenttype); info->contenttype = NULL; info->header_size = 0; info->request_size = 0; info->numconnects = 0; return CURLE_OK; } CURLcode Curl_getinfo(struct SessionHandle *data, CURLINFO info, ...) { va_list arg; long *param_longp=NULL; double *param_doublep=NULL; char **param_charp=NULL; struct curl_slist **param_slistp=NULL; va_start(arg, info); switch(info&CURLINFO_TYPEMASK) { default: return CURLE_BAD_FUNCTION_ARGUMENT; case CURLINFO_STRING: param_charp = va_arg(arg, char **); if(NULL == param_charp) return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLINFO_LONG: param_longp = va_arg(arg, long *); if(NULL == param_longp) return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLINFO_DOUBLE: param_doublep = va_arg(arg, double *); if(NULL == param_doublep) return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLINFO_SLIST: param_slistp = va_arg(arg, struct curl_slist **); if(NULL == param_slistp) return CURLE_BAD_FUNCTION_ARGUMENT; break; } switch(info) { case CURLINFO_EFFECTIVE_URL: *param_charp = data->change.url?data->change.url:(char *)""; break; case CURLINFO_RESPONSE_CODE: *param_longp = data->info.httpcode; break; case CURLINFO_HTTP_CONNECTCODE: *param_longp = data->info.httpproxycode; break; case CURLINFO_FILETIME: *param_longp = data->info.filetime; break; case CURLINFO_HEADER_SIZE: *param_longp = data->info.header_size; break; case CURLINFO_REQUEST_SIZE: *param_longp = data->info.request_size; break; case CURLINFO_TOTAL_TIME: *param_doublep = data->progress.timespent; break; case CURLINFO_NAMELOOKUP_TIME: *param_doublep = data->progress.t_nslookup; break; case CURLINFO_CONNECT_TIME: *param_doublep = data->progress.t_connect; break; case CURLINFO_PRETRANSFER_TIME: *param_doublep = data->progress.t_pretransfer; break; case CURLINFO_STARTTRANSFER_TIME: *param_doublep = data->progress.t_starttransfer; break; case CURLINFO_SIZE_UPLOAD: *param_doublep = (double)data->progress.uploaded; break; case CURLINFO_SIZE_DOWNLOAD: *param_doublep = (double)data->progress.downloaded; break; case CURLINFO_SPEED_DOWNLOAD: *param_doublep = (double)data->progress.dlspeed; break; case CURLINFO_SPEED_UPLOAD: *param_doublep = (double)data->progress.ulspeed; break; case CURLINFO_SSL_VERIFYRESULT: *param_longp = data->set.ssl.certverifyresult; break; case CURLINFO_CONTENT_LENGTH_DOWNLOAD: *param_doublep = (double)data->progress.size_dl; break; case CURLINFO_CONTENT_LENGTH_UPLOAD: *param_doublep = (double)data->progress.size_ul; break; case CURLINFO_REDIRECT_TIME: *param_doublep = data->progress.t_redirect; break; case CURLINFO_REDIRECT_COUNT: *param_longp = data->set.followlocation; break; case CURLINFO_CONTENT_TYPE: *param_charp = data->info.contenttype; break; case CURLINFO_PRIVATE: *param_charp = data->set.private_data; break; case CURLINFO_HTTPAUTH_AVAIL: *param_longp = data->info.httpauthavail; break; case CURLINFO_PROXYAUTH_AVAIL: *param_longp = data->info.proxyauthavail; break; case CURLINFO_OS_ERRNO: *param_longp = data->state.os_errno; break; case CURLINFO_NUM_CONNECTS: *param_longp = data->info.numconnects; break; case CURLINFO_SSL_ENGINES: *param_slistp = Curl_ssl_engines_list(data); break; case CURLINFO_COOKIELIST: *param_slistp = Curl_cookie_list(data); break; case CURLINFO_LASTSOCKET: if((data->state.lastconnect != -1) && (data->state.connects[data->state.lastconnect] != NULL)) *param_longp = data->state.connects[data->state.lastconnect]-> sock[FIRSTSOCKET]; else *param_longp = -1; break; default: return CURLE_BAD_FUNCTION_ARGUMENT; } return CURLE_OK; }
pfchrono/mudmagic-client
bundled/curl/getinfo.c
C
gpl-2.0
5,871
/* * Copyright (c) 2017 Red Hat, Inc. and/or its affiliates. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /** * @test TestMemoryMXBeans * @key gc * @summary Test JMX memory beans * @modules java.base/jdk.internal.misc * java.management * @run main/othervm -XX:+UseShenandoahGC -Xmx1g TestMemoryMXBeans -1 1024 * @run main/othervm -XX:+UseShenandoahGC -Xms1g -Xmx1g TestMemoryMXBeans 1024 1024 * @run main/othervm -XX:+UseShenandoahGC -Xms128m -Xmx1g TestMemoryMXBeans 128 1024 */ import java.lang.management.*; import java.util.*; public class TestMemoryMXBeans { public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalStateException("Should provide expected heap sizes"); } long initSize = 1L * Integer.parseInt(args[0]) * 1024 * 1024; long maxSize = 1L * Integer.parseInt(args[1]) * 1024 * 1024; testMemoryBean(initSize, maxSize); } public static void testMemoryBean(long initSize, long maxSize) { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long heapInit = memoryMXBean.getHeapMemoryUsage().getInit(); long heapMax = memoryMXBean.getHeapMemoryUsage().getMax(); long nonHeapInit = memoryMXBean.getNonHeapMemoryUsage().getInit(); long nonHeapMax = memoryMXBean.getNonHeapMemoryUsage().getMax(); if (initSize > 0 && heapInit != initSize) { throw new IllegalStateException("Init heap size is wrong: " + heapInit + " vs " + initSize); } if (maxSize > 0 && heapMax != maxSize) { throw new IllegalStateException("Max heap size is wrong: " + heapMax + " vs " + maxSize); } } }
ojdkbuild/lookaside_java-1.8.0-openjdk
hotspot/test/gc/shenandoah/TestMemoryMXBeans.java
Java
gpl-2.0
2,609
typedef struct effect_uuid_s { uint32_t timeLow; uint16_t timeMid; uint16_t timeHiAndVersion; uint16_t clockSeq; uint8_t node[6]; } effect_uuid_t; // Maximum length of character strings in structures defines by this API. #define EFFECT_STRING_LEN_MAX 64 // NULL UUID definition (matches SL_IID_NULL_) #define EFFECT_UUID_INITIALIZER { 0xec7178ec, 0xe5e1, 0x4432, 0xa3f4, \ { 0x46, 0x57, 0xe6, 0x79, 0x52, 0x10 } } static const effect_uuid_t EFFECT_UUID_NULL_ = EFFECT_UUID_INITIALIZER; static const effect_uuid_t * const EFFECT_UUID_NULL = &EFFECT_UUID_NULL_; static const char * const EFFECT_UUID_NULL_STR = "ec7178ec-e5e1-4432-a3f4-4657e6795210"; // The effect descriptor contains necessary information to facilitate the enumeration of the effect // engines present in a library. typedef struct effect_descriptor_s { effect_uuid_t type; // UUID of to the OpenSL ES interface implemented by this effect effect_uuid_t uuid; // UUID for this particular implementation uint32_t apiVersion; // Version of the effect control API implemented uint32_t flags; // effect engine capabilities/requirements flags (see below) uint16_t cpuLoad; // CPU load indication (see below) uint16_t memoryUsage; // Data Memory usage (see below) char name[EFFECT_STRING_LEN_MAX]; // human readable effect name char implementor[EFFECT_STRING_LEN_MAX]; // human readable effect implementor name } effect_descriptor_t; // CPU load and memory usage indication: each effect implementation must provide an indication of // its CPU and memory usage for the audio effect framework to limit the number of effects // instantiated at a given time on a given platform. // The CPU load is expressed in 0.1 MIPS units as estimated on an ARM9E core (ARMv5TE) with 0 WS. // The memory usage is expressed in KB and includes only dynamically allocated memory // Definitions for flags field of effect descriptor. // +---------------------------+-----------+----------------------------------- // | description | bits | values // +---------------------------+-----------+----------------------------------- // | connection mode | 0..2 | 0 insert: after track process // | | | 1 auxiliary: connect to track auxiliary // | | | output and use send level // | | | 2 replace: replaces track process function; // | | | must implement SRC, volume and mono to stereo. // | | | 3 pre processing: applied below audio HAL on input // | | | 4 post processing: applied below audio HAL on output // | | | 5 - 7 reserved // +---------------------------+-----------+----------------------------------- // | insertion preference | 3..5 | 0 none // | | | 1 first of the chain // | | | 2 last of the chain // | | | 3 exclusive (only effect in the insert chain) // | | | 4..7 reserved // +---------------------------+-----------+----------------------------------- // | Volume management | 6..8 | 0 none // | | | 1 implements volume control // | | | 2 requires volume indication // | | | 4 reserved // +---------------------------+-----------+----------------------------------- // | Device indication | 9..11 | 0 none // | | | 1 requires device updates // | | | 2, 4 reserved // +---------------------------+-----------+----------------------------------- // | Sample input mode | 12..13 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG // | | | command must specify a buffer descriptor // | | | 2 provider: process() function uses the // | | | bufferProvider indicated by the // | | | EFFECT_CMD_SET_CONFIG command to request input. // | | | buffers. // | | | 3 both: both input modes are supported // +---------------------------+-----------+----------------------------------- // | Sample output mode | 14..15 | 1 direct: process() function or EFFECT_CMD_SET_CONFIG // | | | command must specify a buffer descriptor // | | | 2 provider: process() function uses the // | | | bufferProvider indicated by the // | | | EFFECT_CMD_SET_CONFIG command to request output // | | | buffers. // | | | 3 both: both output modes are supported // +---------------------------+-----------+----------------------------------- // | Hardware acceleration | 16..17 | 0 No hardware acceleration // | | | 1 non tunneled hw acceleration: the process() function // | | | reads the samples, send them to HW accelerated // | | | effect processor, reads back the processed samples // | | | and returns them to the output buffer. // | | | 2 tunneled hw acceleration: the process() function is // | | | transparent. The effect interface is only used to // | | | control the effect engine. This mode is relevant for // | | | global effects actually applied by the audio // | | | hardware on the output stream. // +---------------------------+-----------+----------------------------------- // | Audio Mode indication | 18..19 | 0 none // | | | 1 requires audio mode updates // | | | 2..3 reserved // +---------------------------+-----------+----------------------------------- // | Audio source indication | 20..21 | 0 none // | | | 1 requires audio source updates // | | | 2..3 reserved // +---------------------------+-----------+----------------------------------- // | Effect offload supported | 22 | 0 The effect cannot be offloaded to an audio DSP // | | | 1 The effect can be offloaded to an audio DSP // +---------------------------+-----------+----------------------------------- // Insert mode #define EFFECT_FLAG_TYPE_SHIFT 0 #define EFFECT_FLAG_TYPE_SIZE 3 #define EFFECT_FLAG_TYPE_MASK (((1 << EFFECT_FLAG_TYPE_SIZE) -1) \ << EFFECT_FLAG_TYPE_SHIFT) #define EFFECT_FLAG_TYPE_INSERT (0 << EFFECT_FLAG_TYPE_SHIFT) #define EFFECT_FLAG_TYPE_AUXILIARY (1 << EFFECT_FLAG_TYPE_SHIFT) #define EFFECT_FLAG_TYPE_REPLACE (2 << EFFECT_FLAG_TYPE_SHIFT) #define EFFECT_FLAG_TYPE_PRE_PROC (3 << EFFECT_FLAG_TYPE_SHIFT) #define EFFECT_FLAG_TYPE_POST_PROC (4 << EFFECT_FLAG_TYPE_SHIFT) // Insert preference #define EFFECT_FLAG_INSERT_SHIFT (EFFECT_FLAG_TYPE_SHIFT + EFFECT_FLAG_TYPE_SIZE) #define EFFECT_FLAG_INSERT_SIZE 3 #define EFFECT_FLAG_INSERT_MASK (((1 << EFFECT_FLAG_INSERT_SIZE) -1) \ << EFFECT_FLAG_INSERT_SHIFT) #define EFFECT_FLAG_INSERT_ANY (0 << EFFECT_FLAG_INSERT_SHIFT) #define EFFECT_FLAG_INSERT_FIRST (1 << EFFECT_FLAG_INSERT_SHIFT) #define EFFECT_FLAG_INSERT_LAST (2 << EFFECT_FLAG_INSERT_SHIFT) #define EFFECT_FLAG_INSERT_EXCLUSIVE (3 << EFFECT_FLAG_INSERT_SHIFT) // Volume control #define EFFECT_FLAG_VOLUME_SHIFT (EFFECT_FLAG_INSERT_SHIFT + EFFECT_FLAG_INSERT_SIZE) #define EFFECT_FLAG_VOLUME_SIZE 3 #define EFFECT_FLAG_VOLUME_MASK (((1 << EFFECT_FLAG_VOLUME_SIZE) -1) \ << EFFECT_FLAG_VOLUME_SHIFT) #define EFFECT_FLAG_VOLUME_CTRL (1 << EFFECT_FLAG_VOLUME_SHIFT) #define EFFECT_FLAG_VOLUME_IND (2 << EFFECT_FLAG_VOLUME_SHIFT) #define EFFECT_FLAG_VOLUME_NONE (0 << EFFECT_FLAG_VOLUME_SHIFT) // Device indication #define EFFECT_FLAG_DEVICE_SHIFT (EFFECT_FLAG_VOLUME_SHIFT + EFFECT_FLAG_VOLUME_SIZE) #define EFFECT_FLAG_DEVICE_SIZE 3 #define EFFECT_FLAG_DEVICE_MASK (((1 << EFFECT_FLAG_DEVICE_SIZE) -1) \ << EFFECT_FLAG_DEVICE_SHIFT) #define EFFECT_FLAG_DEVICE_IND (1 << EFFECT_FLAG_DEVICE_SHIFT) #define EFFECT_FLAG_DEVICE_NONE (0 << EFFECT_FLAG_DEVICE_SHIFT) // Sample input modes #define EFFECT_FLAG_INPUT_SHIFT (EFFECT_FLAG_DEVICE_SHIFT + EFFECT_FLAG_DEVICE_SIZE) #define EFFECT_FLAG_INPUT_SIZE 2 #define EFFECT_FLAG_INPUT_MASK (((1 << EFFECT_FLAG_INPUT_SIZE) -1) \ << EFFECT_FLAG_INPUT_SHIFT) #define EFFECT_FLAG_INPUT_DIRECT (1 << EFFECT_FLAG_INPUT_SHIFT) #define EFFECT_FLAG_INPUT_PROVIDER (2 << EFFECT_FLAG_INPUT_SHIFT) #define EFFECT_FLAG_INPUT_BOTH (3 << EFFECT_FLAG_INPUT_SHIFT) // Sample output modes #define EFFECT_FLAG_OUTPUT_SHIFT (EFFECT_FLAG_INPUT_SHIFT + EFFECT_FLAG_INPUT_SIZE) #define EFFECT_FLAG_OUTPUT_SIZE 2 #define EFFECT_FLAG_OUTPUT_MASK (((1 << EFFECT_FLAG_OUTPUT_SIZE) -1) \ << EFFECT_FLAG_OUTPUT_SHIFT) #define EFFECT_FLAG_OUTPUT_DIRECT (1 << EFFECT_FLAG_OUTPUT_SHIFT) #define EFFECT_FLAG_OUTPUT_PROVIDER (2 << EFFECT_FLAG_OUTPUT_SHIFT) #define EFFECT_FLAG_OUTPUT_BOTH (3 << EFFECT_FLAG_OUTPUT_SHIFT) // Hardware acceleration mode #define EFFECT_FLAG_HW_ACC_SHIFT (EFFECT_FLAG_OUTPUT_SHIFT + EFFECT_FLAG_OUTPUT_SIZE) #define EFFECT_FLAG_HW_ACC_SIZE 2 #define EFFECT_FLAG_HW_ACC_MASK (((1 << EFFECT_FLAG_HW_ACC_SIZE) -1) \ << EFFECT_FLAG_HW_ACC_SHIFT) #define EFFECT_FLAG_HW_ACC_SIMPLE (1 << EFFECT_FLAG_HW_ACC_SHIFT) #define EFFECT_FLAG_HW_ACC_TUNNEL (2 << EFFECT_FLAG_HW_ACC_SHIFT) // Audio mode indication #define EFFECT_FLAG_AUDIO_MODE_SHIFT (EFFECT_FLAG_HW_ACC_SHIFT + EFFECT_FLAG_HW_ACC_SIZE) #define EFFECT_FLAG_AUDIO_MODE_SIZE 2 #define EFFECT_FLAG_AUDIO_MODE_MASK (((1 << EFFECT_FLAG_AUDIO_MODE_SIZE) -1) \ << EFFECT_FLAG_AUDIO_MODE_SHIFT) #define EFFECT_FLAG_AUDIO_MODE_IND (1 << EFFECT_FLAG_AUDIO_MODE_SHIFT) #define EFFECT_FLAG_AUDIO_MODE_NONE (0 << EFFECT_FLAG_AUDIO_MODE_SHIFT) // Audio source indication #define EFFECT_FLAG_AUDIO_SOURCE_SHIFT (EFFECT_FLAG_AUDIO_MODE_SHIFT + EFFECT_FLAG_AUDIO_MODE_SIZE) #define EFFECT_FLAG_AUDIO_SOURCE_SIZE 2 #define EFFECT_FLAG_AUDIO_SOURCE_MASK (((1 << EFFECT_FLAG_AUDIO_SOURCE_SIZE) -1) \ << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) #define EFFECT_FLAG_AUDIO_SOURCE_IND (1 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) #define EFFECT_FLAG_AUDIO_SOURCE_NONE (0 << EFFECT_FLAG_AUDIO_SOURCE_SHIFT) // Effect offload indication #define EFFECT_FLAG_OFFLOAD_SHIFT (EFFECT_FLAG_AUDIO_SOURCE_SHIFT + \ EFFECT_FLAG_AUDIO_SOURCE_SIZE) #define EFFECT_FLAG_OFFLOAD_SIZE 1 #define EFFECT_FLAG_OFFLOAD_MASK (((1 << EFFECT_FLAG_OFFLOAD_SIZE) -1) \ << EFFECT_FLAG_OFFLOAD_SHIFT) #define EFFECT_FLAG_OFFLOAD_SUPPORTED (1 << EFFECT_FLAG_OFFLOAD_SHIFT) #define EFFECT_MAKE_API_VERSION(M, m) (((M)<<16) | ((m) & 0xFFFF)) #define EFFECT_API_VERSION_MAJOR(v) ((v)>>16) #define EFFECT_API_VERSION_MINOR(v) ((m) & 0xFFFF) ///////////////////////////////////////////////// // Effect control interface ///////////////////////////////////////////////// // Effect control interface version 2.0 #define EFFECT_CONTROL_API_VERSION EFFECT_MAKE_API_VERSION(2,0) // Effect control interface structure: effect_interface_s // The effect control interface is exposed by each effect engine implementation. It consists of // a set of functions controlling the configuration, activation and process of the engine. // The functions are grouped in a structure of type effect_interface_s. // // Effect control interface handle: effect_handle_t // The effect_handle_t serves two purposes regarding the implementation of the effect engine: // - 1 it is the address of a pointer to an effect_interface_s structure where the functions // of the effect control API for a particular effect are located. // - 2 it is the address of the context of a particular effect instance. // A typical implementation in the effect library would define a structure as follows: // struct effect_module_s { // const struct effect_interface_s *itfe; // effect_config_t config; // effect_context_t context; // } // The implementation of EffectCreate() function would then allocate a structure of this // type and return its address as effect_handle_t typedef struct effect_interface_s **effect_handle_t; // Forward definition of type audio_buffer_t typedef struct audio_buffer_s audio_buffer_t; // Effect control interface definition struct effect_interface_s { //////////////////////////////////////////////////////////////////////////////// // // Function: process // // Description: Effect process function. Takes input samples as specified // (count and location) in input buffer descriptor and output processed // samples as specified in output buffer descriptor. If the buffer descriptor // is not specified the function must use either the buffer or the // buffer provider function installed by the EFFECT_CMD_SET_CONFIG command. // The effect framework will call the process() function after the EFFECT_CMD_ENABLE // command is received and until the EFFECT_CMD_DISABLE is received. When the engine // receives the EFFECT_CMD_DISABLE command it should turn off the effect gracefully // and when done indicate that it is OK to stop calling the process() function by // returning the -ENODATA status. // // NOTE: the process() function implementation should be "real-time safe" that is // it should not perform blocking calls: malloc/free, sleep, read/write/open/close, // pthread_cond_wait/pthread_mutex_lock... // // Input: // self: handle to the effect interface this function // is called on. // inBuffer: buffer descriptor indicating where to read samples to process. // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command. // // outBuffer: buffer descriptor indicating where to write processed samples. // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG command. // // Output: // returned value: 0 successful operation // -ENODATA the engine has finished the disable phase and the framework // can stop calling process() // -EINVAL invalid interface handle or // invalid input/output buffer description //////////////////////////////////////////////////////////////////////////////// int32_t (*process)(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer); //////////////////////////////////////////////////////////////////////////////// // // Function: command // // Description: Send a command and receive a response to/from effect engine. // // Input: // self: handle to the effect interface this function // is called on. // cmdCode: command code: the command can be a standardized command defined in // effect_command_e (see below) or a proprietary command. // cmdSize: size of command in bytes // pCmdData: pointer to command data // pReplyData: pointer to reply data // // Input/Output: // replySize: maximum size of reply data as input // actual size of reply data as output // // Output: // returned value: 0 successful operation // -EINVAL invalid interface handle or // invalid command/reply size or format according to command code // The return code should be restricted to indicate problems related to the this // API specification. Status related to the execution of a particular command should be // indicated as part of the reply field. // // *pReplyData updated with command response // //////////////////////////////////////////////////////////////////////////////// int32_t (*command)(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData); //////////////////////////////////////////////////////////////////////////////// // // Function: get_descriptor // // Description: Returns the effect descriptor // // Input: // self: handle to the effect interface this function // is called on. // // Input/Output: // pDescriptor: address where to return the effect descriptor. // // Output: // returned value: 0 successful operation. // -EINVAL invalid interface handle or invalid pDescriptor // *pDescriptor: updated with the effect descriptor. // //////////////////////////////////////////////////////////////////////////////// int32_t (*get_descriptor)(effect_handle_t self, effect_descriptor_t *pDescriptor); //////////////////////////////////////////////////////////////////////////////// // // Function: process_reverse // // Description: Process reverse stream function. This function is used to pass // a reference stream to the effect engine. If the engine does not need a reference // stream, this function pointer can be set to NULL. // This function would typically implemented by an Echo Canceler. // // Input: // self: handle to the effect interface this function // is called on. // inBuffer: buffer descriptor indicating where to read samples to process. // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command. // // outBuffer: buffer descriptor indicating where to write processed samples. // If NULL, use the configuration passed by EFFECT_CMD_SET_CONFIG_REVERSE command. // If the buffer and buffer provider in the configuration received by // EFFECT_CMD_SET_CONFIG_REVERSE are also NULL, do not return modified reverse // stream data // // Output: // returned value: 0 successful operation // -ENODATA the engine has finished the disable phase and the framework // can stop calling process_reverse() // -EINVAL invalid interface handle or // invalid input/output buffer description //////////////////////////////////////////////////////////////////////////////// int32_t (*process_reverse)(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer); }; // //--- Standardized command codes for command() function // enum effect_command_e { EFFECT_CMD_INIT, // initialize effect engine EFFECT_CMD_SET_CONFIG, // configure effect engine (see effect_config_t) EFFECT_CMD_RESET, // reset effect engine EFFECT_CMD_ENABLE, // enable effect process EFFECT_CMD_DISABLE, // disable effect process EFFECT_CMD_SET_PARAM, // set parameter immediately (see effect_param_t) EFFECT_CMD_SET_PARAM_DEFERRED, // set parameter deferred EFFECT_CMD_SET_PARAM_COMMIT, // commit previous set parameter deferred EFFECT_CMD_GET_PARAM, // get parameter EFFECT_CMD_SET_DEVICE, // set audio device (see audio.h, audio_devices_t) EFFECT_CMD_SET_VOLUME, // set volume EFFECT_CMD_SET_AUDIO_MODE, // set the audio mode (normal, ring, ...) EFFECT_CMD_SET_CONFIG_REVERSE, // configure effect engine reverse stream(see effect_config_t) EFFECT_CMD_SET_INPUT_DEVICE, // set capture device (see audio.h, audio_devices_t) EFFECT_CMD_GET_CONFIG, // read effect engine configuration EFFECT_CMD_GET_CONFIG_REVERSE, // read configure effect engine reverse stream configuration EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS,// get all supported configurations for a feature. EFFECT_CMD_GET_FEATURE_CONFIG, // get current feature configuration EFFECT_CMD_SET_FEATURE_CONFIG, // set current feature configuration EFFECT_CMD_SET_AUDIO_SOURCE, // set the audio source (see audio.h, audio_source_t) EFFECT_CMD_OFFLOAD, // set if effect thread is an offload one, // send the ioHandle of the effect thread EFFECT_CMD_FIRST_PROPRIETARY = 0x10000 // first proprietary command code }; //================================================================================================== // command: EFFECT_CMD_INIT //-------------------------------------------------------------------------------------------------- // description: // Initialize effect engine: All configurations return to default //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_SET_CONFIG //-------------------------------------------------------------------------------------------------- // description: // Apply new audio parameters configurations for input and output buffers //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_config_t) // data: effect_config_t //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_RESET //-------------------------------------------------------------------------------------------------- // description: // Reset the effect engine. Keep configuration but resets state and buffer content //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_ENABLE //-------------------------------------------------------------------------------------------------- // description: // Enable the process. Called by the framework before the first call to process() //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_DISABLE //-------------------------------------------------------------------------------------------------- // description: // Disable the process. Called by the framework after the last call to process() //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_SET_PARAM //-------------------------------------------------------------------------------------------------- // description: // Set a parameter and apply it immediately //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_param_t) + size of param and value // data: effect_param_t + param + value. See effect_param_t definition below for value offset //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_SET_PARAM_DEFERRED //-------------------------------------------------------------------------------------------------- // description: // Set a parameter but apply it only when receiving EFFECT_CMD_SET_PARAM_COMMIT command //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_param_t) + size of param and value // data: effect_param_t + param + value. See effect_param_t definition below for value offset //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_SET_PARAM_COMMIT //-------------------------------------------------------------------------------------------------- // description: // Apply all previously received EFFECT_CMD_SET_PARAM_DEFERRED commands //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_GET_PARAM //-------------------------------------------------------------------------------------------------- // description: // Get a parameter value //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_param_t) + size of param // data: effect_param_t + param //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(effect_param_t) + size of param and value // data: effect_param_t + param + value. See effect_param_t definition below for value offset //================================================================================================== // command: EFFECT_CMD_SET_DEVICE //-------------------------------------------------------------------------------------------------- // description: // Set the rendering device the audio output path is connected to. See audio.h, audio_devices_t // for device values. // The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this // command when the device changes //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) // data: uint32_t //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_SET_VOLUME //-------------------------------------------------------------------------------------------------- // description: // Set and get volume. Used by audio framework to delegate volume control to effect engine. // The effect implementation must set EFFECT_FLAG_VOLUME_IND or EFFECT_FLAG_VOLUME_CTRL flag in // its descriptor to receive this command before every call to process() function // If EFFECT_FLAG_VOLUME_CTRL flag is set in the effect descriptor, the effect engine must return // the volume that should be applied before the effect is processed. The overall volume (the volume // actually applied by the effect engine multiplied by the returned value) should match the value // indicated in the command. //-------------------------------------------------------------------------------------------------- // command format: // size: n * sizeof(uint32_t) // data: volume for each channel defined in effect_config_t for output buffer expressed in // 8.24 fixed point format //-------------------------------------------------------------------------------------------------- // reply format: // size: n * sizeof(uint32_t) / 0 // data: - if EFFECT_FLAG_VOLUME_CTRL is set in effect descriptor: // volume for each channel defined in effect_config_t for output buffer expressed in // 8.24 fixed point format // - if EFFECT_FLAG_VOLUME_CTRL is not set in effect descriptor: // N/A // It is legal to receive a null pointer as pReplyData in which case the effect framework has // delegated volume control to another effect //================================================================================================== // command: EFFECT_CMD_SET_AUDIO_MODE //-------------------------------------------------------------------------------------------------- // description: // Set the audio mode. The effect implementation must set EFFECT_FLAG_AUDIO_MODE_IND flag in its // descriptor to receive this command when the audio mode changes. //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) // data: audio_mode_t //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_SET_CONFIG_REVERSE //-------------------------------------------------------------------------------------------------- // description: // Apply new audio parameters configurations for input and output buffers of reverse stream. // An example of reverse stream is the echo reference supplied to an Acoustic Echo Canceler. //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_config_t) // data: effect_config_t //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(int) // data: status //================================================================================================== // command: EFFECT_CMD_SET_INPUT_DEVICE //-------------------------------------------------------------------------------------------------- // description: // Set the capture device the audio input path is connected to. See audio.h, audio_devices_t // for device values. // The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this // command when the device changes //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) // data: uint32_t //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_GET_CONFIG //-------------------------------------------------------------------------------------------------- // description: // Read audio parameters configurations for input and output buffers //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(effect_config_t) // data: effect_config_t //================================================================================================== // command: EFFECT_CMD_GET_CONFIG_REVERSE //-------------------------------------------------------------------------------------------------- // description: // Read audio parameters configurations for input and output buffers of reverse stream //-------------------------------------------------------------------------------------------------- // command format: // size: 0 // data: N/A //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(effect_config_t) // data: effect_config_t //================================================================================================== // command: EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS //-------------------------------------------------------------------------------------------------- // description: // Queries for supported configurations for a particular feature (e.g. get the supported // combinations of main and auxiliary channels for a noise suppressor). // The command parameter is the feature identifier (See effect_feature_e for a list of defined // features) followed by the maximum number of configuration descriptor to return. // The reply is composed of: // - status (uint32_t): // - 0 if feature is supported // - -ENOSYS if the feature is not supported, // - -ENOMEM if the feature is supported but the total number of supported configurations // exceeds the maximum number indicated by the caller. // - total number of supported configurations (uint32_t) // - an array of configuration descriptors. // The actual number of descriptors returned must not exceed the maximum number indicated by // the caller. //-------------------------------------------------------------------------------------------------- // command format: // size: 2 x sizeof(uint32_t) // data: effect_feature_e + maximum number of configurations to return //-------------------------------------------------------------------------------------------------- // reply format: // size: 2 x sizeof(uint32_t) + n x sizeof (<config descriptor>) // data: status + total number of configurations supported + array of n config descriptors //================================================================================================== // command: EFFECT_CMD_GET_FEATURE_CONFIG //-------------------------------------------------------------------------------------------------- // description: // Retrieves current configuration for a given feature. // The reply status is: // - 0 if feature is supported // - -ENOSYS if the feature is not supported, //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) // data: effect_feature_e //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(uint32_t) + sizeof (<config descriptor>) // data: status + config descriptor //================================================================================================== // command: EFFECT_CMD_SET_FEATURE_CONFIG //-------------------------------------------------------------------------------------------------- // description: // Sets current configuration for a given feature. // The reply status is: // - 0 if feature is supported // - -ENOSYS if the feature is not supported, // - -EINVAL if the configuration is invalid //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) + sizeof (<config descriptor>) // data: effect_feature_e + config descriptor //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(uint32_t) // data: status //================================================================================================== // command: EFFECT_CMD_SET_AUDIO_SOURCE //-------------------------------------------------------------------------------------------------- // description: // Set the audio source the capture path is configured for (Camcorder, voice recognition...). // See audio.h, audio_source_t for values. //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(uint32_t) // data: uint32_t //-------------------------------------------------------------------------------------------------- // reply format: // size: 0 // data: N/A //================================================================================================== // command: EFFECT_CMD_OFFLOAD //-------------------------------------------------------------------------------------------------- // description: // 1.indicate if the playback thread the effect is attached to is offloaded or not // 2.update the io handle of the playback thread the effect is attached to //-------------------------------------------------------------------------------------------------- // command format: // size: sizeof(effect_offload_param_t) // data: effect_offload_param_t //-------------------------------------------------------------------------------------------------- // reply format: // size: sizeof(uint32_t) // data: uint32_t //-------------------------------------------------------------------------------------------------- // command: EFFECT_CMD_FIRST_PROPRIETARY //-------------------------------------------------------------------------------------------------- // description: // All proprietary effect commands must use command codes above this value. The size and format of // command and response fields is free in this case //================================================================================================== // Audio buffer descriptor used by process(), bufferProvider() functions and buffer_config_t // structure. Multi-channel audio is always interleaved. The channel order is from LSB to MSB with // regard to the channel mask definition in audio.h, audio_channel_mask_t e.g : // Stereo: left, right // 5 point 1: front left, front right, front center, low frequency, back left, back right // The buffer size is expressed in frame count, a frame being composed of samples for all // channels at a given time. Frame size for unspecified format (AUDIO_FORMAT_OTHER) is 8 bit by // definition typedef struct audio_buffer_s { size_t frameCount; // number of frames in buffer union { void* raw; // raw pointer to start of buffer float* f32; // pointer to float 32 bit data at start of buffer int32_t* s32; // pointer to signed 32 bit data at start of buffer int16_t* s16; // pointer to signed 16 bit data at start of buffer uint8_t* u8; // pointer to unsigned 8 bit data at start of buffer }; } audio_buffer_t; typedef int32_t (* buffer_function_t)(void *cookie, audio_buffer_t *buffer); typedef struct buffer_provider_s { buffer_function_t getBuffer; // retrieve next buffer buffer_function_t releaseBuffer; // release used buffer void *cookie; // for use by client of buffer provider functions } buffer_provider_t; // The buffer_config_s structure specifies the input or output audio format // to be used by the effect engine. It is part of the effect_config_t // structure that defines both input and output buffer configurations and is // passed by the EFFECT_CMD_SET_CONFIG or EFFECT_CMD_SET_CONFIG_REVERSE command. typedef struct buffer_config_s { audio_buffer_t buffer; // buffer for use by process() function if not passed explicitly uint32_t samplingRate; // sampling rate uint32_t channels; // channel mask (see audio_channel_mask_t in audio.h) buffer_provider_t bufferProvider; // buffer provider uint8_t format; // Audio format (see audio_format_t in audio.h) uint8_t accessMode; // read/write or accumulate in buffer (effect_buffer_access_e) uint16_t mask; // indicates which of the above fields is valid } buffer_config_t; // Values for "accessMode" field of buffer_config_t: // overwrite, read only, accumulate (read/modify/write) typedef enum { EFFECT_BUFFER_ACCESS_WRITE, EFFECT_BUFFER_ACCESS_READ, EFFECT_BUFFER_ACCESS_ACCUMULATE } effect_buffer_access_e; // effect_config_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_CONFIG // command to configure audio parameters and buffers for effect engine input and output. typedef struct effect_config_s { buffer_config_t inputCfg; buffer_config_t outputCfg; } effect_config_t; // effect_param_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_PARAM // command and pCmdData and pReplyData of EFFECT_CMD_GET_PARAM command. // psize and vsize represent the actual size of parameter and value. // // NOTE: the start of value field inside the data field is always on a 32 bit boundary: // // +-----------+ // | status | sizeof(int) // +-----------+ // | psize | sizeof(int) // +-----------+ // | vsize | sizeof(int) // +-----------+ // | | | | // ~ parameter ~ > psize | // | | | > ((psize - 1)/sizeof(int) + 1) * sizeof(int) // +-----------+ | // | padding | | // +-----------+ // | | | // ~ value ~ > vsize // | | | // +-----------+ typedef struct effect_param_s { int32_t status; // Transaction status (unused for command, used for reply) uint32_t psize; // Parameter size uint32_t vsize; // Value size char data[]; // Start of Parameter + Value data } effect_param_t; ///////////////////////////////////////////////// // Effect library interface ///////////////////////////////////////////////// // Effect library interface version 3.0 // Note that EffectsFactory.c only checks the major version component, so changes to the minor // number can only be used for fully backwards compatible changes #define EFFECT_LIBRARY_API_VERSION EFFECT_MAKE_API_VERSION(3,0) #define AUDIO_EFFECT_LIBRARY_TAG ((('A') << 24) | (('E') << 16) | (('L') << 8) | ('T')) // Every effect library must have a data structure named AUDIO_EFFECT_LIBRARY_INFO_SYM // and the fields of this data structure must begin with audio_effect_library_t typedef struct audio_effect_library_s { // tag must be initialized to AUDIO_EFFECT_LIBRARY_TAG uint32_t tag; // Version of the effect library API : 0xMMMMmmmm MMMM: Major, mmmm: minor uint32_t version; // Name of this library const char *name; // Author/owner/implementor of the library const char *implementor; //////////////////////////////////////////////////////////////////////////////// // // Function: create_effect // // Description: Creates an effect engine of the specified implementation uuid and // returns an effect control interface on this engine. The function will allocate the // resources for an instance of the requested effect engine and return // a handle on the effect control interface. // // Input: // uuid: pointer to the effect uuid. // sessionId: audio session to which this effect instance will be attached. All effects // created with the same session ID are connected in series and process the same signal // stream. Knowing that two effects are part of the same effect chain can help the // library implement some kind of optimizations. // ioId: identifies the output or input stream this effect is directed to at audio HAL. // For future use especially with tunneled HW accelerated effects // // Input/Output: // pHandle: address where to return the effect interface handle. // // Output: // returned value: 0 successful operation. // -ENODEV library failed to initialize // -EINVAL invalid pEffectUuid or pHandle // -ENOENT no effect with this uuid found // *pHandle: updated with the effect interface handle. // //////////////////////////////////////////////////////////////////////////////// int32_t (*create_effect)(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle); //////////////////////////////////////////////////////////////////////////////// // // Function: release_effect // // Description: Releases the effect engine whose handle is given as argument. // All resources allocated to this particular instance of the effect are // released. // // Input: // handle: handle on the effect interface to be released. // // Output: // returned value: 0 successful operation. // -ENODEV library failed to initialize // -EINVAL invalid interface handle // //////////////////////////////////////////////////////////////////////////////// int32_t (*release_effect)(effect_handle_t handle); //////////////////////////////////////////////////////////////////////////////// // // Function: get_descriptor // // Description: Returns the descriptor of the effect engine which implementation UUID is // given as argument. // // Input/Output: // uuid: pointer to the effect uuid. // pDescriptor: address where to return the effect descriptor. // // Output: // returned value: 0 successful operation. // -ENODEV library failed to initialize // -EINVAL invalid pDescriptor or uuid // *pDescriptor: updated with the effect descriptor. // //////////////////////////////////////////////////////////////////////////////// int32_t (*get_descriptor)(const effect_uuid_t *uuid, effect_descriptor_t *pDescriptor); } audio_effect_library_t; // Name of the hal_module_info #define AUDIO_EFFECT_LIBRARY_INFO_SYM AELI // Name of the hal_module_info as a string #define AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR "AELI" // Values for bit field "mask" in buffer_config_t. If a bit is set, the corresponding field // in buffer_config_t must be taken into account when executing the EFFECT_CMD_SET_CONFIG command #define EFFECT_CONFIG_BUFFER 0x0001 // buffer field must be taken into account #define EFFECT_CONFIG_SMP_RATE 0x0002 // samplingRate field must be taken into account #define EFFECT_CONFIG_CHANNELS 0x0004 // channels field must be taken into account #define EFFECT_CONFIG_FORMAT 0x0008 // format field must be taken into account #define EFFECT_CONFIG_ACC_MODE 0x0010 // accessMode field must be taken into account #define EFFECT_CONFIG_PROVIDER 0x0020 // bufferProvider field must be taken into account #define EFFECT_CONFIG_ALL (EFFECT_CONFIG_BUFFER | EFFECT_CONFIG_SMP_RATE | \ EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT | \ EFFECT_CONFIG_ACC_MODE | EFFECT_CONFIG_PROVIDER) enum { AUDIO_IO_HANDLE_NONE = 0, AUDIO_MODULE_HANDLE_NONE = 0, AUDIO_PORT_HANDLE_NONE = 0, AUDIO_PATCH_HANDLE_NONE = 0, }; typedef enum { AUDIO_STREAM_DEFAULT = -1, // (-1) AUDIO_STREAM_MIN = 0, AUDIO_STREAM_VOICE_CALL = 0, AUDIO_STREAM_SYSTEM = 1, AUDIO_STREAM_RING = 2, AUDIO_STREAM_MUSIC = 3, AUDIO_STREAM_ALARM = 4, AUDIO_STREAM_NOTIFICATION = 5, AUDIO_STREAM_BLUETOOTH_SCO = 6, AUDIO_STREAM_ENFORCED_AUDIBLE = 7, AUDIO_STREAM_DTMF = 8, AUDIO_STREAM_TTS = 9, AUDIO_STREAM_ACCESSIBILITY = 10, #ifndef AUDIO_NO_SYSTEM_DECLARATIONS /** For dynamic policy output mixes. Only used by the audio policy */ AUDIO_STREAM_REROUTING = 11, /** For audio flinger tracks volume. Only used by the audioflinger */ AUDIO_STREAM_PATCH = 12, #endif // AUDIO_NO_SYSTEM_DECLARATIONS } audio_stream_type_t; typedef enum { AUDIO_SOURCE_DEFAULT = 0, AUDIO_SOURCE_MIC = 1, AUDIO_SOURCE_VOICE_UPLINK = 2, AUDIO_SOURCE_VOICE_DOWNLINK = 3, AUDIO_SOURCE_VOICE_CALL = 4, AUDIO_SOURCE_CAMCORDER = 5, AUDIO_SOURCE_VOICE_RECOGNITION = 6, AUDIO_SOURCE_VOICE_COMMUNICATION = 7, AUDIO_SOURCE_REMOTE_SUBMIX = 8, AUDIO_SOURCE_UNPROCESSED = 9, AUDIO_SOURCE_FM_TUNER = 1998, #ifndef AUDIO_NO_SYSTEM_DECLARATIONS /** * A low-priority, preemptible audio source for for background software * hotword detection. Same tuning as VOICE_RECOGNITION. * Used only internally by the framework. */ AUDIO_SOURCE_HOTWORD = 1999, #endif // AUDIO_NO_SYSTEM_DECLARATIONS } audio_source_t; typedef enum { AUDIO_SESSION_OUTPUT_STAGE = -1, // (-1) AUDIO_SESSION_OUTPUT_MIX = 0, AUDIO_SESSION_ALLOCATE = 0, AUDIO_SESSION_NONE = 0, } audio_session_t; typedef enum { AUDIO_FORMAT_INVALID = 0xFFFFFFFFu, AUDIO_FORMAT_DEFAULT = 0, AUDIO_FORMAT_PCM = 0x00000000u, AUDIO_FORMAT_MP3 = 0x01000000u, AUDIO_FORMAT_AMR_NB = 0x02000000u, AUDIO_FORMAT_AMR_WB = 0x03000000u, AUDIO_FORMAT_AAC = 0x04000000u, AUDIO_FORMAT_HE_AAC_V1 = 0x05000000u, AUDIO_FORMAT_HE_AAC_V2 = 0x06000000u, AUDIO_FORMAT_VORBIS = 0x07000000u, AUDIO_FORMAT_OPUS = 0x08000000u, AUDIO_FORMAT_AC3 = 0x09000000u, AUDIO_FORMAT_E_AC3 = 0x0A000000u, AUDIO_FORMAT_DTS = 0x0B000000u, AUDIO_FORMAT_DTS_HD = 0x0C000000u, AUDIO_FORMAT_IEC61937 = 0x0D000000u, AUDIO_FORMAT_DOLBY_TRUEHD = 0x0E000000u, AUDIO_FORMAT_EVRC = 0x10000000u, AUDIO_FORMAT_EVRCB = 0x11000000u, AUDIO_FORMAT_EVRCWB = 0x12000000u, AUDIO_FORMAT_EVRCNW = 0x13000000u, AUDIO_FORMAT_AAC_ADIF = 0x14000000u, AUDIO_FORMAT_WMA = 0x15000000u, AUDIO_FORMAT_WMA_PRO = 0x16000000u, AUDIO_FORMAT_AMR_WB_PLUS = 0x17000000u, AUDIO_FORMAT_MP2 = 0x18000000u, AUDIO_FORMAT_QCELP = 0x19000000u, AUDIO_FORMAT_DSD = 0x1A000000u, AUDIO_FORMAT_FLAC = 0x1B000000u, AUDIO_FORMAT_ALAC = 0x1C000000u, AUDIO_FORMAT_APE = 0x1D000000u, AUDIO_FORMAT_AAC_ADTS = 0x1E000000u, AUDIO_FORMAT_SBC = 0x1F000000u, AUDIO_FORMAT_APTX = 0x20000000u, AUDIO_FORMAT_APTX_HD = 0x21000000u, AUDIO_FORMAT_AC4 = 0x22000000u, AUDIO_FORMAT_LDAC = 0x23000000u, AUDIO_FORMAT_MAT = 0x24000000u, AUDIO_FORMAT_MAIN_MASK = 0xFF000000u, AUDIO_FORMAT_SUB_MASK = 0x00FFFFFFu, /* Subformats */ AUDIO_FORMAT_PCM_SUB_16_BIT = 0x1u, AUDIO_FORMAT_PCM_SUB_8_BIT = 0x2u, AUDIO_FORMAT_PCM_SUB_32_BIT = 0x3u, AUDIO_FORMAT_PCM_SUB_8_24_BIT = 0x4u, AUDIO_FORMAT_PCM_SUB_FLOAT = 0x5u, AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED = 0x6u, AUDIO_FORMAT_MP3_SUB_NONE = 0x0u, AUDIO_FORMAT_AMR_SUB_NONE = 0x0u, AUDIO_FORMAT_AAC_SUB_MAIN = 0x1u, AUDIO_FORMAT_AAC_SUB_LC = 0x2u, AUDIO_FORMAT_AAC_SUB_SSR = 0x4u, AUDIO_FORMAT_AAC_SUB_LTP = 0x8u, AUDIO_FORMAT_AAC_SUB_HE_V1 = 0x10u, AUDIO_FORMAT_AAC_SUB_SCALABLE = 0x20u, AUDIO_FORMAT_AAC_SUB_ERLC = 0x40u, AUDIO_FORMAT_AAC_SUB_LD = 0x80u, AUDIO_FORMAT_AAC_SUB_HE_V2 = 0x100u, AUDIO_FORMAT_AAC_SUB_ELD = 0x200u, AUDIO_FORMAT_AAC_SUB_XHE = 0x300u, AUDIO_FORMAT_VORBIS_SUB_NONE = 0x0u, AUDIO_FORMAT_E_AC3_SUB_JOC = 0x1u, AUDIO_FORMAT_MAT_SUB_1_0 = 0x1u, AUDIO_FORMAT_MAT_SUB_2_0 = 0x2u, AUDIO_FORMAT_MAT_SUB_2_1 = 0x3u, /* Aliases */ AUDIO_FORMAT_PCM_16_BIT = 0x1u, // (PCM | PCM_SUB_16_BIT) AUDIO_FORMAT_PCM_8_BIT = 0x2u, // (PCM | PCM_SUB_8_BIT) AUDIO_FORMAT_PCM_32_BIT = 0x3u, // (PCM | PCM_SUB_32_BIT) AUDIO_FORMAT_PCM_8_24_BIT = 0x4u, // (PCM | PCM_SUB_8_24_BIT) AUDIO_FORMAT_PCM_FLOAT = 0x5u, // (PCM | PCM_SUB_FLOAT) AUDIO_FORMAT_PCM_24_BIT_PACKED = 0x6u, // (PCM | PCM_SUB_24_BIT_PACKED) AUDIO_FORMAT_AAC_MAIN = 0x4000001u, // (AAC | AAC_SUB_MAIN) AUDIO_FORMAT_AAC_LC = 0x4000002u, // (AAC | AAC_SUB_LC) AUDIO_FORMAT_AAC_SSR = 0x4000004u, // (AAC | AAC_SUB_SSR) AUDIO_FORMAT_AAC_LTP = 0x4000008u, // (AAC | AAC_SUB_LTP) AUDIO_FORMAT_AAC_HE_V1 = 0x4000010u, // (AAC | AAC_SUB_HE_V1) AUDIO_FORMAT_AAC_SCALABLE = 0x4000020u, // (AAC | AAC_SUB_SCALABLE) AUDIO_FORMAT_AAC_ERLC = 0x4000040u, // (AAC | AAC_SUB_ERLC) AUDIO_FORMAT_AAC_LD = 0x4000080u, // (AAC | AAC_SUB_LD) AUDIO_FORMAT_AAC_HE_V2 = 0x4000100u, // (AAC | AAC_SUB_HE_V2) AUDIO_FORMAT_AAC_ELD = 0x4000200u, // (AAC | AAC_SUB_ELD) AUDIO_FORMAT_AAC_XHE = 0x4000300u, // (AAC | AAC_SUB_XHE) AUDIO_FORMAT_AAC_ADTS_MAIN = 0x1e000001u, // (AAC_ADTS | AAC_SUB_MAIN) AUDIO_FORMAT_AAC_ADTS_LC = 0x1e000002u, // (AAC_ADTS | AAC_SUB_LC) AUDIO_FORMAT_AAC_ADTS_SSR = 0x1e000004u, // (AAC_ADTS | AAC_SUB_SSR) AUDIO_FORMAT_AAC_ADTS_LTP = 0x1e000008u, // (AAC_ADTS | AAC_SUB_LTP) AUDIO_FORMAT_AAC_ADTS_HE_V1 = 0x1e000010u, // (AAC_ADTS | AAC_SUB_HE_V1) AUDIO_FORMAT_AAC_ADTS_SCALABLE = 0x1e000020u, // (AAC_ADTS | AAC_SUB_SCALABLE) AUDIO_FORMAT_AAC_ADTS_ERLC = 0x1e000040u, // (AAC_ADTS | AAC_SUB_ERLC) AUDIO_FORMAT_AAC_ADTS_LD = 0x1e000080u, // (AAC_ADTS | AAC_SUB_LD) AUDIO_FORMAT_AAC_ADTS_HE_V2 = 0x1e000100u, // (AAC_ADTS | AAC_SUB_HE_V2) AUDIO_FORMAT_AAC_ADTS_ELD = 0x1e000200u, // (AAC_ADTS | AAC_SUB_ELD) AUDIO_FORMAT_AAC_ADTS_XHE = 0x1e000300u, // (AAC_ADTS | AAC_SUB_XHE) AUDIO_FORMAT_E_AC3_JOC = 0xA000001u, // (E_AC3 | E_AC3_SUB_JOC) AUDIO_FORMAT_MAT_1_0 = 0x24000001u, // (MAT | MAT_SUB_1_0) AUDIO_FORMAT_MAT_2_0 = 0x24000002u, // (MAT | MAT_SUB_2_0) AUDIO_FORMAT_MAT_2_1 = 0x24000003u, // (MAT | MAT_SUB_2_1) } audio_format_t; enum { FCC_2 = 2, FCC_8 = 8, }; enum { AUDIO_CHANNEL_REPRESENTATION_POSITION = 0x0u, AUDIO_CHANNEL_REPRESENTATION_INDEX = 0x2u, AUDIO_CHANNEL_NONE = 0x0u, AUDIO_CHANNEL_INVALID = 0xC0000000u, AUDIO_CHANNEL_OUT_FRONT_LEFT = 0x1u, AUDIO_CHANNEL_OUT_FRONT_RIGHT = 0x2u, AUDIO_CHANNEL_OUT_FRONT_CENTER = 0x4u, AUDIO_CHANNEL_OUT_LOW_FREQUENCY = 0x8u, AUDIO_CHANNEL_OUT_BACK_LEFT = 0x10u, AUDIO_CHANNEL_OUT_BACK_RIGHT = 0x20u, AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40u, AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80u, AUDIO_CHANNEL_OUT_BACK_CENTER = 0x100u, AUDIO_CHANNEL_OUT_SIDE_LEFT = 0x200u, AUDIO_CHANNEL_OUT_SIDE_RIGHT = 0x400u, AUDIO_CHANNEL_OUT_TOP_CENTER = 0x800u, AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT = 0x1000u, AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER = 0x2000u, AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT = 0x4000u, AUDIO_CHANNEL_OUT_TOP_BACK_LEFT = 0x8000u, AUDIO_CHANNEL_OUT_TOP_BACK_CENTER = 0x10000u, AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT = 0x20000u, AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT = 0x40000u, AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT = 0x80000u, AUDIO_CHANNEL_OUT_MONO = 0x1u, // OUT_FRONT_LEFT AUDIO_CHANNEL_OUT_STEREO = 0x3u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT AUDIO_CHANNEL_OUT_2POINT1 = 0xBu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_2POINT0POINT2 = 0xC0003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_2POINT1POINT2 = 0xC000Bu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_3POINT0POINT2 = 0xC0007u, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_3POINT1POINT2 = 0xC000Fu, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_QUAD = 0x33u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_BACK_LEFT | OUT_BACK_RIGHT AUDIO_CHANNEL_OUT_QUAD_BACK = 0x33u, // OUT_QUAD AUDIO_CHANNEL_OUT_QUAD_SIDE = 0x603u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_SURROUND = 0x107u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_BACK_CENTER AUDIO_CHANNEL_OUT_PENTA = 0x37u, // OUT_QUAD | OUT_FRONT_CENTER AUDIO_CHANNEL_OUT_5POINT1 = 0x3Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT AUDIO_CHANNEL_OUT_5POINT1_BACK = 0x3Fu, // OUT_5POINT1 AUDIO_CHANNEL_OUT_5POINT1_SIDE = 0x60Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT2 = 0xC003Fu, // OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT4 = 0x2D03Fu, // OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT AUDIO_CHANNEL_OUT_6POINT1 = 0x13Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_BACK_CENTER AUDIO_CHANNEL_OUT_7POINT1 = 0x63Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT2 = 0xC063Fu, // OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT4 = 0x2D63Fu, // OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT AUDIO_CHANNEL_IN_LEFT = 0x4u, AUDIO_CHANNEL_IN_RIGHT = 0x8u, AUDIO_CHANNEL_IN_FRONT = 0x10u, AUDIO_CHANNEL_IN_BACK = 0x20u, AUDIO_CHANNEL_IN_LEFT_PROCESSED = 0x40u, AUDIO_CHANNEL_IN_RIGHT_PROCESSED = 0x80u, AUDIO_CHANNEL_IN_FRONT_PROCESSED = 0x100u, AUDIO_CHANNEL_IN_BACK_PROCESSED = 0x200u, AUDIO_CHANNEL_IN_PRESSURE = 0x400u, AUDIO_CHANNEL_IN_X_AXIS = 0x800u, AUDIO_CHANNEL_IN_Y_AXIS = 0x1000u, AUDIO_CHANNEL_IN_Z_AXIS = 0x2000u, AUDIO_CHANNEL_IN_BACK_LEFT = 0x10000u, AUDIO_CHANNEL_IN_BACK_RIGHT = 0x20000u, AUDIO_CHANNEL_IN_CENTER = 0x40000u, AUDIO_CHANNEL_IN_LOW_FREQUENCY = 0x100000u, AUDIO_CHANNEL_IN_TOP_LEFT = 0x200000u, AUDIO_CHANNEL_IN_TOP_RIGHT = 0x400000u, AUDIO_CHANNEL_IN_VOICE_UPLINK = 0x4000u, AUDIO_CHANNEL_IN_VOICE_DNLINK = 0x8000u, AUDIO_CHANNEL_IN_MONO = 0x10u, // IN_FRONT AUDIO_CHANNEL_IN_STEREO = 0xCu, // IN_LEFT | IN_RIGHT AUDIO_CHANNEL_IN_FRONT_BACK = 0x30u, // IN_FRONT | IN_BACK AUDIO_CHANNEL_IN_6 = 0xFCu, // IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED AUDIO_CHANNEL_IN_2POINT0POINT2 = 0x60000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT AUDIO_CHANNEL_IN_2POINT1POINT2 = 0x70000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_3POINT0POINT2 = 0x64000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT AUDIO_CHANNEL_IN_3POINT1POINT2 = 0x74000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_5POINT1 = 0x17000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | IN_BACK_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO = 0x4010u, // IN_VOICE_UPLINK | IN_MONO AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO = 0x8010u, // IN_VOICE_DNLINK | IN_MONO AUDIO_CHANNEL_IN_VOICE_CALL_MONO = 0xC010u, // IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO AUDIO_CHANNEL_COUNT_MAX = 30u, AUDIO_CHANNEL_INDEX_HDR = 0x80000000u, // REPRESENTATION_INDEX << COUNT_MAX AUDIO_CHANNEL_INDEX_MASK_1 = 0x80000001u, // INDEX_HDR | (1 << 1) - 1 AUDIO_CHANNEL_INDEX_MASK_2 = 0x80000003u, // INDEX_HDR | (1 << 2) - 1 AUDIO_CHANNEL_INDEX_MASK_3 = 0x80000007u, // INDEX_HDR | (1 << 3) - 1 AUDIO_CHANNEL_INDEX_MASK_4 = 0x8000000Fu, // INDEX_HDR | (1 << 4) - 1 AUDIO_CHANNEL_INDEX_MASK_5 = 0x8000001Fu, // INDEX_HDR | (1 << 5) - 1 AUDIO_CHANNEL_INDEX_MASK_6 = 0x8000003Fu, // INDEX_HDR | (1 << 6) - 1 AUDIO_CHANNEL_INDEX_MASK_7 = 0x8000007Fu, // INDEX_HDR | (1 << 7) - 1 AUDIO_CHANNEL_INDEX_MASK_8 = 0x800000FFu, // INDEX_HDR | (1 << 8) - 1 };
james34602/JamesDSPManager
Tutorials/src/essential.h
C
gpl-2.0
65,033
jQuery(function($) { /////////////////////////////////////////////////////////////////// ///// META BOXES JS /////////////////////////////////////////////////////////////////// jQuery('.repeatable-add').live('click', function() { var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true); var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last'); field.find('input.regular-text, textarea, select').val(''); field.find('input, textarea, select').attr('name', function(index, name) { return name.replace(/(\d+)/, function(fullMatch, n) { return Number(n) + 1; }); }); field.insertAfter(fieldLocation, jQuery(this).closest('td')); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount > 1 ) { jQuery('.repeatable-remove').css('display','inline'); } return false; }); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount == 1 ) { jQuery('.repeatable-remove').css('display','none'); } jQuery('.repeatable-remove').live('click', function() { jQuery(this).parent().remove(); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount == 1 ) { jQuery('.repeatable-remove').css('display','none'); } return false; }); jQuery('.custom_repeatable').sortable({ opacity: 0.6, revert: true, cursor: 'move', handle: '.sort' }); // the upload image button, saves the id and outputs a preview of the image var imageFrame; $('.rg-bb_upload_image_button').live('click', function(event) { event.preventDefault(); var options, attachment; $self = $(event.target); $div = $self.closest('div.rg-bb_image'); // if the frame already exists, open it if ( imageFrame ) { imageFrame.open(); return; } // set our settings imageFrame = wp.media({ title: 'Choose Image', multiple: true, library: { type: 'image' }, button: { text: 'Use This Image' } }); // set up our select handler imageFrame.on( 'select', function() { selection = imageFrame.state().get('selection'); if ( ! selection ) return; // loop through the selected files selection.each( function( attachment ) { console.log(attachment); var src = attachment.attributes.sizes.full.url; var id = attachment.id; $div.find('.rg-bb_preview_image').attr('src', src); $div.find('.rg-bb_upload_image').val(id); } ); }); // open the frame imageFrame.open(); }); // the remove image link, removes the image id from the hidden field and replaces the image preview $('.rg-bb_clear_image_button').live('click', function() { var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text(); $(this).parent().siblings('.rg-bb_upload_image').val(''); $(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage); return false; }); // function to create an array of input values function ids(inputs) { var a = []; for (var i = 0; i < inputs.length; i++) { a.push(inputs[i].val); } //$("span").text(a.join(" ")); } // repeatable fields $('.toggle').on("click", function() { console.log($(this).parent().siblings().toggleClass('closed')); }); $('.meta_box_repeatable_add').live('click', function(e) { e.preventDefault(); // clone var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child'); var clone = row.clone(); var defaultImage = clone.find('.meta_box_default_image').text(); clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove(); // clone.find('input.regular-text, textarea, select').val(''); clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded'); clone.find('input[type=checkbox], input[type=radio]').attr('checked', false); row.after(clone); // increment name and id clone.find('input, textarea, select').attr('name', function(index, name) { return name.replace(/(\d+)/, function(fullMatch, n) { return Number(n) + 1; }); }); var arr = []; $('input.repeatable_id:text').each(function(){ arr.push($(this).val()); }); clone.find('input.repeatable_id') .val(Number(Math.max.apply( Math, arr )) + 1); if (!!$.prototype.chosen) { clone.find('select.chosen') .chosen({allow_single_deselect: true}); } }); $('.meta_box_repeatable_remove').live('click', function(e){ e.preventDefault(); $(this).closest('tr').remove(); }); $('.meta_box_repeatable tbody').sortable({ opacity: 0.6, revert: true, cursor: 'move', handle: '.hndle' }); // post_drop_sort $('.sort_list').sortable({ connectWith: '.sort_list', opacity: 0.6, revert: true, cursor: 'move', cancel: '.post_drop_sort_area_name', items: 'li:not(.post_drop_sort_area_name)', update: function(event, ui) { var result = $(this).sortable('toArray'); var thisID = $(this).attr('id'); $('.store-' + thisID).val(result) } }); $('.sort_list').disableSelection(); // turn select boxes into something magical if (!!$.prototype.chosen) $('.chosen').chosen({ allow_single_deselect: true }); });
StefanDindyal/wordpresser
wp-content/themes/bobbarnyc/inc/settings-panel/js/custom-admin.js
JavaScript
gpl-2.0
5,266
/* nip2-cli.c ... run the nip2 executable, connecting stdin and stdout to the * console * * 11/12/09 * - use SetHandleInformation() to stop the child inheriting the read * handle (thanks Leo) */ /* Copyright (C) 2008 Imperial College, London This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ /* Adapted from sample code by Leo Davidson, with the author's permission. */ /* Windows does not let a single exe run in both command-line and GUI mode. To * run nip2 in command-line mode, we run this CLI wrapper program instead, * which starts the main nip2 exe, connecting stdin/out/err appropriately. */ #include <windows.h> #include <stdio.h> #include <io.h> #include <ctype.h> #include <glib.h> void print_last_error () { char *buf; if (FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) & buf, 0, NULL)) { fprintf (stderr, "%s", buf); LocalFree (buf); } } int main (int argc, char **argv) { char *dirname; char command[2048]; gboolean quote; int i, j; HANDLE hChildStdoutRd; HANDLE hChildStdoutWr; SECURITY_ATTRIBUTES saAttr; PROCESS_INFORMATION processInformation; STARTUPINFO startUpInfo; DWORD dwRead; CHAR buf[1024]; /* we run the nip2.exe in the same directory as this exe: swap the last * pathname component for nip2.exe * we change the argv[0] pointer, probably not a good idea */ dirname = g_path_get_dirname (argv[0]); argv[0] = g_build_filename (dirname, "nip2.exe", NULL); g_free (dirname); if (_access (argv[0], 00)) { fprintf (stderr, "cannot access \"%s\"\n", argv[0]); exit (1); } /* build the command string ... we have to quote items containing spaces */ command[0] = '\0'; for (i = 0; i < argc; i++) { quote = FALSE; for (j = 0; argv[i][j]; j++) { if (isspace (argv[i][j])) { quote = TRUE; break; } } if (i > 0) { strncat (command, " ", sizeof (command) - 1); } if (quote) { strncat (command, "\"", sizeof (command) - 1); } strncat (command, argv[i], sizeof (command) - 1); if (quote) { strncat (command, "\"", sizeof (command) - 1); } } if (strlen (command) == sizeof (command) - 1) { fprintf (stderr, "command too long\n"); exit (1); } /* Create a pipe for the child process's STDOUT. */ hChildStdoutRd = NULL; hChildStdoutWr = NULL; saAttr.nLength = sizeof (SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe (&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) { fprintf (stderr, "CreatePipe failed: "); print_last_error (); fprintf (stderr, "\n"); exit (1); } /* Ensure the read handle to the pipe for STDOUT is not inherited. */ if (!SetHandleInformation(hChildStdoutRd, HANDLE_FLAG_INHERIT, 0)) { fprintf (stderr, "SetHandleInformation failed: "); print_last_error (); fprintf (stderr, "\n"); exit (1); } /* Run command. */ startUpInfo.cb = sizeof (STARTUPINFO); startUpInfo.lpReserved = NULL; startUpInfo.lpDesktop = NULL; startUpInfo.lpTitle = NULL; startUpInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; startUpInfo.hStdOutput = hChildStdoutWr; startUpInfo.hStdError = hChildStdoutWr; startUpInfo.cbReserved2 = 0; startUpInfo.lpReserved2 = NULL; startUpInfo.wShowWindow = SW_SHOWNORMAL; if (!CreateProcess (NULL, command, NULL, /* default security */ NULL, /* default thread security */ TRUE, /* inherit handles */ CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS, NULL, /* use default environment */ NULL, /* set default directory */ &startUpInfo, &processInformation)) { fprintf (stderr, "error running \"%s\": ", command); print_last_error (); fprintf (stderr, "\n"); exit (1); } /* Close the write end of the pipe before reading from the read end. */ CloseHandle (hChildStdoutWr); while (ReadFile (hChildStdoutRd, buf, sizeof (buf) - 1, &dwRead, NULL) && dwRead > 0) { buf[dwRead] = '\0'; printf ("%s", buf); } CloseHandle (hChildStdoutRd); return (0); }
jcupitt/nip2
src/nip2-cli.c
C
gpl-2.0
5,159
/* # -- BEGIN LICENSE BLOCK -------------------------------------------------- # This file is part of Dotclear 2. # Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear # Licensed under the GPL version 2.0 license. # See LICENSE file or http://www.gnu.org/licenses/old-licenses/gpl-2.0.html # -- END LICENSE BLOCK ---------------------------------------------------- LAYOUTS HTML TAGS FORMULAIRES BOUTONS MESSAGES ELEMENTS PRINCIPAUX REGLES SPECIFIQUES MEDIA QUERIES */ /* --------------------------------------------------------------------------- START ---------------------------------------------------------------------------- */ html { font-size: 62.5%; } body { font-size: 12px; /* ie < 9 sucks */ font-size: 1.2rem; line-height: 1.5; font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; margin: 0; padding: 0; } /* --------------------------------------------------------------------------- LAYOUTS ---------------------------------------------------------------------------- */ *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } #header { background: #676e78; color: #FFF; border-bottom: 4px solid #A2CBE9; width: 100%; display: table; position: relative; } #wrapper { position: relative; padding-top: 1.5em; float: left; width: 100%; z-index: 10; background: #F7F7F7 url(bg_wrapper.png) repeat-y 15em; } .with-js #wrapper { padding-top: 0; } #main { width: 100%; float: right; margin-left: -14em; margin-top: 0; } #content { margin: 0 0 0 14em; padding: .5em 1.5em .75em 2.5em; background: #fff; } #main-menu { width: 14em; float: left; margin: 0; padding-top: .5em; padding-bottom: 1em; overflow: hidden; background: #f7f7f7; } #footer { clear: both; position: relative; padding: .5em 1em .5em 0; text-align: right; border-top: 1px solid #ccc; background-color: #fff; } /* to hide main-menu */ #collapser { position: absolute; top: 0; left: 14em; width: 15px; height: 100%; overflow: hidden; display: block; background: #f3f3f3 url(../images/collapser-hide.png) no-repeat center bottom; border-right: double #dfdfdf; z-index: 1; } .expand-mm { display: none; } /* if main-menu is hidden */ #wrapper.hide-mm { background: #fff; } .hide-mm #main { margin-left: 0; } .hide-mm #content { margin-left: 1em; } .hide-mm #main-menu { display: none; } .hide-mm #collapser { left: 0; background: #e3e3e3 url(../images/collapser-show.png) no-repeat center bottom; } .hide-mm .collapse-mm { display: none; } .hide-mm .expand-mm { display: block; } /* -------------------------------------------------------------- layout: two-cols */ .two-cols { position: static; } .two-cols .col { width: 48%; margin-left: 2%; float: left; } .two-cols .col70 { width: 68%; margin-left: 0; float: left; } .col30 { width: 28%; margin-left: 2%; float: left; } .two-cols .col:first-child, .two-cols .col30.first-col { margin-left: 0; margin-right: 2%; } .two-cols .col:last-child, .two-cols .col70.last-col { margin-left: 2%; margin-right: 0; } .two-cols table { width: 90%; } /* -------------------------------------------------------------- layout: three-cols */ .three-cols { position: static; } .three-cols .col { width: 32.3%; float: left; margin-left: 1%; } .three-cols .col:first-child { margin-left: 0; } /* ------------------------------------------------- layout: optionnal one/two/three-boxes */ .one-box { text-align: justify; } .two-boxes { width: 48.5%; } .three-boxes { width: 30%; } .two-boxes, .three-boxes { display: inline-block; vertical-align: top; margin: 0 1.5% 1em; text-align: left; } .two-boxes:nth-of-type(odd), .three-boxes:nth-of-type(3n+1) { margin-left: 0; } .two-boxes:nth-of-type(even), .three-boxes:nth-of-type(3n) { margin-right: 0; } /* ---------------------------------------------------------------- layout: popups */ .popup h1 { display: block; width: 100%; margin: 0; background: #676e78; font-size: 1.5em; text-indent: 1em; line-height: 1.5em; font-weight: normal; color: #fff; } .popup #wrapper { display: block; float: none; width: 100%; margin: 0; padding: 0; background-position: 0 0; } .popup #main { margin: 0; padding: 0; } .popup #content { margin: 0; padding: 1em; } .popup #content h2 { margin: 0 0 1em 0; padding: 0; } .popup #footer p { border: none; } /* -------------------------------------------------------- layout: classes de complément */ .constrained { margin: 0; padding: 0; border: none; background: transparent; } .table { display: table; } .cell { display: table-cell; vertical-align: top; } .clear { clear: both; } .lclear { clear: left; } .clearer { height: 1px; font-size: 1px; } /* Micro clearfix thx to Nicolas Gallagher */ .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .frame-shrink { border: 1px solid #676e78; padding: 0.5em; margin-bottom: 1em; height: 120px; overflow: auto; } .box { display: inline-block; vertical-align: top; margin: 0 10px 10px; text-align: left; } .box.small { width: 312px; } .box.medium { width: 644px; } .box.large { width: 100%; } .odd { margin-left: 0; } .even { margin-right: 0; } /* --------------------------------------------------------------------------- HTML TAGS ---------------------------------------------------------------------------- */ body { color: #333; background: #fff; } /* ------------------------------------------------------------------ titres */ h1, h2, h3, .as_h3, h4, .as_h4, h5, h6 { margin-top: 0; margin-bottom: 1em; } h2 { color: #676e78; font-size: 1.5em; padding: 0 0 1.5em; font-weight: normal; line-height: 1.25; } /* fil d'ariane */ #content > h2 { padding: 0 1em .5em 1em; margin: 0 -1em 1em -1em; background: #fff url(bg_h2.png) repeat-x center bottom; } h2 a:link, h2 a:visited { color: #676e78; border-color: #000; } /* page courante dans le fil d'ariane */ .page-title { color: #d30e60; } .page-title img { padding-left: .5em; vertical-align: middle; } /* autres titres */ h3, .as_h3 { margin-top: 1em; color: #D33800; font-weight: normal; font-size: 1.34em; } #main-menu h3 { font-weight: bold; } h4, .as_h4 { font-size: 1.16em; color: #676e78; } .fieldset h3, .fieldset h4, .pretty-title { color: #D33800; font-size: 1em; font-weight: bold; } .fieldset h3 { font-size: 1.17em; } .fieldset h3.smart-title, .fieldset h4.smart-title, .smart-title { font-size: 1em; text-transform: uppercase; font-weight: bold; color: #333; text-shadow: 0 1px 0 rgba(200, 200, 200, 0.6) } h5 { font-size: 1em; font-weight: bold; color: #676e78; } #entry-sidebar h5 { font-weight: normal; color: #333; } .entry-status img.img_select_option { padding-left: 4px; vertical-align: text-top; } h4 label, h5 label { color: #333; } h2:first-child, h3:first-child, h4:first-child, h5:first-child, ul:first-child, p:first-child { margin-top: 0; } /* ---------------------------------------------------------------- tableaux */ /* Pour autoriser le scroll sur les petites largeurs envelopper les tableaux dans une div.table-outer */ .table-outer { width: 100%; overflow: auto; } table { font-size: 1em; border-collapse: collapse; margin: 0 0 1em 0; width: 100%; } caption { color: #333; font-weight: bold; text-align: left; margin-bottom: .5em; } th { border-width: 1px 0 1px 0; border-style: solid; border-color: #dfdfdf; background: #eef1ec; padding: .4em 1em .4em .5em; vertical-align: top; text-align: left; } td { border-width: 0 0 1px 0; border-style: solid; border-color: #e3e3e3; padding: .4em 1em .4em .5em; vertical-align: top; } /* ---------------------------------------------------------- autres balises */ p { margin: 0 0 1em 0; } hr { height: 1px; border-width: 1px 0 0; border-color: #dfdfdf; background: #dfdfdf; border-style: solid; } hr.clearer { clear: both; } pre, code, #debug { font: 100% "Andale Mono","Courier New",monospace; } code { background: #fefacd; } pre { white-space: pre; white-space: -moz-pre-wrap; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word; } abbr { cursor: help; } input, textarea, select, option, optgroup, legend,label { font-size: 1em; } /* ------------------------------------------------------------------ liens */ a, a:link, a:visited { color: #2373A8; text-decoration: none; border-bottom: 1px dotted #999; background-color: inherit; outline: 0; } a:hover, a:active { border-bottom-style: solid; } a img, a:link img, a:visited img { border: none; background: inherit; } h1 a:link, h1 a:visited { border: none; } .discrete a { color: #333; } a:link { transition: .5s; } a:focus, a:focus img { outline: 2px solid #bee74b; border-bottom: none; text-decoration: none; } /* ---------------------------------------------------------------------------- FORMULAIRES ---------------------------------------------------------------------------- */ input[type=text], input[type=password], input[type=submit], input[type=button], input[type=reset], a.button, button, textarea, select, legend { border-radius: 3px; max-width: 100%; } form { display: block; margin: 0; padding: 0; } fieldset { display: block; margin: 1em 0; padding: 1em 0.5em; border-width: 1px 0; border-style: solid; border-color: #ccc; background: #f7f7f7; } input[type=text], textarea { font: 100% "DejaVu Sans","Lucida Grande","Lucida Sans Unicode",Arial,sans-serif; } legend { padding: 0.2em 0.6em; border-width: 1px; border-style: solid; border-color: #676e78; background: #fff; margin-bottom: 0.5em; } label .maximal, textarea.maximal, input.maximal, select.maximal { width: 99%; } input[type=text], input[type=password], textarea, select { background: #fcfcfc; color: #000; border-width: 1px; border-style: solid; border-color: #dfdfdf; box-shadow: 1px 1px 2px #f3f3f3 inset; padding: 3px; vertical-align: top; } input:focus, textarea:focus, select:focus { border-color: #9bca1c; } textarea { padding: 2px 0; } textarea.maximal { resize: vertical; } .area textarea { display: block; width: 100%; resize: vertical; } select { padding: 2px 0; vertical-align: middle; } select.l10n option { padding-left: 16px; } option.avail10n { background: transparent url(../images/check-on.png) no-repeat 0 50%; } option.sub-option1 { margin-left: .5em; } option.sub-option2 { margin-left: 1.5em; } option.sub-option3 { margin-left: 2.5em; } option.sub-option4 { margin-left: 3.5em; } option.sub-option5 { margin-left: 4.5em; } option.sub-option6 { margin-left: 5.5em; } option.sub-option7 { margin-left: 6.5em; } option.sub-option8 { margin-left: 7.5em; } option.sub-option1:before, option.sub-option2:before, option.sub-option3:before, option.sub-option4:before, option.sub-option5:before, option.sub-option6:before, option.sub-option7:before, option.sub-option8:before { content: "\002022\0000a0"; } input.invalid, textarea.invalid, select.invalid { border: 1px solid red; background: #FFBABA; color: #900; box-shadow: 0 0 0 3px rgba(218, 62, 90, 0.3); } input[type=text], input[type=password], textarea { margin-right: .3em; } input[type=checkbox], input[type=radio], input[type=file] { border: none; margin: 0 .33em 0 0; padding: 0; background: transparent; } input[type=file] { margin-top: .3em; margin-bottom: .3em; } optgroup { font-weight: bold; font-style: normal; } option { font-weight: normal; } label, label span { display: block; } label.ib, input.ib { display: inline-block; } label.classic { display: inline; } label.classic input, label span input, label.classic select, label span select { display: inline; } label.required { font-weight: bold; } label.required abbr { color: #900; font-size: 1.3em; } label.bold { text-transform: uppercase; font-weight: bold; margin-top: 2em; } label.area, p.area { width: inherit !important; } p.field { position: relative; } p.field label { display: inline-block; width: 14em; } p.field.wide label { width: 21em; } p.field input, p.field select { display: inline-block; } .form-note { font-style: italic; font-weight: normal; color: #676e78; } p.form-note { margin-top: -.7em; } span.form-note { text-transform: none; } /* ---------------------------------------------------------------------------- BOUTONS ---------------------------------------------------------------------------- */ /* Removes inner padding and border in FF3+ - Knacss */ button::-moz-focus-inner, input[type=button]::-moz-focus-inner, input[type=reset]::-moz-focus-inner, input[type=submit]::-moz-focus-inner { border: 0; padding: 0; } /* tous les boutons */ button, a.button, input[type=button], input[type=reset], input[type=submit] { border: 1px solid #ccc; font-family: "DejaVu Sans","Lucida Grande","Lucida Sans Unicode",Arial,sans-serif; padding: 3px 10px; line-height: normal !important; display: inline-block; font-size: 100%; text-align: center; text-decoration: none; cursor: pointer; position: relative; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); border-style: solid; border-width: 1px; } button, input[type=button], input[type=reset], input[type=submit] { -webkit-appearance: button; } /* validation */ input[type=submit], a.button.submit, input.button.start { color: #fff; background-color: #25A6E1; background-image: -webkit-gradient(linear,left top,left bottom, from(#25A6E1), to(#188BC0)); background-image: linear-gradient(#25A6E1,#188BC0); border-color: #25A6E1; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } input[type=submit]:hover, input[type=submit]:focus, input.button.start:hover, input.button.start:focus, a.button.submit:hover, a.button.submit:focus { background-color: #188BC0; background-image: -webkit-gradient(linear,left top,left bottom, from(#188BC0),to(#25A6E1)); background-image: linear-gradient(#188BC0,#25A6E1); border-color: #188BC0; } /* suppression, reset, "neutres" fond gris */ button, input[type=button], input.button, input[type=reset], input[type=submit].reset, input.reset, input[type=submit].delete, input.delete, a.button, a.button.delete, a.button.reset { color: #000; background-color: #EAEAEA; background-image: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#EAEAEA)); background-image: linear-gradient(#f9f9f9,#EAEAEA); background-repeat: repeat-x; border-color: #dfdfdf #dfdfdf #C5C5C5; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.9); } button:hover, input[type=button]:hover, input.button:hover, button:focus, input[type=button]:focus, input.button:focus, input[type=reset]:hover, input[type=submit].reset:hover, input.reset:hover, input[type=reset]:focus, input[type=submit].reset:focus, input.reset:focus, input[type=submit].delete:hover, input.delete:hover, input[type=submit].delete:focus, input.delete:focus, a.button.delete:hover, a.button.reset:hover, a.button:hover, a.button.delete:focus, a.button.reset:focus, a.button:focus { background-color: #DADADA; background-image: -webkit-gradient( linear, left top, left bottom, from(#EAEAEA), to(#DADADA)); background-image: linear-gradient(#EAEAEA, #DADADA); background-repeat: repeat-x; border-color: #CCCCCC #CCCCCC #B5B5B5; } /* suppression */ input[type=submit].delete, input.delete, a.button.delete { color: #900; } input[type=submit].delete:hover, input.delete:hover, a.button.delete:hover, input[type=submit].delete:focus, input.delete:focus, a.button.delete:focus { color: #FFFFFF; background-color: #B33630; background-image: -webkit-gradient( linear, left top, left bottom, from(#DC5F59), to(#B33630)); background-image: linear-gradient(#DC5F59, #B33630); background-repeat: repeat-x; border-color: #CD504A; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3); } #info-box a.button { padding: 0 .5em; margin-left: 2em; } .button.add { color: #000; background-color: #bee74b; background-image: -webkit-gradient(linear, left top, left bottom, from(#bee74b), to(#9BCA1C)); background-image: linear-gradient(#bee74b, #9BCA1C); border-color: #bee74b; padding: .33em 1.33em .5em; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6); font-weight: normal; font-size: 1.16em; } .button.add:hover, .button.add:active, .button.add:focus { background-color: #9BCA1C; background-image: -webkit-gradient(linear, left top, left bottom, from(#9BCA1C), to(#bee74b)); background-image: linear-gradient(#9BCA1C, #bee74b); border-color: #9BCA1C; } .button-add:focus { outline: dotted 1px; } /* paragraphe pour bouton Nouveau bidule */ p.top-add { text-align: right; margin: 0; } /* disabled */ input.disabled, input[type=submit].disabled { text-shadow: none; color: #676e78; background: #F5F5F5; border: 1px solid #CCC; } input.disabled:hover, input[type=submit].disabled:hover { color: #676e78; background: #eee; border: 1px solid #CCC; } /* ---------------------------------------------------------------------------- MESSAGES ---------------------------------------------------------------------------- */ .warn, .warning, .info { font-style: normal; padding: .2em .66em .2em; text-indent: 24px; color: #333; display: inline-block; line-height: 1.5em; border-radius: 3px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6) } div.warn, div.warning, div.info { display: block; padding: 1em 1em .33em 1em; margin-bottom: 1em; } .warn, .warning { background: #FEFACD url(msg-warning.png) no-repeat .3em .3em; border: 1px solid #ffd478; } .info { background: #D9EDF7 url(msg-info.png) no-repeat .3em .3em; border: 1px solid #BCE8F1; } span.warn, span.warning, span.info { padding-top: 1px; padding-bottom: 1px; background-position: .3em .2em; } .error, .message, .static-msg, .success, .warning-msg { padding: 1em 0.5em 0.5em 48px; margin-bottom: 1em; border-radius: 8px; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1); } p.error, p.message, p.static-msg, p.success, p.warning-msg { padding-top: 1em; padding-bottom: 1em; margin-top: .5em; } .error { background: #FFBABA url(msg-error.png) no-repeat .7em .7em; color: #000; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6); } .message, .static-msg { background: #676e78 url(msg-std.png) no-repeat .7em .7em; color: #fff; } .message a, .static-msg a, .message h3, .static-msg h3 { color: #fff; } .success, .warning-msg { color: #000; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6) } .success { background: #9bca1c url(msg-success.png) no-repeat .7em .7em; } .warning-msg { background: #ffd478 url(msg-warning.png) no-repeat .7em .7em; border: 1px solid #ffd478; } .success a, .warning-msg a, .info a { color: #333; } .dc-update { padding: 1em 48px 0.5em 48px; margin-bottom: 1em; border-radius: 8px; background: #A2CBE9 url(msg-success.png) no-repeat .7em .7em; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6); color: #000; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1) } .dc-update h3 { margin-top: 0; color: #000; } .dc-update p { display: inline-block; vertical-align: middle; } .dc-update a { color: #000; margin-right: 1em; } .dc-update a.button { padding: .5em 1em; } .updt-info a { margin-left: 2em; border-color: #000; font-weight: bold; } /* --------------------------------------------------------------------------------- ELEMENTS PRINCIPAUX --------------------------------------------------------------------------------- */ /* -------------------------------------------------------------- HEADER ELEMENTS */ /* prelude */ #prelude { line-height: 1.5; margin: 0; padding: 0; overflow: hidden; position: absolute; top: 3em; left: 0; background: #A2CBE9; width: 100%; z-index: 100; } #prelude li { list-style-type: none; margin: 0; background: transparent; display: inline; } #prelude li a { padding: 3px 16px 3px 8px; background: #A2CBE9; color: #000; text-decoration: underline; } #prelude li a:hover, #prelude li a:focus { background: #FFF; } /* si le prélude est affiché on repousse les trucs dessous */ #wrapper.with-prelude { padding-top: 1em; } #help-button.with-prelude, #collapser.with-prelude { top: 1em; } /* header global h1, form#top-info-blog, ul#top-info-user */ #header a { color: #FFF; } #header img { vertical-align: middle; padding-left: .5em; } h1, #top-info-blog, #top-info-user { display: table-cell; padding: 8px 0; margin: 0; font-size: 1em; vertical-align: top; } /* h1 */ h1 { text-indent: 100%; width: 16.5em; } h1 a { position: absolute; top: 0; left: 0; width: 150px; height: 3em; color: #fff; background: transparent url(dc_logos/b-dotclear120.png) no-repeat 0 6px; transition: none; } h1 a:hover, h1 a:focus { background-position: 0 -94px; background-color: transparent; transition: none; } /* top-info-blog */ #top-info-blog select { max-width: 20em; } #top-info-blog a { margin-left: 1.5em; } #top-info-blog input[type=submit] { background: #000; border-color: #999; margin-left: .33em; } #top-info-blog input[type=submit]:hover { background: #999; } #top-info-blog p { display: inline-block; margin: 0; } /* top-info-user */ #top-info-user { padding-right: 18px; list-style-type: none; text-align: right; } #top-info-user li { display: inline-block; margin-left: .5em; padding-left: .5em; border-left: 1px solid #999; } #top-info-user li:first-child { border-left: none; } #top-info-user a.active { border-bottom-color: #fff; margin: 0; padding: 18px .5em; background-color: #fff; color: #333; font-weight: bold; } /* ---------------------------------------------------------- MAIN-MENU ELEMENTS */ #favorites-menu, #blog-menu, #system-menu, #plugins-menu { border-bottom: 1px dashed #A2CBE9; } #main-menu h3 { margin: 0; padding: 10px 0 10px 8px; color: #676e78; font-size: 1.15em; } #favorites-menu h3 { color: #000; font-variant: small-caps; padding-top: .2em; } #main-menu a { color: #333; border-bottom-color: #ccc; } #main-menu ul { margin: 0 0 1.5em 0; padding: 0; list-style: none; } #main-menu li { display: block; margin: 0.5em 0 0; padding: 4px 0 1px 32px; background-repeat: no-repeat; background-position: 8px .3em; } #main-menu ul li:first-child { margin-top: 0; } #main-menu li.active { background-color: #fff; font-weight: bold; } #favorites-menu li.active { background-color: transparent; } #main-menu .active a { border-bottom: none; color: #d30e60; } #favorites-menu .active a { color: #000; } #search-menu { padding: 4px 5px 0; font-size: 100% } #search-menu * { height: 2em; display: inline-block; vertical-align: top; line-height: 24px; } #search-menu p { border: 1px solid #999; border-radius: .3em; position: relative; width: 95%; overflow: hidden; } #qx { width: 80%; border-bottom-left-radius: .3em; border-top-left-radius: .3em; background: transparent url(search.png) no-repeat 4px center; text-indent: 18px; padding: 0; border: none; height: 2em; } #qx:focus { border: 1px solid #bee74b; } #search-menu input[type="submit"] { padding: 0 .25em; margin-left: .33em; background: #dfdfdf; border-color: #999; color: #333; border-bottom-right-radius: .3em; border-top-right-radius: .3em; border-top-left-radius: 0; border-bottom-left-radius: 0; text-shadow: none; border: none; border-left: 1px solid #999; font-size: .91em; float: right; } #search-menu input[type="submit"]:hover, #search-menu input[type="submit"]:focus { background: #676e78; color: #fff; } /* ----------------------------------------------------------------- CONTENT ELEMENTS */ .part-tabs ul { padding: .5em 0 0 1em; border-bottom: 1px solid #ccc; line-height: 1.8; } .part-tabs li { list-style: none; margin: 0; display: inline; } .part-tabs li:first-child a { border-top-left-radius: 3px; } .part-tabs li:last-child a { border-top-right-radius: 3px; } .part-tabs li a { padding: .33em 1.5em; margin-right: -1px; border: 1px solid #ccc; border-bottom: none; text-decoration: none; color: #333; background-color: #ecf0f1; display: inline-block; } .part-tabs li a:hover, .part-tabs li a:focus { color: #000; background: #fff; border-bottom-color: #fff; } .part-tabs li.part-tabs-active a { background: #fff; font-weight: bold; border-bottom-color: #fff; } .multi-part { padding-left: 1em; } .pseudo-tabs { margin: -.75em 0 2em 0; border-bottom: 1px solid #bbb; display: table; width: 100%; padding: 0; line-height: 24px; border-collapse: collapse; } .pseudo-tabs li { display: table-cell; border-width: 0 1px; border-style: solid; border-color: #ccc; padding: 0; margin: 0; text-align: center; } .pseudo-tabs a { display: block; font-weight: bold; padding: 0 24px; border-bottom: none; } .pseudo-tabs a:hover, .pseudo-tabs a:focus { background-color: #ecf0f1; color: #333; } .pseudo-tabs a.active { background-color: #ecf0f1; color: #d30e60; } /* contextual help */ #help { margin-top: 4em; background: #f5f5f5; z-index: 100; clear: both; padding: 0 1em; } #content.with-help #help { display: block; position: absolute; top: 0; right: 0; width: 24em; border-left: 2px solid #FFD478; border-top: 2px solid #FFD478; margin-top: 0; padding: .5em 0 0 0; overflow: auto; } #help-button { background: transparent url(help-mini.png) no-repeat 6px center; position: absolute; top: 0; right: 0; padding: 0 1.5em 0 30px; cursor: pointer; color: #2373A8; line-height: 3; } #help-button.floatable { border-top: 2px solid #ccc; border-left: 2px solid #ccc; border-bottom: 2px solid #ccc; border-bottom-left-radius: 1em; border-top-left-radius: 1em; background-color: #f5f5f5; position: fixed; top: 10px; -webkit-transform:translateZ(0); /* Let GPU doing his job */ } .no-js #help-button { top: 1em; } #help-button span { padding: .5em 0 .1em 0; } #content.with-help #help-button { right: 24em; background-color: #f5f5f5; position: fixed; top: 50px; z-index: 100; border-top: 2px solid #FFD478; border-left: 2px solid #FFD478; border-bottom: 2px solid #FFD478; border-bottom-left-radius: 1em; border-top-left-radius: 1em; } .help-box { display: none; } .help-box ul { padding-left: 20px; margin-left: 0; } #content.with-help .help-content { padding: 0 1em 1em; } .help-content dt { font-weight: bold; color: #676e78; margin: 0; } .help-content dd { margin: 0.3em 0 1.5em 0; } /* lien d'aide générale dans le help content */ #helplink p { padding: 0 0 0 .5em; } /* ------------------------------------------------------------------ FOOTER ELEMENTS */ #footer p { margin: 0; padding: 0 1em; font-size: 1em; } span.credit { font-size: 1em; font-weight: normal; } span.tooltip { position: absolute; padding: 0; border: 0; height: 1px; width: 1px; overflow: hidden; } #footer a:hover span.tooltip { padding: 10px 10px 0 40px; color: #d30e60; height: auto; width: auto; right: 0; bottom: 0; background: #FFF; z-index: 99; font-family: monospace; border: none; text-align: left; } /* --------------------------------------------------------------------------------------- RÈGLES SPÉCIFIQUES ---------------------------------------------------------------------------------------- */ /* ---------------------------------------------------------------- LISTES TABLEAUX */ table .maximal, table.maximal { width: 100%; } table .minimal { width: 1px; } table .nowrap { white-space: nowrap; vertical-align: top; } table .count { text-align: right; padding-right: 1.5em; } th.first input { padding-right: 34px; } .line img { vertical-align: middle; } tr.line img.expand, th img.expand { margin-right: 6px; margin-bottom: -2px; } tr.line p { margin: 0; } tr.line input[type=text] { background: #FFF; } tr.line input, tr.line select { vertical-align: middle; -webkit-box-shadow: none; box-shadow: none; } tr.line select { width: 6em; } tr.line:hover { background: #f3f3f3; } td.status { vertical-align: middle; } td.status img { margin-bottom: -2px; } td.status a { border: none; } .noborder td, td.noborder, .noborder th, th.noborder { border-width: 0 0 1px 0; border-color: #dfdfdf; line-height: 2em; padding-bottom: 0; } .noborder p { margin-bottom: 0; } table.posts-list { min-width: 50%; } table.settings, table.prefs { margin-bottom: 3em; } table.settings th:first-child, table.prefs th:first-child { width: 20%; } table.settings th + th, table.prefs th + th { width: 30%; } table.settings th + th + th, table.prefs th + th + th { width: 10%; } table.settings th:last-child, table.prefs th:last-child { width: 40%; } /* js */ td.expand { padding: 1em; } tr.expand td { border-bottom: none; } .handle { padding: 0; } .handler { cursor: move; background: transparent url(drag.png) no-repeat 0 50%; padding-left: 15px; } /* ----------------------------------------------------------- BOITES À FILTRES */ a.form-control { display: none; background: url(../images/expand.png) no-repeat 4px center; padding-left: 20px; color: #000; } a.form-control.open { background: url(../images/hide.png) no-repeat 4px center; } #filters-form { border: 1px dashed #999; border-radius: .3em; margin-bottom: 2em; padding: .5em 1em 0; } #filters-form .table { width: 100%; padding: 0; margin-bottom: 1em; margin-top: .5em; } #filters-form .cell { padding: 0 2em 0 0; } #filters-form .filters-sibling-cell { padding-top: 3.8em; } #filters-form .filters-options { padding-left: 2em; border-left: 1px solid #ccc; } #filters-form label.ib, span.ib { width: 7em; } #filters-form label.ibw, span.ibw { width: 9em; display: inline-block; } #filters-form select { width: 14em; vertical-align: middle; } #filters-form h4 { margin-top: 0; margin-bottom: 2em; } /* ---------------------------------------------------------------------------- SPEC PAGES */ /* ---------------------------------------------------------------------------- auth.php */ #login-screen { display: block; width: 20em; margin: 1.5em auto 0; font-size: 1.16em; } #login-screen h1 { text-indent: -2000px; background: transparent url(dc_logos/w-dotclear240.png) no-repeat top left; height: 66px; width: 20em; margin-bottom: .5em; margin-left: 0; } #login-screen .fieldset { border: 1px solid #9bca1c; padding: 1em 1em 0 1em; background: #fff; margin-bottom: 0; margin-top: 1em; } #login-screen input[type=text], #login-screen input[type=password], #login-screen input[type=submit], #login-screen input[type=text]:focus, #login-screen input[type=password]:focus, #login-screen input[type=submit]:focus { width: 100%; margin: 0; padding: 5px 3px; } #login-screen input.login, #login-screen input.login:focus { padding-top: 6px; padding-bottom: 6px; font-size: 1em; } #login-screen #issue { margin-left: 1.33em; font-size: .91em; } #issue p:first-child { text-align: right; } #login-screen #issue strong { font-weight: normal; } /* ------------------------------------------------------------------------- index.php */ #dashboard-main { padding: 1em; text-align: center; } /* raccourcis */ #icons { overflow: hidden; padding-bottom: 1em; text-align: center; } #icons p { width: 14em; text-align: center; margin: 1em 0 2em; padding: 1em 0; display: inline-block; vertical-align: top; } #icons a, #icons a:link, #icons a:visited, #icons a:hover, #icons a:focus { border-bottom-width: 0; text-decoration: none; } #icons a span { border-bottom: 1px dotted #999; color: #333; } #icons a img { padding: 1.5em; background-color: #f9f9f9; border-radius: 8px; border: 1px solid #dadada; display: inline-block; } #icons a:focus img, #icons a:hover img { background: #bee74b; outline: 0; border-color: #dadada; } #icons a:focus { outline: 0; border-color: #fff; } #icons a:hover span, #icons a:focus span { border-bottom-style: solid; } #icons a:focus span { border: 2px solid #bee74b; } /* billet rapide */ #quick { padding: 1em; max-width: 976px; margin: 0 auto; background: #f5f5f5; box-shadow: 0 1px 2px rgba(0, 0, 0, .2); text-align: left; } #quick h3 { margin-bottom: 0.2em; font-size: 1.2em; } #quick p.qinfo { margin: -.7em -1em 1em; background: #D9EDF7 url(info.png) no-repeat .2em .2em; border: 1px solid #BCE8F1; padding: .2em 1em .1em 24px; color: #000; } #quick #new_cat, .q-cat, .q-cat label { display: inline-block; vertical-align: top; margin-right: 1em; margin-top: 0; } .q-cat label { margin-right: .3em; } #quick #new_cat { margin-bottom: 2em; } /* modules additionnels */ #dashboard-boxes { margin: 1em auto 1em; padding-top: 2em; } .db-items, .db-contents { display: inline-block; text-align: center; } .no-js .outgoing img { display: none; } #dashboard-boxes .box { padding: 10px; border: 1px solid #ccc; border-radius: 3px; min-height: 200px; margin: 10px; text-align: left; } .dc-box { background: transparent url(dc_logos/sq-logo-32.png) no-repeat top right; } .db-items img, .db-contents img { vertical-align: middle; } .db-items ul, .db-contents ul { display: block; padding-left: 1.5em; list-style: square; } .db-items li, .db-contents li { margin: 0.25em 0 0 0; } #news dt { font-weight: bold; margin: 0 0 0.4em 0; } #news dd { margin: 0 0 1em 0; } #news dd p { margin: 0.2em 0 0 0; } /* message de mise à jour */ #upg-notify ul { padding-left: 1.5em; } #upg-notify li { color: #fff; } /* ------------------------------------------------------------------- blog_pref.php */ #media_img_title_pattern { margin-right: 1em; } .user-perm { margin: 2em 0px; background: transparent url(user.png) no-repeat left top; width: 320px; display: inline-block; vertical-align: top; } .user-perm h4, .user-perm h5, .user-perm p, .user-perm ul, .user-perm li { margin: .5em 0 .33em; padding: 0; } .user-perm h4 { padding-left: 28px; } .user-perm h5 { margin: 1em 0 0 0; } .user-perm ul { list-style-type: inside; } .user-perm li { margin-left: 1em; padding-left: 0; } li.user_super, li.user_admin { margin-left: 0; padding-left: 20px; list-style: none; background: transparent url(../images/superadmin.png) no-repeat 0 .3em; } li.user_admin { background-image: url(../images/admin.png); } /* ------------------------------------------------------------------- blog_theme.php */ /* pour les alignements verticaux */ #theme-new, #theme-activate, #theme-deactivate, #theme-update { margin-left: -10px; margin-right: -10px; } .box.theme { margin: 5px; padding: 10px 10px 5px 10px; border: 1px solid #dfdfdf; position: relative; } .box.theme:hover { background: #ecf0f1 url(texture.png); } .module-name, .module-name label { margin-bottom: .5em; color: #676e78; } .module-sshot { text-align: center; } .module-sshot img { padding: 5px; background: #f7f7f7; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2); border: 3px solid #fff; max-width: 100%; } .module-actions { margin-top: 1em; } .bloc-toggler { text-align: right; } .bloc-toggler img { opacity: .4; } .bloc-toggler img:hover { opacity: 1; } .bloc-toggler a:focus img { opacity: 1; } span.module-version:before { content: "- "; } .toggle-bloc .mod-more { display: block; margin-left: 0; } .box.theme input { margin-bottom: 1em; } .module-name input[type="checkbox"] { margin-bottom: 0; } /** Les screenshots des thèmes ont deux tailles possibles : - dans Ajouter des thèmes : 240px (+ 10 padding image + 20 padding boîte + 6 bordure + 2 ombrage = 278) - dans Thèmes installés : 280px (+ 10 padding-image + 20 padding-boîte + 2 ombrage = 318) On adapte largeur et hauteur en fonction */ #theme-new .box.theme, #theme-update .box.theme { /* Ajouter un thème */ width: 278px; min-height: 275px; } #theme-new .module-sshot img { /* Pour ceux qui n'ont pas de miniature on contraint l'image */ max-width: 240px; max-height: 210px; overflow: hidden; } #theme-deactivate .box.theme { /* Thèmes désactivés */ width: 278px; } #theme-activate .box.theme { /* Thèmes installés */ width: 318px; min-height: 304px; max-width: 100%; } #theme-deactivate .box.theme:hover { background: transparent url(dc_logos/sq-logo-32.png) no-repeat top right; } /* si js est là, les infos viennent par dessus le screenshot */ .with-js #theme-new .module-infos.toggle-bloc, .with-js #theme-new .module-actions.toggle-bloc { position: absolute; left: 10px; width: 239px; margin: 0; padding: 10px; background: rgba(250, 250, 250, .95); } .with-js #theme-new .module-infos.toggle-bloc { top: 128px; height: 80px; border-top: 1px solid #e3e3e3; } .with-js #theme-new .module-actions.toggle-bloc { top: 208px; height: 40px; border-bottom: 1px solid #e3e3e3; } .with-js .module-sshot:hover { cursor: pointer; } /* mise en forme pour la boîte du thème courant */ .box.current-theme { /* Thème courant */ width: 646px; margin: 5px; padding: 20px 18px 6px; background: #fff url(texture.png); border: 1px solid #eee; border-radius: .5em; min-height: 326px; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2); position: relative; } .current-theme .module-sshot:hover { cursor: auto; } .current-theme .module-sshot img { float: left; margin-right: 2em; border: 9px solid #fff; padding: 5px; max-width: 308px; max-height: 273px; } .current-theme .module-name { color: #D33800; font-size: 1.5em; margin-bottom: 1em; } .current-actions { width: auto; overflow: hidden; padding-top: 2em; margin: 1.5em 0 2em; background: transparent url(../images/minus-theme.png) no-repeat left top; } .current-theme .actions-buttons { position: absolute; bottom: 0; right: 18px; } /* ------------------------------------------------------------------ categories.php */ #categories { margin: 1em 0; } #categories ul { list-style: none; margin-top: 2em; padding: 0; } .cat-line { position: relative; margin: .66em 0; padding: .66em 1em; border: 1px solid #ccc; border-radius: 3px; } .cat-line label { margin-right: .25em; } .cat-line label a { font-weight: bold; } .cat-line p, .cat-line label { margin: 0; display: inline-block; } p.cat-title { margin-right: 1em; } .cat-nb-posts a { color: #333; } .cat-url { padding-left: 1em; } #categories .placeholder { outline: 1px dashed #4183C4; min-height: 2.5em; } .cat-buttons { float: right; margin-top: -.2em; font-size: .91em; } .cat-buttons select { padding: 1px 2px 3px 2px; margin-right: .25em; } .cat-buttons .reset { padding-left: 4px; padding-right: 4px; } #categories ul ul { margin-right: 2em; margin-left: 2em; } .cat-line .cat-line { border: 1px solid #dfdfdf; } .cat-actions { line-height: 2; } #del_cat { width: 100%; } /* ------------------------------------------------------------------ media.php */ .media-item { position: relative; border: 1px solid #dfdfdf; margin: 9px; padding: 10px 12px 6px; width: 320px; display: inline-block; vertical-align: top; min-height: 140px; word-wrap: break-word; } .media-item p { margin: 0 0 .5em; } .media-item object { margin-top: .5em; } .media-item ul { display: block; list-style: none; margin: 0; padding: 0; } a.media-icon { display: block; border-bottom: none; margin: 0 auto; } .media-icon img { display: block; } .media-link { font-size: 1.1em; } .media-action-box { position: relative; margin: 3em 3em 1em 1em; display: inline-block; vertical-align: top; } li.media-action { display: block; position: absolute; bottom: 4px; right: 8px; height: 16px; } li.media-action a { border: none; } li.media-action a.attach-media { margin-right: 5px; } li.media-action form { display: inline; } li.media-action input { border: none; } #entry-sidebar .media-item { width: 100%; min-height: 0; padding: 4px; margin: .33em 0; } #entry-sidebar li.media-action { top: 4px; } .folders-group .media-item { min-height: 70px; } .folders-group .media-item p { margin-bottom: 0; } .media-folder { background: transparent url(bg_menu.png) repeat-y; border-color: #eee; } .media-folder-up { border-color: #fff; padding-bottom: 6px; } .media-folder .media-link { font-size: 1.25em; margin-left: 2em; color: #676e78; border-bottom: none; } .medias-delete { text-align: right; } /* upload multiple */ .enhanced_uploader .choose_files, .enhanced_uploader .cancel, .enhanced_uploader .clean, .enhanced_uploader .start { margin-right: .4em; } .enhanced_uploader #upfile { visibility: hidden; width: 0; height: 0; margin: 0; opacity: 0; filter: alpha(opacity=0); cursor: pointer; } .button.clean, .button.cancel, .button.choose_files { display: none; } .enhanced_uploader .button.choose_files { display: inline-block; } .enhanced_uploader .max-size { display: block; } .enhanced_uploader .one-file { display: none; } label span.one-file { display: inline; } .enhanced_uploader p.clear { padding-top: 1em; margin-bottom: 1em; } #add-file-f p.clear { margin-top: 1em; margin-bottom: 0; clear: both; } .files { list-style-type: none; margin-left: 0; padding-left: 0; border-bottom: 1px solid #dfdfdf; } .files li { margin-left: 0; padding-left: 0; } .upload-msg { font-weight: bold; } .upload-msg.upload-error { color: #900; } .upload-files { padding: 0 0.5em; margin: 1em 0; } .upload-file { margin: 0; padding: .3em 0; border-top: 1px solid #dfdfdf; position: relative; } .upload-fileinfo { margin-left: 0; } .upload-fileinfo input { position: absolute; top: .5em; right: .5em; } .upload-fileinfo span { padding-right: 8px; } .upload-fileinfo .upload-filecancel { display: block; padding-right: 0; margin-top: 3px; width: 20px; height: 20px; background: transparent url("cancel.png") no-repeat left top; text-indent: -1000px; cursor: pointer; float: left; } .upload-filemsg { font-weight: bold; color: green; } .upload-filemsg.upload-error { color: #900; } .upload-progress { padding: .3em 0; } .upload-progress div { width: 0; height: 1.2em; font-weight: bold; line-height: 1.2em; text-align: right; background: green url(loader.png) repeat-x left top; color: white; border-radius: 3px; } div.template-upload { clear: both; } .queue-message { font-weight: bold; } /* --------------------------------------------------------------- media-item.php */ #media-icon { float: left; } .near-icon { margin-left: 70px; margin-bottom: 3em; } #media-details ul { display: block; margin-left: 0; padding: 0; } #media-details li { list-style: square inside; margin: 0; padding: 0; } #media-original-image { overflow: auto; } #media-original-image.overheight { height: 500px; } /* -------------------------------------------------------------------- plugins.php */ .modules td.module-actions, .modules td.module-icon { vertical-align: middle; } .modules td.module-icon img:last-child { width: 16px; height: 16px; } .modules td.module-icon img.expand { margin-bottom: 3px; } .modules td.module-distrib img { display: block; float: right; } .modules dt { font-weight: bold; } .modules a.module-details { background: transparent url(search.png) no-repeat 2px center; padding: 4px 4px 0 20px; } .modules a.module-support { background: transparent url(help12.png) no-repeat 2px center; padding: 4px 4px 0 20px; } .modules a.module-config { background: transparent url(settings.png) no-repeat 2px 6px; padding: 4px 4px 0 18px; } #m_search { background: transparent url(search.png) no-repeat 4px center; padding-left: 20px; } .modules tr.expand, .modules td.expand { background: #f7f7f7; border-color: #bee74b; } .modules tr.expand td:first-child { font-weight: bold; background: #DFE5E7; } .modules td.expand { padding: 0 0 1em; border-top: 1px solid #eaeaea; } .modules td.expand div { display: inline-block; vertical-align: top; margin-right: 3em; } .mod-more, .mod-more li { margin: .25em 0 0 1em; padding: 0; list-style-type: none; } .mod-more { padding-top: .5em; } #plugin-update td { vertical-align: baseline; } /* ---------------------------------------------------------- post.php, page.php */ #entry-wrapper { float: left; width: 100%; margin-right: -16em; } #entry-content { margin-right: 18em; margin-left: 0; } #entry-sidebar { width: 16em; float: right; } #entry-sidebar h4 { font-size: 1.08em; margin-top: .3em; } #entry-sidebar select { width: 100%; } #entry-sidebar input#post_position { width: 4em; } .sb-box { border-bottom: 1px solid #dfdfdf; margin-bottom: 1em; } #tb_excerpt { width: 100%; } /* ---------------------------------------------------------- preferences.php */ .fav-list { list-style-type: none; margin-left: 0; padding-left: 0; } #my-favs .fav-list { border-top: 1px solid #eee; } .fav-list li { margin-left: 0; padding-left: 0; padding-top: 3px; padding-bottom: 3px; position: relative; } #my-favs .fav-list li { line-height: 2; border-bottom: 1px solid #eee; padding-top: 3px; padding-bottom: 3px; position: relative; } .fav-list img { vertical-align: middle; margin-right: .2em; } .fav-list li span.zoom { display: none; } .fav-list li:hover span.zoom { display: block; position: absolute; bottom: 0; left: 10em; background-color: #f7f7f7; border: 1px solid #dfdfdf; padding: .2em; border-radius: .5em; } #my-favs { border-color: #9bca1c; } #my-favs input.position { margin: 0 0 .4em .2em; } #available-favs input, #available-favs label, #available-favs label span { white-space: normal; display: inline; } #available-favs label span.zoom { display: none; } #available-favs li:hover label span.zoom { display: block; position: absolute; bottom: 0; left: 10em; background-color: #f7f7f7; border: 1px solid #dfdfdf; padding: .2em; border-radius: .5em; } #user-options label.ib { display: inline-block; width: 14em; padding-right: 1em; } /* --------------------------------------------------------------------- user.php */ .blog-perm { padding-top: 2em; } .blog-perm { margin-top: 2em; font-weight: bold; } .ul-perm { list-style-type: square; margin-left: 0; padding-left: 3.5em; margin-bottom: 0 } .add-perm { padding-top: .5em; padding-left: 2.5em; margin-left: 0; } /* --------------------------------------------------------------------- _charte.php */ .guideline #content h2 { color: #D33800; padding: 2em 0 0 0; margin: 1em 0; font-size: 2em; } .guideline #content h2:first-child { margin-top: 0; padding-top: .5em; } .guideline h3 { margin-top: 2em; } .guideline .dc-update h3 { margin-top: 0; } .guideline .one-box .box { border: 1px solid #dfdfdf; padding: 2px .5em; } .guideline #main-menu ul { margin: 0; padding: 0; font-weight: normal; } .guideline #main-menu li { padding-left: 1em; } /* ------------------------------------------------------------------------------------ CLASSES ------------------------------------------------------------------------------------ */ /* jQuery Autocomplete plugin */ .ac_results { padding: 0px; border: 1px dotted #f90; background-color: white; overflow: hidden; z-index: 99999; } .ac_results ul { width: 100%; list-style-position: outside; list-style: none; padding: 0; margin: 0; } .ac_results li { margin: 0px; padding: 2px 5px; cursor: default; display: block; font-size: 1em; line-height: 16px; overflow: hidden; } .ac_loading { background: transparent url('loader.gif') right center no-repeat; } .ac_over { background-color: #2373A8; color: white; } /* password indicator */ .pw-table { display: table; margin-bottom: 1em; } .pw-cell { display: table-cell; margin-bottom: 1em; } #pwindicator { display: table-cell; vertical-align: bottom; padding-left: 1.5em; height: 3.8em; } #pwindicator .bar { height: 6px; margin-bottom: 4px; } .pw-very-weak .bar { background: #b33630; width: 30px; } .pw-weak .bar { background: #b33630; width: 60px; } .pw-mediocre .bar { background: #f90; width: 90px; } .pw-strong .bar { background: #9bca1c; width: 120px; } .pw-very-strong .bar { background: #9bca1c; width: 150px; } /* ------------------------------------------------------------------ navigation */ /* selects accès rapide */ .anchor-nav { background: #ecf0f1; color: #000; padding: 4px 1em; } .anchor-nav label { vertical-align: bottom; } /* nav links */ .nav_prevnext { margin-bottom: 2em; color: #fff; } .nav_prevnext a, a.back { color: #2373A8; border: 1px solid #dfdfdf; padding: 2px 1.5em; border-radius: .75em; background-color: #f3f3f3; } a.back:before { content: "\ab\a0"; } a.onblog_link { color: #333; float: right; border: 1px solid #eee; padding: 2px 1.5em; border-radius: .75em; background-color: #ECF0F1; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); } /* Pagination */ .pager { margin: 2em 0 1em 0; clear: left; } .pager ul { list-style-type: none; margin: 0; padding: 0; } .pager li, .pager input { display: inline-block; vertical-align: middle; margin: 0 .33em 0 0; padding: 0; text-align: center; } .pager .btn { border: 1px solid #dfdfdf; background-color: #fcfcfc; color: #676e78; border-radius: 3px; overflow: hidden; } .btn.no-link { border-color: #dfdfdf; background-color: #f9f9f9; padding: 1px 3px 0; } .pager .active { padding: 4px 12px; color: #676e78; } .pager .direct-access { margin-left: 2em; } .direct-access input[type=text] { border: 1px solid #dfdfdf; padding: 3px 8px; margin-left: .25em; background-color: #fff; } .direct-access input[type=submit] { padding: 3px 6px; } .pager a { display: block; padding: 1px 3px 0; border: none; } .pager a:hover, .pager a:focus { background-color: #ecf0f1; } .index .btn.no-link, .index a { padding: 2px 8px 3px; font-variant: small-caps; } .index li {margin-bottom: 3px;} .index a { font-weight: bold; } .index .btn.no-link { color: #ccc; } .index .active { padding: 4px 8px; color: #fff; background: #676e78; border-radius: 3px; font-variant: small-caps; } /* Etapes */ .step { display: inline-block; float: left; margin: 3px 10px 2px 0; padding: 5px .5em; background: #ecf0f1; border-radius: 3px; font-weight: bold; border: 1px solid #c5c5c5; color: #676e78; } /* ---------------------------------------------------------------- utilisables partout */ .legible { font-size: 1.16em; max-width: 62em; } .fieldset { background: #fff; border: 1px solid #c5c5c5; border-radius: 3px; padding: 1em .7em .5em; margin-bottom: 1em; } .fieldset h3 { margin-top: 0; } .right, .txt-right { text-align: right; } .txt-center { text-align: center; } .txt-left { text-align: left; } .no-margin, label.no-margin { margin-top: 0; margin-bottom: 0; } .vertical-separator { margin-top: 2em; } p.clear.vertical-separator { padding-top: 2em; } .border-top { border-top: 1px solid #999; padding-top: 1em; margin-top: 1em; } .grid { background: transparent repeat url('grid.png') 0 0; } ul.nice { margin: 1em 0; padding: 0 0 0 2em; list-style: square; } ul.nice li { margin: 0; padding: 0; } ul.from-left { list-style-type: none; padding-left: 0; margin: 1em 0; } ul.from-left > li { margin-top: 1em; margin-bottom: 1em; } ul.from-left ul { list-style-type: square; } .offline { color: #676e78; } /* caché pour tout le monde */ .hide, .button.hide { display: none !important; } /* Caché sauf pour les revues d'écran */ .hidden, .with-js .out-of-screen-if-js { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px, 1px, 1px, 1px); padding: 0 !important; border: 0 !important; height: 1px !important; width: 1px !important; overflow: hidden; } /* caché si js est inactif */ .no-js .hidden-if-no-js { display: none; } /* caché si js est actif */ .with-js .hidden-if-js { display: none; } /* ------------------------------------------------------------------------------------ UTILS ------------------------------------------------------------------------------------ */ /* debug */ #debug { position: absolute; top: 0; width: 100%; height: 4px; background: #ffd478; } #debug div { display: none; padding: 3px 0.5em 2px; } #debug p { margin: 0.5em 0; } #debug:hover { height: auto; padding: 2px 1em; z-index: 100; } #debug:hover div { display: block; } .debug { background: #ffd478; padding: 3px 0.5em 2px; } input[type=submit].delete.debug, a.delete.debug { border-color: #ffd478; } input[type=submit].delete.debug:hover, a.delete.debug:hover { background: #ffd478; color: #900; border-color: #ffd478; } /* ---------------------------------------------- Couleurs ajoutées via javascript /* color-picker.js */ .color-color-picker { border: 1px solid #000; width: 195px; background: #fff; } /* _media_item.js */ .color-div { border: 1px solid #ccc; } /* fadings ('color' est utilisé comme variable, pas comme text color) */ .colorBeginPassword, .colorBeginValidatorErr, .colorBeginUserMail { color: #fff; } .colorEndPassword, .colorEndError, .colorEndValidatorErr, .colorEndUserMail { color: #ffbaba; } .colorBeginMessage { color: #ccc; } .colorEndMessage, .colorBeginValidatorMsg { color: #676e78; } .colorBeginError { color: #fefacd; } .colorBeginSuccess { color: #9BCA1C; } .colorEndSuccess { color: #bee74b; } .colorEndValidatorMsg { color: #ffcc00; } /* ------------------------------------------------------------------------------------ UN POIL DE MEDIA QUERIES ------------------------------------------------------------------------------------ */ @media screen and (min-width: 80em) { #wrapper { background: #F7F7F7 url(bg_wrapper.png) repeat-y 18em; } #main { margin-left: -17em; } #content { margin: 0 0 0 17em; } #main-menu { width: 17em; } #collapser { left: 17em; } h1 { width: 19.5em; } } @media screen and (max-width: 61em) { #top-info-blog #switchblog { max-width: 16em; } #top-info-blog a { margin-left: 2em; } #header { display: block; width: 100%; text-align: right; background: #333; } #header h1, #header h1 a { width: 120px; padding: 0; margin: 0; } h1, #top-info-blog { display: inline-block; vertical-align: top; margin-right: 1em; } #top-info-user { display: block; width: 100%; background: #676e78; padding-right: 0; } #top-info-user li:last-child { padding-right: 1em; } #top-info-user a.active { padding: 2px 8px; background: #999; color: #FFF; border-width: 0; border-radius: 6px; } .three-boxes, .three-boxes .box, .two-cols .col70, .two-cols .col30 { width: 100%; margin-left: 0; margin-right: 0; } } @media screen and (max-width: 48em) { #dashboard-boxes .box.medium, .box.medium, #dashboard-boxes .box.small, .box.small, #dashboard-boxes .box.large, .box.large { width: 95%; margin: 10px auto; } } @media screen and (max-width: 44em) { #help-button { height: 26px; width: 26px; background-color: #A2CBE9; padding: 0; margin: 0; font-size: .83em; line-height: 68px; overflow: hidden; } #content.with-help #help-button { top: 77px; } .one-box, .two-boxes, .box, .two-cols .col { width: 96%; margin-left: 0; margin-right: 0; } #entry-wrapper { float: none; width: 100%; margin-right: 0; } #entry-content { margin-right: 0; margin-left: 0; } #entry-sidebar { width: 100%; float: none; } } @media screen and (max-width: 38em) { #header h1, #header h1 a { width: 42px !important; height: 42px; } h1 a:link { background: transparent url(dc_logos/b-dotclear120.png) no-repeat -270px 6px; border-right: 1px solid #ccc; } h1 a:hover, h1 a:focus { background: url(dc_logos/b-dotclear120.png) no-repeat -270px -94px; border-right: 1px solid #A2CBE9; } #wrapper, #main, #main-menu { display: block; float: none; width: 100%; margin: 0; } #dashboard-main { padding: 0; } #main-menu a { display: block; width: 100%; } #main-menu h3 a { display: inline; } #content, .hide-mm #content { margin: 0; padding: 0 .5em !important; } #collapser { display: none; } #main #content > h2 { margin: 0 -.5em 1em; padding: 6px 30px 4px .5em; } #dashboard-boxes .box.medium, .box.medium, #dashboard-boxes .box.small, .box.small, #dashboard-boxes .box.large, .box.large { width: 95%; margin: 10px auto; } .cell, #filters-form .cell { display: inline-block; border: none; padding: 1em; vertical-align: bottom; } .pseudo-tabs li { display: block; float: left; width: 50%; border-top: 1px solid #ddd; padding: .25em; } .pseudo-tabs li:first-child, .pseudo-tabs li:nth-of-type(2) { border-top: none; } } @media screen and (max-width: 26.5em) { h1, h1 a { padding: 0; border-right: #333 !important; } #top-info-blog label, .nomobile { display: none; } #top-info-blog { margin-bottom: .5em; max-width: 75%; } #top-info-blog select { margin-bottom: .5em; } #wrapper { font-size: 1.4em; } #content.with-help #help-button { top: 120px; right: 20.5em; } #content.with-help #help { font-size: 12px; } p.top-add { margin-bottom: .5em; text-align: center; } .multi-part { padding-left: 0; } .part-tabs ul { margin: 1em 0; padding: 0 .5em; } .part-tabs li a { display: block; width: 100%; } #icons p { width: 9em; padding: 1em .25em; } .media-item { width: 90%; } #theme-new, #theme-activate, #theme-deactivate { margin-left: 0; margin-right: 0; } .box.current-theme { margin: 5px; padding: 10px; width: 100%; } .current-theme .module-sshot img { margin: 0; float: none; max-width: 100%; } table .maximal { min-width: 14em; } th, td { padding: 0.3em 1em 0.3em 0; } .pseudo-tabs li { display: block; width: 100%; float: none; border-top: 1px solid #ddd !important; } .pseudo-tabs li:first-child { border-top: none; } }
dascritch/dotclear
admin/style/default.css
CSS
gpl-2.0
57,881
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Poisson Distribution &mdash; SciPy v0.16.1 Reference Guide</title> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-bootstrap.css"> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-extend.css"> <link rel="stylesheet" href="../../static_/scipy.css" type="text/css" > <link rel="stylesheet" href="../../static_/pygments.css" type="text/css" > <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '0.16.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../static_/jquery.js"></script> <script type="text/javascript" src="../../static_/underscore.js"></script> <script type="text/javascript" src="../../static_/doctools.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../../static_/js/copybutton.js"></script> <link rel="top" title="SciPy v0.16.1 Reference Guide" href="../../index.html" > </head> <body> <div class="container"> <div class="header"> </div> </div> <div class="container"> <div class="main"> <div class="row-fluid"> <div class="span12"> <div class="spc-navbar"> <ul class="nav nav-pills pull-left"> <li class="active"><a href="../../index.html">SciPy v0.16.1 Reference Guide</a></li> </ul> <ul class="nav nav-pills pull-right"> <li class="active"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a> </li> <li class="active"> <a href="../../py-modindex.html" title="Python Module Index" >modules</a> </li> <li class="active"> <a href="../../scipy-optimize-modindex.html" title="Python Module Index" >modules</a> </li> </ul> </div> </div> </div> <div class="row-fluid"> <div class="spc-rightsidebar span3"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../../index.html"> <img class="logo" src="../../static_/scipyshiny_small.png" alt="Logo"> </a></p> </div> </div> <div class="span9"> <div class="bodywrapper"> <div class="body" id="spc-section-body"> <div class="section" id="poisson-distribution"> <span id="discrete-poisson"></span><h1>Poisson Distribution<a class="headerlink" href="#poisson-distribution" title="Permalink to this headline">¶</a></h1> <p>The Poisson random variable counts the number of successes in <span class="math">\(n\)</span> independent Bernoulli trials in the limit as <span class="math">\(n\rightarrow\infty\)</span> and <span class="math">\(p\rightarrow0\)</span> where the probability of success in each trial is <span class="math">\(p\)</span> and <span class="math">\(np=\lambda\geq0\)</span> is a constant. It can be used to approximate the Binomial random variable or in it&#8217;s own right to count the number of events that occur in the interval <span class="math">\(\left[0,t\right]\)</span> for a process satisfying certain &#8220;sparsity &#8220;constraints. The functions are</p> <div class="math"> \[ \begin{eqnarray*} p\left(k;\lambda\right) & = & e^{-\lambda}\frac{\lambda^{k}}{k!}\quad k\geq0,\\ F\left(x;\lambda\right) & = & \sum_{n=0}^{\left\lfloor x\right\rfloor }e^{-\lambda}\frac{\lambda^{n}}{n!}=\frac{1}{\Gamma\left(\left\lfloor x\right\rfloor +1\right)}\int_{\lambda}^{\infty}t^{\left\lfloor x\right\rfloor }e^{-t}dt,\\ \mu & = & \lambda\\ \mu_{2} & = & \lambda\\ \gamma_{1} & = & \frac{1}{\sqrt{\lambda}}\\ \gamma_{2} & = & \frac{1}{\lambda}.\end{eqnarray*}\]</div><div class="math"> \[ M\left(t\right)=\exp\left[\lambda\left(e^{t}-1\right)\right].\]</div><p>Implementation: <a class="reference internal" href="../../generated/scipy.stats.poisson.html#scipy.stats.poisson" title="scipy.stats.poisson"><tt class="xref py py-obj docutils literal"><span class="pre">scipy.stats.poisson</span></tt></a></p> </div> </div> </div> </div> </div> </div> </div> <div class="container container-navbar-bottom"> <div class="spc-navbar"> </div> </div> <div class="container"> <div class="footer"> <div class="row-fluid"> <ul class="inline pull-left"> <li> &copy; Copyright 2008-2014, The Scipy community. </li> <li> Last updated on Oct 24, 2015. </li> <li> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </li> </ul> </div> </div> </div> </body> </html>
platinhom/ManualHom
Coding/Python/scipy-html-0.16.1/tutorial/stats/discrete_poisson.html
HTML
gpl-2.0
4,971
# # Walldo - A wallpaper downloader # Copyright (C) 2012 Fernando Castillo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import unittest from walldo.parser import Parser; class ParserTestCase(unittest.TestCase): lines = ['<select class="select" style="margin: 0 2px 0 0; margin-top: 4px; float: left; width: 145px; max-width: 145px;" name="resolution" onChange="javascript:imgload(\'ithilien\', this,\'2949\')">'] expected = ['/wallpaper/7yz4ma1/2949_ithilien_1024x768.jpg'] def setUp(self): self.parser = Parser() def testParse(self): current = self.parser.parse(self.lines, '1024x768') for i in range(len(current)): self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
skibyte/walldo
walldo/parsertestcase.py
Python
gpl-2.0
1,409
<?php /** * @version $Id: mod_communitysurvey.php 01 2011-11-08 11:37:09Z maverick $ * @package CoreJoomla.Surveys * @subpackage Modules.site * @copyright Copyright (C) 2009 - 2012 corejoomla.com, Inc. All rights reserved. * @author Maverick * @link http://www.corejoomla.com/ * @license License GNU General Public License version 2 or later */ //don't allow other scripts to grab and execute our file defined('_JEXEC') or die('Direct Access to this location is not allowed.'); defined('S_APP_NAME') or define('S_APP_NAME', 'com_communitysurveys'); // include the helper file require_once(dirname(__FILE__).'/helper.php'); require_once(JPATH_SITE.'/components/com_communitysurveys/router.php'); require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/constants.php'); require_once(JPATH_SITE.'/components/com_communitysurveys/helpers/helper.php'); // CJLib includes $cjlib = JPATH_ROOT.'/components/com_cjlib/framework.php'; if(file_exists($cjlib)){ require_once $cjlib; }else{ die('CJLib (CoreJoomla API Library) component not found. Please download and install it to continue.'); } CJLib::import('corejoomla.framework.core'); // Get the properties $show_latest = intval($params->get('show_latest','1')); $show_popular = intval($params->get('show_most_popular','1')); $show_tabs = intval($params->get('show_tabs','1')); $tab_order = trim($params->get('tab_order', 'L,M')); // Get the item id for community answers $itemid = CJFunctions::get_active_menu_id(true, 'index.php?option='.S_APP_NAME.'&view=survey'); $document = JFactory::getDocument(); $document->addStyleSheet(JURI::base(true).'/modules/mod_communitysurveys/assets/communitysurveys.css'); // get the items to display from the helper $order = explode(',', $tab_order); if($show_tabs == 1){ CJLib::import('corejoomla.ui.bootstrap', true); echo '<div id="cj-wrapper">'; echo '<ul class="nav nav-tabs" data-tabs="tabs">'; foreach ($order as $i=>$tab){ if((strcmp($tab, "L") == 0) && $show_latest){ echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-1" data-toggle="tab">'.JText::_('LBL_LATEST_SURVEYS').'</a></li>'; } if((strcmp($tab, 'M') == 0) && $show_popular){ echo '<li'.($i == 0 ? ' class="active"' : '').'><a href="#cstab-2" data-toggle="tab">'.JText::_('LBL_MOST_POPULAR_SURVEYS').'</a></li>'; } } echo '</ul>'; foreach ($order as $i=>$tab){ if((strcmp($tab,'L') == 0) && $show_latest){ $latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params); echo '<div id="cstab-1" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">'; require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys')); echo '</div>'; } if((strcmp($tab,'M') == 0) && $show_popular){ $popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params); echo '<div id="cstab-2" class="tab-pane fade'.($i == 0 ? ' in active' : '').'">'; require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular')); echo '</div>'; } } echo '</div>'; }else{ foreach ($order as $tab){ if((strcmp($tab,'L') == 0) && $show_latest){ $latest_surveys = modCommunitySurveysHelper::getLatestSurveys($params); require(JModuleHelper::getLayoutPath('mod_communitysurveys','latest_surveys')); } if((strcmp($tab,'M') == 0) && $show_popular){ $popular_surveys = modCommunitySurveysHelper::getMostPopularSurveys($params); require(JModuleHelper::getLayoutPath('mod_communitysurveys','most_popular')); } } } ?>
LauraRey/oacfdc
modules/mod_communitysurveys/mod_communitysurveys.php
PHP
gpl-2.0
3,653
#!/usr/bin/perl -w # This script was originally based on the script of the same name from # the KDE SDK (by [email protected]) # # This version is # Copyright (C) 2007, 2008 Adam D. Barratt # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. =head1 NAME licensecheck - simple license checker for source files =head1 SYNOPSIS B<licensecheck> B<--help|--version> B<licensecheck> [B<--no-conf>] [B<--verbose>] [B<--copyright>] [B<-l|--lines=N>] [B<-i|--ignore=regex>] [B<-c|--check=regex>] [B<-r|--recursive>] I<list of files and directories to check> =head1 DESCRIPTION B<licensecheck> attempts to determine the license that applies to each file passed to it, by searching the start of the file for text belonging to various licenses. If any of the arguments passed are directories, B<licensecheck> will add the files contained within to the list of files to process. =head1 OPTIONS =over 4 =item B<--verbose> B<--no-verbose> Specify whether to output the text being processed from each file before the corresponding license information. Default is to be quiet. =item B<-l=N> B<--lines=N> Specify the number of lines of each file's header which should be parsed for license information. (Default is 60). =item B<-i=regex> B<--ignore=regex> When processing the list of files and directories, the regular expression specified by this option will be used to indicate those which should not be considered (e.g. backup files, VCS metadata). =item B<-r> B<--recursive> Specify that the contents of directories should be added recursively. =item B<-c=regex> B<--check=regex> Specify a pattern against which filenames will be matched in order to decide which files to check the license of. The default includes common source files. =item B<--copyright> Also display copyright text found within the file =item B<--no-conf> B<--noconf> Do not read any configuration files. This can only be used as the first option given on the command-line. =back =head1 CONFIGURATION VARIABLES The two configuration files F<__SYSCONFDIR__/rpmdevtools/devscripts.conf> and F<~/.devscripts> are sourced by a shell in that order to set configuration variables. Command line options can be used to override configuration file settings. Environment variable settings are ignored for this purpose. The currently recognised variables are: =over 4 =item B<LICENSECHECK_VERBOSE> If this is set to I<yes>, then it is the same as the --verbose command line parameter being used. The default is I<no>. =item B<LICENSECHECK_PARSELINES> If this is set to a positive number then the specified number of lines at the start of each file will be read whilst attempting to determine the license(s) in use. This is equivalent to the --lines command line option. =back =head1 LICENSE This code is copyright by Adam D. Barratt <[email protected]>, all rights reserved; based on a script of the same name from the KDE SDK, which is copyright by <[email protected]>. This program comes with ABSOLUTELY NO WARRANTY. You are free to redistribute this code under the terms of the GNU General Public License, version 2 or later. =head1 AUTHOR Adam D. Barratt <[email protected]> =cut use strict; use warnings; use Getopt::Long; use File::Basename; sub fatal($); sub parse_copyright($); sub parselicense($); my $progname = basename($0); # From dpkg-source my $default_ignore_regex = ' # Ignore general backup files (?:^|/).*~$| # Ignore emacs recovery files (?:^|/)\.#.*$| # Ignore vi swap files (?:^|/)\..*\.swp$| # Ignore baz-style junk files or directories (?:^|/),,.*(?:$|/.*$)| # File-names that should be ignored (never directories) (?:^|/)(?:DEADJOE|\.cvsignore|\.arch-inventory|\.bzrignore|\.gitignore)$| # File or directory names that should be ignored (?:^|/)(?:CVS|RCS|\.deps|\{arch\}|\.arch-ids|\.svn|\.hg|_darcs|\.git| \.shelf|_MTN|\.bzr(?:\.backup|tags)?)(?:$|/.*$) '; # Take out comments and newlines $default_ignore_regex =~ s/^#.*$//mg; $default_ignore_regex =~ s/\n//sg; my $default_check_regex = '\.(c(c|pp|xx)?|h(h|pp|xx)?|f(77|90)?|p(l|m)|xs|sh|php|py|rb|java|vala|el|sc(i|e)|cs)$'; my $modified_conf_msg; my ($opt_verbose, $opt_lines, $opt_noconf, $opt_ignore_regex, $opt_check_regex) = ('', '', '', '', ''); my $opt_recursive = 0; my $opt_copyright = 0; my ($opt_help, $opt_version); my $def_lines = 60; # Read configuration files and then command line # This is boilerplate if (@ARGV and $ARGV[0] =~ /^--no-?conf$/) { $modified_conf_msg = " (no configuration files read)"; shift; } else { my @config_files = ('__SYSCONFDIR__/rpmdevtools/devscripts.conf', '~/.devscripts'); my %config_vars = ( 'LICENSECHECK_VERBOSE' => 'no', 'LICENSECHECK_PARSELINES' => $def_lines, ); my %config_default = %config_vars; my $shell_cmd; # Set defaults foreach my $var (keys %config_vars) { $shell_cmd .= qq[$var="$config_vars{$var}";\n]; } $shell_cmd .= 'for file in ' . join(" ", @config_files) . "; do\n"; $shell_cmd .= '[ -f $file ] && . $file; done;' . "\n"; # Read back values foreach my $var (keys %config_vars) { $shell_cmd .= "echo \$$var;\n" } my $shell_out = `/bin/bash -c '$shell_cmd'`; @config_vars{keys %config_vars} = split /\n/, $shell_out, -1; # Check validity $config_vars{'LICENSECHECK_VERBOSE'} =~ /^(yes|no)$/ or $config_vars{'LICENSECHECK_VERBOSE'} = 'no'; $config_vars{'LICENSECHECK_PARSELINES'} =~ /^[1-9][0-9]*$/ or $config_vars{'LICENSECHECK_PARSELINES'} = $def_lines; foreach my $var (sort keys %config_vars) { if ($config_vars{$var} ne $config_default{$var}) { $modified_conf_msg .= " $var=$config_vars{$var}\n"; } } $modified_conf_msg ||= " (none)\n"; chomp $modified_conf_msg; $opt_verbose = $config_vars{'LICENSECHECK_VERBOSE'} eq 'yes' ? 1 : 0; $opt_lines = $config_vars{'LICENSECHECK_PARSELINES'}; } GetOptions("help|h" => \$opt_help, "version|v" => \$opt_version, "verbose!" => \$opt_verbose, "lines|l=i" => \$opt_lines, "ignore|i=s" => \$opt_ignore_regex, "recursive|r" => \$opt_recursive, "check|c=s" => \$opt_check_regex, "copyright" => \$opt_copyright, "noconf" => \$opt_noconf, "no-conf" => \$opt_noconf, ) or die "Usage: $progname [options] filelist\nRun $progname --help for more details\n"; $opt_lines = $def_lines if $opt_lines !~ /^[1-9][0-9]*$/; $opt_ignore_regex = $default_ignore_regex if ! length $opt_ignore_regex; $opt_check_regex = $default_check_regex if ! length $opt_check_regex; if ($opt_noconf) { fatal "--no-conf is only acceptable as the first command-line option!"; } if ($opt_help) { help(); exit 0; } if ($opt_version) { version(); exit 0; } die "Usage: $progname [options] filelist\nRun $progname --help for more details\n" unless @ARGV; $opt_lines = $def_lines if not defined $opt_lines; my @files = (); my @find_args = (); my $files_count = @ARGV; push @find_args, qw(-maxdepth 1) unless $opt_recursive; push @find_args, qw(-follow -type f -print); while (@ARGV) { my $file = shift @ARGV; if (-d $file) { open FIND, '-|', 'find', $file, @find_args or die "$progname: couldn't exec find: $!\n"; while (<FIND>) { chomp; next unless m%$opt_check_regex%; # Skip empty files next if (-z $_); push @files, $_ unless m%$opt_ignore_regex%; } close FIND; } else { next unless ($files_count == 1) or $file =~ m%$opt_check_regex%; push @files, $file unless $file =~ m%$opt_ignore_regex%; } } while (@files) { my $file = shift @files; my $content = ''; my $copyright_match; my $copyright = ''; my $license = ''; my %copyrights; open (F, "<$file") or die "Unable to access $file\n"; while (<F>) { last if ($. > $opt_lines); $content .= $_; $copyright_match = parse_copyright($_); if ($copyright_match) { $copyrights{lc("$copyright_match")} = "$copyright_match"; } } close(F); $copyright = join(" / ", values %copyrights); print qq(----- $file header -----\n$content----- end header -----\n\n) if $opt_verbose; $content =~ tr/\t\r\n/ /; # Remove C / C++ comments $content =~ s#(\*/|/[/*])##g; $content =~ tr% A-Za-z.,@;0-9\(\)/-%%cd; $content =~ s/ c //g; # Remove fortran comments $content =~ tr/ //s; $license = parselicense($content); print "$file: "; print "*No copyright* " unless $copyright; print $license . "\n"; print " [Copyright: " . $copyright . "]\n" if $copyright and $opt_copyright; print "\n" if $opt_copyright; } sub parse_copyright($) { my $copyright = ''; my $match; my $copyright_indicator_regex = ' (?:copyright # The full word |copr\. # Legally-valid abbreviation |\x{00a9} # Unicode character COPYRIGHT SIGN |\xc2\xa9 # Unicode copyright sign encoded in iso8859 |\(c\) # Legally-null representation of sign )'; my $copyright_disindicator_regex = ' \b(?:info(?:rmation)? # Discussing copyright information |notice # Discussing the notice |and|or # Part of a sentence )\b'; if (m%$copyright_indicator_regex(?::\s*|\s+)(\S.*)$%ix) { $match = $1; # Ignore lines matching "see foo for copyright information" etc. if ($match !~ m%^\s*$copyright_disindicator_regex%ix) { # De-cruft $match =~ s/([,.])?\s*$//; $match =~ s/$copyright_indicator_regex//igx; $match =~ s/^\s+//; $match =~ s/\s{2,}/ /g; $match =~ s/\\@/@/g; $copyright = $match; } } return $copyright; } sub help { print <<"EOF"; Usage: $progname [options] filename [filename ...] Valid options are: --help, -h Display this message --version, -v Display version and copyright info --no-conf, --noconf Don't read devscripts config files; must be the first option given --verbose Display the header of each file before its license information --lines, -l Specify how many lines of the file header should be parsed for license information (Default: $def_lines) --check, -c Specify a pattern indicating which files should be checked (Default: '$default_check_regex') --recursive, -r Add the contents of directories recursively --copyright Also display the file's copyright --ignore, -i Specify that files / directories matching the regular expression should be ignored when checking files (Default: '$default_ignore_regex') Default settings modified by devscripts configuration files: $modified_conf_msg EOF } sub version { print <<"EOF"; This is $progname, from the Debian devscripts package, version ###VERSION### Copyright (C) 2007, 2008 by Adam D. Barratt <adam\@adam-barratt.org.uk>; based on a script of the same name from the KDE SDK by <dfaure\@kde.org>. This program comes with ABSOLUTELY NO WARRANTY. You are free to redistribute this code under the terms of the GNU General Public License, version 2, or (at your option) any later version. EOF } sub parselicense($) { my ($licensetext) = @_; my $gplver = ""; my $extrainfo = ""; my $license = ""; if ($licensetext =~ /version ([^ ]+) (?:\(?only\)?.? )?(?:of the GNU (Affero )?General Public License )?as published by the Free Software Foundation/i or $licensetext =~ /GNU (?:Affero )?General Public License as published by the Free Software Foundation; version ([^ ]+) /i) { $gplver = " (v$1)"; } elsif ($licensetext =~ /GNU (Affero ?)General Public License, version ([^ ]+?)[ .]/) { $gplver = " (v$1)"; } elsif ($licensetext =~ /either version ([^ ]+) of the License, or \(at your option\) any later version/) { $gplver = " (v$1 or later)"; } if ($licensetext =~ /(?:675 Mass Ave|59 Temple Place|51 Franklin Steet|02139|02111-1307)/i) { $extrainfo = " (with incorrect FSF address)$extrainfo"; } if ($licensetext =~ /permission (?:is (also granted|given))? to link (the code of )?this program with (any edition of )?(Qt|the Qt library)/i) { $extrainfo = " (with Qt exception)$extrainfo" } if ($licensetext =~ /(All changes made in this file will be lost|DO NOT (EDIT|delete this file)|Generated by)/i) { $license = "GENERATED FILE"; } if ($licensetext =~ /is free software.? you can redistribute it and\/or modify it under the terms of the (GNU (Library|Lesser) General Public License|LGPL)/i) { $license = "LGPL$gplver$extrainfo $license"; } if ($licensetext =~ /is free software.? you can redistribute it and\/or modify it under the terms of the (GNU Affero General Public License|AGPL)/i) { $license = "AGPL$gplver$extrainfo $license"; } if ($licensetext =~ /is free software.? you (can|may) redistribute it and\/or modify it under the terms of (?:version [^ ]+ (?:\(?only\)? )?of )?the GNU General Public License/i) { $license = "GPL$gplver$extrainfo $license"; } if ($licensetext =~ /is distributed under the terms of the GNU General Public License,/ and length $gplver) { $license = "GPL$gplver$extrainfo $license"; } if ($licensetext =~ /is distributed.*terms.*GPL/) { $license = "GPL (unversioned/unknown version) $license"; } if ($licensetext =~ /This file is part of the .*Qt GUI Toolkit. This file may be distributed under the terms of the Q Public License as defined/) { $license = "QPL (part of Qt) $license"; } elsif ($licensetext =~ /may be distributed under the terms of the Q Public License as defined/) { $license = "QPL $license"; } if ($licensetext =~ /http:\/\/opensource\.org\/licenses\/mit-license\.php/) { $license = "MIT/X11 (BSD like) $license"; } elsif ($licensetext =~ /Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files \(the Software\), to deal in the Software/) { $license = "MIT/X11 (BSD like) $license"; } if ($licensetext =~ /Permission to use, copy, modify, and(\/or)? distribute this software for any purpose with or without fee is hereby granted, provided.*copyright notice.*permission notice.*all copies/) { $license = "ISC $license"; } if ($licensetext =~ /THIS SOFTWARE IS PROVIDED .*AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY/) { if ($licensetext =~ /All advertising materials mentioning features or use of this software must display the following acknowledge?ment.*This product includes software developed by/i) { $license = "BSD (4 clause) $license"; } elsif ($licensetext =~ /(The name of .*? may not|Neither the names? of .*? nor the names of (its|their) contributors may) be used to endorse or promote products derived from this software/i) { $license = "BSD (3 clause) $license"; } elsif ($licensetext =~ /Redistributions of source code must retain the above copyright notice/i) { $license = "BSD (2 clause) $license"; } else { $license = "BSD $license"; } } if ($licensetext =~ /Mozilla Public License Version ([^ ]+)/) { $license = "MPL (v$1) $license"; } if ($licensetext =~ /Released under the terms of the Artistic License ([^ ]+)/) { $license = "Artistic (v$1) $license"; } if ($licensetext =~ /is free software under the Artistic [Ll]icense/) { $license = "Artistic $license"; } if ($licensetext =~ /This program is free software; you can redistribute it and\/or modify it under the same terms as Perl itself/) { $license = "Perl $license"; } if ($licensetext =~ /under the Apache License, Version ([^ ]+) \(the License\)/) { $license = "Apache (v$1) $license"; } if ($licensetext =~ /This source file is subject to version ([^ ]+) of the PHP license/) { $license = "PHP (v$1) $license"; } if ($licensetext =~ /under the terms of the CeCILL /) { $license = "CeCILL $license"; } if ($licensetext =~ /under the terms of the CeCILL-([^ ]+) /) { $license = "CeCILL-$1 $license"; } if ($licensetext =~ /under the SGI Free Software License B/) { $license = "SGI Free Software License B $license"; } if ($licensetext =~ /is in the public domain/i) { $license = "Public domain"; } if ($licensetext =~ /terms of the Common Development and Distribution License(, Version ([^(]+))? \(the License\)/) { $license = "CDDL " . ($1 ? "(v$2) " : '') . $license; } if ($licensetext =~ /Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license \(the \"Software\"\)/ or $licensetext =~ /Boost Software License([ ,-]+Version ([^ ]+)?(\.))/i) { $license = "BSL " . ($1 ? "(v$2) " : '') . $license; } if ($licensetext =~ /PYTHON SOFTWARE FOUNDATION LICENSE (VERSION ([^ ]+))/i) { $license = "PSF " . ($1 ? "(v$2) " : '') . $license; } if ($licensetext =~ /The origin of this software must not be misrepresented.*Altered source versions must be plainly marked as such.*This notice may not be removed or altered from any source distribution/ or $licensetext =~ /see copyright notice in zlib\.h/) { $license = "zlib/libpng $license"; } if ($licensetext =~ /Do What The Fuck You Want To Public License, Version ([^, ]+)/i) { $license = "WTFPL (v$1)"; } if ($licensetext =~ /Do what The Fuck You Want To Public License/i) { $license = "WTFPL"; } if ($licensetext =~ /(License WTFPL|Under (the|a) WTFPL)/i) { $license = "WTFPL"; } $license = "UNKNOWN" if (!length($license)); return $license; } sub fatal($) { my ($pack,$file,$line); ($pack,$file,$line) = caller(); (my $msg = "$progname: fatal error at line $line:\n@_\n") =~ tr/\0//d; $msg =~ s/\n\n$/\n/; die $msg; }
RsrchBoy/rpmdevtools
devscripts/scripts/licensecheck.pl
Perl
gpl-2.0
18,704
#!/bin/sh if [ $# -gt 0 ]; then echo $1 > .version fi buildid=$(( $1 + 1 )) zipfile="Chroma.Kernel-r$buildid.zip" . ./env_setup.sh ${1} || exit 1; if [ -e .config ]; then rm .config fi cp arch/arm/configs/aosp_defconfig .config >> /dev/null make aosp_defconfig >> /dev/null make -j$NUMBEROFCPUS CONFIG_NO_ERROR_ON_MISMATCH=y cp arch/arm/boot/zImage-dtb ramdisk/ cd ramdisk/ ./mkbootfs boot.img-ramdisk | gzip > ramdisk.gz ./mkbootimg --kernel zImage-dtb --cmdline 'console=ttyHSL0,115200,n8 androidboot.hardware=hammerhead user_debug=31 msm_watchdog_v2.enable=1' --base 0x00000000 --pagesize 2048 --ramdisk_offset 0x02900000 --tags_offset 0x02700000 --ramdisk ramdisk.gz --output ../boot.img rm -rf ramdisk.gz rm -rf zImage cd .. if [ -e arch/arm/boot/zImage ]; then cp boot.img zip/ rm -rf ramdisk/boot.img cd zip/ rm -f *.zip zip -r -9 $zipfile * rm -f /tmp/*.zip cp *.zip /tmp cd .. else echo "Something goes wrong aborting!" return fi
artcotto/CharizardX_kernel_hammerhead
build.sh
Shell
gpl-2.0
965
""" SALTS XBMC Addon Copyright (C) 2015 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import xbmcaddon import xbmcplugin import xbmcgui import xbmc import xbmcvfs import urllib import urlparse import sys import os import re addon = xbmcaddon.Addon() get_setting = addon.getSetting show_settings = addon.openSettings def get_path(): return addon.getAddonInfo('path').decode('utf-8') def get_profile(): return addon.getAddonInfo('profile').decode('utf-8') def translate_path(path): return xbmc.translatePath(path).decode('utf-8') def set_setting(id, value): if not isinstance(value, basestring): value = str(value) addon.setSetting(id, value) def get_version(): return addon.getAddonInfo('version') def get_id(): return addon.getAddonInfo('id') def get_name(): return addon.getAddonInfo('name') def get_plugin_url(queries): try: query = urllib.urlencode(queries) except UnicodeEncodeError: for k in queries: if isinstance(queries[k], unicode): queries[k] = queries[k].encode('utf-8') query = urllib.urlencode(queries) return sys.argv[0] + '?' + query def end_of_directory(cache_to_disc=True): xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=cache_to_disc) def set_content(content): xbmcplugin.setContent(int(sys.argv[1]), content) def create_item(queries, label, thumb='', fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False): list_item = xbmcgui.ListItem(label, iconImage=thumb, thumbnailImage=thumb) add_item(queries, list_item, fanart, is_folder, is_playable, total_items, menu_items, replace_menu) def add_item(queries, list_item, fanart='', is_folder=None, is_playable=None, total_items=0, menu_items=None, replace_menu=False): if menu_items is None: menu_items = [] if is_folder is None: is_folder = False if is_playable else True if is_playable is None: playable = 'false' if is_folder else 'true' else: playable = 'true' if is_playable else 'false' liz_url = get_plugin_url(queries) if fanart: list_item.setProperty('fanart_image', fanart) list_item.setInfo('video', {'title': list_item.getLabel()}) list_item.setProperty('isPlayable', playable) list_item.addContextMenuItems(menu_items, replaceItems=replace_menu) xbmcplugin.addDirectoryItem(int(sys.argv[1]), liz_url, list_item, isFolder=is_folder, totalItems=total_items) def parse_query(query): q = {'mode': 'main'} if query.startswith('?'): query = query[1:] queries = urlparse.parse_qs(query) for key in queries: if len(queries[key]) == 1: q[key] = queries[key][0] else: q[key] = queries[key] return q def notify(header=None, msg='', duration=2000, sound=None): if header is None: header = get_name() if sound is None: sound = get_setting('mute_notifications') == 'false' icon_path = os.path.join(get_path(), 'icon.png') try: xbmcgui.Dialog().notification(header, msg, icon_path, duration, sound) except: builtin = "XBMC.Notification(%s,%s, %s, %s)" % (header, msg, duration, icon_path) xbmc.executebuiltin(builtin) def get_current_view(): skinPath = translate_path('special://skin/') xml = os.path.join(skinPath, 'addon.xml') f = xbmcvfs.File(xml) read = f.read() f.close() try: src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1) except: src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1) src = os.path.join(skinPath, src, 'MyVideoNav.xml') f = xbmcvfs.File(src) read = f.read() f.close() match = re.search('<views>([^<]+)', read, re.DOTALL) if match: views = match.group(1) for view in views.split(','): if xbmc.getInfoLabel('Control.GetLabel(%s)' % (view)): return view
azumimuo/family-xbmc-addon
plugin.video.salts/salts_lib/kodi.py
Python
gpl-2.0
4,540
using System; using System.Collections.Generic; using UnityEngine; using YinYang.CodeProject.Projects.SimplePathfinding.PathFinders.AStar; namespace YinYang.CodeProject.Projects.SimplePathfinding.PathFinders { public abstract class BaseGraphSearchMap<TNode, TValue> where TNode : BaseGraphSearchNode<TNode, TValue> { #region | Fields | private Dictionary<TValue, TNode> nodes; #endregion #region | Properties | /// <summary> /// Gets the open nodes count. /// </summary> public Int32 OpenCount { get { return OnGetCount(); } } public Dictionary<TValue, TNode> Nodes { get { return nodes; } } #endregion #region | Indexers | /// <summary> /// Gets the <see cref="AStarNode"/> on a given coordinates. /// </summary> public TNode this[TValue value] { get { return nodes[value]; } } #endregion #region | Constructors | /// <summary> /// Initializes a new instance of the <see cref="BaseGraphSearchMap{TNode}"/> class. /// </summary> protected BaseGraphSearchMap() { nodes = new Dictionary<TValue, TNode>(); } #endregion #region | Helper methods | private void OpenNodeInternal(TValue value, TNode result) { nodes[value] = result; OnAddNewNode(result); } #endregion #region | Virtual/abstract methods | protected abstract TNode OnCreateFirstNode(TValue startPosition, TValue endPosition); protected abstract TNode OnCreateNode(TValue position, TNode origin, params object[] arguments); protected abstract Int32 OnGetCount(); protected abstract void OnAddNewNode(TNode result); protected abstract TNode OnGetTopNode(); protected abstract void OnClear(); #endregion #region | Methods | /// <summary> /// Creates new open node on a map at given coordinates and parameters. /// </summary> public void OpenNode(TValue value, TNode origin, params object[] arguments) { TNode result = OnCreateNode(value, origin, arguments); OpenNodeInternal(value, result); } public void OpenFirstNode(TValue startPosition, TValue endPosition) { TNode result = OnCreateFirstNode(startPosition, endPosition); OpenNodeInternal(startPosition, result); } /// <summary> /// Creates the empty node at given point. /// </summary> /// <param name="position">The point.</param> /// <returns></returns> public TNode CreateEmptyNode(TValue position) { return OnCreateNode(position, null); } /// <summary> /// Returns top node (best estimated score), and closes it. /// </summary> /// <returns></returns> public TNode CloseTopNode() { TNode result = OnGetTopNode(); result.MarkClosed(); return result; } /// <summary> /// Clears map for another round. /// </summary> public void Clear() { nodes.Clear(); OnClear(); } #endregion } }
lauw/Albion-Online-Bot
Albion/Merlin/Pathing/BaseGraphSearchMap.cs
C#
gpl-2.0
3,406
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Foam::DICGaussSeidelSmoother Description Combined DIC/GaussSeidel smoother for symmetric matrices in which DIC smoothing is followed by GaussSeidel to ensure that any "spikes" created by the DIC sweeps are smoothed-out. SourceFiles DICGaussSeidelSmoother.C \*---------------------------------------------------------------------------*/ #ifndef DICGaussSeidelSmoother_H #define DICGaussSeidelSmoother_H #include "DICSmoother.H" #include "GaussSeidelSmoother.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class DICGaussSeidelSmoother Declaration \*---------------------------------------------------------------------------*/ class DICGaussSeidelSmoother : public lduSmoother { // Private data DICSmoother dicSmoother_; GaussSeidelSmoother gsSmoother_; public: //- Runtime type information TypeName("DICGaussSeidel"); // Constructors //- Construct from matrix components DICGaussSeidelSmoother ( const lduMatrix& matrix, const FieldField<Field, scalar>& coupleBouCoeffs, const FieldField<Field, scalar>& coupleIntCoeffs, const lduInterfaceFieldPtrsList& interfaces ); // Member Functions //- Execute smoothing virtual void smooth ( scalarField& psi, const scalarField& Source, const direction cmpt, const label nSweeps ) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev
src/OpenFOAM/matrices/lduMatrix/smoothers/DICGaussSeidel/DICGaussSeidelSmoother.H
C++
gpl-2.0
3,048
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "soccerbase.h" #include <oxygen/physicsserver/rigidbody.h> #include <oxygen/physicsserver/spherecollider.h> #include <oxygen/agentaspect/perceptor.h> #include <oxygen/agentaspect/agentaspect.h> #include <oxygen/sceneserver/sceneserver.h> #include <oxygen/sceneserver/scene.h> #include <oxygen/sceneserver/transform.h> #include <oxygen/controlaspect/controlaspect.h> #include <oxygen/gamecontrolserver/gamecontrolserver.h> #include <gamestateaspect/gamestateaspect.h> #include <soccerruleaspect/soccerruleaspect.h> #include <agentstate/agentstate.h> #include <ball/ball.h> #include <oxygen/physicsserver/space.h> #include <zeitgeist/leaf.h> using namespace boost; using namespace zeitgeist; using namespace oxygen; using namespace std; using namespace salt; bool SoccerBase::GetSceneServer(const Leaf& base, boost::shared_ptr<SceneServer>& scene_server) { scene_server = static_pointer_cast<SceneServer> (base.GetCore()->Get("/sys/server/scene")); if (scene_server.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") scene server not found.\n"; return false; } return true; } bool SoccerBase::GetTransformParent(const Leaf& base, boost::shared_ptr<Transform>& transform_parent) { transform_parent = dynamic_pointer_cast<Transform> ((base.FindParentSupportingClass<Transform>()).lock()); if (transform_parent.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") parent node is not derived from TransformNode\n"; return false; } return true; } bool SoccerBase::GetAgentState(const boost::shared_ptr<Transform> transform, boost::shared_ptr<AgentState>& agent_state) { agent_state = dynamic_pointer_cast<AgentState>(transform->GetChild("AgentState", true)); if (agent_state.get() == 0) { return false; } return true; } bool SoccerBase::GetAgentBody(const boost::shared_ptr<Transform> transform, boost::shared_ptr<RigidBody>& agent_body) { agent_body = transform->FindChildSupportingClass<RigidBody>(true); if (agent_body.get() == 0) { transform->GetLog()->Error() << "(SoccerBase) ERROR: " << transform->GetName() << " node has no Body child\n"; return false; } return true; } bool SoccerBase::GetAgentBody(const Leaf& base, TTeamIndex idx, int unum, boost::shared_ptr<RigidBody>& agent_body) { boost::shared_ptr<AgentState> agentState; boost::shared_ptr<Transform> parent; // get matching AgentState if (!GetAgentState(base, idx, unum, agentState)) return false; // get AgentAspect if (!GetTransformParent(*agentState, parent)) return false; // call GetAgentBody with matching AgentAspect return GetAgentBody(parent, agent_body); } bool SoccerBase::GetAgentState(const Leaf& base, boost::shared_ptr<AgentState>& agent_state) { boost::shared_ptr<Transform> parent; if (! GetTransformParent(base,parent)) { return false; } return GetAgentState(parent,agent_state); } bool SoccerBase::GetAgentState(const Leaf& base, TTeamIndex idx, int unum, boost::shared_ptr<AgentState>& agentState) { static TAgentStateMap mAgentStateMapLeft; static TAgentStateMap mAgentStateMapRight; if (idx == TI_NONE) return false; // do we have a cached reference? if ( idx == TI_LEFT && !mAgentStateMapLeft.empty() ) { TAgentStateMap::iterator iter = mAgentStateMapLeft.find(unum); if (iter != mAgentStateMapLeft.end()) { // is the pointer to the parent (AgentAspect) still valid // (maybe the agent disconnected)? if (!(iter->second)->GetParent().lock().get()) { base.GetLog()->Error() << "(SoccerBase) WARNING: " << "AgentState has invalid parent! " << "The agent probably disconnected, removing from map." << "\n"; mAgentStateMapLeft.erase(iter); } else { agentState = (*iter).second; return true; } } } else if ( idx == TI_RIGHT && !mAgentStateMapRight.empty() ) { TAgentStateMap::iterator iter = mAgentStateMapRight.find(unum); if (iter != mAgentStateMapRight.end()) { // is the pointer to the parent (AgentAspect) still valid // (maybe the agent disconnected)? if ((iter->second)->GetParent().lock().get() == 0) { base.GetLog()->Error() << "(SoccerBase) WARNING: " << "AgentState has invalid parent! " << "The agent probably disconnected, removing from map." << "\n"; mAgentStateMapRight.erase(iter); } else { agentState = (*iter).second; return true; } } } // we have to get all agent states for this team TAgentStateList agentStates; GetAgentStates(base, agentStates, idx); for (TAgentStateList::iterator iter = agentStates.begin(); iter != agentStates.end(); ++iter) { if ((*iter)->GetUniformNumber() == unum) { agentState = *iter; if (idx == TI_LEFT) { mAgentStateMapLeft[unum] = agentState; } else { mAgentStateMapRight[unum] = agentState; } return true; } } return false; } bool SoccerBase::GetAgentStates(const zeitgeist::Leaf& base, TAgentStateList& agentStates, TTeamIndex idx) { static boost::shared_ptr<GameControlServer> gameCtrl; if (gameCtrl.get() == 0) { GetGameControlServer(base, gameCtrl); if (gameCtrl.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: can't get " << "GameControlServer\n"; return false; } } GameControlServer::TAgentAspectList aspectList; gameCtrl->GetAgentAspectList(aspectList); GameControlServer::TAgentAspectList::iterator iter; boost::shared_ptr<AgentState> agentState; for ( iter = aspectList.begin(); iter != aspectList.end(); ++iter ) { agentState = dynamic_pointer_cast<AgentState>((*iter)->GetChild("AgentState", true)); if ( agentState.get() != 0 && ( agentState->GetTeamIndex() == idx || idx == TI_NONE ) ) { agentStates.push_back(agentState); } } return true; } bool SoccerBase::GetGameState(const Leaf& base, boost::shared_ptr<GameStateAspect>& game_state) { game_state = dynamic_pointer_cast<GameStateAspect> (base.GetCore()->Get("/sys/server/gamecontrol/GameStateAspect")); if (game_state.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") found no GameStateAspect\n"; return false; } return true; } bool SoccerBase::GetSoccerRuleAspect(const Leaf& base, boost::shared_ptr<SoccerRuleAspect> & soccer_rule_aspect) { soccer_rule_aspect = dynamic_pointer_cast<SoccerRuleAspect> (base.GetCore()->Get("/sys/server/gamecontrol/SoccerRuleAspect")); if (soccer_rule_aspect.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << " found no SoccerRuleAspect\n"; return false; } return true; } bool SoccerBase::GetGameControlServer(const Leaf& base, boost::shared_ptr<GameControlServer> & game_control_server) { static boost::shared_ptr<GameControlServer> gameControlServer; if (gameControlServer.get() == 0) { gameControlServer = boost::dynamic_pointer_cast<GameControlServer> (base.GetCore()->Get("/sys/server/gamecontrol")); if (gameControlServer.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << " found no GameControlServer\n"; return false; } } game_control_server = gameControlServer; return true; } bool SoccerBase::GetActiveScene(const Leaf& base, boost::shared_ptr<Scene>& active_scene) { static boost::shared_ptr<SceneServer> sceneServer; if (sceneServer.get() == 0) { if (! GetSceneServer(base,sceneServer)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get SceneServer\n"; return false; } } active_scene = sceneServer->GetActiveScene(); if (active_scene.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ", SceneServer reports no active scene\n"; return false; } return true; } bool SoccerBase::GetBody(const Leaf& base, boost::shared_ptr<RigidBody>& body) { boost::shared_ptr<Transform> parent; if (! GetTransformParent(base,parent)) { base.GetLog()->Error() << "(SoccerBase) ERROR: no transform parent " << "found in GetBody()\n"; return false; } body = dynamic_pointer_cast<RigidBody>(parent->FindChildSupportingClass<RigidBody>()); if (body.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ") parent node has no Body child."; return false; } return true; } bool SoccerBase::GetBall(const Leaf& base, boost::shared_ptr<Ball>& ball) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<Ball> ballRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (ballRef.get() == 0) { ballRef = dynamic_pointer_cast<Ball> (base.GetCore()->Get(scene->GetFullPath() + "Ball")); if (ballRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", found no ball node\n"; return false; } } ball = ballRef; return true; } bool SoccerBase::GetBallBody(const Leaf& base, boost::shared_ptr<RigidBody>& body) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<RigidBody> bodyRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (bodyRef.get() == 0) { bodyRef = dynamic_pointer_cast<RigidBody> (base.GetCore()->Get(scene->GetFullPath() + "Ball/physics")); if (bodyRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", found no ball body node\n"; return false; } } body = bodyRef; return true; } bool SoccerBase::GetBallCollider(const zeitgeist::Leaf& base, boost::shared_ptr<oxygen::SphereCollider>& sphere) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<SphereCollider> sphereRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (sphereRef.get() == 0) { sphereRef = dynamic_pointer_cast<SphereCollider> (base.GetCore()->Get(scene->GetFullPath() + "Ball/geometry")); if (sphereRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR:" << base.GetName() << ", Ball got no SphereCollider node\n"; return false; } } sphere = sphereRef; return true; } salt::Vector3f SoccerBase::FlipView(const salt::Vector3f& pos, TTeamIndex ti) { salt::Vector3f newPos; switch (ti) { case TI_RIGHT: newPos[0] = -pos[0]; newPos[1] = -pos[1]; newPos[2] = pos[2]; break; case TI_NONE: case TI_LEFT: newPos = pos; break; } return newPos; } TTeamIndex SoccerBase::OpponentTeam(TTeamIndex ti) { switch (ti) { case TI_RIGHT: return TI_LEFT; case TI_LEFT: return TI_RIGHT; default: return TI_NONE; } } string SoccerBase::PlayMode2Str(const TPlayMode mode) { switch (mode) { case PM_BeforeKickOff: return STR_PM_BeforeKickOff; case PM_KickOff_Left: return STR_PM_KickOff_Left; case PM_KickOff_Right: return STR_PM_KickOff_Right; case PM_PlayOn: return STR_PM_PlayOn; case PM_KickIn_Left: return STR_PM_KickIn_Left; case PM_KickIn_Right: return STR_PM_KickIn_Right; case PM_CORNER_KICK_LEFT: return STR_PM_CORNER_KICK_LEFT; case PM_CORNER_KICK_RIGHT: return STR_PM_CORNER_KICK_RIGHT; case PM_GOAL_KICK_LEFT: return STR_PM_GOAL_KICK_LEFT; case PM_GOAL_KICK_RIGHT: return STR_PM_GOAL_KICK_RIGHT; case PM_OFFSIDE_LEFT: return STR_PM_OFFSIDE_LEFT; case PM_OFFSIDE_RIGHT: return STR_PM_OFFSIDE_RIGHT; case PM_GameOver: return STR_PM_GameOver; case PM_Goal_Left: return STR_PM_Goal_Left; case PM_Goal_Right: return STR_PM_Goal_Right; case PM_FREE_KICK_LEFT: return STR_PM_FREE_KICK_LEFT; case PM_FREE_KICK_RIGHT: return STR_PM_FREE_KICK_RIGHT; default: return STR_PM_Unknown; }; } boost::shared_ptr<ControlAspect> SoccerBase::GetControlAspect(const zeitgeist::Leaf& base,const string& name) { static const string gcsPath = "/sys/server/gamecontrol/"; boost::shared_ptr<ControlAspect> aspect = dynamic_pointer_cast<ControlAspect> (base.GetCore()->Get(gcsPath + name)); if (aspect.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ") found no ControlAspect " << name << "\n"; } return aspect; } bool SoccerBase::MoveAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos) { Vector3f agentPos = agent_aspect->GetWorldTransform().Pos(); boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform> (agent_aspect->FindParentSupportingClass<Transform>().lock()); if (parent.get() == 0) { agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: can't get parent node.\n"; return false; } Leaf::TLeafList leafList; parent->ListChildrenSupportingClass<RigidBody>(leafList, true); if (leafList.size() == 0) { agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: agent aspect doesn't have " << "children of type Body\n"; return false; } Leaf::TLeafList::iterator iter = leafList.begin(); // move all child bodies for (; iter != leafList.end(); ++iter) { boost::shared_ptr<RigidBody> childBody = dynamic_pointer_cast<RigidBody>(*iter); Vector3f childPos = childBody->GetPosition(); childBody->SetPosition(pos + (childPos-agentPos)); childBody->SetVelocity(Vector3f(0,0,0)); childBody->SetAngularVelocity(Vector3f(0,0,0)); } return true; } bool SoccerBase::MoveAndRotateAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos, float angle) { boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform> (agent_aspect->FindParentSupportingClass<Transform>().lock()); if (parent.get() == 0) { agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: can't get parent node.\n"; return false; } Leaf::TLeafList leafList; parent->ListChildrenSupportingClass<RigidBody>(leafList, true); if (leafList.size() == 0) { agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: agent aspect doesn't have " << "children of type Body\n"; return false; } boost::shared_ptr<RigidBody> body; GetAgentBody(agent_aspect, body); const Vector3f& agentPos = body->GetPosition(); Matrix bodyR = body->GetRotation(); bodyR.InvertRotationMatrix(); Matrix mat; mat.RotationZ(gDegToRad(angle)); mat *= bodyR; Leaf::TLeafList::iterator iter = leafList.begin(); // move all child bodies for (; iter != leafList.end(); ++iter ) { boost::shared_ptr<RigidBody> childBody = dynamic_pointer_cast<RigidBody>(*iter); Vector3f childPos = childBody->GetPosition(); Matrix childR = childBody->GetRotation(); childR = mat*childR; childBody->SetPosition(pos + mat.Rotate(childPos-agentPos)); childBody->SetVelocity(Vector3f(0,0,0)); childBody->SetAngularVelocity(Vector3f(0,0,0)); childBody->SetRotation(childR); } return true; } AABB3 SoccerBase::GetAgentBoundingBox(const Leaf& base) { AABB3 boundingBox; boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock(); if (!parent) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: can't get parent node.\n"; return boundingBox; } /* We can't simply use the GetWorldBoundingBox of the space node, becuase * (at least currently) it'll return a wrong answer. Currently, the space * object is always at (0,0,0) which is encapsulated in the result of it's * GetWorldBoundingBox method call. */ Leaf::TLeafList baseNodes; parent->ListChildrenSupportingClass<BaseNode>(baseNodes); if (baseNodes.empty()) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: space object doesn't have any" << " children of type BaseNode.\n"; } for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i) { boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i); boundingBox.Encapsulate(node->GetWorldBoundingBox()); } return boundingBox; } AABB2 SoccerBase::GetAgentBoundingRect(const Leaf& base) { AABB2 boundingRect; boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock(); if (!parent) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: can't get parent node.\n"; return boundingRect; } /* We can't simply use the GetWorldBoundingBox of the space node, becuase * (at least currently) it'll return a wrong answer. Currently, the space * object is always at (0,0,0) which is encapsulated in the result of it's * GetWorldBoundingBox method call. */ Leaf::TLeafList baseNodes; parent->ListChildrenSupportingClass<Collider>(baseNodes,true); if (baseNodes.empty()) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: space object doesn't have any" << " children of type BaseNode.\n"; } for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i) { boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i); const AABB3 &box = node->GetWorldBoundingBox(); boundingRect.Encapsulate(box.minVec.x(), box.minVec.y()); boundingRect.Encapsulate(box.maxVec.x(), box.maxVec.y()); } return boundingRect; } std::string SoccerBase::SPLState2Str(const spl::TSPLState state) { switch (state) { case spl::Initial: return STR_SPL_STATE_INITIAL; case spl::Ready: return STR_SPL_STATE_READY; case spl::Set: return STR_SPL_STATE_SET; case spl::Playing: return STR_SPL_STATE_PLAYING; case spl::Finished: return STR_SPL_STATE_FINISHED; case spl::Penalized: return STR_SPL_STATE_PENALIZED; default: return STR_SPL_STATE_UNKNOWN; } }
xuyuan/rcssserver3d-spl-release
plugin/soccer/soccerbase/soccerbase.cpp
C++
gpl-2.0
22,704
# -*- coding: utf-8 -*- # # HnTool rules - php # Copyright (C) 2009-2010 Candido Vieira <[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 # import os import ConfigParser import HnTool.modules.util from HnTool.modules.rule import Rule as MasterRule class Rule(MasterRule): def __init__(self, options): MasterRule.__init__(self, options) self.short_name="php" self.long_name="Checks security problems on php config file" self.type="config" self.required_files = ['/etc/php5/apache2/php.ini', '/etc/php5/cli/php.ini', '/etc/php.ini'] def requires(self): return self.required_files def analyze(self, options): check_results = self.check_results conf_files = self.required_files for php_conf in conf_files: if os.path.isfile(php_conf): config = ConfigParser.ConfigParser() try: config.read(php_conf) except ConfigParser.ParsingError, (errno, strerror): check_results['info'].append('Could not parse %s: %s' % (php_conf, strerror)) continue if not config.has_section('PHP'): check_results['info'].append('%s is not a PHP config file' % (php_conf)) continue if config.has_option('PHP', 'register_globals'): rg = config.get('PHP', 'register_globals').lower() if rg == 'on': check_results['medium'].append('Register globals is on (%s)' % (php_conf)) elif rg == 'off': check_results['ok'].append('Register globals is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for register globals (%s)' % (php_conf)) else: check_results['info'].append('Register globals not found (%s)' % (php_conf)) if config.has_option('PHP', 'safe_mode'): sm = config.get('PHP', 'safe_mode').lower() if sm == 'on': check_results['low'].append('Safe mode is on (fake security) (%s)' % (php_conf)) elif sm == 'off': check_results['info'].append('Safe mode is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for safe mode (%s)' % (php_conf)) else: check_results['info'].append('Safe mode not found (%s)' % (php_conf)) if config.has_option('PHP', 'display_errors'): de = config.get('PHP', 'display_errors').lower() if de == 'on': check_results['medium'].append('Display errors is on (stdout) (%s)' % (php_conf)) elif de == 'off': check_results['ok'].append('Display errors is off (%s)' % (php_conf)) elif de == 'stderr': check_results['info'].append('Display errors set to stderr (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for display errors (%s)' % (php_conf)) else: check_results['info'].append('Display errors not found (%s)' % (php_conf)) if config.has_option('PHP', 'expose_php'): ep = config.get('PHP', 'expose_php').lower() if ep == 'on': check_results['low'].append('Expose PHP is on (%s)' % (php_conf)) elif ep == 'off': check_results['ok'].append('Expose PHP is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for expose PHP (%s)' % (php_conf)) else: check_results['info'].append('Expose PHP not found (%s)' % (php_conf)) return check_results
hdoria/HnTool
HnTool/modules/php.py
Python
gpl-2.0
4,760
#ifndef _UMLINTERRUPTIBLEACTIVITYREGION_H #define _UMLINTERRUPTIBLEACTIVITYREGION_H #include "UmlBaseInterruptibleActivityRegion.h" #include <qcstring.h> class UmlInterruptibleActivityRegion : public UmlBaseInterruptibleActivityRegion { public: // the constructor, do not call it yourself !!!!!!!!!! UmlInterruptibleActivityRegion(void * id, const QCString & s) : UmlBaseInterruptibleActivityRegion(id, s) { } //returns a string indicating the king of the element virtual QCString sKind(); //entry to produce the html code receiving chapter number //path, rank in the mother and level in the browser tree virtual void html(QCString pfix, unsigned int rank, unsigned int level); }; #endif
gregsmirnov/bouml
genplugouts/html/cpp/UmlInterruptibleActivityRegion.h
C
gpl-2.0
731
/* JavaScript User Interface Library -- Common datatypes for user elements * Copyright 2010 Jaakko-Heikki Heusala <[email protected]> * $Id: common.js 415 2010-10-15 05:00:51Z jheusala $ */ /** Simple message box constructor * @params type The message type: error, notice, info or success * @params msg Message */ function UIMessage(type, msg) { var undefined; if(this instanceof arguments.callee) { if(type === undefined) throw TypeError("type undefined"); if(msg === undefined) { msg = type; type = undefined; } this.type = type || "info"; this.msg = ""+msg; } else { return new UIMessage(type, msg); } } /** Get the message as a string */ UIMessage.prototype.toString = function() { return this.type + ": " + this.msg; } /** Convert to JSON using JSONObject extension */ UIMessage.prototype.toJSON = function() { return new JSONObject("UIMessage", this.type + ":" + this.msg ); }; /* Setup reviver for JSONObject */ JSONObject.revivers.UIMessage = function(value) { var parts = (""+value).split(":"); return new UIMessage(parts.shift(), parts.join(":")); }; /* EOF */
jheusala/jsui
lib/jsui/common.js
JavaScript
gpl-2.0
1,101
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace PlaneGame { class ProgressBar { public Rectangle rc, fon; protected int maxValue; protected int value; protected Texture2D texture; protected int step; public int maxLenght; public ProgressBar(Texture2D textur, int height = 30, int value = 0, int maxValue = 100, int maxLenght = 200) { this.texture = textur; this.value = value; this.maxValue = maxValue; this.maxLenght = maxLenght; step = maxLenght / maxValue; rc = new Rectangle(0, 0, 1, height); fon = new Rectangle(0, 0, this.maxLenght, height); } public void setValue(int val) { this.value = val; this.rc.Width = (int)(value * step); if (this.rc.Width > this.maxLenght) { this.rc.Width = this.maxLenght; } if (this.rc.Width < 1) { this.rc.Width = 1; } } public void Draw(SpriteBatch sb,bool powernut, Color color, Color fonColor,float alpha,int x = 0, int y = 0) { if (powernut == true) { fon.X = rc.X = x; fon.Y = rc.Y = y; sb.Draw(texture, fon, null, fonColor * alpha, 0, Vector2.Zero, SpriteEffects.None, 0.9f); sb.Draw(texture, rc, null, color * alpha, 0, Vector2.Zero, SpriteEffects.None, 1); } else { fon.X = rc.X = x+this.maxLenght; fon.Y = rc.Y = y + this.fon.Height; sb.Draw(texture, fon, null, fonColor * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 0.9f); sb.Draw(texture, rc, null, color * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 1); } } } }
macrocephalus/MegaGamesVortexLimited
MegaGamesVortexLimited/MegaGamesVortexLimited/ProgressBar.cs
C#
gpl-2.0
2,237
<!DOCTYPE html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title><?php wp_title(''); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php wp_head(); ?> <!--[if lt IE 9]><script src="<?php echo get_template_directory_uri(); ?>/assets/js/html5shiv.min.js"></script><![endif]--> <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/"> </head>
brandonhimpfen/Darkly-WordPress
templates/head.php
PHP
gpl-2.0
564
/* dfilter_expr_dlg.h * Definitions for dialog boxes for display filter expression construction * * $Id: dfilter_expr_dlg.h 24034 2008-01-08 22:54:51Z stig $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * * 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. */ #ifndef __DFILTER_EXPR_DLG_H__ #define __DFILTER_EXPR_DLG_H__ /** @file * "Add Expression" dialog box. * @ingroup dialog_group */ /** User requested the "Add Expression" dialog box by menu or toolbar. * * @param widget corresponding text entry widget * @return the newly created dialog widget */ GtkWidget *dfilter_expr_dlg_new(GtkWidget *widget); #endif /* dfilter_expr_dlg.h */
Abhi9k/wireshark-dissector
ui/gtk/dfilter_expr_dlg.h
C
gpl-2.0
1,395
<!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"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>oRTP: /Users/jehanmonnier/workspaces/workspace-iphone-port/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">oRTP &#160;<span id="projectnumber">0.24.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_9e51036813d6151dfecc72d5fa7c02b3.html">Users</a></li><li class="navelem"><a class="el" href="dir_0086a5bc28c2c80fdd65429b30ec7201.html">jehanmonnier</a></li><li class="navelem"><a class="el" href="dir_b858f17e34ed058634411ab8c7d24549.html">workspaces</a></li><li class="navelem"><a class="el" href="dir_0b63d9ddac5e0eae8010f03443fa7c42.html">workspace-iphone-port</a></li><li class="navelem"><a class="el" href="dir_70e119ec7732bd017bc188a7129d48ee.html">linphone-iphone</a></li><li class="navelem"><a class="el" href="dir_cf4c98acb38bffd48d5ffefce9055b2c.html">submodules</a></li><li class="navelem"><a class="el" href="dir_b04f89f5a7f8ec29a0b9160f0e142536.html">linphone</a></li><li class="navelem"><a class="el" href="dir_868997901fe332c5ff1ebd4a06734a1f.html">oRTP</a></li><li class="navelem"><a class="el" href="dir_7559c465e4c3d013b6e747e2a6ffd6d9.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">src Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:extremum_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>extremum.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__fb_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_fb.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__xr_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_xr.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="rtpsession__priv_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="winrttimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Mar 23 2015 12:57:57 for oRTP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.7 </small></address> </body> </html>
PlayboyThailand/PlayboyPhone
liblinphone-sdk/new_apple-darwin/share/doc/ortp-0.24.0/html/dir_7559c465e4c3d013b6e747e2a6ffd6d9.html
HTML
gpl-2.0
11,432
<?php /** * Shows a welcome or update message after the plugin is installed/updated */ class Tribe__Events__Activation_Page { /** @var self */ private static $instance = null; public function add_hooks() { add_action( 'admin_init', array( $this, 'maybe_redirect' ), 10, 0 ); add_action( 'admin_menu', array( $this, 'register_page' ), 100, 0 ); // come in after the default page is registered add_action( 'update_plugin_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 ); add_action( 'update_bulk_plugins_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 ); } /** * Filter the Default WordPress actions when updating the plugin to prevent users to be redirected if they have an * specfific intention of going back to the plugins page. * * @param array $actions The Array of links (html) * @param string $plugin Which plugins are been updated * @return array The filtered Links */ public function update_complete_actions( $actions, $plugin ) { $plugins = array(); if ( ! empty( $_GET['plugins'] ) ) { $plugins = explode( ',', esc_attr( $_GET['plugins'] ) ); } if ( ! in_array( Tribe__Events__Main::instance()->pluginDir . 'the-events-calendar.php', $plugins ) ){ return $actions; } if ( isset( $actions['plugins_page'] ) ) { $actions['plugins_page'] = '<a href="' . esc_url( self_admin_url( 'plugins.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to plugins page' ) . '" target="_parent">' . esc_html__( 'Return to Plugins page' ) . '</a>'; if ( ! current_user_can( 'activate_plugins' ) ){ unset( $actions['plugins_page'] ); } } if ( isset( $actions['updates_page'] ) ) { $actions['updates_page'] = '<a href="' . esc_url( self_admin_url( 'update-core.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to WordPress Updates page' ) . '" target="_parent">' . esc_html__( 'Return to WordPress Updates' ) . '</a>'; } return $actions; } public function maybe_redirect() { if ( ! empty( $_POST ) ) { return; // don't interrupt anything the user's trying to do } if ( ! is_admin() || defined( 'DOING_AJAX' ) ) { return; } if ( defined( 'IFRAME_REQUEST' ) && IFRAME_REQUEST ) { return; // probably the plugin update/install iframe } if ( isset( $_GET['tec-welcome-message'] ) || isset( $_GET['tec-update-message'] ) ) { return; // no infinite redirects } if ( isset( $_GET['tec-skip-welcome'] ) ) { return; // a way to skip these checks and } // bail if we aren't activating a plugin if ( ! get_transient( '_tribe_events_activation_redirect' ) ) { return; } delete_transient( '_tribe_events_activation_redirect' ); if ( ! current_user_can( Tribe__Events__Settings::instance()->requiredCap ) ){ return; } if ( $this->showed_update_message_for_current_version() ) { return; } // the redirect might be intercepted by another plugin, but // we'll go ahead and mark it as viewed right now, just in case // we end up in a redirect loop // see #31088 $this->log_display_of_message_page(); if ( $this->is_new_install() ) { $this->redirect_to_welcome_page(); } /* * TODO: determine if we wish to keep the update splash screen in the future else { $this->redirect_to_update_page(); } */ } /** * Have we shown the welcome/update message for the current version? * * @return bool */ protected function showed_update_message_for_current_version() { $tec = Tribe__Events__Main::instance(); $message_version_displayed = $tec->getOption( 'last-update-message' ); if ( empty( $message_version_displayed ) ) { return false; } if ( version_compare( $message_version_displayed, Tribe__Events__Main::VERSION, '<' ) ) { return false; } return true; } protected function log_display_of_message_page() { $tec = Tribe__Events__Main::instance(); $tec->setOption( 'last-update-message', Tribe__Events__Main::VERSION ); } /** * The previous_ecp_versions option will be empty or set to 0 * if the current version is the first version to be installed. * * @return bool * @see Tribe__Events__Main::maybeSetTECVersion() */ protected function is_new_install() { $tec = Tribe__Events__Main::instance(); $previous_versions = $tec->getOption( 'previous_ecp_versions' ); return empty( $previous_versions ) || ( end( $previous_versions ) == '0' ); } protected function redirect_to_welcome_page() { $url = $this->get_message_page_url( 'tec-welcome-message' ); wp_safe_redirect( $url ); exit(); } protected function redirect_to_update_page() { $url = $this->get_message_page_url( 'tec-update-message' ); wp_safe_redirect( $url ); exit(); } protected function get_message_page_url( $slug ) { $settings = Tribe__Events__Settings::instance(); // get the base settings page url $url = apply_filters( 'tribe_settings_url', add_query_arg( array( 'post_type' => Tribe__Events__Main::POSTTYPE, 'page' => $settings->adminSlug, ), admin_url( 'edit.php' ) ) ); $url = esc_url_raw( add_query_arg( $slug, 1, $url ) ); return $url; } public function register_page() { // tribe_events_page_tribe-events-calendar if ( isset( $_GET['tec-welcome-message'] ) ) { $this->disable_default_settings_page(); add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_welcome_page' ) ); } elseif ( isset( $_GET['tec-update-message'] ) ) { $this->disable_default_settings_page(); add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_update_page' ) ); } } protected function disable_default_settings_page() { remove_action( 'tribe_events_page_tribe-events-calendar', array( Tribe__Events__Settings::instance(), 'generatePage' ) ); } public function display_welcome_page() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_welcome_page wrap">'; echo '<h1>'; echo $this->welcome_page_title(); echo '</h1>'; echo $this->welcome_page_content(); echo '</div>'; do_action( 'tribe_settings_bottom' ); $this->log_display_of_message_page(); } protected function welcome_page_title() { return __( 'Welcome to The Events Calendar', 'the-events-calendar' ); } protected function welcome_page_content() { return $this->load_template( 'admin-welcome-message' ); } public function display_update_page() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_update_page wrap">'; echo '<h1>'; echo $this->update_page_title(); echo '</h1>'; echo $this->update_page_content(); echo '</div>'; do_action( 'tribe_settings_bottom' ); $this->log_display_of_message_page(); } protected function update_page_title() { return __( 'Thanks for Updating The Events Calendar', 'the-events-calendar' ); } protected function update_page_content() { return $this->load_template( 'admin-update-message' ); } protected function load_template( $name ) { ob_start(); include trailingslashit( Tribe__Events__Main::instance()->pluginPath ) . 'src/admin-views/' . $name . '.php'; return ob_get_clean(); } /** * Initialize the global instance of the class. */ public static function init() { self::instance()->add_hooks(); } /** * @return self */ public static function instance() { if ( empty( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } }
casedot/AllYourBaseTemplate
wp-content/plugins/the-events-calendar/src/Tribe/Activation_Page.php
PHP
gpl-2.0
7,703
; size_t fread_unlocked(void *ptr, size_t size, size_t nmemb, FILE *stream) SECTION code_clib SECTION code_stdio PUBLIC fread_unlocked EXTERN asm_fread_unlocked fread_unlocked: pop af pop ix pop hl pop bc pop de push de push bc push hl push hl push af jp asm_fread_unlocked
bitfixer/bitfixer
dg/z88dk/libsrc/_DEVELOPMENT/stdio/c/sccz80/fread_unlocked.asm
Assembly
gpl-2.0
321
Audit Plugin Audit for GLPI Français Ce plugin vous permet créer des Scans des équipements des réseaux afin de visualiser les vulnerabilités et les failles sur un réseau donné. Génération de la liste des vulnerabilités pour tout type de matériel ayant une IP. Scan Mensuelles. Scan un équipement avec une adresse IP Bien précises. English This plugin allows you to create Network Equipment Scans to visualize vulnerabilities and vulnerabilities on a given network. Generation of the list of vulnerabilities for any type of hardware having an IP. Monthly Scan. Scan a device with an IP address.
mohamed3/Audit
README.md
Markdown
gpl-2.0
600
<?php /** * @version 1.0 $Id$ * @package Joomla * @subpackage redEVENT * @copyright redEVENT (C) 2008 redCOMPONENT.com / EventList (C) 2005 - 2008 Christoph Lukes * @license GNU/GPL, see LICENSE.php * redEVENT is based on EventList made by Christoph Lukes from schlu.net * redEVENT can be downloaded from www.redcomponent.com * redEVENT is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License 2 * as published by the Free Software Foundation. * redEVENT 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 redEVENT; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ defined('_JEXEC') or die('Restricted access'); ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <table class="adminform"> <tr> <td width="100%"> <?php echo JText::_('COM_REDEVENT_SEARCH' );?> <input type="text" name="search" id="search" value="<?php echo $this->lists['search']; ?>" class="text_area" onChange="document.adminForm.submit();" /> <button onclick="this.form.submit();"><?php echo JText::_('COM_REDEVENT_Go' ); ?></button> <button onclick="this.form.getElementById('search').value='';this.form.submit();"><?php echo JText::_('COM_REDEVENT_Reset' ); ?></button> </td> </tr> </table> <table class="adminlist" cellspacing="1"> <thead> <tr> <th width="5">#</th> <th width="20"><input type="checkbox" name="toggle" value="" onClick="checkAll(<?php echo count( $this->rows ); ?>);" /></th> <th width="30%" class="title"><?php echo JHTML::_('grid.sort', 'COM_REDEVENT_GROUP_NAME', 'name', $this->lists['order_Dir'], $this->lists['order'] ); ?></th> <th><?php echo JText::_('COM_REDEVENT_DESCRIPTION' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Default' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Members' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Group_ACL' ); ?></th> </tr> </thead> <tfoot> <tr> <td colspan="7"> <?php echo $this->pageNav->getListFooter(); ?> </td> </tr> </tfoot> <tbody> <?php $k = 0; for($i=0, $n=count( $this->rows ); $i < $n; $i++) { $row = &$this->rows[$i]; $link = 'index.php?option=com_redevent&amp;controller=groups&amp;task=edit&amp;cid[]='.$row->id; $checked = JHTML::_('grid.checkedout', $row, $i ); ?> <tr class="<?php echo "row$k"; ?>"> <td><?php echo $this->pageNav->getRowOffset( $i ); ?></td> <td><?php echo $checked; ?></td> <td> <?php if ( $row->checked_out && ( $row->checked_out != $this->user->get('id') ) ) { echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_('COM_REDEVENT_EDIT_GROUP' );?>::<?php echo $row->name; ?>"> <a href="<?php echo $link; ?>"> <?php echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); ?> </a></span> <?php } ?> </td> <td><?php echo htmlspecialchars($row->description, ENT_QUOTES, 'UTF-8'); ?></td> <td><?php echo ($row->isdefault ? 'yes' : 'no'); ?></td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=editmembers&amp;group_id='.$row->id, $row->members . ' ' . JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/groupmembers.png', JText::_('COM_REDEVENT_Edit_group_members' ), 'title= "'. JText::_('COM_REDEVENT_Edit_group_members' ) . '"' )); ?> </td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=groupacl&amp;group_id='.$row->id, JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/icon-16-categories.png', JText::_('COM_REDEVENT_Edit_group_ACL' ), 'title= "'. JText::_('COM_REDEVENT_Edit_group_ACL' ) . '"' )); ?> </td> </tr> <?php $k = 1 - $k; } ?> </tbody> </table> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="option" value="com_redevent" /> <input type="hidden" name="controller" value="groups" /> <input type="hidden" name="view" value="groups" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="filter_order" value="<?php echo $this->lists['order']; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']; ?>" /> </form>
jaanusnurmoja/redjoomla
administrator/components/com_redevent/views/groups/tmpl/default.php
PHP
gpl-2.0
4,833
#!/usr/bin/env python # -*- coding: utf-8 -*- # # progreso.py # # Copyright 2010 Jesús Hómez <jesus@jesus-laptop> # # 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 gtk, time import threading import thread import gobject #Iniciando el hilo sin usarlo gtk.gdk.threads_init() #La clase App hereda threading.Thread class App(threading.Thread): def __init__(self): #Método constructor, asociando los widgets self.glade_file = "progreso.glade" self.glade = gtk.Builder() self.glade.add_from_file(self.glade_file) self.window1 = self.glade.get_object('window1') self.togglebutton1 = self.glade.get_object('togglebutton1') self.button1 = self.glade.get_object('button1') self.progressbar1 = self.glade.get_object('progressbar1') self.new_val = 0.0 self.rango =60 #Definiendo el valor inicial de la barra de proceso, definiendo los saltos en 0.1 self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_pulse_step(0.1) self.window1.connect("destroy",self.on_window1_destroy) self.button1.connect('clicked', self.on_button1_clicked) self.togglebutton1.connect('toggled',self.on_togglebutton1_toggled) #Iniciando el hilo en el constructor threading.Thread.__init__(self) self.window1.show_all() def __iteracion__(self): #Iteración en segundos cambiando el valor en la barra de progreso. for i in range(self.rango): if self.togglebutton1.get_active() == True: self.new_val = self.progressbar1.get_fraction() + 0.01 if self.new_val > 1.0: self.new_val = 0.0 self.togglebutton1.set_active(False) break else: time.sleep(1) self.x = self.new_val*100 self.progressbar1.set_text("%s" %self.x) self.progressbar1.set_fraction(self.new_val) else: return def on_togglebutton1_toggled(self,*args): #Si cambia el evento en el boton biestado se inicia la iteración entre los hilos. variable = self.togglebutton1.get_active() self.rango = 100 if variable == True: lock = thread.allocate_lock() lock.acquire() thread.start_new_thread( self.__iteracion__, ()) lock.release() else: #Se detiene la barra de progreso self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_text("%s" %self.x)
jehomez/pymeadmin
progreso.py
Python
gpl-2.0
3,388
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Battery.hpp" #ifdef HAVE_BATTERY #if (defined(_WIN32_WCE) && !defined(GNAV)) #include <windows.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { SYSTEM_POWER_STATUS_EX2 sps; // request the power status DWORD result = GetSystemPowerStatusEx2(&sps, sizeof(sps), TRUE); if (result >= sizeof(sps)) { if (sps.BatteryLifePercent != BATTERY_PERCENTAGE_UNKNOWN){ Power::Battery::RemainingPercent = sps.BatteryLifePercent; Power::Battery::RemainingPercentValid = true; } else Power::Battery::RemainingPercentValid = false; switch (sps.BatteryFlag) { case BATTERY_FLAG_HIGH: Power::Battery::Status = Power::Battery::HIGH; break; case BATTERY_FLAG_LOW: Power::Battery::Status = Power::Battery::LOW; break; case BATTERY_FLAG_CRITICAL: Power::Battery::Status = Power::Battery::CRITICAL; break; case BATTERY_FLAG_CHARGING: Power::Battery::Status = Power::Battery::CHARGING; break; case BATTERY_FLAG_NO_BATTERY: Power::Battery::Status = Power::Battery::NOBATTERY; break; case BATTERY_FLAG_UNKNOWN: default: Power::Battery::Status = Power::Battery::UNKNOWN; } switch (sps.ACLineStatus) { case AC_LINE_OFFLINE: Power::External::Status = Power::External::OFF; break; case AC_LINE_BACKUP_POWER: case AC_LINE_ONLINE: Power::External::Status = Power::External::ON; break; case AC_LINE_UNKNOWN: default: Power::External::Status = Power::External::UNKNOWN; } } else { Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; } } #endif #ifdef KOBO #include "OS/FileUtil.hpp" #include <string.h> #include <stdlib.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { // assume failure at entry Power::Battery::RemainingPercentValid = false; Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; // code shamelessly copied from OS/SystemLoad.cpp char line[256]; if (!File::ReadString("/sys/bus/platform/drivers/pmic_battery/pmic_battery.1/power_supply/mc13892_bat/uevent", line, sizeof(line))) return; char field[80], value[80]; int n; char* ptr = line; while (sscanf(ptr, "%[^=]=%[^\n]\n%n", field, value, &n)==2) { ptr += n; if (!strcmp(field,"POWER_SUPPLY_STATUS")) { if (!strcmp(value,"Not charging") || !strcmp(value,"Charging")) { Power::External::Status = Power::External::ON; } else if (!strcmp(value,"Discharging")) { Power::External::Status = Power::External::OFF; } } else if (!strcmp(field,"POWER_SUPPLY_CAPACITY")) { int rem = atoi(value); Power::Battery::RemainingPercentValid = true; Power::Battery::RemainingPercent = rem; if (Power::External::Status == Power::External::OFF) { if (rem>30) { Power::Battery::Status = Power::Battery::HIGH; } else if (rem>10) { Power::Battery::Status = Power::Battery::LOW; } else if (rem<10) { Power::Battery::Status = Power::Battery::CRITICAL; } } else { Power::Battery::Status = Power::Battery::CHARGING; } } } } #endif #endif
robertscottbeattie/xcsoardev
src/Hardware/Battery.cpp
C++
gpl-2.0
4,640
<?php /** * KohaRest ILS Driver * * PHP version 7 * * Copyright (C) The National Library of Finland 2017-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 ILS_Drivers * @author Ere Maijala <[email protected]> * @author Juha Luoma <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki */ namespace Finna\ILS\Driver; use VuFind\Exception\ILS as ILSException; /** * VuFind Driver for Koha, using REST API * * Minimum Koha Version: work in progress as of 23 Jan 2017 * * @category VuFind * @package ILS_Drivers * @author Ere Maijala <[email protected]> * @author Juha Luoma <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki */ class KohaRest extends \VuFind\ILS\Driver\KohaRest { /** * Mappings from Koha messaging preferences * * @var array */ protected $messagingPrefTypeMap = [ 'Advance_Notice' => 'dueDateAlert', 'Hold_Filled' => 'pickUpNotice', 'Item_Check_in' => 'checkinNotice', 'Item_Checkout' => 'checkoutNotice', 'Item_Due' => 'dueDateNotice' ]; /** * Whether to use location in addition to branch when grouping holdings * * @param bool */ protected $groupHoldingsByLocation; /** * Priority settings for the order of branches or branch/location combinations * * @var array */ protected $holdingsBranchOrder; /** * Priority settings for the order of locations (in branches) * * @var array */ protected $holdingsLocationOrder; /** * Initialize the driver. * * Validate configuration and perform all resource-intensive tasks needed to * make the driver active. * * @throws ILSException * @return void */ public function init() { parent::init(); $this->groupHoldingsByLocation = isset($this->config['Holdings']['group_by_location']) ? $this->config['Holdings']['group_by_location'] : ''; if (isset($this->config['Holdings']['holdings_branch_order'])) { $values = explode( ':', $this->config['Holdings']['holdings_branch_order'] ); foreach ($values as $i => $value) { $parts = explode('=', $value, 2); $idx = $parts[1] ?? $i; $this->holdingsBranchOrder[$parts[0]] = $idx; } } $this->holdingsLocationOrder = isset($this->config['Holdings']['holdings_location_order']) ? explode(':', $this->config['Holdings']['holdings_location_order']) : []; $this->holdingsLocationOrder = array_flip($this->holdingsLocationOrder); } /** * Get Holding * * This is responsible for retrieving the holding information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron data * @param array $options Extra options * * @throws \VuFind\Exception\ILS * @return array On success, an associative array with the following * keys: id, availability (boolean), status, location, reserve, callnumber, * duedate, number, barcode. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getHolding($id, array $patron = null, array $options = []) { $data = parent::getHolding($id, $patron); if (!empty($data['holdings'])) { $summary = $this->getHoldingsSummary($data['holdings']); // Remove request counts before adding the summary if necessary if (isset($this->config['Holdings']['display_item_hold_counts']) && !$this->config['Holdings']['display_item_hold_counts'] ) { foreach ($data['holdings'] as &$item) { unset($item['requests_placed']); } } $data['holdings'][] = $summary; } return $data; } /** * Get Status * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ public function getStatus($id) { $data = parent::getStatus($id); if (!empty($data)) { $summary = $this->getHoldingsSummary($data); $data[] = $summary; } return $data; } /** * Get Statuses * * This is responsible for retrieving the status information for a * collection of records. * * @param array $ids The array of record ids to retrieve the status for * * @return mixed An array of getStatus() return values on success. */ public function getStatuses($ids) { $items = []; foreach ($ids as $id) { $statuses = $this->getItemStatusesForBiblio($id); if (isset($statuses['holdings'])) { $items[] = array_merge( $statuses['holdings'], $statuses['electronic_holdings'] ); } else { $items[] = $statuses; } } return $items; } /** * Get Patron Fines * * This is responsible for retrieving all fines by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's fines on success. */ public function getMyFines($patron) { $fines = parent::getMyFines($patron); foreach ($fines as &$fine) { $fine['payableOnline'] = true; } return $fines; } /** * Get Patron Profile * * This is responsible for retrieving the profile for a specific patron. * * @param array $patron The patron array * * @throws ILSException * @return array Array of the patron's profile data on success. */ public function getMyProfile($patron) { $result = $this->makeRequest( ['v1', 'patrons', $patron['id']], false, 'GET', $patron ); $expirationDate = !empty($result['dateexpiry']) ? $this->dateConverter->convertToDisplayDate( 'Y-m-d', $result['dateexpiry'] ) : ''; $guarantor = []; $guarantees = []; if (!empty($result['guarantorid'])) { $guarantorRecord = $this->makeRequest( ['v1', 'patrons', $result['guarantorid']], false, 'GET', $patron ); if ($guarantorRecord) { $guarantor['firstname'] = $guarantorRecord['firstname']; $guarantor['lastname'] = $guarantorRecord['surname']; } } else { // Assume patron can have guarantees only if there is no guarantor $guaranteeRecords = $this->makeRequest( ['v1', 'patrons'], ['guarantorid' => $patron['id']], 'GET', $patron ); foreach ($guaranteeRecords as $guarantee) { $guarantees[] = [ 'firstname' => $guarantee['firstname'], 'lastname' => $guarantee['surname'] ]; } } list($resultCode, $messagingPrefs) = $this->makeRequest( ['v1', 'messaging_preferences'], ['borrowernumber' => $patron['id']], 'GET', $patron, true ); $messagingSettings = []; if (200 === $resultCode) { foreach ($messagingPrefs as $type => $prefs) { $typeName = isset($this->messagingPrefTypeMap[$type]) ? $this->messagingPrefTypeMap[$type] : $type; $settings = [ 'type' => $typeName ]; if (isset($prefs['transport_types'])) { $settings['settings']['transport_types'] = [ 'type' => 'multiselect' ]; foreach ($prefs['transport_types'] as $key => $active) { $settings['settings']['transport_types']['options'][$key] = [ 'active' => $active ]; } } if (isset($prefs['digest'])) { $settings['settings']['digest'] = [ 'type' => 'boolean', 'name' => '', 'active' => $prefs['digest']['value'], 'readonly' => !$prefs['digest']['configurable'] ]; } if (isset($prefs['days_in_advance']) && ($prefs['days_in_advance']['configurable'] || null !== $prefs['days_in_advance']['value']) ) { $options = []; for ($i = 0; $i <= 30; $i++) { $options[$i] = [ 'name' => $this->translate( 1 === $i ? 'messaging_settings_num_of_days' : 'messaging_settings_num_of_days_plural', ['%%days%%' => $i] ), 'active' => $i == $prefs['days_in_advance']['value'] ]; } $settings['settings']['days_in_advance'] = [ 'type' => 'select', 'value' => $prefs['days_in_advance']['value'], 'options' => $options, 'readonly' => !$prefs['days_in_advance']['configurable'] ]; } $messagingSettings[$type] = $settings; } } $phoneField = isset($this->config['Profile']['phoneNumberField']) ? $this->config['Profile']['phoneNumberField'] : 'mobile'; return [ 'firstname' => $result['firstname'], 'lastname' => $result['surname'], 'phone' => $phoneField && !empty($result[$phoneField]) ? $result[$phoneField] : '', 'smsnumber' => $result['smsalertnumber'], 'email' => $result['email'], 'address1' => $result['address'], 'address2' => $result['address2'], 'zip' => $result['zipcode'], 'city' => $result['city'], 'country' => $result['country'], 'category' => $result['categorycode'] ?? '', 'expiration_date' => $expirationDate, 'hold_identifier' => $result['othernames'], 'guarantor' => $guarantor, 'guarantees' => $guarantees, 'loan_history' => $result['privacy'], 'messagingServices' => $messagingSettings, 'notes' => $result['opacnote'], 'full_data' => $result ]; } /** * Purge Patron Transaction History * * @param array $patron The patron array from patronLogin * * @throws ILSException * @return array Associative array of the results */ public function purgeTransactionHistory($patron) { list($code, $result) = $this->makeRequest( ['v1', 'checkouts', 'history'], ['borrowernumber' => $patron['id']], 'DELETE', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Purging the loan history failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => 'loan_history_purged', 'sys_message' => '' ]; } /** * Update Patron Transaction History State * * Enable or disable patron's transaction history * * @param array $patron The patron array from patronLogin * @param mixed $state Any of the configured values * * @return array Associative array of the results */ public function updateTransactionHistoryState($patron, $state) { $request = [ 'privacy' => (int)$state ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the checkout history state failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's phone number * * @param array $patron Patron array * @param string $phone Phone number * * @throws ILSException * * @return array Associative array of the results */ public function updatePhone($patron, $phone) { $request = [ 'mobile' => $phone ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's SMS alert number * * @param array $patron Patron array * @param string $number SMS alert number * * @throws ILSException * * @return array Associative array of the results */ public function updateSmsNumber($patron, $number) { $fields = !empty($this->config['updateSmsNumber']['fields']) ? explode(',', $this->config['updateSmsNumber']['fields']) : ['smsalertnumber']; $request = []; foreach ($fields as $field) { $request[$field] = $number; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's email address * * @param array $patron Patron array * @param String $email Email address * * @throws ILSException * * @return array Associative array of the results */ public function updateEmail($patron, $email) { $request = [ 'email' => $email ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the email address failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron contact information * * @param array $patron Patron array * @param array $details Associative array of patron contact information * * @throws ILSException * * @return array Associative array of the results */ public function updateAddress($patron, $details) { $addressFields = []; $fieldConfig = isset($this->config['updateAddress']['fields']) ? $this->config['updateAddress']['fields'] : []; foreach ($fieldConfig as $field) { $parts = explode(':', $field, 2); if (isset($parts[1])) { $addressFields[$parts[1]] = $parts[0]; } } // Pick the configured fields from the request $request = []; foreach ($details as $key => $value) { if (isset($addressFields[$key])) { $request[$key] = $value; } } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { if (409 === $code && !empty($result['conflict'])) { $keys = array_keys($result['conflict']); $key = reset($keys); $fieldName = isset($addressFields[$key]) ? $this->translate($addressFields[$key]) : '???'; $status = $this->translate( 'request_change_value_already_in_use', ['%%field%%' => $fieldName] ); } else { $status = 'Changing the contact information failed'; } return [ 'success' => false, 'status' => $status, 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron messaging settings * * @param array $patron Patron array * @param array $details Associative array of messaging settings * * @throws ILSException * * @return array Associative array of the results */ public function updateMessagingSettings($patron, $details) { $messagingPrefs = $this->makeRequest( ['v1', 'messaging_preferences'], ['borrowernumber' => $patron['id']], 'GET', $patron ); $messagingSettings = []; foreach ($details as $prefId => $pref) { $result = []; foreach ($pref['settings'] as $settingId => $setting) { if (!empty($setting['readonly'])) { continue; } if ('boolean' === $setting['type']) { $result[$settingId] = [ 'value' => $setting['active'] ]; } elseif ('select' === $setting['type']) { $result[$settingId] = [ 'value' => ctype_digit($setting['value']) ? (int)$setting['value'] : $setting['value'] ]; } else { foreach ($setting['options'] as $optionId => $option) { $result[$settingId][$optionId] = $option['active']; } } } $messagingSettings[$prefId] = $result; } list($code, $result) = $this->makeRequest( ['v1', 'messaging_preferences'], [ 'borrowernumber' => $patron['id'], '##body##' => json_encode($messagingSettings) ], 'PUT', $patron, true ); if ($code >= 300) { return [ 'success' => false, 'status' => 'Changing the preferences failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Change pickup location * * This is responsible for changing the pickup location of a hold * * @param string $patron Patron array * @param string $holdDetails The request details * * @return array Associative array of the results */ public function changePickupLocation($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $pickUpLocation = $holdDetails['pickupLocationId']; if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'branchcode' => $pickUpLocation ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Change request status * * This is responsible for changing the status of a hold request * * @param string $patron Patron array * @param string $holdDetails The request details (at the moment only 'frozen' * is supported) * * @return array Associative array of the results */ public function changeRequestStatus($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $frozen = !empty($holdDetails['frozen']); $request = [ 'suspend' => $frozen ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Return total amount of fees that may be paid online. * * @param array $patron Patron * @param array $fines Patron's fines * * @throws ILSException * @return array Associative array of payment info, * false if an ILSException occurred. */ public function getOnlinePayableAmount($patron, $fines) { if (!empty($fines)) { $amount = 0; foreach ($fines as $fine) { $amount += $fine['balance']; } $config = $this->getConfig('onlinePayment'); $nonPayableReason = false; if (isset($config['minimumFee']) && $amount < $config['minimumFee']) { $nonPayableReason = 'online_payment_minimum_fee'; } $res = ['payable' => empty($nonPayableReason), 'amount' => $amount]; if ($nonPayableReason) { $res['reason'] = $nonPayableReason; } return $res; } return [ 'payable' => false, 'amount' => 0, 'reason' => 'online_payment_minimum_fee' ]; } /** * Mark fees as paid. * * This is called after a successful online payment. * * @param array $patron Patron * @param int $amount Amount to be registered as paid * @param string $transactionId Transaction ID * @param int $transactionNumber Internal transaction number * * @throws ILSException * @return boolean success */ public function markFeesAsPaid($patron, $amount, $transactionId, $transactionNumber ) { $request = [ 'amount' => $amount / 100, 'note' => "Online transaction $transactionId" ]; $operator = $patron; if (!empty($this->config['onlinePayment']['userId']) && !empty($this->config['onlinePayment']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['onlinePayment']['userId'], 'cat_password' => $this->config['onlinePayment']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id'], 'payment'], json_encode($request), 'POST', $operator, true ); if ($code != 204) { $error = "Failed to mark payment of $amount paid for patron" . " {$patron['id']}: $code: " . print_r($result, true); $this->error($error); throw new ILSException($error); } // Clear patron's block cache $cacheId = 'blocks|' . $patron['id']; $this->removeCachedData($cacheId); return true; } /** * Get a password recovery token for a user * * @param array $params Required params such as cat_username and email * * @return array Associative array of the results */ public function getPasswordRecoveryToken($params) { $request = [ 'cardnumber' => $params['cat_username'], 'email' => $params['email'], 'skip_email' => true ]; $operator = []; if (!empty($this->config['PasswordRecovery']['userId']) && !empty($this->config['PasswordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['PasswordRecovery']['userId'], 'cat_password' => $this->config['PasswordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery'], json_encode($request), 'POST', $operator, true ); if (201 != $code) { if (404 != $code) { throw new ILSException("Failed to get a recovery token: $code"); } return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true, 'token' => $result['uuid'] ]; } /** * Recover user's password with a token from getPasswordRecoveryToken * * @param array $params Required params such as cat_username, token and new * password * * @return array Associative array of the results */ public function recoverPassword($params) { $request = [ 'uuid' => $params['token'], 'new_password' => $params['password'], 'confirm_new_password' => $params['password'] ]; $operator = []; if (!empty($this->config['passwordRecovery']['userId']) && !empty($this->config['passwordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['passwordRecovery']['userId'], 'cat_password' => $this->config['passwordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery', 'complete'], json_encode($request), 'POST', $operator, true ); if (200 != $code) { return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true ]; } /** * Get Patron Holds * * This is responsible for retrieving all holds by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's holds on success. */ public function getMyHolds($patron) { $result = $this->makeRequest( ['v1', 'holds'], ['borrowernumber' => $patron['id']], 'GET', $patron ); if (!isset($result)) { return []; } $holds = []; foreach ($result as $entry) { $bibId = $entry['biblionumber'] ?? null; $itemId = $entry['itemnumber'] ?? null; $title = ''; $volume = ''; if ($itemId) { $item = $this->getItem($itemId); $bibId = $item['biblionumber'] ?? null; $volume = $item['enumchron'] ?? ''; } if (!empty($bibId)) { $bib = $this->getBibRecord($bibId); $title = $bib['title'] ?? ''; if (!empty($bib['title_remainder'])) { $title .= ' ' . $bib['title_remainder']; $title = trim($title); } } $frozen = false; if (!empty($entry['suspend'])) { $frozen = !empty($entry['suspend_until']) ? $entry['suspend_until'] : true; } $available = !empty($entry['waitingdate']); $inTransit = isset($entry['found']) && strtolower($entry['found']) == 't'; $holds[] = [ 'id' => $bibId, 'item_id' => $itemId ? $itemId : $entry['reserve_id'], 'location' => $entry['branchcode'], 'create' => $this->dateConverter->convertToDisplayDate( 'Y-m-d', $entry['reservedate'] ), 'expire' => !empty($entry['expirationdate']) ? $this->dateConverter->convertToDisplayDate( 'Y-m-d', $entry['expirationdate'] ) : '', 'position' => $entry['priority'], 'available' => $available, 'in_transit' => $inTransit, 'requestId' => $entry['reserve_id'], 'title' => $title, 'volume' => $volume, 'frozen' => $frozen, 'is_editable' => !$available && !$inTransit ]; } return $holds; } /** * Public Function which retrieves renew, hold and cancel settings from the * driver ini file. * * @param string $function The name of the feature to be checked * @param array $params Optional feature-specific parameters (array) * * @return array An array with key-value pairs. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getConfig($function, $params = null) { if ('getPasswordRecoveryToken' === $function || 'recoverPassword' === $function ) { return !empty($this->config['PasswordRecovery']['enabled']) ? $this->config['PasswordRecovery'] : false; } elseif ('getPatronStaffAuthorizationStatus' === $function) { return ['enabled' => true]; } $functionConfig = parent::getConfig($function, $params); if ($functionConfig && 'onlinePayment' === $function) { if (!isset($functionConfig['exactBalanceRequired'])) { $functionConfig['exactBalanceRequired'] = false; } } return $functionConfig; } /** * Check if patron belongs to staff. * * @param array $patron The patron array from patronLogin * * @return bool True if patron is staff, false if not */ public function getPatronStaffAuthorizationStatus($patron) { $username = $patron['cat_username']; if ($this->sessionCache->patron != $username) { if (!$this->renewPatronCookie($patron)) { return false; } } return !empty( array_intersect( ['superlibrarian', 'catalogue'], $this->sessionCache->patronPermissions ) ); } /** * Get Pick Up Locations * * This is responsible for gettting a list of valid library locations for * holds / recall retrieval * * @param array $patron Patron information returned by the patronLogin * method. * @param array $holdDetails Optional array, only passed in when getting a list * in the context of placing a hold; contains most of the same values passed to * placeHold, minus the patron data. May be used to limit the pickup options * or may be ignored. The driver must not add new options to the return array * based on this data or other areas of VuFind may behave incorrectly. * * @throws ILSException * @return array An array of associative arrays with locationID and * locationDisplay keys * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getPickUpLocations($patron = false, $holdDetails = null) { $locations = []; $section = array_key_exists('StorageRetrievalRequest', $holdDetails ?? []) ? 'StorageRetrievalRequests' : 'Holds'; $excluded = isset($this->config[$section]['excludePickupLocations']) ? explode(':', $this->config[$section]['excludePickupLocations']) : []; $included = null; if (!empty($this->config['Catalog']['availabilitySupportsPickupLocations']) ) { $included = []; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $bibId = $holdDetails['id']; $itemId = $holdDetails['item_id'] ?? false; if ('copy' === $level && false === $itemId) { return []; } // Collect branch codes that are to be included if ('copy' === $level) { $result = $this->makeRequest( ['v1', 'availability', 'item', 'hold'], [ 'itemnumber' => $itemId, 'borrowernumber' => (int)$patron['id'], 'query_pickup_locations' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Item::PickupLocations'] ?? []; } else { $result = $this->makeRequest( ['v1', 'availability', 'biblio', 'hold'], [ 'biblionumber' => $bibId, 'borrowernumber' => (int)$patron['id'], 'query_pickup_locations' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Biblio::PickupLocations'] ?? []; } foreach ($pickupLocs['to_libraries'] ?? [] as $code) { $included[] = $code; } } $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET', $patron ); if (empty($result)) { return []; } foreach ($result as $location) { $code = $location['branchcode']; if ((null === $included && !$location['pickup_location']) || in_array($code, $excluded) || (null !== $included && !in_array($code, $included)) ) { continue; } $locations[] = [ 'locationID' => $code, 'locationDisplay' => $location['branchname'] ]; } // Do we need to sort pickup locations? If the setting is false, don't // bother doing any more work. If it's not set at all, default to // alphabetical order. $orderSetting = isset($this->config[$section]['pickUpLocationOrder']) ? $this->config[$section]['pickUpLocationOrder'] : 'default'; if (count($locations) > 1 && !empty($orderSetting)) { $locationOrder = $orderSetting === 'default' ? [] : array_flip(explode(':', $orderSetting)); $sortFunction = function ($a, $b) use ($locationOrder) { $aLoc = $a['locationID']; $bLoc = $b['locationID']; if (isset($locationOrder[$aLoc])) { if (isset($locationOrder[$bLoc])) { return $locationOrder[$aLoc] - $locationOrder[$bLoc]; } return -1; } if (isset($locationOrder[$bLoc])) { return 1; } return strcasecmp($a['locationDisplay'], $b['locationDisplay']); }; usort($locations, $sortFunction); } return $locations; } /** * Return summary of holdings items. * * @param array $holdings Parsed holdings items * * @return array summary */ protected function getHoldingsSummary($holdings) { $availableTotal = $itemsTotal = $reservationsTotal = 0; $requests = 0; $locations = []; foreach ($holdings as $item) { if (!empty($item['availability'])) { $availableTotal++; } if (strncmp($item['item_id'], 'HLD_', 4) !== 0) { $itemsTotal++; } $locations[$item['location']] = true; if ($item['requests_placed'] > $requests) { $requests = $item['requests_placed']; } } // Since summary data is appended to the holdings array as a fake item, // we need to add a few dummy-fields that VuFind expects to be // defined for all elements. // Use a stupid location name to make sure this doesn't get mixed with // real items that don't have a proper location. $result = [ 'available' => $availableTotal, 'total' => $itemsTotal, 'locations' => count($locations), 'availability' => null, 'callnumber' => null, 'location' => '__HOLDINGSSUMMARYLOCATION__' ]; if (!empty($this->config['Holdings']['display_total_hold_count'])) { $result['reservations'] = $requests; } return $result; } /** * Return a location for a Koha item * * @param array $item Item * * @return string */ protected function getItemLocationName($item) { $result = parent::getItemLocationName($item); if ($this->groupHoldingsByLocation) { $location = $this->translateLocation( $item['location'], !empty($item['location_description']) ? $item['location_description'] : $item['location'] ); if ($location) { // Empty translation will result in &#x200C $emptyChar = html_entity_decode('&#x200C;', ENT_NOQUOTES, 'UTF-8'); if ($result && $result !== $emptyChar) { $result .= ', '; } $result .= $location; } } return $result; } /** * Return a call number for a Koha item * * @param array $item Item * * @return string */ protected function getItemCallNumber($item) { $result = []; if (!empty($item['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $result[] = $this->translateCollection( $item['ccode'], $item['ccode_description'] ?? $item['ccode'] ); } if (!$this->groupHoldingsByLocation) { $result[] = $this->translateLocation( $item['location'], !empty($item['location_description']) ? $item['location_description'] : $item['location'] ); } if ((!empty($item['itemcallnumber']) || !empty($item['itemcallnumber_display'])) && !empty($this->config['Holdings']['display_full_call_number']) ) { if (!empty($this->config['Holdings']['use_non_display_call_number'])) { $result[] = $item['itemcallnumber']; } else { $result[] = !empty($item['itemcallnumber_display']) ? $item['itemcallnumber_display'] : $item['itemcallnumber']; } } $str = implode(', ', $result); return $str; } /** * Place Hold * * Attempts to place a hold or recall on a particular item and returns * an array with result details or throws an exception on failure of support * classes * * @param array $holdDetails An array of item and patron data * * @throws ILSException * @return mixed An array of data on the request including * whether or not it was successful and a system message (if available) */ public function placeHold($holdDetails) { $patron = $holdDetails['patron']; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $pickUpLocation = !empty($holdDetails['pickUpLocation']) ? $holdDetails['pickUpLocation'] : $this->defaultPickUpLocation; $itemId = $holdDetails['item_id'] ?? false; $comment = $holdDetails['comment'] ?? ''; $bibId = $holdDetails['id']; // Convert last interest date from Display Format to Koha's required format try { $lastInterestDate = $this->dateConverter->convertFromDisplayDate( 'Y-m-d', $holdDetails['requiredBy'] ); } catch (DateException $e) { // Hold Date is invalid return $this->holdError('hold_date_invalid'); } if ($level == 'copy' && empty($itemId)) { throw new ILSException("Hold level is 'copy', but item ID is empty"); } try { $checkTime = $this->dateConverter->convertFromDisplayDate( 'U', $holdDetails['requiredBy'] ); if (!is_numeric($checkTime)) { throw new DateException('Result should be numeric'); } } catch (DateException $e) { throw new ILSException('Problem parsing required by date.'); } if (time() > $checkTime) { // Hold Date is in the past return $this->holdError('hold_date_past'); } // Make sure pickup location is valid if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'biblionumber' => (int)$bibId, 'borrowernumber' => (int)$patron['id'], 'branchcode' => $pickUpLocation, 'reservenotes' => $comment, 'expirationdate' => $this->dateConverter->convertFromDisplayDate( 'Y-m-d', $holdDetails['requiredBy'] ) ]; if ($level == 'copy') { $request['itemnumber'] = (int)$itemId; } list($code, $result) = $this->makeRequest( ['v1', 'holds'], json_encode($request), 'POST', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Get Item Statuses * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron information, if available * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ protected function getItemStatusesForBiblio($id, $patron = null) { $holdings = []; if (!empty($this->config['Holdings']['use_holding_records'])) { list($code, $holdingsResult) = $this->makeRequest( ['v1', 'biblios', $id, 'holdings'], [], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } // Turn the holdings into a keyed array if (!empty($holdingsResult['holdings'])) { foreach ($holdingsResult['holdings'] as $holding) { $holdings[$holding['holding_id']] = $holding; } } } list($code, $result) = $this->makeRequest( ['v1', 'availability', 'biblio', 'search'], ['biblionumber' => $id], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } $statuses = []; foreach ($result[0]['item_availabilities'] ?? [] as $i => $item) { // $holding is a reference! unset($holding); if (!empty($item['holding_id']) && isset($holdings[$item['holding_id']]) ) { $holding = &$holdings[$item['holding_id']]; if ($holding['suppress']) { continue; } } $avail = $item['availability']; $available = $avail['available']; $statusCodes = $this->getItemStatusCodes($item); $status = $this->pickStatus($statusCodes); if (isset($avail['unavailabilities']['Item::CheckedOut']['date_due'])) { $duedate = $this->dateConverter->convertToDisplayDate( 'Y-m-d\TH:i:sP', $avail['unavailabilities']['Item::CheckedOut']['date_due'] ); } else { $duedate = null; } $location = $this->getItemLocationName($item); $callnumber = $this->getItemCallNumber($item); $sublocation = $item['sub_description'] ?? ''; $branchId = (!$this->useHomeBranch && null !== $item['holdingbranch']) ? $item['holdingbranch'] : $item['homebranch']; $locationId = $item['location']; $entry = [ 'id' => $id, 'item_id' => $item['itemnumber'], 'location' => $location, 'department' => $sublocation, 'availability' => $available, 'status' => $status, 'status_array' => $statusCodes, 'reserve' => 'N', 'callnumber' => $callnumber, 'duedate' => $duedate, 'number' => $item['enumchron'], 'barcode' => $item['barcode'], 'sort' => $i, 'requests_placed' => max( [$item['hold_queue_length'], $result[0]['hold_queue_length']] ), 'branchId' => $branchId, 'locationId' => $locationId ]; if (!empty($item['itemnotes'])) { $entry['item_notes'] = [$item['itemnotes']]; } if ($patron && $this->itemHoldAllowed($item)) { $entry['is_holdable'] = true; $entry['level'] = 'copy'; $entry['addLink'] = 'check'; } else { $entry['is_holdable'] = false; } if ($patron && $this->itemArticleRequestAllowed($item)) { $entry['storageRetrievalRequest'] = 'auto'; $entry['addStorageRetrievalRequestLink'] = 'check'; } if (isset($holding)) { $entry += $this->getHoldingData($holding); $holding['_hasItems'] = true; } $statuses[] = $entry; } // $holding is a reference! unset($holding); if (!isset($i)) { $i = 0; } // Add holdings that don't have items if (!empty($holdings)) { foreach ($holdings as $holding) { if ($holding['suppress'] || !empty($holding['_hasItems'])) { continue; } $holdingData = $this->getHoldingData($holding, true); $i++; $entry = $this->createHoldingEntry($id, $holding, $i); $entry += $holdingData; $statuses[] = $entry; } } // See if there are links in holdings $electronic = []; if (!empty($holdings)) { foreach ($holdings as $holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { continue; } $notes = []; if ($fields = $marc->getFields('852')) { foreach ($fields as $field) { if ($subfield = $field->getSubfield('z')) { $notes[] = $subfield->getData(); } } } if ($fields = $marc->getFields('856')) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $urls = []; $desc = []; $parts = []; foreach ($subfields as $code => $subfield) { if ('u' === $code) { $urls[] = $subfield->getData(); } elseif ('3' === $code) { $parts[] = $subfield->getData(); } elseif (in_array($code, ['y', 'z'])) { $desc[] = $subfield->getData(); } } foreach ($urls as $url) { ++$i; $entry = $this->createHoldingEntry($id, $holding, $i); $entry['availability'] = true; $entry['location'] = implode('. ', $desc); $entry['locationhref'] = $url; $entry['use_unknown_message'] = false; $entry['status'] = implode('. ', array_merge($parts, $notes)); $electronic[] = $entry; } } } } } } usort($statuses, [$this, 'statusSortFunction']); usort($electronic, [$this, 'statusSortFunction']); return [ 'holdings' => $statuses, 'electronic_holdings' => $electronic ]; } /** * Create a holding entry * * @param string $id Bib ID * @param array $holding Holding * @param int $sortKey Sort key * * @return array */ protected function createHoldingEntry($id, $holding, $sortKey) { $location = $this->getBranchName($holding['holdingbranch']); $callnumber = ''; if (!empty($holding['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $callnumber = $this->translateCollection( $holding['ccode'], $holding['ccode_description'] ?? $holding['ccode'] ); } if ($this->groupHoldingsByLocation) { $holdingLoc = $this->translateLocation( $holding['location'], !empty($holding['location_description']) ? $holding['location_description'] : $holding['location'] ); if ($holdingLoc) { if ($location) { $location .= ', '; } $location .= $holdingLoc; } } else { if ($callnumber) { $callnumber .= ', '; } $callnumber .= $this->translateLocation( $holding['location'], !empty($holding['location_description']) ? $holding['location_description'] : $holding['location'] ); } if ($holding['callnumber']) { $callnumber .= ' ' . $holding['callnumber']; } $callnumber = trim($callnumber); $branchId = $holding['holdingbranch']; $locationId = $holding['location']; return [ 'id' => $id, 'item_id' => 'HLD_' . $holding['biblionumber'], 'location' => $location, 'requests_placed' => 0, 'status' => '', 'use_unknown_message' => true, 'availability' => false, 'duedate' => '', 'barcode' => '', 'callnumber' => $callnumber, 'sort' => $sortKey, 'branchId' => $branchId, 'locationId' => $locationId ]; } /** * Return a location for a Koha branch ID * * @param string $branchId Branch ID * * @return string */ protected function getBranchName($branchId) { $name = $this->translate("location_$branchId"); if ($name === "location_$branchId") { $branches = $this->getCachedData('branches'); if (null === $branches) { $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET' ); $branches = []; foreach ($result as $branch) { $branches[$branch['branchcode']] = $branch['branchname']; } $this->putCachedData('branches', $branches); } $name = $branches[$branchId] ?? $branchId; } return $name; } /** * Get a MARC record for the given holding or null if not available * * @param array $holding Holding * * @return \File_MARCXML */ protected function getHoldingMarc(&$holding) { if (!isset($holding['_marcRecord'])) { foreach ($holding['holdings_metadata'] ?? [$holding['metadata']] as $metadata ) { if ('marcxml' === $metadata['format'] && 'MARC21' === $metadata['marcflavour'] ) { $marc = new \File_MARCXML( $metadata['metadata'], \File_MARCXML::SOURCE_STRING ); $holding['_marcRecord'] = $marc->next(); return $holding['_marcRecord']; } } $holding['_marcRecord'] = null; } return $holding['_marcRecord']; } /** * Get holding data from a holding record * * @param array $holding Holding record from Koha * * @return array */ protected function getHoldingData(&$holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { return []; } $marcDetails = []; // Get Notes $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['notes']) ? $this->config['Holdings']['notes'] : '852z' ); if ($data) { $marcDetails['notes'] = $data; } // Get Summary (may be multiple lines) $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['summary']) ? $this->config['Holdings']['summary'] : '866a' ); if ($data) { $marcDetails['summary'] = $data; } // Get Supplements if (isset($this->config['Holdings']['supplements'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['supplements'] ); if ($data) { $marcDetails['supplements'] = $data; } } // Get Indexes if (isset($this->config['Holdings']['indexes'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['indexes'] ); if ($data) { $marcDetails['indexes'] = $data; } } // Get links if (isset($this->config['Holdings']['links'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['links'] ); if ($data) { $marcDetails['links'] = $data; } } // Make sure to return an empty array unless we have details to display if (!empty($marcDetails)) { $marcDetails['holdings_id'] = $holding['holding_id']; } return $marcDetails; } /** * Get specified fields from an MFHD MARC Record * * @param object $record File_MARC object * @param array|string $fieldSpecs Array or colon-separated list of * field/subfield specifications (3 chars for field code and then subfields, * e.g. 866az) * * @return string|string[] Results as a string if single, array if multiple */ protected function getMFHDData($record, $fieldSpecs) { if (!is_array($fieldSpecs)) { $fieldSpecs = explode(':', $fieldSpecs); } $results = ''; foreach ($fieldSpecs as $fieldSpec) { $fieldCode = substr($fieldSpec, 0, 3); $subfieldCodes = substr($fieldSpec, 3); if ($fields = $record->getFields($fieldCode)) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $line = ''; foreach ($subfields as $code => $subfield) { if (!strstr($subfieldCodes, $code)) { continue; } if ($line) { $line .= ' '; } $line .= $subfield->getData(); } if ($line) { if (!$results) { $results = $line; } else { if (!is_array($results)) { $results = [$results]; } $results[] = $line; } } } } } } return $results; } /** * Translate location name * * @param string $location Location code * @param string $default Default value if translation is not available * * @return string */ protected function translateLocation($location, $default = null) { if (empty($location)) { return null !== $default ? $default : ''; } $prefix = $catPrefix = 'location_'; if (!empty($this->config['Catalog']['id'])) { $catPrefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$catPrefix$location", null, $this->translate( "$prefix$location", null, null !== $default ? $default : $location ) ); } /** * Translate collection name * * @param string $code Collection code * @param string $description Collection description * * @return string */ protected function translateCollection($code, $description) { $prefix = 'collection_'; if (!empty($this->config['Catalog']['id'])) { $prefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$prefix$code", null, $description ); } /** * Status item sort function * * @param array $a First status record to compare * @param array $b Second status record to compare * * @return int */ protected function statusSortFunction($a, $b) { $orderA = $this->holdingsBranchOrder[$a['branchId'] . '/' . $a['locationId']] ?? $this->holdingsBranchOrder[$a['branchId']] ?? 999; $orderB = $this->holdingsBranchOrder[$b['branchId'] . '/' . $b['locationId']] ?? $this->holdingsBranchOrder[$b['branchId']] ?? 999; $result = $orderA - $orderB; if (0 === $result) { $orderA = $this->holdingsLocationOrder[$a['locationId']] ?? 999; $orderB = $this->holdingsLocationOrder[$b['locationId']] ?? 999; $result = $orderA - $orderB; } if (0 === $result) { $result = strcmp($a['location'], $b['location']); } if (0 === $result && $this->sortItemsByEnumChron) { // Reverse chronological order $result = strnatcmp($b['number'] ?? '', $a['number'] ?? ''); } if (0 === $result) { $result = $a['sort'] - $b['sort']; } return $result; } }
arto70/NDL-VuFind2
module/Finna/src/Finna/ILS/Driver/KohaRest.php
PHP
gpl-2.0
64,182
package com.github.esadmin.meta.model; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.guess.core.orm.IdEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * 索引对象Entity * @author Joe.zhang * @version 2015-12-08 */ @Entity @Table(name = "meta_dbindex") @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler", "columns"}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class DBIndex extends IdEntity { /** * 数据表 */ @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = DBTable.class) @JoinTable(name = "meta_table_index", joinColumns = { @JoinColumn(name = "index_id") }, inverseJoinColumns = { @JoinColumn(name = "table_id") }) @JsonIgnoreProperties(value = { "hibernateLazyInitializer","handler","datasource"}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<DBTable> tables = new HashSet<DBTable>(0); /** * 索引库名 */ @Column(name="index_name") private String index_name; /** * 索引表名 */ @Column(name="type_name") private String type_name; /** * 索引类别 */ @Column(name="index_type") private Integer indexType; /** * 建立者 */ @Column(name="createby_id") private Long createbyId; /** * 更新者 */ @Column(name="updateby_id") private Long updatebyId; /** * 建立世间 */ @Column(name="create_date") private Date createDate; /** * 更新世间 */ @Column(name="update_date") private Date updateDate; /** * 备注 */ @Column(name="remark") private String remark; @OneToMany(targetEntity = DbColumn.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="dbindex") @OrderBy("id ASC") private Set<DbColumn> columns; @Column(name="check_label") private Integer checkLabel; public Integer getCheckLabel() { return checkLabel; } public void setCheckLabel(Integer checkLabel) { this.checkLabel = checkLabel; } public Set<DBTable> getTables() { return tables; } public void setTables(Set<DBTable> tables) { this.tables = tables; } public String getIndex_name() { return index_name; } public void setIndex_name(String index_name) { this.index_name = index_name; } public String getType_name() { return type_name; } public void setType_name(String type_name) { this.type_name = type_name; } public Integer getIndexType() { return indexType; } public void setIndexType(Integer indexType) { this.indexType = indexType; } public Long getCreatebyId() { return createbyId; } public void setCreatebyId(Long createbyId) { this.createbyId = createbyId; } public Set<DbColumn> getColumns() { return columns; } public void setColumns(Set<DbColumn> columns) { this.columns = columns; } public Long getUpdatebyId() { return updatebyId; } public void setUpdatebyId(Long updatebyId) { this.updatebyId = updatebyId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
joezxh/DATAX-UI
eshbase-proxy/src/main/java/com/github/esadmin/meta/model/DBIndex.java
Java
gpl-2.0
3,790
# Copyright (c) 1998 Cygnus Support # # The authors hereby grant permission to use, copy, modify, distribute, # and license this software and its documentation for any purpose, provided # that existing copyright notices are retained in all copies and that this # notice is included verbatim in any distributions. No written agreement, # license, or royalty fee is required for any of the authorized uses. # Modifications to this software may be copyrighted by their authors # and need not follow the licensing terms described here, provided that # the new terms are clearly indicated on the first page of each file where # they apply. DESTDIR = VPATH = ../../.././libgloss/libnosys srcdir = ../../.././libgloss/libnosys objdir = . srcroot = $(srcdir)/../.. objroot = $(objdir)/../.. prefix = /usr/local exec_prefix = ${prefix} host_alias = arm-none-eabi target_alias = arm-none-eabi program_transform_name = s&^&arm-none-eabi-& bindir = ${exec_prefix}/bin libdir = ${exec_prefix}/lib tooldir = $(exec_prefix)/$(target_alias) # Multilib support variables. # TOP is used instead of MULTI{BUILD,SRC}TOP. MULTIDIRS = MULTISUBDIR = MULTIDO = true MULTICLEAN = true INSTALL = /usr/bin/install -c INSTALL_PROGRAM = /usr/bin/install -c INSTALL_DATA = /usr/bin/install -c -m 644 SHELL = /bin/sh CC = arm-none-eabi-gcc -B/sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/ -isystem /sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/targ-include -isystem /sources/newlib/newlib-1.18.0/newlib/libc/include -B/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/arm -L/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/libnosys -L/sources/newlib/newlib-1.18.0/libgloss/arm #AS = arm-none-eabi-as AS = `if [ -f ${objroot}/../gas/as-new ] ; \ then echo ${objroot}/../gas/as-new ; \ else echo as ; fi` AR = arm-none-eabi-ar #LD = arm-none-eabi-ld LD = `if [ -f ${objroot}/../ld/ld-new ] ; \ then echo ${objroot}/../ld/ld-new ; \ else echo ld ; fi` RANLIB = arm-none-eabi-ranlib OBJDUMP = `if [ -f ${objroot}/../binutils/objdump ] ; \ then echo ${objroot}/../binutils/objdump ; \ else t='$(program_transform_name)'; echo objdump | sed -e $$t ; fi` OBJCOPY = `if [ -f ${objroot}/../binutils/objcopy ] ; \ then echo ${objroot}/../binutils/objcopy ; \ else t='$(program_transform_name)'; echo objcopy | sed -e $$t ; fi` # object files needed OBJS = chown.o close.o environ.o errno.o execve.o fork.o fstat.o \ getpid.o gettod.o isatty.o kill.o link.o lseek.o open.o \ read.o readlink.o sbrk.o stat.o symlink.o times.o unlink.o \ wait.o write.o _exit.o # Object files specific to particular targets. EVALOBJS = ${OBJS} GCC_LDFLAGS = `if [ -d ${objroot}/../gcc ] ; \ then echo -L${objroot}/../gcc ; fi` OUTPUTS = libnosys.a NEWLIB_CFLAGS = `if [ -d ${objroot}/newlib ]; then echo -I${objroot}/newlib/targ-include -I${srcroot}/newlib/libc/include; fi` NEWLIB_LDFLAGS = `if [ -d ${objroot}/newlib ]; then echo -B${objroot}/newlib/ -L${objroot}/newlib/; fi` INCLUDES = -I. -I$(srcdir)/.. # Note that when building the library, ${MULTILIB} is not the way multilib # options are passed; they're passed in $(CFLAGS). CFLAGS_FOR_TARGET = ${MULTILIB} ${INCLUDES} ${NEWLIB_CFLAGS} LDFLAGS_FOR_TARGET = ${MULTILIB} ${NEWLIB_LDFLAGS} AR_FLAGS = qc .c.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .C.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .s.o: $(AS) $(ASFLAGS_FOR_TARGET) $(INCLUDES) $(ASFLAGS) -o $*.o $< # # GCC knows to run the preprocessor on .S files before it assembles them. # .S.o: $(CC) $(CFLAGS_FOR_TARGET) $(INCLUDES) $(CFLAGS) -c $< # # this is a bogus target that'll produce an assembler from the # C source with the right compiler options. this is so we can # track down code generation or debug symbol bugs. # .c.s: $(CC) $(CFLAGS_FOR_TARGET) -S $(INCLUDES) $(CFLAGS) $< all: ${OUTPUTS} # # here's where we build the library for each target # libnosys.a: $(EVALOBJS) ${AR} ${ARFLAGS} $@ $(EVALOBJS) ${RANLIB} $@ doc: clean mostlyclean: rm -f $(OUTPUTS) *.i *~ *.o *-test *.srec *.dis *.map *.x distclean maintainer-clean realclean: clean rm -f Makefile config.status $(OUTPUTS) .PHONY: install info install-info clean-info install: @for outputs in ${OUTPUTS}; do\ mkdir -p $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ $(INSTALL_PROGRAM) $${outputs} $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ done info: install-info: clean-info: Makefile: Makefile.in config.status ../../.././libgloss/libnosys/../config/default.mh $(SHELL) config.status config.status: configure $(SHELL) config.status --recheck
pavel-ruban/hldi_hardware
src/system/arm-none-eabi/libgloss/libnosys/Makefile
Makefile
gpl-2.0
4,584
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct base_unit_info&lt;imperial::ounce_base_unit&gt;</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp" title="Header &lt;boost/units/base_units/imperial/ounce.hpp&gt;"> <link rel="prev" href="base_unit_info_imperial_id1623224.html" title="Struct base_unit_info&lt;imperial::mile_base_unit&gt;"> <link rel="next" href="imperial/pint_base_unit.html" title="Struct pint_base_unit"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id1623224.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="imperial/pint_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.units.base_unit_info_imperial_id1623277"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct base_unit_info&lt;imperial::ounce_base_unit&gt;</span></h2> <p>boost::units::base_unit_info&lt;imperial::ounce_base_unit&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp" title="Header &lt;boost/units/base_units/imperial/ounce.hpp&gt;">boost/units/base_units/imperial/ounce.hpp</a>&gt; </span> <span class="keyword">struct</span> <a class="link" href="base_unit_info_imperial_id1623277.html" title="Struct base_unit_info&lt;imperial::ounce_base_unit&gt;">base_unit_info</a><span class="special">&lt;</span><span class="identifier">imperial</span><span class="special">::</span><span class="identifier">ounce_base_unit</span><span class="special">&gt;</span> <span class="special">{</span> <span class="comment">// <a class="link" href="base_unit_info_imperial_id1623277.html#id1623286-bb">public static functions</a></span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_imperial_id1623277.html#id1623289-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_imperial_id1623277.html#id1623297-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="id3312168"></a><h2>Description</h2> <div class="refsect2"> <a name="id3312172"></a><h3> <a name="id1623286-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id1623289-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id1623297-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2008 Matthias Christian Schabel<br>Copyright &#169; 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id1623224.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="imperial/pint_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
geodynamics/gale
boost/doc/html/boost/units/base_unit_info_imperial_id1623277.html
HTML
gpl-2.0
6,187
\hypertarget{padlock_8h}{\section{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.h File Reference} \label{padlock_8h}\index{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h@{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h}} } V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. {\ttfamily \#include \char`\"{}aes.\-h\char`\"{}}\\* \subsection*{Macros} \begin{DoxyCompactItemize} \item \#define \hyperlink{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72}{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}~-\/0x0030 \end{DoxyCompactItemize} \subsection{Detailed Description} V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. Copyright (C) 2006-\/2015, A\-R\-M Limited, All Rights Reserved This file is part of mbed T\-L\-S (\href{https://tls.mbed.org}{\tt https\-://tls.\-mbed.\-org}) This program is free software; you can redistribute it and/or modify it under the terms of the G\-N\-U 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 W\-I\-T\-H\-O\-U\-T A\-N\-Y W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or F\-I\-T\-N\-E\-S\-S F\-O\-R A P\-A\-R\-T\-I\-C\-U\-L\-A\-R P\-U\-R\-P\-O\-S\-E. See the G\-N\-U General Public License for more details. You should have received a copy of the G\-N\-U General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, M\-A 02110-\/1301 U\-S\-A. Definition in file \hyperlink{padlock_8h_source}{padlock.\-h}. \subsection{Macro Definition Documentation} \hypertarget{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72}{\index{padlock.\-h@{padlock.\-h}!M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}} \index{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}!padlock.h@{padlock.\-h}} \subsubsection[{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}]{\setlength{\rightskip}{0pt plus 5cm}\#define M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D~-\/0x0030}}\label{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72} Input data should be aligned. Definition at line 30 of file padlock.\-h.
soulik/luambedtls
doc/latex/padlock_8h.tex
TeX
gpl-2.0
2,935
<?php /* core/themes/stable/templates/block/block--system-messages-block.html.twig */ class __TwigTemplate_0c8ec01fa0528f682259cd616ff9ee5ee8ceeeb5ec7cf0b3ece249a3727465d5 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/stable/templates/block/block--system-messages-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 13,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for the messages block.*/ /* **/ /* * Removes wrapper elements from block so that empty block does not appear when*/ /* * there are no messages.*/ /* **/ /* * Available variables:*/ /* * - content: The content of this block.*/ /* *//* */ /* #}*/ /* {{ content }}*/ /* */
dhrubajs/drupal_8.0.3
sites/default/files/php/twig/bdd6b639_block--system-messages-block.html.twig_41faf232cd42e8ec796f15a9bb08f1a5f7eaf6bd977aaa861b52c4ad353c5f10/41244d26af175744d9765a17dcb06990bbb9472557ce348f7ba1670b703f8a3d.php
PHP
gpl-2.0
2,313
import unittest from pyxt.mda import * from pyxt.chargen import CharacterGeneratorMock class MDATests(unittest.TestCase): def setUp(self): self.cg = CharacterGeneratorMock(width = 9, height = 14) self.mda = MonochromeDisplayAdapter(self.cg) # Hijack reset so it doesn't call into Pygame during the tests. self.reset_count = 0 self.mda.reset = self.reset_testable def reset_testable(self): self.reset_count += 1 def test_ports_list(self): self.assertEqual(self.mda.get_ports_list(), [0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB]) def test_get_memory_size(self): self.assertEqual(self.mda.get_memory_size(), 4096) def test_initial_state(self): self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.screen, None) self.assertEqual(self.mda.char_generator, self.cg) self.assertEqual(len(self.mda.video_ram), 4096) def test_mem_write_byte_updates_video_ram(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.mda.video_ram[0x0000], 0x41) def test_mem_write_byte_calls_char_generator_top_left(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_calls_char_generator_bottom_right(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_char_before_attribute(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_attribute_before_char(self): self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_write_off_screen(self): self.mda.mem_write_byte(4000, 0xFF) self.assertEqual(self.cg.last_blit, None) def test_mem_read_byte(self): self.mda.video_ram[77] = 0xA5 self.assertEqual(self.mda.mem_read_byte(77), 0xA5) def test_mem_read_byte_off_screen(self): self.assertEqual(self.mda.mem_read_byte(4000), 0x00) @unittest.skip("We need to initialize Pygame exactly once at startup.") def test_reset_on_high_resolution_enable(self): self.assertEqual(self.reset_count, 0) self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) # Second write shouldn't call reset again. self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) def test_mem_write_word_at_top_left(self): self.mda.mem_write_word(0x0000, 0x0841) # 'A' with intensity. self.assertEqual(self.mda.video_ram[0x0000], 0x41) self.assertEqual(self.mda.video_ram[0x0001], 0x08) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right(self): self.mda.mem_write_word(3998, 0x085A) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x5A) self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x5A, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right_just_past(self): self.mda.mem_write_word(3999, 0xFF08) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x00) # Should be unmodified. self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_read_word(self): self.mda.video_ram[0x0000] = 0x41 self.mda.video_ram[0x0001] = 0x08 self.assertEqual(self.mda.mem_read_word(0x0000), 0x0841) def test_mem_read_word_just_past_the_end(self): self.mda.video_ram[3998] = 0x12 self.mda.video_ram[3999] = 0x34 self.assertEqual(self.mda.mem_read_word(3999), 0x0034) def test_horizontal_retrace_toggles(self): self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF1) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) def test_current_pixel_updates_on_status_read(self): self.assertEqual(self.mda.current_pixel, [0, 0]) self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [1, 0]) def test_current_pixel_wraps_right(self): self.mda.current_pixel = [719, 0] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 1]) def test_current_pixel_wraps_bottom(self): self.mda.current_pixel = [719, 349] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 0])
astamp/PyXT
pyxt/tests/test_mda.py
Python
gpl-2.0
5,655
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ ( function($) { } )( jQuery ); var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })();
jsxmedia/jgm-wp-theme
js/global-functions.js
JavaScript
gpl-2.0
566
/** * board/annapurna-labs/common/gpio_board_init.h * * Board GPIO initialization service * * Copyright (C) 2013 Annapurna Labs Ltd. * * 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 <asm/gpio.h> /* Board GPIO configuration entry */ struct gpio_cfg_ent { /* GPIO number */ int gpio_num; /* Configure GPIO as output */ int is_output; /* Initial output value for output */ int output_val; }; /** * Board GPIO Initialization * * @param[in] cfg * Board GPIO configuration entry array * * @param[in] cnt * Number of board GPIO configuration entries * * @return 0 upon success */ int gpio_board_init( const struct gpio_cfg_ent *cfg, int cnt);
SVoxel/R9000
git_home/u-boot.git/board/annapurna-labs/common/gpio_board_init.h
C
gpl-2.0
1,373
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Sunwell_Plateau SD%Complete: 70% SDComment: SDCategory: Sunwell_Plateau EndScriptData */ #include "precompiled.h" #include "sunwell_plateau.h" /* Sunwell Plateau: 0 - Kalecgos and Sathrovarr 1 - Brutallus 2 - Felmyst 3 - Eredar Twins (Alythess and Sacrolash) 4 - M'uru 5 - Kil'Jaeden */ static const DialogueEntry aFelmystOutroDialogue[] = { {NPC_KALECGOS_MADRIGOSA, 0, 10000}, {SAY_KALECGOS_OUTRO, NPC_KALECGOS_MADRIGOSA, 5000}, {NPC_FELMYST, 0, 5000}, {SPELL_OPEN_BACK_DOOR, 0, 9000}, {NPC_BRUTALLUS, 0, 0}, {0, 0, 0}, }; instance_sunwell_plateau::instance_sunwell_plateau(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aFelmystOutroDialogue), m_uiDeceiversKilled(0), m_uiSpectralRealmTimer(5000), m_uiKalecRespawnTimer(0), m_uiMuruBerserkTimer(0), m_uiKiljaedenYellTimer(90000) { Initialize(); } void instance_sunwell_plateau::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); InitializeDialogueHelper(this); } bool instance_sunwell_plateau::IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) return true; } return false; } void instance_sunwell_plateau::OnPlayerEnter(Player* pPlayer) { // Return if Felmyst already dead, or Brutallus alive if (m_auiEncounter[TYPE_BRUTALLUS] != DONE || m_auiEncounter[TYPE_FELMYST] == DONE) return; // Return if already summoned if (GetSingleCreatureFromStorage(NPC_FELMYST, true)) return; // Summon Felmyst in reload case pPlayer->SummonCreature(NPC_FELMYST, aMadrigosaLoc[0].m_fX, aMadrigosaLoc[0].m_fY, aMadrigosaLoc[0].m_fZ, aMadrigosaLoc[0].m_fO, TEMPSUMMON_DEAD_DESPAWN, 0); } void instance_sunwell_plateau::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_KALECGOS_DRAGON: case NPC_KALECGOS_HUMAN: case NPC_SATHROVARR: case NPC_FLIGHT_TRIGGER_LEFT: case NPC_FLIGHT_TRIGGER_RIGHT: case NPC_MADRIGOSA: case NPC_BRUTALLUS: case NPC_FELMYST: case NPC_KALECGOS_MADRIGOSA: case NPC_ALYTHESS: case NPC_SACROLASH: case NPC_MURU: case NPC_ENTROPIUS: case NPC_KILJAEDEN_CONTROLLER: case NPC_KILJAEDEN: case NPC_KALECGOS: case NPC_ANVEENA: case NPC_VELEN: case NPC_LIADRIN: m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_DECEIVER: m_lDeceiversGuidList.push_back(pCreature->GetObjectGuid()); break; case NPC_WORLD_TRIGGER: // sort triggers for flightpath if (pCreature->GetPositionZ() < 51.0f) m_lAllFlightTriggersList.push_back(pCreature->GetObjectGuid()); break; case NPC_WORLD_TRIGGER_LARGE: if (pCreature->GetPositionY() < 523.0f) m_lBackdoorTriggersList.push_back(pCreature->GetObjectGuid()); break; } } void instance_sunwell_plateau::OnCreatureDeath(Creature* pCreature) { if (pCreature->GetEntry() == NPC_DECEIVER) { ++m_uiDeceiversKilled; // Spawn Kiljaeden when all deceivers are killed if (m_uiDeceiversKilled == MAX_DECEIVERS) { if (Creature* pController = GetSingleCreatureFromStorage(NPC_KILJAEDEN_CONTROLLER)) { if (Creature* pKiljaeden = pController->SummonCreature(NPC_KILJAEDEN, pController->GetPositionX(), pController->GetPositionY(), pController->GetPositionZ(), pController->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0)) pKiljaeden->SetInCombatWithZone(); pController->RemoveAurasDueToSpell(SPELL_ANVEENA_DRAIN); } } } } void instance_sunwell_plateau::OnCreatureEvade(Creature* pCreature) { // Reset encounter if raid wipes at deceivers if (pCreature->GetEntry() == NPC_DECEIVER) SetData(TYPE_KILJAEDEN, FAIL); } void instance_sunwell_plateau::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_FORCEFIELD: case GO_BOSS_COLLISION_1: case GO_BOSS_COLLISION_2: case GO_ICE_BARRIER: break; case GO_FIRE_BARRIER: if (m_auiEncounter[TYPE_KALECGOS] == DONE && m_auiEncounter[TYPE_BRUTALLUS] == DONE && m_auiEncounter[TYPE_FELMYST] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_FIRST_GATE: break; case GO_SECOND_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_ENTER_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_EXIT_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_THIRD_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_ORB_BLUE_FLIGHT_1: case GO_ORB_BLUE_FLIGHT_2: case GO_ORB_BLUE_FLIGHT_3: case GO_ORB_BLUE_FLIGHT_4: break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_sunwell_plateau::SetData(uint32 uiType, uint32 uiData) { switch (uiType) { case TYPE_KALECGOS: m_auiEncounter[uiType] = uiData; // combat doors DoUseDoorOrButton(GO_FORCEFIELD); DoUseDoorOrButton(GO_BOSS_COLLISION_1); DoUseDoorOrButton(GO_BOSS_COLLISION_2); if (uiData == FAIL) { m_uiKalecRespawnTimer = 20000; if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) pKalecDragon->ForcedDespawn(); if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN)) pKalecHuman->ForcedDespawn(); if (Creature* pSathrovarr = GetSingleCreatureFromStorage(NPC_SATHROVARR)) pSathrovarr->AI()->EnterEvadeMode(); } break; case TYPE_BRUTALLUS: m_auiEncounter[uiType] = uiData; break; case TYPE_FELMYST: m_auiEncounter[uiType] = uiData; if (uiData == DONE) StartNextDialogueText(NPC_KALECGOS_MADRIGOSA); else if (uiData == IN_PROGRESS) DoSortFlightTriggers(); break; case TYPE_EREDAR_TWINS: m_auiEncounter[uiType] = uiData; if (uiData == DONE) { DoUseDoorOrButton(GO_SECOND_GATE); DoUseDoorOrButton(GO_MURU_ENTER_GATE); } break; case TYPE_MURU: m_auiEncounter[uiType] = uiData; // combat door DoUseDoorOrButton(GO_MURU_ENTER_GATE); if (uiData == DONE) { DoUseDoorOrButton(GO_MURU_EXIT_GATE); DoUseDoorOrButton(GO_THIRD_GATE); } else if (uiData == IN_PROGRESS) m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS; break; case TYPE_KILJAEDEN: m_auiEncounter[uiType] = uiData; if (uiData == FAIL) { m_uiDeceiversKilled = 0; // Reset Orbs DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_1, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_2, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_3, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_4, GO_FLAG_NO_INTERACT, true); // Respawn deceivers for (GuidList::const_iterator itr = m_lDeceiversGuidList.begin(); itr != m_lDeceiversGuidList.end(); ++itr) { if (Creature* pDeceiver = instance->GetCreature(*itr)) { if (!pDeceiver->isAlive()) pDeceiver->Respawn(); } } } break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } uint32 instance_sunwell_plateau::GetData(uint32 uiType) const { if (uiType < MAX_ENCOUNTER) return m_auiEncounter[uiType]; return 0; } void instance_sunwell_plateau::Update(uint32 uiDiff) { DialogueUpdate(uiDiff); if (m_uiKalecRespawnTimer) { if (m_uiKalecRespawnTimer <= uiDiff) { if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) pKalecDragon->Respawn(); if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN)) pKalecHuman->Respawn(); m_uiKalecRespawnTimer = 0; } else m_uiKalecRespawnTimer -= uiDiff; } // Muru berserk timer; needs to be done here because it involves two distinct creatures if (m_auiEncounter[TYPE_MURU] == IN_PROGRESS) { if (m_uiMuruBerserkTimer < uiDiff) { if (Creature* pEntrpius = GetSingleCreatureFromStorage(NPC_ENTROPIUS, true)) pEntrpius->CastSpell(pEntrpius, SPELL_MURU_BERSERK, true); else if (Creature* pMuru = GetSingleCreatureFromStorage(NPC_MURU)) pMuru->CastSpell(pMuru, SPELL_MURU_BERSERK, true); m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS; } else m_uiMuruBerserkTimer -= uiDiff; } if (m_auiEncounter[TYPE_KILJAEDEN] == NOT_STARTED || m_auiEncounter[TYPE_KILJAEDEN] == FAIL) { if (m_uiKiljaedenYellTimer < uiDiff) { switch (urand(0, 4)) { case 0: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_1, NPC_KILJAEDEN_CONTROLLER); break; case 1: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_2, NPC_KILJAEDEN_CONTROLLER); break; case 2: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_3, NPC_KILJAEDEN_CONTROLLER); break; case 3: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_4, NPC_KILJAEDEN_CONTROLLER); break; case 4: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_5, NPC_KILJAEDEN_CONTROLLER); break; } m_uiKiljaedenYellTimer = 90000; } else m_uiKiljaedenYellTimer -= uiDiff; } } void instance_sunwell_plateau::Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); std::istringstream loadStream(in); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5]; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } static bool sortByPositionX(Creature* pFirst, Creature* pSecond) { return pFirst && pSecond && pFirst->GetPositionX() > pSecond->GetPositionX(); } void instance_sunwell_plateau::DoSortFlightTriggers() { if (m_lAllFlightTriggersList.empty()) { script_error_log("Instance Sunwell Plateau: ERROR Failed to load flight triggers for creature id %u.", NPC_FELMYST); return; } std::list<Creature*> lTriggers; // Valid pointers, only used locally for (GuidList::const_iterator itr = m_lAllFlightTriggersList.begin(); itr != m_lAllFlightTriggersList.end(); ++itr) { if (Creature* pTrigger = instance->GetCreature(*itr)) lTriggers.push_back(pTrigger); } if (lTriggers.empty()) return; // sort the flight triggers; first by position X, then group them by Y (left and right) lTriggers.sort(sortByPositionX); for (std::list<Creature*>::iterator itr = lTriggers.begin(); itr != lTriggers.end(); ++itr) { if ((*itr)->GetPositionY() < 600.0f) m_vRightFlightTriggersVect.push_back((*itr)->GetObjectGuid()); else m_vLeftFlightTriggersVect.push_back((*itr)->GetObjectGuid()); } } ObjectGuid instance_sunwell_plateau::SelectFelmystFlightTrigger(bool bLeftSide, uint8 uiIndex) { // Return the flight trigger from the selected index GuidVector& vTemp = bLeftSide ? m_vLeftFlightTriggersVect : m_vRightFlightTriggersVect; if (uiIndex >= vTemp.size()) return ObjectGuid(); return vTemp[uiIndex]; } void instance_sunwell_plateau::DoEjectSpectralPlayers() { for (GuidSet::const_iterator itr = m_spectralRealmPlayers.begin(); itr != m_spectralRealmPlayers.end(); ++itr) { if (Player* pPlayer = instance->GetPlayer(*itr)) { if (!pPlayer->HasAura(SPELL_SPECTRAL_REALM_AURA)) continue; pPlayer->CastSpell(pPlayer, SPELL_TELEPORT_NORMAL_REALM, true); pPlayer->CastSpell(pPlayer, SPELL_SPECTRAL_EXHAUSTION, true); pPlayer->RemoveAurasDueToSpell(SPELL_SPECTRAL_REALM_AURA); } } } void instance_sunwell_plateau::JustDidDialogueStep(int32 iEntry) { switch (iEntry) { case NPC_KALECGOS_MADRIGOSA: if (Creature* pTrigger = GetSingleCreatureFromStorage(NPC_FLIGHT_TRIGGER_LEFT)) { if (Creature* pKalec = pTrigger->SummonCreature(NPC_KALECGOS_MADRIGOSA, aKalecLoc[0].m_fX, aKalecLoc[0].m_fY, aKalecLoc[0].m_fZ, aKalecLoc[0].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0)) { pKalec->SetWalk(false); pKalec->SetLevitate(true); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[1].m_fX, aKalecLoc[1].m_fY, aKalecLoc[1].m_fZ, false); } } break; case NPC_FELMYST: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[2].m_fX, aKalecLoc[2].m_fY, aKalecLoc[2].m_fZ, false); break; case SPELL_OPEN_BACK_DOOR: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) { // ToDo: update this when the AoE spell targeting will support many explicit target. Kalec should target all creatures from the list if (Creature* pTrigger = instance->GetCreature(m_lBackdoorTriggersList.front())) pKalec->CastSpell(pTrigger, SPELL_OPEN_BACK_DOOR, true); } break; case NPC_BRUTALLUS: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) { pKalec->ForcedDespawn(10000); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[3].m_fX, aKalecLoc[3].m_fY, aKalecLoc[3].m_fZ, false); } break; } } InstanceData* GetInstanceData_instance_sunwell_plateau(Map* pMap) { return new instance_sunwell_plateau(pMap); } bool AreaTrigger_at_sunwell_plateau(Player* pPlayer, AreaTriggerEntry const* pAt) { if (pAt->id == AREATRIGGER_TWINS) { if (pPlayer->isGameMaster() || pPlayer->isDead()) return false; instance_sunwell_plateau* pInstance = (instance_sunwell_plateau*)pPlayer->GetInstanceData(); if (pInstance && pInstance->GetData(TYPE_EREDAR_TWINS) == NOT_STARTED) pInstance->SetData(TYPE_EREDAR_TWINS, SPECIAL); } return false; } void AddSC_instance_sunwell_plateau() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_sunwell_plateau"; pNewScript->GetInstanceData = &GetInstanceData_instance_sunwell_plateau; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "at_sunwell_plateau"; pNewScript->pAreaTrigger = &AreaTrigger_at_sunwell_plateau; pNewScript->RegisterSelf(); }
concept45/TwoScripts
scripts/eastern_kingdoms/sunwell_plateau/instance_sunwell_plateau.cpp
C++
gpl-2.0
17,598
package com.cluit.util.dataTypes; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import com.cluit.util.Const; import com.cluit.util.AoP.MethodMapper; import com.cluit.util.methods.ClusteringUtils; import com.cluit.util.structures.KeyPriorityQueue_Max; import com.cluit.util.structures.Pair; /**A cluster is a collection of entries. * * The class has a lot of utility functions related to clusters such as calculating centoid, finding the entry furthest * from the centoid and so on. * * @author Simon * */ public class Cluster { //******************************************************************************************************* //region VARIABLES //******************************************************************************************************* private Entry centoid; public Pair<Double, Entry> cache = new Pair<Double, Entry>( 0.0, new Entry() ); private final int dimensions; private final Set<Entry> members = new HashSet<>(); private final KeyPriorityQueue_Max<Entry> distanceQueue = new KeyPriorityQueue_Max<Entry>(); //endregion ********************************************************************************************* //region CUNSTRUCTOR //******************************************************************************************************* /** * * @param position * @param centoidIsMember */ public Cluster(double[] position) { if( position.length < 1){ API_Exeption("A cluster's position must be defined and have 1 or more dimenstions!"); } this.centoid = new Entry(position); this.dimensions = centoid.getDimensions(); }; //endregion ********************************************************************************************* //region STATIC METHODS //******************************************************************************************************* /**Calculates a central point (centoid) from a collection of entries. Not that all entries must have the same dimensionality. * * @param entries * @return A new entry, with a position that is the mean of all parameter entries (NULL if entries.lenght == 0) */ public static Entry calculateCentoid(Entry[] entries){ if( entries.length == 0) return null; //Fetch dimensionality for the entries and set up the coordinate array int dim = entries[0].getDimensions(); double[] centoidCoordinates = new double[dim]; //Add all entries positions together (for example, add all entries x-values together in one array slot, //and all y-values together in the next array slot). for( Entry p : entries ){ for( int i = 0; i < p.getDimensions(); i++ ) centoidCoordinates[i] += p.getCoordinateAt(i); } //Divide each position by the number of entries (to get the mean of each dimension's position for( int i = 0; i < centoidCoordinates.length; i++) centoidCoordinates[i] /= entries.length; return new Entry(centoidCoordinates); } /**Calculates the sum of squared errors for a given set of entries, given a centoid.<br> * The calculation is simply: For each point, calculate the euclidian distance from that point to the centoid, and square the distance * * @param centoid The mean position of the entries (see @link {@link Cluster.calculateCentoid} ) * @param entries * @return */ public static double calculateSquaredError(Entry centoid, Entry[] entries){ double out = 0; double dist = 0; for(Entry e : entries ){ dist = ClusteringUtils.eucDistance(centoid, e); out += (dist*dist); } return out; } //endregion ********************************************************************************************* //region PUBLIC //******************************************************************************************************* public int getNumberOfMembers(){ return distanceQueue.size() == members.size() ? distanceQueue.size() : -1; } /**Returns the distance to the centoid for the point which is farthest from the centoid * * @return The distance, if there are any members of the cluster. -1 otherwise */ public double getFurthestMembersDistance(){ if( distanceQueue.size() == 0 ) return -1; return distanceQueue.peekKey(); } /** Calculates a new centoid for the cluster. This method also update each points distance to the centoid * <br><br> * Complexity = <b>O(n * d)</b>, * where <b>n</b> is the number of elements in the cluster * where <b>d</b> the number of dimensions for each point */ public void calculateCentoid(){ int dim = centoid.getDimensions(); double[] newCentoidCoordinates = new double[dim]; for( Entry p : distanceQueue.values() ){ for( int i = 0; i < p.getDimensions(); i++ ) newCentoidCoordinates[i] += p.getCoordinateAt(i); } for( int i = 0; i < newCentoidCoordinates.length; i++) newCentoidCoordinates[i] /= distanceQueue.size(); centoid = new Entry(newCentoidCoordinates ); updateMemberDistances(); } /**Fetches a <b>copy</b> of the centoid of the cluster * * @return A new Entry, which is a copy of the cluster's centoid */ public Entry getCentoid(){ return new Entry(centoid); } /**Adds an entry to the cluster. The same entry cannot be added twice to the same cluster. * This does not automatically update the cluster centoid. To do that, call "UpdateCentoid" * * @param e * @return True if the entry was added, false if it was not */ public boolean add(Entry e){ if( e.getDimensions() != dimensions ){ API_Exeption("An entry cannot be added to a cluster if their dimenstions does not match! Cluster.dim = "+dimensions+" Entry.dim = "+e.getDimensions() ); return false; } if( members.contains(e) ){ API_Exeption("An entry cannot be added to a cluster twice! The entry "+e+" is already present in the cluster" ); return false; } double dist; if( e == cache.right ) dist = cache.left; else dist = ClusteringUtils.eucDistance(e, centoid); boolean a = distanceQueue.put(dist, e); boolean b = members.add(e); return a & b; } /**Removes a point from the cluster * * @param e The point to be removed * @return True if it was found. False if the point wasn't found. */ public boolean removeEntry(Entry e){ boolean a = distanceQueue.remove(e); boolean b = members.remove(e); return a & b; } /**Calculates a points distance to the clusters centoid. * The result is cached (the cache stores only 1 element), to prevent * the result from having to be re-computed in the near future. * <br>It is therefore recommended that whenever a point checks its distance to * all clusters, it should be added to a cluster before another point checks * it's distances. * * @param p The point * @return Distance to the centoid */ public double distanceToCentoid(Entry p){ double dist = ClusteringUtils.eucDistance(p, centoid); cache = new Pair<Double, Entry>(dist, p); return dist; } /**Checks whether a given point is member of this cluster or not * * @param p The point * @return True if the point is found within the cluster */ public boolean isMember(Entry e) { return members.contains(e); } /**Fetches an array of all entries that are present within this cluster. This array can have a lenght of 0, in case no * entries are registered within this cluster */ public Entry[] getMembers() { return members.toArray( new Entry[0] ); } /**Calculates the sum of squared errors for this cluster * * @return */ public double getSquaredError(){ return Cluster.calculateSquaredError(centoid, getMembers()) ; } public String toString(){ String out = "[ "; for( Entry e : members ){ out += e.toString() + " : "; } return members.size() > 0 ? out.substring(0, out.length() - 3) + " ]" : "[ ]"; } //endregion ********************************************************************************************* //region PRIVATE //******************************************************************************************************* /**Update each member's distance to the centoid * */ private void updateMemberDistances() { ArrayList<Entry> list = distanceQueue.values(); distanceQueue.clear(); for(Entry p : list){ double newDistance = ClusteringUtils.eucDistance(centoid, p); distanceQueue.add(newDistance, p); } } private int API_Exeption(String s){ MethodMapper.invoke(Const.METHOD_EXCEPTION_GENERAL, "Error in Cluster.java! " + s +" " + com.cluit.util.methods.MiscUtils.getStackPos(), new Exception() ); return -1; } //endregion ********************************************************************************************* //******************************************************************************************************* }
Gikkman/CluIt
CluIt/src/com/cluit/util/dataTypes/Cluster.java
Java
gpl-2.0
8,826
SUBROUTINE STPTRS( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, INFO ) * * -- LAPACK routine (version 3.2) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. CHARACTER DIAG, TRANS, UPLO INTEGER INFO, LDB, N, NRHS * .. * .. Array Arguments .. REAL AP( * ), B( LDB, * ) * .. * * Purpose * ======= * * STPTRS solves a triangular system of the form * * A * X = B or A**T * X = B, * * where A is a triangular matrix of order N stored in packed format, * and B is an N-by-NRHS matrix. A check is made to verify that A is * nonsingular. * * Arguments * ========= * * UPLO (input) CHARACTER*1 * = 'U': A is upper triangular; * = 'L': A is lower triangular. * * TRANS (input) CHARACTER*1 * Specifies the form of the system of equations: * = 'N': A * X = B (No transpose) * = 'T': A**T * X = B (Transpose) * = 'C': A**H * X = B (Conjugate transpose = Transpose) * * DIAG (input) CHARACTER*1 * = 'N': A is non-unit triangular; * = 'U': A is unit triangular. * * N (input) INTEGER * The order of the matrix A. N >= 0. * * NRHS (input) INTEGER * The number of right hand sides, i.e., the number of columns * of the matrix B. NRHS >= 0. * * AP (input) REAL array, dimension (N*(N+1)/2) * The upper or lower triangular matrix A, packed columnwise in * a linear array. The j-th column of A is stored in the array * AP as follows: * if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; * if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n. * * B (input/output) REAL array, dimension (LDB,NRHS) * On entry, the right hand side matrix B. * On exit, if INFO = 0, the solution matrix X. * * LDB (input) INTEGER * The leading dimension of the array B. LDB >= max(1,N). * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -i, the i-th argument had an illegal value * > 0: if INFO = i, the i-th diagonal element of A is zero, * indicating that the matrix is singular and the * solutions X have not been computed. * * ===================================================================== * * .. Parameters .. REAL ZERO PARAMETER ( ZERO = 0.0E+0 ) * .. * .. Local Scalars .. LOGICAL NOUNIT, UPPER INTEGER J, JC * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL STPSV, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) NOUNIT = LSAME( DIAG, 'N' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( .NOT.LSAME( TRANS, 'N' ) .AND. .NOT. $ LSAME( TRANS, 'T' ) .AND. .NOT.LSAME( TRANS, 'C' ) ) THEN INFO = -2 ELSE IF( .NOT.NOUNIT .AND. .NOT.LSAME( DIAG, 'U' ) ) THEN INFO = -3 ELSE IF( N.LT.0 ) THEN INFO = -4 ELSE IF( NRHS.LT.0 ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -8 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'STPTRS', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Check for singularity. * IF( NOUNIT ) THEN IF( UPPER ) THEN JC = 1 DO 10 INFO = 1, N IF( AP( JC+INFO-1 ).EQ.ZERO ) $ RETURN JC = JC + INFO 10 CONTINUE ELSE JC = 1 DO 20 INFO = 1, N IF( AP( JC ).EQ.ZERO ) $ RETURN JC = JC + N - INFO + 1 20 CONTINUE END IF END IF INFO = 0 * * Solve A * x = b or A' * x = b. * DO 30 J = 1, NRHS CALL STPSV( UPLO, TRANS, DIAG, N, AP, B( 1, J ), 1 ) 30 CONTINUE * RETURN * * End of STPTRS * END
apollos/Quantum-ESPRESSO
lapack-3.2/SRC/stptrs.f
FORTRAN
gpl-2.0
4,366
<?php /** * SFN Live Report. * * @package SFN Live Report * @author Hampus Persson <[email protected]> * @license GPL-2.0+ * @link http:// * @copyright 2013 Swedish Football Network */ /** * Plugin class. * * * @package SNF_Live_Report * @author Hampus Persson <[email protected]> */ class SFN_Live_Report { /** * Plugin version, used for cache-busting of style and script file references. * * @since 1.0.0 * * @var string */ protected $version = '1.1.0'; /** * Unique identifier for your plugin. * * Use this value (not the variable name) as the text domain when internationalizing strings of text. It should * match the Text Domain file header in the main plugin file. * * @since 1.0.0 * * @var string */ protected $plugin_slug = 'sfn-live-report'; /** * Instance of this class. * * @since 1.0.0 * * @var object */ protected static $instance = null; /** * Slug of the plugin screen. * * @since 1.0.0 * * @var string */ protected $plugin_screen_hook_suffix = null; /** * Initialize the plugin by setting localization, filters, and administration functions. * * @since 1.0.0 */ private function __construct() { // Load plugin text domain add_action( 'init', array( $this, 'load_plugin_textdomain' ) ); // At this point no options are needed but if the need arises this is // how to add the options page and menu item. // add_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) ); // Load admin style sheet and JavaScript. add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) ); // Load public-facing style sheet and JavaScript. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); // Add actions to remove some unwanted scripts and styles that wp_head() forces on us // add_action( 'wp_print_scripts', array( $this, 'sfn_live_report_remove_scripts' ) ); // add_action( 'wp_print_styles', array( $this, 'sfn_live_report_remove_styles' ) ); // Setup callback for AJAX, through WPs admin-ajax add_action('wp_ajax_sfn-submit', array( $this, 'sfn_live_report_callback' )); // Add the shortcode that sets up the whole operation add_shortcode( 'sfn-live-report', array( $this, 'report_games' ) ); } /** * Return an instance of this class. * * @since 1.0.0 * * @return object A single instance of this class. */ public static function get_instance() { // If the single instance hasn't been set, set it now. if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Fired when the plugin is activated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog. */ public static function activate( $network_wide ) { // TODO: Define activation functionality here } /** * Fired when the plugin is deactivated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Deactivate" action, false if WPMU is disabled or plugin is deactivated on an individual blog. */ public static function deactivate( $network_wide ) { // TODO: Define deactivation functionality here } /** * Load the plugin text domain for translation. * * @since 1.0.0 */ public function load_plugin_textdomain() { $domain = $this->plugin_slug; $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); load_textdomain( $domain, WP_LANG_DIR . '/' . $domain . '/' . $domain . '-' . $locale . '.mo' ); load_plugin_textdomain( $domain, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/lang/' ); } /** * Register and enqueue admin-specific style sheet. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_styles() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this->plugin_screen_hook_suffix ) { wp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), $this->version ); } } /** * Register and enqueue admin-specific JS. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_scripts() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this->plugin_screen_hook_suffix ) { wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/javascripts/admin.js', __FILE__ ), array( 'jquery' ), $this->version ); } } /** * Register and enqueue public-facing style sheet. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/style.css', __FILE__ ), array(), $this->version ); } /** * Register and enqueues public-facing JS files. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/javascripts/main.min.js', __FILE__ ), array( 'jquery' ), $this->version ); // Set an object with the ajaxurl for use in main JS wp_localize_script( $this->plugin_slug . '-plugin-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } /** * Since this plugin doesn't use any other plugins we can remove all scripts that are queued and registered properly * * @since 1.0.0 */ public function sfn_live_report_remove_scripts() { global $wp_scripts; foreach( $wp_scripts->queue as $handle ) : if( 'jquery' != $handle && 'sfn-live-report-plugin-script' != $handle ) { wp_deregister_script( $handle ); wp_dequeue_script( $handle ); } endforeach; } /** * Since this plugin doesn't use any other plugins we can remove all styles that are queued and registered properly * * @since 1.0.0 */ public function sfn_live_report_remove_styles() { global $wp_styles; foreach( $wp_styles->queue as $handle ) : if( 'sfn-live-report-plugin-styles' != $handle ) { wp_deregister_style( $handle ); wp_dequeue_style( $handle ); } endforeach; } /** * Register the administration menu for this plugin into the WordPress Dashboard menu. * * @since 1.0.0 */ public function add_plugin_admin_menu() { $this->plugin_screen_hook_suffix = add_plugins_page( __( 'SFN Live Report', $this->plugin_slug ), __( 'Settings', $this->plugin_slug ), 'read', $this->plugin_slug, array( $this, 'display_plugin_admin_page' ) ); } /** * Render the settings page for this plugin. * * @since 1.0.0 */ public function display_plugin_admin_page() { include_once( 'views/admin.php' ); } /** * Callback for ajax call when the form is submitted * * @since 1.0.0 */ public function sfn_live_report_callback() { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // If everything checks out and a game is submitted we'll update the meta if( $_POST['game'] ) { update_post_meta($_POST['game'], 'hemmares', $_POST['home']); update_post_meta($_POST['game'], 'bortares', $_POST['away']); update_post_meta($_POST['game'], 'matchtid', $_POST['time']); if( "true" === $_POST['sendToTwitter'] ) { $url = "http://www.swedishfootballnetwork.se/games/" . $_POST['game']; if( "true" === $_POST['finalScore'] ) { $time = ' (Slut)'; } else { $time = empty($_POST['time']) ? '' : ' (' . $_POST['time'] . ')'; } $tweet = $_POST['home-team'] . ' - ' . $_POST['away-team'] . ' ' . $_POST['home'] . '-' . $_POST['away'] . $time . '. Mer info om matchen på: ' . $url; $this->tweetUpdate($tweet); } } } private function tweetUpdate($tweet) { require_once('twitteroauth/twitteroauth.php'); define('CONSUMER_KEY', 'VPWk1tJtrYVoTMTWTLe30A'); define('CONSUMER_SECRET', 'EohfFFQzUSlsQnVjG9aVS1fCdxVv6GCzv6wEkTXYSi8'); define('OAUTH_CALLBACK', 'http://example.com/twitteroauth/callback.php'); /* TOP SECRET STUFF, DO NOT SHARE! */ $access_token = array( "oauth_token" => "1080024924-NpA52OvkNMzzeJivBpHKEEenBzfVdrutsr4qJy4", "oauth_token_secret" => "Xuk19qsgsrlnkTr3VCLnvtwjg1yUnW1u6ykCnbOjkE" ); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); $parameters = array('status' => $tweet); $content = $connection->post('statuses/update', $parameters); return $content; } /** * Function to output the form to the user * * @since 1.0.0 */ public function report_games( $atts ) { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // Store the output we want in a variable $return_page = include('views/public.php'); return $return_page; } private function check_access() { $allowed_users = array( 6, // Hampus Persson, SFN 373 // Carl Klimfors, LG ); $current_user = wp_get_current_user(); if ( in_array($current_user->ID, $allowed_users) ) { return true; } return false; } }
swedish-football-network/wp-live-report
class-sfn-live-report.php
PHP
gpl-2.0
9,879
# MSH ## Beta Version ### Created by Ne02ptzero (Louis Solofrizzo), Fusiow (Ryad Kharif) and Ivory9334 (Aurelien Ardjoune) Stable version for **MacOSX** Work on **Linux**, but no manual completion (options & description of command) ## What's MSH ? Msh is a colorful shell to help beginners in learning Linux, but also to confirm that users desire to enjoy a visual comfort. ![alt text](screens/screen1.png) ____ ![alt text](screens/screen2.png) ____ ![alt text](screens/screen3.png) ____ ![alt text](screens/screen5.png) ____ #### Why? - The command is colored in blue if it exists, otherwise red. - When the command is good, all options for this command are posters suggestions. - In addition, there is an auto-completion on the options that allows to know the list of options for a command, and their utilites. - Autocompletion also on files as well as folders. #### Builtins: - Builtins environment (env, setenv and unsetenv) - Alias - Local Variables - Job Control - Configuration file - Advanced prompt ____ ![alt text](screens/screen4.png) For more information see the documentation (docs /). #### Installation: ##### -Compilation: git clone https://github.com/Ne02ptzero/msh.git && cd msh && make ##### -Installation: make install; (For 42 students) make install42; *(Copy the binary to ~/.brew/bin)* Launch with "msh" You don't want the amazing colored read ? Launch with -no-color options.
Ne02ptzero/msh
README.md
Markdown
gpl-2.0
1,435
# encoding: utf-8 # Copyright (c) 2012 Novell, Inc. # # All Rights Reserved. # # This program is free software; you can redistribute it and/or modify it # under the terms of version 2 of the GNU General Public License as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, contact Novell, Inc. # # To contact Novell about this file by physical or electronic mail, you may # find current contact information at www.novell.com. require "yast" module UI # UI layout helpers. # # These started out in the Expert Partitioner in yast2-storage. # The use case is reusing pieces of this legacy code in the new # yast2-partitioner. # That is why the API and the implementation look old. module Greasemonkey include Yast::UIShortcuts extend Yast::UIShortcuts Builtins = Yast::Builtins Convert = Yast::Convert Ops = Yast::Ops Yast.import "Directory" @handlers = [ :VStackFrames, :FrameWithMarginBox, :ComboBoxSelected, :LeftRadioButton, :LeftRadioButtonWithAttachment, :LeftCheckBox, :LeftCheckBoxWithAttachment, :IconAndHeading ] # The compatibility API needs CamelCase method names # rubocop:disable MethodName # Wrap terms in a VBox with small vertical spacings in between. # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :VStackFrames, # Frame("f1"), # Frame("f2"), # Frame("f3") # ) # -> # VBox( # Frame("f1"), # VSpacing(0.45), # Frame("f2"), # VSpacing(0.45), # Frame("f3") # ) def VStackFrames(old) frames = Convert.convert( Builtins.argsof(old), from: "list", to: "list <term>" ) new = VBox() Builtins.foreach(frames) do |frame| new = Builtins.add(new, VSpacing(0.45)) if Builtins.size(new) != 0 new = Builtins.add(new, frame) end new end module_function :VStackFrames # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:FrameWithMarginBox, "Title", "arg1", "arg2") # -> # Frame("Title", MarginBox(1.45, 0.45, "arg1", "arg2")) def FrameWithMarginBox(old) title = Ops.get_string(old, 0, "error") args = Builtins.sublist(Builtins.argsof(old), 1) Frame( title, Builtins.toterm(:MarginBox, Builtins.union([1.45, 0.45], args)) ) end module_function :FrameWithMarginBox # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :ComboBoxSelected, # Id(:wish), Opt(:notify), "Wish", # [ # Item(Id(:time), "Time"), # Item(Id(:love), "Love"), # Item(Id(:money), "Money") # ], # Id(:love) # ) # -> # ComboBox( # Id(:wish), Opt(:notify), "Wish", # [ # Item(Id(:time), "Time", false), # Item(Id(:love), "Love", true), # Item(Id(:money), "Money", false) # ] # ) def ComboBoxSelected(old) args = Builtins.argsof(old) tmp = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 2)) items = Ops.get_list(args, Ops.subtract(Builtins.size(args), 2), []) id = Ops.get_term(args, Ops.subtract(Builtins.size(args), 1), Id()) items = Builtins.maplist(items) do |item| Item(Ops.get(item, 0), Ops.get(item, 1), Ops.get(item, 0) == id) end Builtins.toterm(:ComboBox, Builtins.add(tmp, items)) end module_function :ComboBoxSelected # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftRadioButton, Id(...), "args") # -> # Left(RadioButton(Id(...), "args")) def LeftRadioButton(old) Left(Builtins.toterm(:RadioButton, Builtins.argsof(old))) end module_function :LeftRadioButton # NOTE that it does not expand the nested # Greasemonkey term LeftRadioButton! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftRadioButtonWithAttachment, "foo", "bar", "contents") # -> # VBox( # term(:LeftRadioButton, "foo", "bar"), # HBox(HSpacing(4), "contents") # ) def LeftRadioButtonWithAttachment(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftRadioButton, tmp1)) else return VBox( Builtins.toterm(:LeftRadioButton, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :LeftRadioButtonWithAttachment # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftCheckBox, Id(...), "args") # -> # Left(CheckBox(Id(...), "args")) def LeftCheckBox(old) Left(Builtins.toterm(:CheckBox, Builtins.argsof(old))) end module_function :LeftCheckBox # NOTE that it does not expand the nested # Greasemonkey term LeftCheckBox! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftCheckBoxWithAttachment, "foo", "bar", "contents") # -> # VBox( # term(:LeftCheckBox, "foo", "bar"), # HBox(HSpacing(4), "contents") # ) def LeftCheckBoxWithAttachment(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftCheckBox, tmp1)) else return VBox( Builtins.toterm(:LeftCheckBox, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :LeftCheckBoxWithAttachment # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:IconAndHeading, "title", "icon") # -> # Left( # HBox( # Image("/usr/share/YaST2/theme/current/icons/22x22/apps/icon", ""), # Heading("title") # ) # ) def IconAndHeading(old) args = Builtins.argsof(old) title = Ops.get_string(args, 0, "") icon = Ops.get_string(args, 1, "") Left(HBox(Image(icon, ""), Heading(title))) end module_function :IconAndHeading # Recursively apply all Greasemonkey methods on *old* # @param old [Yast::Term] # @return [Yast::Term] def Transform(old) s = Builtins.symbolof(old) handler = Greasemonkey.method(s) if @handlers.include?(s) return Transform(handler.call(old)) if !handler.nil? new = Builtins::List.reduce(Builtins.toterm(s), Builtins.argsof(old)) do |tmp, arg| arg = Transform(Convert.to_term(arg)) if Ops.is_term?(arg) Builtins.add(tmp, arg) end new end module_function :Transform alias_method :transform, :Transform module_function :transform end end
mchf/yast-yast2
library/general/src/lib/ui/greasemonkey.rb
Ruby
gpl-2.0
7,562
{ int n, dx, dy, sx, pp_inc_1, pp_inc_2; register int a; register PIXEL *pp; #if defined(INTERP_RGB) register unsigned int r, g, b; #endif #ifdef INTERP_RGB register unsigned int rinc, ginc, binc; #endif #ifdef INTERP_Z register unsigned int *pz; int zinc; register unsigned int z; #endif if (p1->y > p2->y || (p1->y == p2->y && p1->x > p2->x)) { ZBufferPoint *tmp; tmp = p1; p1 = p2; p2 = tmp; } sx = zb->xsize; pp = (PIXEL *)((char *) zb->pbuf.getRawBuffer() + zb->linesize * p1->y + p1->x * PSZB); #ifdef INTERP_Z pz = zb->zbuf + (p1->y * sx + p1->x); z = p1->z; #endif dx = p2->x - p1->x; dy = p2->y - p1->y; #ifdef INTERP_RGB r = p2->r << 8; g = p2->g << 8; b = p2->b << 8; #endif #ifdef INTERP_RGB #define RGB(x) x #define RGBPIXEL *pp = RGB_TO_PIXEL(r >> 8,g >> 8,b >> 8) #else // INTERP_RGB #define RGB(x) #define RGBPIXEL *pp = color #endif // INTERP_RGB #ifdef INTERP_Z #define ZZ(x) x #define PUTPIXEL() \ { \ if (ZCMP(z, *pz)) { \ RGBPIXEL; \ *pz = z; \ } \ } #else // INTERP_Z #define ZZ(x) #define PUTPIXEL() RGBPIXEL #endif // INTERP_Z #define DRAWLINE(dx, dy, inc_1, inc_2) \ n = dx; \ ZZ(zinc = (p2->z - p1->z)/n); \ RGB(rinc=((p2->r - p1->r) << 8)/n; \ ginc=((p2->g - p1->g) << 8)/n; \ binc=((p2->b - p1->b) << 8)/n); \ a = 2 * dy - dx; \ dy = 2 * dy; \ dx = 2 * dx - dy; \ pp_inc_1 = (inc_1) * PSZB; \ pp_inc_2 = (inc_2) * PSZB; \ do { \ PUTPIXEL(); \ ZZ(z += zinc); \ RGB(r += rinc; g += ginc; b += binc); \ if (a > 0) { \ pp = (PIXEL *)((char *)pp + pp_inc_1); \ ZZ(pz+=(inc_1)); \ a -= dx; \ } else { \ pp = (PIXEL *)((char *)pp + pp_inc_2); \ ZZ(pz += (inc_2)); \ a += dy; \ } \ } while (--n >= 0); // fin macro if (dx == 0 && dy == 0) { PUTPIXEL(); } else if (dx > 0) { if (dx >= dy) { DRAWLINE(dx, dy, sx + 1, 1); } else { DRAWLINE(dy, dx, sx + 1, sx); } } else { dx = -dx; if (dx >= dy) { DRAWLINE(dx, dy, sx - 1, -1); } else { DRAWLINE(dy, dx, sx - 1, sx); } } } #undef INTERP_Z #undef INTERP_RGB // internal defines #undef DRAWLINE #undef PUTPIXEL #undef ZZ #undef RGB #undef RGBPIXEL
clone2727/residual
graphics/tinygl/zline.h
C
gpl-2.0
2,256
/* utility routines for keeping some statistics */ /* (C) 2009 by Harald Welte <[email protected]> * * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License 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 <sys/types.h> #include <osmocore/linuxlist.h> #include <osmocore/talloc.h> #include <osmocore/statistics.h> static LLIST_HEAD(counters); void *tall_ctr_ctx; struct counter *counter_alloc(const char *name) { struct counter *ctr = talloc_zero(tall_ctr_ctx, struct counter); if (!ctr) return NULL; ctr->name = name; llist_add_tail(&ctr->list, &counters); return ctr; } void counter_free(struct counter *ctr) { llist_del(&ctr->list); talloc_free(ctr); } int counters_for_each(int (*handle_counter)(struct counter *, void *), void *data) { struct counter *ctr; int rc = 0; llist_for_each_entry(ctr, &counters, list) { rc = handle_counter(ctr, data); if (rc < 0) return rc; } return rc; }
techniker/libosmocore
src/statistics.c
C
gpl-2.0
1,583
using NetworkProbe.Port.Services; using System.Collections.Generic; using System.Net; using NetworkProbe.Port; using NetworkProbe.Model; using System.Threading.Tasks; using System.Linq; namespace NetworkProbe { public static class Probe { /// <summary> /// Initiates a service scan on a single service to a single network device /// </summary> public static ProbeResult Single(ProbeEntity entity) { var result = Task.Run(() => ReturnSingleResult(entity)); return result.Result; } /// <summary> /// Initiates a service scan on multiple services on multiple devices /// </summary> public static IEnumerable<ProbeResult> Multiple(IEnumerable<ProbeEntity> entities) { List<ProbeResult> results = new List<ProbeResult>(); //Run each probe in parallel Parallel.ForEach(entities, x => { var result = Task.Run(() => ReturnSingleResult(x)); results.Add(result.Result); }); //Order results due to some tasks finishing earlier than others ***this adds around 5-7 seconds on 254 address scan :-( *** return results.OrderBy(x => int.Parse(x.IP.ToString().Split('.')[3])); } private async static Task<ProbeResult> ReturnSingleResult(ProbeEntity entity) { var service = ServiceFactory.Create(entity.Type, entity.IP, entity.Port); await service.ReturnPortData(); PortStatus status = service.PortLive ? PortStatus.Live : PortStatus.Dead; bool isData = service.PortResult != null && service.PortResult.Count > 0 ? true : false; Dictionary<string, string> data = isData ? service.PortResult : new Dictionary<string, string>(); return new ProbeResult(entity.Type, entity.Port, entity.IP, status, isData, data); } } }
K1tson/Network-Probe
NetworkProbe/Probe.cs
C#
gpl-2.0
1,951
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print "error" def main(): e=Estudiante("Diego",22) print"Hola %s" % e.hola() if e.esMayor(): print"Es mayor de edad" else: print"Es menor de edad" contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__=="__main__": main()
DiegoBalandran/prueba
archivo.py
Python
gpl-2.0
1,301
/*************************************************************************** qgsmeasure.h ------------------ begin : March 2005 copyright : (C) 2005 by Radim Blazek email : [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. * * * ***************************************************************************/ #ifndef QGSMEASUREDIALOG_H #define QGSMEASUREDIALOG_H #include "ui_qgsmeasurebase.h" #include "qgspoint.h" #include "qgsdistancearea.h" #include "qgscontexthelp.h" class QCloseEvent; class QgsMeasureTool; class QgsMeasureDialog : public QDialog, private Ui::QgsMeasureBase { Q_OBJECT public: //! Constructor QgsMeasureDialog( QgsMeasureTool* tool, Qt::WFlags f = 0 ); //! Save position void saveWindowLocation( void ); //! Restore last window position/size void restorePosition( void ); //! Add new point void addPoint( QgsPoint &point ); //! Mose move void mouseMove( QgsPoint &point ); //! Mouse press void mousePress( QgsPoint &point ); public slots: //! Reject void on_buttonBox_rejected( void ); //! Reset and start new void restart(); //! Close event void closeEvent( QCloseEvent *e ); //! Show the help for the dialog void on_buttonBox_helpRequested() { QgsContextHelp::run( metaObject()->className() ); } private: //! formats distance to most appropriate units QString formatDistance( double distance, int decimalPlaces ); //! formats area to most appropriate units QString formatArea( double area, int decimalPlaces ); //! shows/hides table, shows correct units void updateUi(); //! Converts the measurement, depending on settings in options and current transformation void convertMeasurement( double &measure, QGis::UnitType &u, bool isArea ); double mTotal; //! indicates whether we're measuring distances or areas bool mMeasureArea; //! pointer to measure tool which owns this dialog QgsMeasureTool* mTool; }; #endif
sourcepole/qgis
qgis/src/app/qgsmeasuredialog.h
C
gpl-2.0
2,706
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Overview &mdash; Python 2.7.10rc0 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '2.7.10rc0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </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/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.10rc0 documentation" href="_static/opensearch.xml"/> <link rel="author" title="About these documents" href="about.html" /> <link rel="copyright" title="Copyright" href="copyright.html" /> <link rel="top" title="Python 2.7.10rc0 documentation" href="#" /> <link rel="shortcut icon" type="image/png" href="_static/py.png" /> <script type="text/javascript" src="_static/copybutton.js"></script> <script type="text/javascript" src="_static/version_switch.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><img src="_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> &raquo;</li> <li> <span class="version_switcher_placeholder">2.7.10rc0</span> <a href="#">Documentation</a> &raquo; </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1>Python 2.7.10rc0 documentation</h1> <p> Welcome! This is the documentation for Python 2.7.10rc0, last updated Apr 13, 2015. </p> <p><strong>Parts of the documentation:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="whatsnew/2.7.html">What's new in Python 2.7?</a><br/> <span class="linkdescr">or <a href="whatsnew/index.html">all "What's new" documents</a> since 2.0</span></p> <p class="biglink"><a class="biglink" href="tutorial/index.html">Tutorial</a><br/> <span class="linkdescr">start here</span></p> <p class="biglink"><a class="biglink" href="library/index.html">Library Reference</a><br/> <span class="linkdescr">keep this under your pillow</span></p> <p class="biglink"><a class="biglink" href="reference/index.html">Language Reference</a><br/> <span class="linkdescr">describes syntax and language elements</span></p> <p class="biglink"><a class="biglink" href="using/index.html">Python Setup and Usage</a><br/> <span class="linkdescr">how to use Python on different platforms</span></p> <p class="biglink"><a class="biglink" href="howto/index.html">Python HOWTOs</a><br/> <span class="linkdescr">in-depth documents on specific topics</span></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="extending/index.html">Extending and Embedding</a><br/> <span class="linkdescr">tutorial for C/C++ programmers</span></p> <p class="biglink"><a class="biglink" href="c-api/index.html">Python/C API</a><br/> <span class="linkdescr">reference for C/C++ programmers</span></p> <p class="biglink"><a class="biglink" href="install/index.html">Installing Python Modules</a><br/> <span class="linkdescr">information for installers &amp; sys-admins</span></p> <p class="biglink"><a class="biglink" href="distutils/index.html">Distributing Python Modules</a><br/> <span class="linkdescr">sharing modules with others</span></p> <p class="biglink"><a class="biglink" href="faq/index.html">FAQs</a><br/> <span class="linkdescr">frequently asked questions (with answers!)</span></p> </td></tr> </table> <p><strong>Indices and tables:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="py-modindex.html">Global Module Index</a><br/> <span class="linkdescr">quick access to all modules</span></p> <p class="biglink"><a class="biglink" href="genindex.html">General Index</a><br/> <span class="linkdescr">all functions, classes, terms</span></p> <p class="biglink"><a class="biglink" href="glossary.html">Glossary</a><br/> <span class="linkdescr">the most important terms explained</span></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="search.html">Search page</a><br/> <span class="linkdescr">search this documentation</span></p> <p class="biglink"><a class="biglink" href="contents.html">Complete Table of Contents</a><br/> <span class="linkdescr">lists all sections and subsections</span></p> </td></tr> </table> <p><strong>Meta information:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="bugs.html">Reporting bugs</a></p> <p class="biglink"><a class="biglink" href="about.html">About the documentation</a></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="license.html">History and License of Python</a></p> <p class="biglink"><a class="biglink" href="copyright.html">Copyright</a></p> </td></tr> </table> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3>Download</h3> <p><a href="download.html">Download these documents</a></p> <h3>Docs for other versions</h3> <ul> <li><a href="https://docs.python.org/3.4/">Python 3.4 (stable)</a></li> <li><a href="https://docs.python.org/3.5/">Python 3.5 (in development)</a></li> <li><a href="https://www.python.org/doc/versions/">Old versions</a></li> </ul> <h3>Other resources</h3> <ul> <li><a href="https://www.python.org/dev/peps/">PEP Index</a></li> <li><a href="https://wiki.python.org/moin/BeginnersGuide">Beginner's Guide</a></li> <li><a href="https://wiki.python.org/moin/PythonBooks">Book List</a></li> <li><a href="https://www.python.org/doc/av/">Audio/Visual Talks</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><img src="_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> &raquo;</li> <li> <span class="version_switcher_placeholder">2.7.10rc0</span> <a href="#">Documentation</a> &raquo; </li> </ul> </div> <div class="footer"> &copy; <a href="copyright.html">Copyright</a> 1990-2015, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Apr 13, 2015. <a href="bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3. </div> </body> </html>
cybint-io/cybint-linux
live-build-config/config/includes.chroot/usr/share/documentation/python/2.7.1/index.html
HTML
gpl-2.0
8,886
class EmailToken < ActiveRecord::Base belongs_to :user validates_presence_of :token validates_presence_of :user_id validates_presence_of :email before_validation(:on => :create) do self.token = EmailToken.generate_token end after_create do # Expire the previous tokens EmailToken.update_all 'expired = true', ['user_id = ? and id != ?', self.user_id, self.id] end def self.token_length 16 end def self.valid_after 1.week.ago end def self.unconfirmed where(confirmed: false) end def self.active where(expired: false).where('created_at > ?', valid_after) end def self.generate_token SecureRandom.hex(EmailToken.token_length) end def self.confirm(token) return unless token.present? return unless token.length/2 == EmailToken.token_length email_token = EmailToken.where("token = ? AND expired = FALSE and created_at >= ?", token, EmailToken.valid_after).includes(:user).first return if email_token.blank? user = email_token.user User.transaction do row_count = EmailToken.update_all 'confirmed = true', ['id = ? AND confirmed = false', email_token.id] if row_count == 1 # If we are activating the user, send the welcome message user.send_welcome_message = !user.active? user.active = true user.email = email_token.email user.save! end end user rescue ActiveRecord::RecordInvalid # If the user's email is already taken, just return nil (failure) nil end end
Ocramius/discourse
app/models/email_token.rb
Ruby
gpl-2.0
1,540
/* * fs/f2fs/recovery.c * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/fs.h> #include <linux/f2fs_fs.h> #include "f2fs.h" #include "node.h" #include "segment.h" /* * Roll forward recovery scenarios. * * [Term] F: fsync_mark, D: dentry_mark * * 1. inode(x) | CP | inode(x) | dnode(F) * -> Update the latest inode(x). * * 2. inode(x) | CP | inode(F) | dnode(F) * -> No problem. * * 3. inode(x) | CP | dnode(F) | inode(x) * -> Recover to the latest dnode(F), and drop the last inode(x) * * 4. inode(x) | CP | dnode(F) | inode(F) * -> No problem. * * 5. CP | inode(x) | dnode(F) * -> The inode(DF) was missing. Should drop this dnode(F). * * 6. CP | inode(DF) | dnode(F) * -> No problem. * * 7. CP | dnode(F) | inode(DF) * -> If f2fs_iget fails, then goto next to find inode(DF). * * 8. CP | dnode(F) | inode(x) * -> If f2fs_iget fails, then goto next to find inode(DF). * But it will fail due to no inode(DF). */ static struct kmem_cache *fsync_entry_slab; bool space_for_roll_forward(struct f2fs_sb_info *sbi) { s64 nalloc = percpu_counter_sum_positive(&sbi->alloc_valid_block_count); if (sbi->last_valid_block_count + nalloc > sbi->user_block_count) return false; return true; } static struct fsync_inode_entry *get_fsync_inode(struct list_head *head, nid_t ino) { struct fsync_inode_entry *entry; list_for_each_entry(entry, head, list) if (entry->inode->i_ino == ino) return entry; return NULL; } static struct fsync_inode_entry *add_fsync_inode(struct list_head *head, struct inode *inode) { struct fsync_inode_entry *entry; entry = kmem_cache_alloc(fsync_entry_slab, GFP_F2FS_ZERO); if (!entry) return NULL; entry->inode = inode; list_add_tail(&entry->list, head); return entry; } static void del_fsync_inode(struct fsync_inode_entry *entry) { iput(entry->inode); list_del(&entry->list); kmem_cache_free(fsync_entry_slab, entry); } static int recover_dentry(struct inode *inode, struct page *ipage, struct list_head *dir_list) { struct f2fs_inode *raw_inode = F2FS_INODE(ipage); nid_t pino = le32_to_cpu(raw_inode->i_pino); struct f2fs_dir_entry *de; struct fscrypt_name fname; struct page *page; struct inode *dir, *einode; struct fsync_inode_entry *entry; int err = 0; char *name; entry = get_fsync_inode(dir_list, pino); if (!entry) { dir = f2fs_iget(inode->i_sb, pino); if (IS_ERR(dir)) { err = PTR_ERR(dir); goto out; } entry = add_fsync_inode(dir_list, dir); if (!entry) { err = -ENOMEM; iput(dir); goto out; } } dir = entry->inode; memset(&fname, 0, sizeof(struct fscrypt_name)); fname.disk_name.len = le32_to_cpu(raw_inode->i_namelen); fname.disk_name.name = raw_inode->i_name; if (unlikely(fname.disk_name.len > F2FS_NAME_LEN)) { WARN_ON(1); err = -ENAMETOOLONG; goto out; } retry: de = __f2fs_find_entry(dir, &fname, &page); if (de && inode->i_ino == le32_to_cpu(de->ino)) goto out_unmap_put; if (de) { einode = f2fs_iget(inode->i_sb, le32_to_cpu(de->ino)); if (IS_ERR(einode)) { WARN_ON(1); err = PTR_ERR(einode); if (err == -ENOENT) err = -EEXIST; goto out_unmap_put; } err = acquire_orphan_inode(F2FS_I_SB(inode)); if (err) { iput(einode); goto out_unmap_put; } f2fs_delete_entry(de, page, dir, einode); iput(einode); goto retry; } else if (IS_ERR(page)) { err = PTR_ERR(page); } else { err = __f2fs_do_add_link(dir, &fname, inode, inode->i_ino, inode->i_mode); } goto out; out_unmap_put: f2fs_dentry_kunmap(dir, page); f2fs_put_page(page, 0); out: if (file_enc_name(inode)) name = "<encrypted>"; else name = raw_inode->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "%s: ino = %x, name = %s, dir = %lx, err = %d", __func__, ino_of_node(ipage), name, IS_ERR(dir) ? 0 : dir->i_ino, err); return err; } static void recover_inode(struct inode *inode, struct page *page) { struct f2fs_inode *raw = F2FS_INODE(page); char *name; inode->i_mode = le16_to_cpu(raw->i_mode); f2fs_i_size_write(inode, le64_to_cpu(raw->i_size)); inode->i_atime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_ctime.tv_sec = le64_to_cpu(raw->i_ctime); inode->i_mtime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_atime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); inode->i_ctime.tv_nsec = le32_to_cpu(raw->i_ctime_nsec); inode->i_mtime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); if (file_enc_name(inode)) name = "<encrypted>"; else name = F2FS_INODE(page)->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "recover_inode: ino = %x, name = %s", ino_of_node(page), name); } static bool is_same_inode(struct inode *inode, struct page *ipage) { struct f2fs_inode *ri = F2FS_INODE(ipage); struct timespec disk; if (!IS_INODE(ipage)) return true; disk.tv_sec = le64_to_cpu(ri->i_ctime); disk.tv_nsec = le32_to_cpu(ri->i_ctime_nsec); if (timespec_compare(&inode->i_ctime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_atime); disk.tv_nsec = le32_to_cpu(ri->i_atime_nsec); if (timespec_compare(&inode->i_atime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_mtime); disk.tv_nsec = le32_to_cpu(ri->i_mtime_nsec); if (timespec_compare(&inode->i_mtime, &disk) > 0) return false; return true; } static int find_fsync_dnodes(struct f2fs_sb_info *sbi, struct list_head *head) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct inode *inode; struct page *page = NULL; block_t blkaddr; int err = 0; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) return 0; page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) break; if (!is_fsync_dnode(page)) goto next; entry = get_fsync_inode(head, ino_of_node(page)); if (entry) { if (!is_same_inode(entry->inode, page)) goto next; } else { if (IS_INODE(page) && is_dent_dnode(page)) { err = recover_inode_page(sbi, page); if (err) break; } /* * CP | dnode(F) | inode(DF) * For this case, we should not give up now. */ inode = f2fs_iget(sbi->sb, ino_of_node(page)); if (IS_ERR(inode)) { err = PTR_ERR(inode); if (err == -ENOENT) { err = 0; goto next; } break; } /* add this fsync inode to the list */ entry = add_fsync_inode(head, inode); if (!entry) { err = -ENOMEM; iput(inode); break; } } entry->blkaddr = blkaddr; if (IS_INODE(page) && is_dent_dnode(page)) entry->last_dentry = blkaddr; next: /* check next segment */ blkaddr = next_blkaddr_of_node(page); f2fs_put_page(page, 1); ra_meta_pages_cond(sbi, blkaddr); } f2fs_put_page(page, 1); return err; } static void destroy_fsync_dnodes(struct list_head *head) { struct fsync_inode_entry *entry, *tmp; list_for_each_entry_safe(entry, tmp, head, list) del_fsync_inode(entry); } static int check_index_in_prev_nodes(struct f2fs_sb_info *sbi, block_t blkaddr, struct dnode_of_data *dn) { struct seg_entry *sentry; unsigned int segno = GET_SEGNO(sbi, blkaddr); unsigned short blkoff = GET_BLKOFF_FROM_SEG0(sbi, blkaddr); struct f2fs_summary_block *sum_node; struct f2fs_summary sum; struct page *sum_page, *node_page; struct dnode_of_data tdn = *dn; nid_t ino, nid; struct inode *inode; unsigned int offset; block_t bidx; int i; sentry = get_seg_entry(sbi, segno); if (!f2fs_test_bit(blkoff, sentry->cur_valid_map)) return 0; /* Get the previous summary */ for (i = CURSEG_WARM_DATA; i <= CURSEG_COLD_DATA; i++) { struct curseg_info *curseg = CURSEG_I(sbi, i); if (curseg->segno == segno) { sum = curseg->sum_blk->entries[blkoff]; goto got_it; } } sum_page = get_sum_page(sbi, segno); sum_node = (struct f2fs_summary_block *)page_address(sum_page); sum = sum_node->entries[blkoff]; f2fs_put_page(sum_page, 1); got_it: /* Use the locked dnode page and inode */ nid = le32_to_cpu(sum.nid); if (dn->inode->i_ino == nid) { tdn.nid = nid; if (!dn->inode_page_locked) lock_page(dn->inode_page); tdn.node_page = dn->inode_page; tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } else if (dn->nid == nid) { tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } /* Get the node page */ node_page = get_node_page(sbi, nid); if (IS_ERR(node_page)) return PTR_ERR(node_page); offset = ofs_of_node(node_page); ino = ino_of_node(node_page); f2fs_put_page(node_page, 1); if (ino != dn->inode->i_ino) { /* Deallocate previous index in the node page */ inode = f2fs_iget(sbi->sb, ino); if (IS_ERR(inode)) return PTR_ERR(inode); } else { inode = dn->inode; } bidx = start_bidx_of_node(offset, inode) + le16_to_cpu(sum.ofs_in_node); /* * if inode page is locked, unlock temporarily, but its reference * count keeps alive. */ if (ino == dn->inode->i_ino && dn->inode_page_locked) unlock_page(dn->inode_page); set_new_dnode(&tdn, inode, NULL, NULL, 0); if (get_dnode_of_data(&tdn, bidx, LOOKUP_NODE)) goto out; if (tdn.data_blkaddr == blkaddr) truncate_data_blocks_range(&tdn, 1); f2fs_put_dnode(&tdn); out: if (ino != dn->inode->i_ino) iput(inode); else if (dn->inode_page_locked) lock_page(dn->inode_page); return 0; truncate_out: if (datablock_addr(tdn.node_page, tdn.ofs_in_node) == blkaddr) truncate_data_blocks_range(&tdn, 1); if (dn->inode->i_ino == nid && !dn->inode_page_locked) unlock_page(dn->inode_page); return 0; } static int do_recover_data(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, block_t blkaddr) { struct dnode_of_data dn; struct node_info ni; unsigned int start, end; int err = 0, recovered = 0; /* step 1: recover xattr */ if (IS_INODE(page)) { recover_inline_xattr(inode, page); } else if (f2fs_has_xattr_block(ofs_of_node(page))) { /* * Deprecated; xattr blocks should be found from cold log. * But, we should remain this for backward compatibility. */ recover_xattr_data(inode, page, blkaddr); goto out; } /* step 2: recover inline data */ if (recover_inline_data(inode, page)) goto out; /* step 3: recover data indices */ start = start_bidx_of_node(ofs_of_node(page), inode); end = start + ADDRS_PER_PAGE(page, inode); set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, start, ALLOC_NODE); if (err) goto out; f2fs_wait_on_page_writeback(dn.node_page, NODE, true); get_node_info(sbi, dn.nid, &ni); f2fs_bug_on(sbi, ni.ino != ino_of_node(page)); f2fs_bug_on(sbi, ofs_of_node(dn.node_page) != ofs_of_node(page)); for (; start < end; start++, dn.ofs_in_node++) { block_t src, dest; src = datablock_addr(dn.node_page, dn.ofs_in_node); dest = datablock_addr(page, dn.ofs_in_node); /* skip recovering if dest is the same as src */ if (src == dest) continue; /* dest is invalid, just invalidate src block */ if (dest == NULL_ADDR) { truncate_data_blocks_range(&dn, 1); continue; } if ((start + 1) << PAGE_SHIFT > i_size_read(inode)) f2fs_i_size_write(inode, (start + 1) << PAGE_SHIFT); /* * dest is reserved block, invalidate src block * and then reserve one new block in dnode page. */ if (dest == NEW_ADDR) { truncate_data_blocks_range(&dn, 1); reserve_new_block(&dn); continue; } /* dest is valid block, try to recover from src to dest */ if (is_valid_blkaddr(sbi, dest, META_POR)) { if (src == NULL_ADDR) { err = reserve_new_block(&dn); #ifdef CONFIG_F2FS_FAULT_INJECTION while (err) err = reserve_new_block(&dn); #endif /* We should not get -ENOSPC */ f2fs_bug_on(sbi, err); if (err) goto err; } /* Check the previous node page having this index */ err = check_index_in_prev_nodes(sbi, dest, &dn); if (err) goto err; /* write dummy data page */ f2fs_replace_block(sbi, &dn, src, dest, ni.version, false, false); recovered++; } } copy_node_footer(dn.node_page, page); fill_node_footer(dn.node_page, dn.nid, ni.ino, ofs_of_node(page), false); set_page_dirty(dn.node_page); err: f2fs_put_dnode(&dn); out: f2fs_msg(sbi->sb, KERN_NOTICE, "recover_data: ino = %lx, recovered = %d blocks, err = %d", inode->i_ino, recovered, err); return err; } static int recover_data(struct f2fs_sb_info *sbi, struct list_head *inode_list, struct list_head *dir_list) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct page *page = NULL; int err = 0; block_t blkaddr; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) break; ra_meta_pages_cond(sbi, blkaddr); page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) { f2fs_put_page(page, 1); break; } entry = get_fsync_inode(inode_list, ino_of_node(page)); if (!entry) goto next; /* * inode(x) | CP | inode(x) | dnode(F) * In this case, we can lose the latest inode(x). * So, call recover_inode for the inode update. */ if (IS_INODE(page)) recover_inode(entry->inode, page); if (entry->last_dentry == blkaddr) { err = recover_dentry(entry->inode, page, dir_list); if (err) { f2fs_put_page(page, 1); break; } } err = do_recover_data(sbi, entry->inode, page, blkaddr); if (err) { f2fs_put_page(page, 1); break; } if (entry->blkaddr == blkaddr) del_fsync_inode(entry); next: /* check next segment */ blkaddr = next_blkaddr_of_node(page); f2fs_put_page(page, 1); } if (!err) allocate_new_segments(sbi); return err; } int recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only) { struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); struct list_head inode_list; struct list_head dir_list; block_t blkaddr; int err; int ret = 0; bool need_writecp = false; fsync_entry_slab = f2fs_kmem_cache_create("f2fs_fsync_inode_entry", sizeof(struct fsync_inode_entry)); if (!fsync_entry_slab) return -ENOMEM; INIT_LIST_HEAD(&inode_list); INIT_LIST_HEAD(&dir_list); /* prevent checkpoint */ mutex_lock(&sbi->cp_mutex); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); /* step #1: find fsynced inode numbers */ err = find_fsync_dnodes(sbi, &inode_list); if (err || list_empty(&inode_list)) goto out; if (check_only) { ret = 1; goto out; } need_writecp = true; /* step #2: recover data */ err = recover_data(sbi, &inode_list, &dir_list); if (!err) f2fs_bug_on(sbi, !list_empty(&inode_list)); out: destroy_fsync_dnodes(&inode_list); /* truncate meta pages to be used by the recovery */ truncate_inode_pages_range(META_MAPPING(sbi), (loff_t)MAIN_BLKADDR(sbi) << PAGE_SHIFT, -1); if (err) { truncate_inode_pages_final(NODE_MAPPING(sbi)); truncate_inode_pages_final(META_MAPPING(sbi)); } clear_sbi_flag(sbi, SBI_POR_DOING); if (err) { bool invalidate = false; if (test_opt(sbi, LFS)) { update_meta_page(sbi, NULL, blkaddr); invalidate = true; } else if (discard_next_dnode(sbi, blkaddr)) { invalidate = true; } f2fs_wait_all_discard_bio(sbi); /* Flush all the NAT/SIT pages */ while (get_pages(sbi, F2FS_DIRTY_META)) sync_meta_pages(sbi, META, LONG_MAX); /* invalidate temporary meta page */ if (invalidate) invalidate_mapping_pages(META_MAPPING(sbi), blkaddr, blkaddr); set_ckpt_flags(sbi->ckpt, CP_ERROR_FLAG); mutex_unlock(&sbi->cp_mutex); } else if (need_writecp) { struct cp_control cpc = { .reason = CP_RECOVERY, }; mutex_unlock(&sbi->cp_mutex); err = write_checkpoint(sbi, &cpc); } else { mutex_unlock(&sbi->cp_mutex); } destroy_fsync_dnodes(&dir_list); kmem_cache_destroy(fsync_entry_slab); return ret ? ret: err; }
flaming-toast/linux-jeyu
fs/f2fs/recovery.c
C
gpl-2.0
16,232
/* * This file is part of MPlayer. * * MPlayer 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. * * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include "config.h" #include "mp_msg.h" #include "help_mp.h" #ifdef __FreeBSD__ #include <sys/cdrio.h> #endif #include "m_option.h" #include "stream.h" #include "libmpdemux/demuxer.h" /// We keep these 2 for the gui atm, but they will be removed. char* cdrom_device=NULL; int dvd_chapter=1; int dvd_last_chapter=0; char* dvd_device=NULL; char *bluray_device=NULL; // Open a new stream (stdin/file/vcd/url) stream_t* open_stream(const char* filename,char** options, int* file_format){ int dummy = DEMUXER_TYPE_UNKNOWN; if (!file_format) file_format = &dummy; // Check if playlist or unknown if (*file_format != DEMUXER_TYPE_PLAYLIST){ *file_format=DEMUXER_TYPE_UNKNOWN; } if(!filename) { mp_msg(MSGT_OPEN,MSGL_ERR,"NULL filename, report this bug\n"); return NULL; } //============ Open STDIN or plain FILE ============ return open_stream_full(filename,STREAM_READ,options,file_format); }
svn2github/MPlayer-SB
stream/open.c
C
gpl-2.0
1,868
/** IneoRealTimeFileFormat class implementation. @file IneoRealTimeFileFormat.cpp This file belongs to the SYNTHESE project (public transportation specialized software) Copyright (C) 2002 Hugues Romain - RCSmobility <[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 "IneoRealTimeFileFormat.hpp" #include "Import.hpp" #include "DataSource.h" #include "DataSourceTableSync.h" #include "DBTransaction.hpp" #include "ImportableTableSync.hpp" #include "ScheduledServiceTableSync.h" #include "StopPointTableSync.hpp" #include "CommercialLineTableSync.h" #include "JourneyPatternTableSync.hpp" #include "DesignatedLinePhysicalStop.hpp" #include "LineStopTableSync.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; using namespace boost::posix_time; using namespace gregorian; namespace synthese { using namespace data_exchange; using namespace pt; using namespace server; using namespace util; using namespace impex; using namespace db; using namespace graph; using namespace util; namespace util { template<> const string FactorableTemplate<FileFormat, IneoRealTimeFileFormat>::FACTORY_KEY("ineo_temps_reel"); } namespace data_exchange { const string IneoRealTimeFileFormat::Importer_::PARAMETER_PLANNED_DATASOURCE_ID("ps"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_COURSE_ID("ci"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_DB_CONN_STRING("conn_string"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_STOP_CODE_PREFIX("stop_code_prefix"); bool IneoRealTimeFileFormat::Importer_::_read( ) const { if(_database.empty() || !_plannedDataSource.get()) { return false; } DataSource& dataSource(*_import.get<DataSource>()); boost::shared_ptr<DB> db; if(_dbConnString) { db = DBModule::GetDBForStandaloneUse(*_dbConnString); } else { db = DBModule::GetDBSPtr(); } date today(day_clock::local_day()); string todayStr("'"+ to_iso_extended_string(today) +"'"); // Services linked to the planned source ImportableTableSync::ObjectBySource<StopPointTableSync> stops(*_plannedDataSource, _env); ImportableTableSync::ObjectBySource<CommercialLineTableSync> lines(*_plannedDataSource, _env); if(!_courseId) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& line, itLine.second) { JourneyPatternTableSync::Search(_env, line->getKey()); ScheduledServiceTableSync::Search(_env, optional<RegistryKeyType>(), line->getKey()); BOOST_FOREACH(const Path* route, line->getPaths()) { LineStopTableSync::Search(_env, route->getKey()); } } } // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env); BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::value_type& itService, sourcedServices.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::mapped_type::value_type& obj, itService.second) { obj->removeSourceLinks(dataSource); } } } else { // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env); set<ScheduledService*> services(sourcedServices.get(*_courseId)); BOOST_FOREACH(ScheduledService* service, services) { service->removeSourceLinks(dataSource); _services.insert(service); } } // 2 : loop on the services present in the database and link to existing or new services stringstream query; query << "SELECT c.ref, c.chainage, c.ligne, l.mnemo as ligne_ref FROM " << _database << ".COURSE c " << "INNER JOIN " << _database << ".LIGNE l on c.ligne=l.ref AND l.jour=c.jour " << "WHERE c.jour=" << todayStr << " AND c.type='C'"; if(_courseId) { query << " AND c.ref=" << *_courseId; } DBResultSPtr result(db->execQuery(query.str())); while(result->next()) { string serviceRef(result->getText("ref")); string chainage(result->getText("chainage")); string ligneRef(result->getText("ligne_ref")); _logDebug( "Processing serviceRef="+ serviceRef +" chainage="+ chainage +" ligneRef="+ ligneRef ); CommercialLine* line( _getLine( lines, ligneRef, *_plannedDataSource ) ); if(!line) { _logWarning( "Line "+ ligneRef +" was not found for service "+ serviceRef ); continue; } stringstream chainageQuery; chainageQuery << "SELECT a.mnemol AS mnemol, h.htd AS htd, h.hta AS hta, h.type AS type, c.pos AS pos FROM " << _database << ".ARRETCHN c " << "INNER JOIN " << _database << ".ARRET a ON a.ref=c.arret AND a.jour=c.jour " << "INNER JOIN " << _database << ".HORAIRE h ON h.arretchn=c.ref AND h.jour=a.jour " << "INNER JOIN " << _database << ".COURSE o ON o.chainage=c.chainage AND o.ref=h.course AND c.jour=o.jour " << "WHERE h.course='" << serviceRef << "' AND h.jour=" << todayStr << " ORDER BY c.pos"; DBResultSPtr chainageResult(db->execQuery(chainageQuery.str())); JourneyPattern::StopsWithDepartureArrivalAuthorization servedStops; SchedulesBasedService::Schedules departureSchedules; SchedulesBasedService::Schedules arrivalSchedules; while(chainageResult->next()) { string type(chainageResult->getText("type")); string stopCode(chainageResult->getText("mnemol")); time_duration departureTime(duration_from_string(chainageResult->getText("htd"))); time_duration arrivalTime(duration_from_string(chainageResult->getText("hta"))); MetricOffset stopPos(chainageResult->getInt("pos")); bool referenceStop(type != "N"); std::set<StopPoint*> stopsSet( _getStopPoints( stops, _stopCodePrefix + stopCode, boost::optional<const std::string&>() ) ); if(stopsSet.empty()) { _logWarning( "Can't find stops for code "+ _stopCodePrefix + stopCode ); continue; } servedStops.push_back( JourneyPattern::StopWithDepartureArrivalAuthorization( stopsSet, stopPos, (type != "A"), (type != "D"), referenceStop ) ); // Ignoring interpolated times if(referenceStop) { // If the bus leaves after midnight, the hours are stored as 0 instead of 24 if( !departureSchedules.empty() && departureTime < *departureSchedules.rbegin()) { departureTime += hours(24); } if( !arrivalSchedules.empty() && arrivalTime < *arrivalSchedules.rbegin()) { arrivalTime += hours(24); } // round of the seconds departureTime -= seconds(departureTime.seconds()); if(arrivalTime.seconds()) { arrivalTime += seconds(60 - arrivalTime.seconds()); } // storage of the times departureSchedules.push_back(departureTime); arrivalSchedules.push_back(arrivalTime); } } set<JourneyPattern*> routes( _getRoutes( *line, servedStops, *_plannedDataSource ) ); if(routes.empty()) { stringstream routeQuery; routeQuery << "SELECT * FROM " << _database << ".CHAINAGE c " << "WHERE c.ref='" << chainage << "' AND c.jour=" << todayStr; DBResultSPtr routeResult(db->execQuery(routeQuery.str())); if(routeResult->next()) { string routeName(routeResult->getText("nom")); bool wayBack(routeResult->getText("sens") != "A"); _logCreation( "Creation of route "+ routeName ); JourneyPattern* result = new JourneyPattern( JourneyPatternTableSync::getId() ); result->setCommercialLine(line); line->addPath(result); result->setName(routeName); result->setWayBack(wayBack); result->addCodeBySource(*_plannedDataSource, string()); _env.getEditableRegistry<JourneyPattern>().add(boost::shared_ptr<JourneyPattern>(result)); routes.insert(result); size_t rank(0); BOOST_FOREACH(const JourneyPattern::StopWithDepartureArrivalAuthorization stop, servedStops) { boost::shared_ptr<LineStop> ls( new LineStop( LineStopTableSync::getId(), result, rank, rank+1 < servedStops.size() && stop._departure, rank > 0 && stop._arrival, *stop._metricOffset, **stop._stop.begin() ) ); ls->set<ScheduleInput>(stop._withTimes ? *stop._withTimes : true); ls->link(_env, true); _env.getEditableRegistry<LineStop>().add(ls); ++rank; } } } assert(!routes.empty()); ScheduledService* service(NULL); BOOST_FOREACH(JourneyPattern* route, routes) { boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock( *route->sharedServicesMutex ); BOOST_FOREACH(Service* sservice, route->getAllServices()) { service = dynamic_cast<ScheduledService*>(sservice); if(!service) { continue; } if( service->isActive(today) && service->comparePlannedSchedules(departureSchedules, arrivalSchedules) ){ _logLoad( "Use of service "+ lexical_cast<string>(service->getKey()) +" ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); service->addCodeBySource(dataSource, serviceRef); _services.insert(service); break; } service = NULL; } if(service) { break; } } if(!service) { if (!departureSchedules.empty() && !arrivalSchedules.empty()) { JourneyPattern* route(*routes.begin()); service = new ScheduledService( ScheduledServiceTableSync::getId(), string(), route ); service->setDataSchedules(departureSchedules, arrivalSchedules); service->setPath(route); service->addCodeBySource(dataSource, serviceRef); service->setActive(today); route->addService(*service, false); _env.getEditableRegistry<ScheduledService>().add(boost::shared_ptr<ScheduledService>(service)); _services.insert(service); _logCreation( "Creation of service ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); } else { _logWarning( "Service (ref="+ serviceRef +") has empty departure or arrival schedules, not creating" ); } } } // 3 : loop on the planned services and remove current day of run if not linked to current source BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& obj, itLine.second) { BOOST_FOREACH(Path* route, obj->getPaths()) { // Avoid junctions if(!dynamic_cast<JourneyPattern*>(route)) { continue; } JourneyPattern* jp(static_cast<JourneyPattern*>(route)); if(!jp->hasLinkWithSource(*_plannedDataSource)) { continue; } boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock( *jp->sharedServicesMutex ); BOOST_FOREACH(const Service* service, jp->getAllServices()) { const ScheduledService* sservice(dynamic_cast<const ScheduledService*>(service)); if( sservice && sservice->isActive(today) && !sservice->hasLinkWithSource(dataSource) ){ const_cast<ScheduledService*>(sservice)->setInactive(today); _logInfo( "Deactivating unlinked service "+ lexical_cast<string>(sservice->getKey()) + " on route "+ lexical_cast<string>(sservice->getRoute()->getKey()) +" (" + sservice->getRoute()->getName() +")" ); } } } } } return true; } IneoRealTimeFileFormat::Importer_::Importer_( util::Env& env, const impex::Import& import, impex::ImportLogLevel minLogLevel, const std::string& logPath, boost::optional<std::ostream&> outputStream, util::ParametersMap& pm ): Importer(env, import, minLogLevel, logPath, outputStream, pm), DatabaseReadImporter<IneoRealTimeFileFormat>(env, import, minLogLevel, logPath, outputStream, pm), PTFileFormat(env, import, minLogLevel, logPath, outputStream, pm) {} util::ParametersMap IneoRealTimeFileFormat::Importer_::_getParametersMap() const { ParametersMap map; if(_plannedDataSource.get()) { map.insert(PARAMETER_PLANNED_DATASOURCE_ID, _plannedDataSource->getKey()); } if(_courseId) { map.insert(PARAMETER_COURSE_ID, *_courseId); } if(_dbConnString) { map.insert(PARAMETER_DB_CONN_STRING, *_dbConnString); } if(!_stopCodePrefix.empty()) { map.insert(PARAMETER_STOP_CODE_PREFIX, _stopCodePrefix); } return map; } void IneoRealTimeFileFormat::Importer_::_setFromParametersMap( const util::ParametersMap& map ) { if(map.isDefined(PARAMETER_PLANNED_DATASOURCE_ID)) try { _plannedDataSource = DataSourceTableSync::Get(map.get<RegistryKeyType>(PARAMETER_PLANNED_DATASOURCE_ID), _env); } catch(ObjectNotFoundException<DataSource>&) { throw Exception("No such planned data source"); } _courseId = map.getOptional<string>(PARAMETER_COURSE_ID); _dbConnString = map.getOptional<string>(PARAMETER_DB_CONN_STRING); _stopCodePrefix = map.getDefault<string>(PARAMETER_STOP_CODE_PREFIX, ""); } db::DBTransaction IneoRealTimeFileFormat::Importer_::_save() const { DBTransaction transaction; if(_courseId) { BOOST_FOREACH(ScheduledService* service, _services) { JourneyPatternTableSync::Save(static_cast<JourneyPattern*>(service->getPath()), transaction); BOOST_FOREACH(LineStop* edge, static_cast<JourneyPattern*>(service->getPath())->getLineStops()) { LineStopTableSync::Save(edge, transaction); } ScheduledServiceTableSync::Save(service, transaction); } } else { BOOST_FOREACH(const Registry<JourneyPattern>::value_type& journeyPattern, _env.getRegistry<JourneyPattern>()) { JourneyPatternTableSync::Save(journeyPattern.second.get(), transaction); } BOOST_FOREACH(Registry<LineStop>::value_type lineStop, _env.getRegistry<LineStop>()) { LineStopTableSync::Save(lineStop.second.get(), transaction); } BOOST_FOREACH(const Registry<ScheduledService>::value_type& service, _env.getRegistry<ScheduledService>()) { ScheduledServiceTableSync::Save(service.second.get(), transaction); } } return transaction; } } }
Open-Transport/synthese
server/src/61_data_exchange/IneoRealTimeFileFormat.cpp
C++
gpl-2.0
15,751
/*************************************************************************** orbitalviewerbase.h - description ------------------- begin : Thu Nov 4 2004 copyright : (C) 2004-2006 by Ben Swerts email : [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. * * * ***************************************************************************/ /// \file /// Contains the declaration of the class OrbitalViewerBase #ifndef ORBITALVIEWERBASE_H #define ORBITALVIEWERBASE_H ///// Forward class declarations & header files /////////////////////////////// ///// Qt forward class declarations class QHBoxLayout; class QTimer; ///// Xbrabo forward class declarations class ColorButton; class GLOrbitalView; class OrbitalOptionsWidget; class OrbitalThread; ///// Base class header file #include <qdialog.h> ///// class OrbitalViewerBase ///////////////////////////////////////////////// class OrbitalViewerBase : public QDialog { Q_OBJECT public: // constructor/destructor OrbitalViewerBase(QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0);// constructor ~OrbitalViewerBase(); // destructor protected: void customEvent(QCustomEvent* e); // reimplemented to receive events from calcThread private slots: void update(); // updates the view with the values of the widgets void adjustL(int newN); // adjust the orbital quantum number to the region 1 - n-1 void adjustM(int newL); // adjust the angular momentum quantum number to the region -l - +l void updateColors(); // updates the view with new colors void updateTypeOptions(int type); // updates the options to correspond to the chosen type void cancelCalculation(); // stops calculating a new orbital private: // private member functions void finishCalculation(); // finished up a calculation // private member variables QHBoxLayout* BigLayout; ///< All encompassing horizontal layout. OrbitalOptionsWidget* options; ///< Shows the options. GLOrbitalView* view; ///< Shows the orbital. ColorButton* ColorButtonPositive; ///< The pushbutton for choosing the colour of the positive values. ColorButton* ColorButtonNegative; ///< The pushbutton for choosing the colour of the negative values. OrbitalThread* calcThread; ///< The thread doing the calculation. QTimer* timer; ///< Handles periodic updating of the view during a calculation. }; #endif
steabert/brabosphere
brabosphere/include/orbitalviewerbase.h
C
gpl-2.0
3,284
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2011 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= #include "Module.h" #include "HostAPI.h" namespace XMP_PLUGIN { static bool CheckAPICompatibility_V1 ( const PluginAPIRef pluginAPIs ) { // these plugin APIs are mandatory to run an XMP file handler if ( pluginAPIs->mTerminatePluginProc && pluginAPIs->mSetHostAPIProc && pluginAPIs->mInitializeSessionProc && pluginAPIs->mTerminateSessionProc && pluginAPIs->mCheckFileFormatProc && pluginAPIs->mCheckFolderFormatProc && pluginAPIs->mGetFileModDateProc && pluginAPIs->mCacheFileDataProc && pluginAPIs->mUpdateFileProc && pluginAPIs->mWriteTempFileProc ) { return true; } return false; } static bool CheckAPICompatibility_V2 ( const PluginAPIRef pluginAPIs ) { if ( CheckAPICompatibility_V1 ( pluginAPIs ) ) { if ( pluginAPIs->mFillMetadataFilesProc && pluginAPIs->mFillAssociatedResourcesProc ) { return true; } } return false; } static bool CheckAPICompatibility_V3 ( const PluginAPIRef pluginAPIs ) { if ( CheckAPICompatibility_V2 ( pluginAPIs ) ) { if ( pluginAPIs->mIsMetadataWritableProc ) { return true; } } return false; } static bool CheckAPICompatibility ( const PluginAPIRef pluginAPIs ) { // Note: This is the place where we can reject old plugins. // For example if we consider all functionality of // plugin API version 2 mandatory we can reject // plugin version 1 by returning false in case 1. switch ( pluginAPIs->mVersion ) { case 1: return CheckAPICompatibility_V1 ( pluginAPIs ); break; case 2: return CheckAPICompatibility_V2 ( pluginAPIs ); break; case 3: return CheckAPICompatibility_V3 ( pluginAPIs ); break; default: // The loaded plugin is newer than the host. // Only basic functionality to run the plugin is required. return CheckAPICompatibility_V1 ( pluginAPIs ); break; } } PluginAPIRef Module::getPluginAPIs() { // // return ref. to Plugin API, load module if not yet loaded // if ( !mPluginAPIs || mLoaded != kModuleLoaded ) { if ( !load() ) { XMP_Throw ( "Plugin API not available.", kXMPErr_Unavailable ); } } return mPluginAPIs; } bool Module::load() { XMP_AutoLock lock ( &mLoadingLock, kXMP_WriteLock ); return loadInternal(); } void Module::unload() { XMP_AutoLock lock (&mLoadingLock, kXMP_WriteLock); unloadInternal(); } void Module::unloadInternal() { WXMP_Error error; // // terminate plugin // if( mPluginAPIs != NULL ) { if( mPluginAPIs->mTerminatePluginProc ) { mPluginAPIs->mTerminatePluginProc( &error ); } delete mPluginAPIs; mPluginAPIs = NULL; } // // unload plugin module // if( mLoaded != kModuleNotLoaded ) { UnloadModule(mHandle, false); mHandle = NULL; if( mLoaded == kModuleLoaded ) { // // Reset mLoaded to kModuleNotLoaded, if the module was loaded successfully. // Otherwise let it remain kModuleErrorOnLoad so that we won't try to load // it again if some other handler ask to do so. // mLoaded = kModuleNotLoaded; } } CheckError( error ); } bool Module::loadInternal() { if( mLoaded == kModuleNotLoaded ) { const char * errorMsg = NULL; // // load module // mLoaded = kModuleErrorOnLoad; mHandle = LoadModule(mPath, false); if( mHandle != NULL ) { // // get entry point function pointer // InitializePluginProc InitializePlugin = reinterpret_cast<InitializePluginProc>( GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin") ); // legacy entry point InitializePlugin2Proc InitializePlugin2 = reinterpret_cast<InitializePlugin2Proc>( GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin2") ); if( InitializePlugin2 != NULL || InitializePlugin != NULL ) { std::string moduleID; GetResourceDataFromModule(mHandle, "MODULE_IDENTIFIER", "txt", moduleID); mPluginAPIs = new PluginAPI(); memset( mPluginAPIs, 0, sizeof(PluginAPI) ); mPluginAPIs->mSize = sizeof(PluginAPI); mPluginAPIs->mVersion = XMP_PLUGIN_VERSION; // informational: the latest version that the host knows about WXMP_Error error; // // initialize plugin by calling entry point function // if( InitializePlugin2 != NULL ) { HostAPIRef hostAPI = PluginManager::getHostAPI( XMP_HOST_API_VERSION ); InitializePlugin2( moduleID.c_str(), hostAPI, mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers if( CheckAPICompatibility( mPluginAPIs ) ) { mLoaded = kModuleLoaded; } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } else if( InitializePlugin != NULL ) { // initialize through legacy plugin entry point InitializePlugin( moduleID.c_str(), mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers bool compatibleAPIs = CheckAPICompatibility(mPluginAPIs); if ( compatibleAPIs ) { // // set host API at plugin // HostAPIRef hostAPI = PluginManager::getHostAPI( mPluginAPIs->mVersion ); mPluginAPIs->mSetHostAPIProc( hostAPI, &error ); if( error.mErrorID == kXMPErr_NoError ) { mLoaded = kModuleLoaded; } else { errorMsg = "Plugin API incomplete."; } } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } } if( mLoaded != kModuleLoaded ) { // // plugin wasn't loaded and initialized successfully, // so unload the module // this->unloadInternal(); } } else { errorMsg = "Can't load module"; } if ( mLoaded != kModuleLoaded && errorMsg ) { // // error occurred // throw XMP_Error( kXMPErr_InternalFailure, errorMsg); } } return ( mLoaded == kModuleLoaded ); } } //namespace XMP_PLUGIN
yanburman/sjcam_raw2dng
xmp_sdk/XMPFiles/source/PluginHandler/Module.cpp
C++
gpl-2.0
6,540
package storm.starter.trident.homework.state; import storm.trident.operation.TridentCollector; import storm.trident.state.BaseStateUpdater; import storm.trident.tuple.TridentTuple; import java.util.ArrayList; import java.util.List; /** * Updater class that updates the state with the new tweets. * Created by Parth Satra on 4/5/15. */ public class TopKStateUpdater extends BaseStateUpdater<TopKState> { @Override public void updateState(TopKState topKState, List<TridentTuple> list, TridentCollector tridentCollector) { for(TridentTuple tuple : list) { // Gets all the space separated hashtags. String hashTags = tuple.getString(0); String[] tag = hashTags.split(" "); // Creates the list to be added to the state List<TopTweet> tweetList = new ArrayList<TopTweet>(); for(String t : tag) { if(t != null && t.trim().length() != 0) { TopTweet tt = new TopTweet(t, 1); tweetList.add(tt); } } // Adds the list to the state. topKState.add(tweetList); } } }
parthsatra/TwitterTopKTrends
apache-storm-0.9.3/examples/storm-starter/src/jvm/storm/starter/trident/homework/state/TopKStateUpdater.java
Java
gpl-2.0
1,167
</div> <footer> <p>copyright <a href="mailto:[email protected]">@Xiaoling Peng</a> <a href="0763363847">call me</a></p> </footer> </body> </html>
pengmaradi/xp_cms
system/cms/views/footer.php
PHP
gpl-2.0
182
@charset "utf-8"; #smenu_srch .iText, #smenu_srch button { background-color: #002a00; } #login_btn svg.active, #login_window .idpwWrap .login, #sider_nav h3 a, #sider_nav ul.smenu_3rdlevel { background-color: #005500; } #sider_nav ul.smenu_3rdlevel li a { border-bottom: 3px solid #005500; } #sider_nav, #login_window .idpw input[type=text], #login_window .idpw input[type=password] { background-color: #007f00; } #sider_nav ul.smenu_2ndlevel li a { border-bottom: 4px solid #007f00; } a:link, a:visited { color: #00aa00; } #topheader, .dialog_tline { background-color: #00aa00; } #header_nav ul li a { border-bottom: 5px solid #00aa00; } a:active, a:hover { /* 흰 바탕에 보이지 않는 #55ff55 색을 다른 색으로 대체 */ color: #55d455; } #header_nav ul li.active a { border-bottom: 5px solid #55ff55; } #sider_nav ul.smenu_2ndlevel li.active a { border-bottom: 4px solid #55ff55; } #sider_nav ul.smenu_3rdlevel li.active a { border-bottom: 3px solid #55ff55; } #topheader a:active, #topheader a:hover, #sider_nav a:active, #sider_nav a:hover, #login_window .idpwWrap .login:active, #login_window .idpwWrap .login:hover { color: #aaffaa; } #smenu_srch button:active svg .stro, #smenu_srch button:hover svg .stro, #login_close:active svg .stro, #login_close:hover svg .stro, #login_btn svg.active .stro { stroke: #aaffaa; } #login_btn svg.active .poly { fill: #aaffaa; }
JuwanPark/xe
layouts/sininen/css/green.css
CSS
gpl-2.0
1,497
<!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"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>ctas: /home/antonmx/work/projects/ctascmake/image/ Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.3 --> <script type="text/javascript"> function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } function toggleVisibility(linkObj) { var base = linkObj.getAttribute('id'); var summary = document.getElementById(base + '-summary'); var content = document.getElementById(base + '-content'); var trigger = document.getElementById(base + '-trigger'); if ( hasClass(linkObj,'closed') ) { summary.style.display = 'none'; content.style.display = 'block'; trigger.src = 'open.png'; removeClass(linkObj,'closed'); addClass(linkObj,'opened'); } else if ( hasClass(linkObj,'opened') ) { summary.style.display = 'block'; content.style.display = 'none'; trigger.src = 'closed.png'; removeClass(linkObj,'opened'); addClass(linkObj,'closed'); } return false; } </script> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">ctas&#160;<span id="projectnumber">0.5.2</span></div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_ce34702ad4994bea558d8c4eb1fcec0d.html">image</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>image Directory Reference</h1> </div> </div> <div class="contents"> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="subdirs"></a> Directories</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">directory &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dir_3ffc36e2e7d775ce6be9331a5d16efc1.html">bin</a></td></tr> </table> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Apr 8 2011 16:06:01 for ctas by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address> </body> </html>
antonmx/ctas
doc/site/develdoc/dir_ce34702ad4994bea558d8c4eb1fcec0d.html
HTML
gpl-2.0
3,189
<?php /** * @package gantry * @subpackage core.params * @version 3.2.11 September 8, 2011 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ defined('GANTRY_VERSION') or die(); gantry_import('core.params.gantryparamoverride'); /** * @package gantry * @subpackage core.params */ class GantrySessionParamOverride extends GantryParamOverride { function store(){ global $gantry; foreach($gantry->_setinsession as $session_var){ if ($gantry->_working_params[$session_var]['setby'] != 'menuitem') { if ($gantry->_working_params[$session_var]['value'] != $gantry->_working_params[$session_var]['sitebase'] && $gantry->_working_params[$session_var]['type'] != 'preset'){ $gantry->session->set($gantry->template_prefix.$gantry->_base_params_checksum."-".$session_var,$gantry->_working_params[$session_var]['value']); } else { $gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null); } } } } function clean(){ global $gantry; foreach($gantry->_setinsession as $session_var){ $gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null); } } function populate(){ global $gantry; // get any session param overrides and set to that // set preset values foreach($gantry->_preset_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); $session_preset_params = $gantry->presets[$param_name][$session_value]; foreach($session_preset_params as $session_preset_param_name => $session_preset_param_value) { if (array_key_exists($session_preset_param_name, $gantry->_working_params) && !is_null($session_preset_param_value)){ $gantry->_working_params[$session_preset_param_name]['value'] = $session_preset_param_value; $gantry->_working_params[$session_preset_param_name]['setby'] = 'session'; } } } } // set individual values foreach($gantry->_param_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); if (!is_null($session_value)){ $gantry->_working_params[$param['name']]['value'] = $session_value; $gantry->_working_params[$param['name']]['setby'] = 'session'; } } } } }
epireve/joomla
libraries/gantry/core/params/overrides/gantrysessionparamoverride.class.php
PHP
gpl-2.0
3,459
<?php /** * Shows basic event infos and countdowns. * * @param array $event_config The event configuration * @return string */ function EventConfig_countdown_page($event_config) { if ($event_config == null) { return div('col-md-12 text-center', [ heading(sprintf(_('Welcome to the %s!'), '<span class="icon-icon_angel"></span> HELFERSYSTEM'), 2) ]); } $elements = []; if ($event_config['event_name'] != null) { $elements[] = div('col-sm-12 text-center', [ heading(sprintf( _('Welcome to the %s!'), $event_config['event_name'] . ' <span class="icon-icon_angel"></span> HELFERSYSTEM' ), 2) ]); } if ($event_config['buildup_start_date'] != null && time() < $event_config['buildup_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Buildup starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['buildup_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['buildup_start_date']) . '</small>' ]); } if ($event_config['event_start_date'] != null && time() < $event_config['event_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_start_date']) . '</small>' ]); } if ($event_config['event_end_date'] != null && time() < $event_config['event_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_end_date']) . '</small>' ]); } if ($event_config['teardown_end_date'] != null && time() < $event_config['teardown_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Teardown ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['teardown_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['teardown_end_date']) . '</small>' ]); } return join('', $elements); } /** * Converts event name and start+end date into a line of text. * * @param array $event_config * @return string */ function EventConfig_info($event_config) { if ($event_config == null) { return ''; } // Event name, start+end date are set if ( $event_config['event_name'] != null && $event_config['event_start_date'] != null && $event_config['event_end_date'] != null ) { return sprintf( _('%s, from %s to %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Event name, start date are set if ($event_config['event_name'] != null && $event_config['event_start_date'] != null) { return sprintf( _('%s, starting %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']) ); } // Event start+end date are set if ($event_config['event_start_date'] != null && $event_config['event_end_date'] != null) { return sprintf( _('Event from %s to %s'), date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Only event name is set if ($event_config['event_name'] != null) { return sprintf($event_config['event_name']); } return ''; } /** * Render edit page for event config. * * @param string $event_name The event name * @param string $event_welcome_msg The welcome message * @param int $buildup_start_date unix time stamp * @param int $event_start_date unix time stamp * @param int $event_end_date unix time stamp * @param int $teardown_end_date unix time stamp * @return string */ function EventConfig_edit_view( $event_name, $event_welcome_msg, $buildup_start_date, $event_start_date, $event_end_date, $teardown_end_date ) { return page_with_title(event_config_title(), [ msg(), form([ div('row', [ div('col-md-6', [ form_text('event_name', _('Event Name'), $event_name), form_info('', _('Event Name is shown on the start page.')), form_textarea('event_welcome_msg', _('Event Welcome Message'), $event_welcome_msg), form_info( '', _('Welcome message is shown after successful registration. You can use markdown.') ) ]), div('col-md-3 col-xs-6', [ form_date('buildup_start_date', _('Buildup date'), $buildup_start_date), form_date('event_start_date', _('Event start date'), $event_start_date) ]), div('col-md-3 col-xs-6', [ form_date('teardown_end_date', _('Teardown end date'), $teardown_end_date), form_date('event_end_date', _('Event end date'), $event_end_date) ]) ]), div('row', [ div('col-md-6', [ form_submit('submit', _('Save')) ]) ]) ]) ]); }
froscon/engelsystem
includes/view/EventConfig_view.php
PHP
gpl-2.0
5,816
"""Module computes indentation for block It contains implementation of indenters, which are supported by katepart xml files """ import logging logger = logging.getLogger('qutepart') from PyQt4.QtGui import QTextCursor def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter) class Indenter: """Qutepart functionality, related to indentation Public attributes: width Indent width useTabs Indent uses Tabs (instead of spaces) """ _DEFAULT_INDENT_WIDTH = 4 _DEFAULT_INDENT_USE_TABS = False def __init__(self, qpart): self._qpart = qpart self.width = self._DEFAULT_INDENT_WIDTH self.useTabs = self._DEFAULT_INDENT_USE_TABS self._smartIndenter = _getSmartIndenter('normal', self._qpart, self) def setSyntax(self, syntax): """Choose smart indentation algorithm according to syntax""" self._smartIndenter = self._chooseSmartIndenter(syntax) def text(self): """Get indent text as \t or string of spaces """ if self.useTabs: return '\t' else: return ' ' * self.width def triggerCharacters(self): """Trigger characters for smart indentation""" return self._smartIndenter.TRIGGER_CHARACTERS def autoIndentBlock(self, block, char = '\n'): """Indent block after Enter pressed or trigger character typed """ cursor = QTextCursor(block) currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent) def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) # If end is positioned in the beginning of a block, do not indent this # block, since no text is selected in it (beginning of line) if endBlock.position()==cursor.selectionEnd(): endBlock=endBlock.previous() indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock) def onShortcutIndentAfterCursor(self): """Tab pressed and no selection. Insert text after cursor """ cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from line start charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width) cursor.insertText(' ' * charsToInsert) if cursor.positionInBlock() == 0: # if no any indent - indent smartly block = cursor.block() self.autoIndentBlock(block, '') # if no smart indentation - just insert one indent if self._qpart.textBeforeCursor() == '': insertIndent() else: insertIndent() def onShortcutUnindentWithBackspace(self): """Backspace pressed, unindent """ assert self._qpart.textBeforeCursor().endswith(self.text()) charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text()) if charsToRemove == 0: charsToRemove = len(self.text()) cursor = self._qpart.textCursor() cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() def onAutoIndentTriggered(self): """Indent current line or selected lines """ cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: self.autoIndentBlock(block, '') block = block.next() else: # indent 1 line self.autoIndentBlock(startBlock, '') def _chooseSmartIndenter(self, syntax): """Get indenter for syntax """ if syntax.indenter is not None: try: return _getSmartIndenter(syntax.indenter, self._qpart, self) except KeyError: logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter) try: return _getSmartIndenter(syntax.name, self._qpart, self) except KeyError: pass return _getSmartIndenter('normal', self._qpart, self)
amirgeva/coide
qutepart/indenter/__init__.py
Python
gpl-2.0
8,924
<?php # Database Configuration define( 'DB_NAME', 'wp_promedia' ); define( 'DB_USER', 'promedia' ); define( 'DB_PASSWORD', 'Hgcjr1nz4UG6M7kD4a2W' ); define( 'DB_HOST', '127.0.0.1' ); define( 'DB_HOST_SLAVE', '127.0.0.1' ); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', 'utf8_unicode_ci'); $table_prefix = 'wp_'; # Security Salts, Keys, Etc define('AUTH_KEY', 'a`F4guyG[^ Y}d c{idj5&MhTD&|JP[[]~@3:[oUZ0C+8}dUu9hqiW9ZJ-5c}6+|'); define('SECURE_AUTH_KEY', 'eU7MN1?7~|AT,pN|!qQ$3BhT%iYHi~}Uf%`R_eH#$I_XJy3utwjOa}-`Z8rP;eZ;'); define('LOGGED_IN_KEY', 'szAvG,^<>/so:#:-(6RKz~caq+*)lRek+o{44r$2?}?Qd.)taRY0+rd+d<6|nb>s'); define('NONCE_KEY', '0Sd#vgoYj|3 _{zHx+O!@bT*l13wu1=N+fNV]P7Cx|JzL_&=_5Kjs$y^P7?IEss+'); define('AUTH_SALT', 'vrQ2560/7/rdC)gXpr+&2;`w-RD%VyZwu+a5sV)!X<5s_Wq,7}S*7Q~vR|K(Lf*B'); define('SECURE_AUTH_SALT', 'wV^Lf;y6[zqv4!Bm8eZuE!u]k||b!mF]vAx|/)5,aQP`,Mav3SFC;2g`gL4*0F{R'); define('LOGGED_IN_SALT', '?|e&TXiXjP$H5#)*!6I+2]^w#?iL? G3H%pG[MvLgr|kT8+0?w&4BTX+nWnp57f`'); define('NONCE_SALT', '4~7piruf+MjyI%%H(U>r|GPuZDtb#EbJ|@ISBwf+V5+nzEzGNv>ihd#?#wpa+~/|'); # Localized Language Stuff define( 'WP_CACHE', TRUE ); define( 'WP_AUTO_UPDATE_CORE', false ); define( 'PWP_NAME', 'promedia' ); define( 'FS_METHOD', 'direct' ); define( 'FS_CHMOD_DIR', 0775 ); define( 'FS_CHMOD_FILE', 0664 ); define( 'PWP_ROOT_DIR', '/nas/wp' ); define( 'WPE_APIKEY', 'dfdfa423dd9708ad4a65f5e571606be13b075046' ); define( 'WPE_FOOTER_HTML', "" ); define( 'WPE_CLUSTER_ID', '1986' ); define( 'WPE_CLUSTER_TYPE', 'pod' ); define( 'WPE_ISP', true ); define( 'WPE_BPOD', false ); define( 'WPE_RO_FILESYSTEM', false ); define( 'WPE_LARGEFS_BUCKET', 'largefs.wpengine' ); define( 'WPE_LBMASTER_IP', '212.71.255.152' ); define( 'WPE_CDN_DISABLE_ALLOWED', true ); define( 'DISALLOW_FILE_EDIT', FALSE ); define( 'DISALLOW_FILE_MODS', FALSE ); define( 'DISABLE_WP_CRON', false ); define( 'WPE_FORCE_SSL_LOGIN', false ); define( 'FORCE_SSL_LOGIN', false ); /*SSLSTART*/ if ( isset($_SERVER['HTTP_X_WPE_SSL']) && $_SERVER['HTTP_X_WPE_SSL'] ) $_SERVER['HTTPS'] = 'on'; /*SSLEND*/ define( 'WPE_EXTERNAL_URL', false ); define( 'WP_POST_REVISIONS', FALSE ); define( 'WPE_WHITELABEL', 'wpengine' ); define( 'WP_TURN_OFF_ADMIN_BAR', false ); define( 'WPE_BETA_TESTER', false ); umask(0002); $wpe_cdn_uris=array ( ); $wpe_no_cdn_uris=array ( ); $wpe_content_regexs=array ( ); $wpe_all_domains=array ( 0 => 'promedia.wpengine.com', ); $wpe_varnish_servers=array ( 0 => 'pod-1986', ); $wpe_special_ips=array ( 0 => '212.71.255.152', ); $wpe_ec_servers=array ( ); $wpe_largefs=array ( ); $wpe_netdna_domains=array ( ); $wpe_netdna_domains_secure=array ( ); $wpe_netdna_push_domains=array ( ); $wpe_domain_mappings=array ( ); $memcached_servers=array ( ); define( 'WPE_SFTP_PORT', 22 ); define('WPLANG',''); # WP Engine ID # WP Engine Settings # That's It. Pencils down if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); require_once(ABSPATH . 'wp-settings.php'); $_wpe_preamble_path = null; if(false){}
clientrelation/promedia
wp-config.php
PHP
gpl-2.0
3,089
#ifndef _SS_CONSTS_HPP_ #define _SS_CONSTS_HPP_ #include "StrideSearchConfig.h" namespace StrideSearch { /// Meters per second to Kilometers per hour conversion factor static const Real MPS2KPH = 3.6; /// Knots to meters per second conversion factor static const Real KTS2MPS = 0.5144444; /// Nautical miles to kilometers conversion factor static const Real NM2KM = 1.852; /// Pi static constexpr Real PI = 3.1415926535897932384626433832795027975; /// Radians to degrees conversion factor static constexpr Real RAD2DEG = 180.0 / PI; /// Degrees to radians conversion factor static constexpr Real DEG2RAD = PI / 180.0; /// Hours to days conversion factor static constexpr Real HOURS2DAYS = 1.0/24.0; /// Minutes to days conversion factor static constexpr Real MINUTES2DAYS = 1.0/24.0/60.0; /// Gravitational acceleration static constexpr Real G = 9.80616; /// Mean sea level radius of the Earth (meters) static constexpr Real EARTH_RADIUS_KM = 6371.220; static constexpr Real SQ_EARTH_RADIUS_KM = EARTH_RADIUS_KM*EARTH_RADIUS_KM; /// One sidereal day, in units of seconds static constexpr Real SIDEREAL_DAY_SEC = 24.0 * 3600.0; /// Rotational rate of Earth about its z-axis static constexpr Real EARTH_OMEGA_HZ = 2.0 * PI / SIDEREAL_DAY_SEC; /// Floating point zero static constexpr Real ZERO_TOL = 1.0e-11; } #endif
pbosler/StrideSearch
src/SSConsts.hpp
C++
gpl-2.0
1,435
<?php /* $Id$ osCmax e-Commerce http://www.oscmax.com Copyright 2000 - 2011 osCmax Released under the GNU General Public License */ define('NAVBAR_TITLE', 'Cuénteselo a un amigo'); define('HEADING_TITLE', 'Háblele a un amigo sobre \'%s\''); define('FORM_TITLE_CUSTOMER_DETAILS', 'Sus datos'); define('FORM_TITLE_FRIEND_DETAILS', 'Los datos de sus amigo'); define('FORM_TITLE_FRIEND_MESSAGE', 'Su mensaje'); define('FORM_FIELD_CUSTOMER_NAME', 'Su nombre:'); define('FORM_FIELD_CUSTOMER_EMAIL', 'Su dirección e-mail:'); define('FORM_FIELD_FRIEND_NAME', 'Nombre de su amigo:'); define('FORM_FIELD_FRIEND_EMAIL', 'Dirección e-mail de su amigo:'); define('TEXT_EMAIL_SUCCESSFUL_SENT', 'Su e-mail acerca de <b>%s</b> ha sido correctamente enviado a <b>%s</b>.'); define('TEXT_EMAIL_SUBJECT', 'Tu amigo %s te ha recomendado este fantástico producto de %s'); define('TEXT_EMAIL_INTRO', '¡Hola %s!' . "\n\n" . 'Tu amigo, %s, cree que puedes estar interesado en %s de %s.'); define('TEXT_EMAIL_LINK', 'Para ver el producto pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); // LINE ADDED: MOD - ARTICLE MANAGER define('TEXT_EMAIL_LINK_ARTICLE', 'Para ver la noticia pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); define('TEXT_EMAIL_SIGNATURE', 'Saludos,' . "\n\n" . '%s'); define('ERROR_TO_NAME', 'Error: Debe rellenar el nombre de tu amigo.'); define('ERROR_TO_ADDRESS', 'Error: La dirección e-mail de su amigo debe ser una dirección válida.'); define('ERROR_FROM_NAME', 'Error: Debes rellenar su nombre.'); define('ERROR_FROM_ADDRESS', 'Error: Su dirección e-mail debe ser una dirección válida.'); ?>
osCmax/oscmax2
catalog/includes/languages/espanol/tell_a_friend.php
PHP
gpl-2.0
1,742
package eu.ttbox.geoping.ui.admob; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import eu.ttbox.geoping.BuildConfig; import eu.ttbox.geoping.R; import eu.ttbox.geoping.core.AppConstants; public class AdmobHelper { private static final String TAG = "AdmobHelper"; // =========================================================== // AdView : https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals // https://groups.google.com/forum/#!msg/google-admob-ads-sdk/8MCNsiVAc7A/pkRLcQ9zPtYJ // =========================================================== public static AdView bindAdMobView(Activity context) { // Admob final View admob = context.findViewById(R.id.admob); final AdView adView = (AdView) context.findViewById(R.id.adView); if (isAddBlocked(context)) { Log.d(TAG, "### is Add Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.GONE); Log.d(TAG, "### is Add Blocked adsContainer ==> GONE"); } } else { // Container Log.d(TAG, "### is Add Not Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.VISIBLE); Log.d(TAG, "### is Add Not Blocked adsContainer ==> VISIBLE"); } } // Request Ad if (adView != null) { // http://stackoverflow.com/questions/11790376/animated-mopub-admob-native-ads-overlayed-on-a-game-black-out-screen //adView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // Listener adView.setAdListener(new AdListener() { public void onAdOpened() { Log.d(TAG, "### AdListener onAdOpened AdView"); } public void onAdLoaded() { Log.d(TAG, "### AdListener onAdLoaded AdView"); } public void onAdFailedToLoad(int errorcode) { if (admob!=null) { Log.d(TAG, "### AdListener onAdFailedToLoad ==> HIDE adsContainer : " + admob); admob.setVisibility(View.GONE); } switch (errorcode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: Log.d(TAG, "### ########################################################################## ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INTERNAL_ERROR ###"); Log.d(TAG, "### ########################################################################## ###"); break; case AdRequest.ERROR_CODE_INVALID_REQUEST: Log.d(TAG, "### ########################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INVALID_REQUEST ###"); Log.d(TAG, "### ########################################################################### ###"); break; case AdRequest.ERROR_CODE_NETWORK_ERROR: Log.d(TAG, "### ######################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NETWORK_ERROR ###"); Log.d(TAG, "### ######################################################################### ###"); break; case AdRequest.ERROR_CODE_NO_FILL: Log.d(TAG, "### ################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NO_FILL ###"); Log.d(TAG, "### ################################################################### ###"); break; default: Log.d(TAG, "### ########################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = " + errorcode + " ###"); Log.d(TAG, "### ########################################################################### ###"); } } }); // adView.setAdUnitId(context.getString(R.string.admob_key)); // adView.setAdSize(AdSize.SMART_BANNER); AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (BuildConfig.DEBUG) { adRequestBuilder .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice("149D6C776DC12F380715698A396A64C4"); } AdRequest adRequest = adRequestBuilder.build(); adView.loadAd(adRequest); Log.d(TAG, "### Load adRequest AdView"); } else { Log.e(TAG, "### Null AdView"); } return adView; } public static boolean isAddBlocked(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean isAddBlocked = sharedPreferences != null ? sharedPreferences.getBoolean(AppConstants.PREFS_ADD_BLOCKED, false) : false; return isAddBlocked; } // =========================================================== // InterstitialAd // =========================================================== public static class AppAdListener extends AdListener { InterstitialAd interstitial; public AppAdListener() { } public AppAdListener(InterstitialAd interstitial) { this.interstitial = interstitial; } @Override public void onAdLoaded() { Log.i(TAG, "### AdListener : onAdLoaded"); super.onAdLoaded(); interstitial.show(); } } public static InterstitialAd displayInterstitialAd(Context context) { return displayInterstitialAd(context, new AppAdListener()); } public static InterstitialAd displayInterstitialAd(Context context, AppAdListener adListener) { final InterstitialAd interstitial = new InterstitialAd(context); interstitial.setAdUnitId(context.getString(R.string.admob_key)); // Add Listener adListener.interstitial = interstitial; interstitial.setAdListener(adListener); // Create ad request. AdRequest adRequest = new AdRequest.Builder().build(); // Begin loading your interstitial. interstitial.loadAd(adRequest); return interstitial; } }
gabuzomeu/geoPingProject
geoPing/src/main/java/eu/ttbox/geoping/ui/admob/AdmobHelper.java
Java
gpl-2.0
7,327
/* ** $Id: lgc.h,v 2.58 2012/09/11 12:53:08 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ #ifndef lgc_h #define lgc_h #include "lobject.h" #include "lstate.h" /* ** Collectable objects may have one of three colors: white, which ** means the object is not marked; gray, which means the ** object is marked, but its references may be not marked; and ** black, which means that the object and all its references are marked. ** The main invariant of the garbage collector, while marking objects, ** is that a black object can never point to a white one. Moreover, ** any gray object must be in a "gray list" (gray, grayagain, weak, ** allweak, ephemeron) so that it can be visited again before finishing ** the collection cycle. These lists have no meaning when the invariant ** is not being enforced (e.g., sweep phase). */ /* how much to allocate before next GC step */ #if !defined(GCSTEPSIZE) /* ~100 small strings */ #define GCSTEPSIZE (cast_int(100 * sizeof(TString))) #endif /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSatomic 1 #define GCSsweepstring 2 #define GCSsweepudata 3 #define GCSsweep 4 #define GCSpause 5 #define issweepphase(g) \ (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep) #define isgenerational(g) ((g)->gckind == KGC_GEN) /* ** macros to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a non-generational collection, the sweep ** phase may break the invariant, as objects turned white may point to ** still-black objects. The invariant is restored when sweep ends and ** all objects are white again. During a generational collection, the ** invariant must be kept all times. */ #define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic) /* ** Outside the collector, the state in generational mode is kept in ** 'propagate', so 'keepinvariant' is always true. */ #define keepinvariantout(g) \ check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \ g->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* Layout for bit use in `marked' field: */ #define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE1BIT 1 /* object is white (type 1) */ #define BLACKBIT 2 /* object is black */ #define FINALIZEDBIT 3 /* object has been separated for finalization */ #define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */ #define FIXEDBIT 5 /* object is fixed (should not be collected) */ #define OLDBIT 6 /* object is old (only in generational mode) */ /* bit 7 is currently used by tests (luaL_checkmemory) */ #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->gch.marked, WHITEBITS) #define isblack(x) testbit((x)->gch.marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT))) #define isold(x) testbit((x)->gch.marked, OLDBIT) /* MOVE OLD rule: whenever an object is moved to the beginning of a GC list, its old bit must be cleared */ #define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT) #define otherwhite(g) (g->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) #define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked) #define changewhite(x) ((x)->gch.marked ^= WHITEBITS) #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) #define luaC_condGC(L,c) \ {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);} #define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);) #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),gcvalue(v)); } #define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrierback_(L,p); } #define luaC_objbarrier(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),obj2gco(o)); } #define luaC_objbarrierback(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); } #define luaC_barrierproto(L,p,c) \ { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); } LUAI_FUNC void luaC_freeallobjects(lua_State *L); LUAI_FUNC void luaC_step(lua_State *L); LUAI_FUNC void luaC_forcestep(lua_State *L); LUAI_FUNC void luaC_runtilstate(lua_State *L, int statesmask); LUAI_FUNC void luaC_fullgc(lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj(lua_State *L, int tt, size_t sz, GCObject **list, int offset); LUAI_FUNC void luaC_barrier_(lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_(lua_State *L, GCObject *o); LUAI_FUNC void luaC_barrierproto_(lua_State *L, Proto *p, Closure *c); LUAI_FUNC void luaC_checkfinalizer(lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void luaC_checkupvalcolor(global_State *g, UpVal *uv); LUAI_FUNC void luaC_changemode(lua_State *L, int mode); #endif
samyk/proxmark3
client/deps/liblua/lgc.h
C
gpl-2.0
5,488
package org.cohorte.utilities.security; /** * @author ogattaz * */ public class CXPassphraseBuilder { /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aValue); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64OBFRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(new CXPassphraseOBF(new CXPassphraseRDM( aValue))); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aValue); } /** * @param aPassphrase * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aValue); } }
isandlaTech/cohorte-utilities
org.cohorte.utilities/src/org/cohorte/utilities/security/CXPassphraseBuilder.java
Java
gpl-2.0
2,174
'''Manual check (not a discoverable unit test) for the key import, to identify problems with gnupg, gpg, gpg1, gpg2 and so on''' import os import shutil from gnupg import GPG def setup_keyring(keyring_name): '''Setup the keyring''' keyring_path = os.path.join("test", "outputdata", keyring_name) # Delete the entire keyring shutil.rmtree(keyring_path, ignore_errors=True) os.makedirs(keyring_path) gpg = GPG(gnupghome=keyring_path, gpgbinary="gpg") for key_name in ["key1_private", "key1_public"]: with open(os.path.join("test", "inputdata", key_name + ".txt"), "r") as keyfile: key_str = "".join(keyfile.readlines()) import_result = gpg.import_keys(key_str) print("Import result:", type(import_result)) print(import_result.__dict__) if import_result.count == 1 and len(set(import_result.fingerprints)) == 1: print("Got one import result") return gpg CRYPTO = setup_keyring("keyringtest") if CRYPTO: print("Ready", CRYPTO) KEY_LIST = CRYPTO.list_keys(False) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of public keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS) KEY_LIST = CRYPTO.list_keys(True) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of private keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS)
activityworkshop/Murmeli
test/check_key_import.py
Python
gpl-2.0
1,429
<html> <head> <title>case sensitivity on id</title> <style> #test { background-color: blue; } #TEST { background-color: pink; } </style> <body> <div id="test">Hello</div> <div id="TEST">Goodbye</div> </body> </html>
geoffmcl/tidy-test
test/input5/in_caseid.html
HTML
gpl-2.0
216
#!/usr/bin/python """ Since functions are function instances you can wrap them Allow you to - modify arguments - modify function - modify results """ call_count = 0 def count(func): def wrapper(*args, **kw): global call_count call_count += 1 return func(*args, **kw) return wrapper def hello(): print 'Invoked hello' hello = count(hello) ## Now decorating hello to increment call count hello() print call_count hello() print call_count """ ## Syntactic Sugar >>> @count ... def hello(): ... print "Invoked hello" equals hello = count(hello) ## Syntactic Sugar 2 Dont add parens to the decorator >>> @count() ... def hello(): ... print "Invoked hello" ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: count() takes exactly 1 argument (0 given) >>> ##Decorator Template def decorator(func_to_decorate): def wrapper(*args, **kwargs): # do something before invocation result = func_to_decorate(*args,**kwargs) # do something after invocation return result #update wrapper.__doc__ and .func_name # or functools.wraps return wrapper ##Decorators can also be classes, to have a class that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result ##Decorators can also be classes 2, to have a instance that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): def wrapper(*args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result return wrapper ## The aboves lets you have an instance of a decorator that stores state (rather than using global state) ## Parameterized decorators (need 2 closures) def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result return wrapper return decorator >>> @limit(5) ## Decorating the simple function echo with limit 5 as parameter ... def echo(foo): ... return foo ... >>> echo ('123456') '12345' >>> Or you can use following as well , to limit the echo function with 3 as parameter >>> echo = limit(3)(echo) >>> echo ('123456') '123' >>> ## Decorator Tidying function attributes get mangled >>> def echo2(input): ... ###return input### I used ### instead of 3 coz that was causing some error ... return input ... >>> echo2.__doc__ 'return input' >>> echo2.func_name 'echo2' >>> >>> echo3 = limit(3)(echo2) >>> echo3.__doc__ >>> echo3.func_name 'wrapper' >>> #Now to fix above define your limit decorator as below def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result wrapper.__doc__ = function.__doc__ wrapper.func_name = function.func_name return wrapper return decorator >>> echo4 = limit(3)(echo2) >>> echo4.__doc__ 'return input' >>> echo4.func_name 'echo2' >>> #Decorator tidying (3) , using functools , more simple import functools def limit(length): def decorator(function): @functools.wraps(function) def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result #wrapper.__doc__ = function.__doc__ #wrapper.func_name = function.func_name return wrapper return decorator Uses for decorator - caching - monkey patching stdio - memoize - jsonify - logging time in function call - change cwd """ def cwd_decorator(func): """ decorator to change cwd to directory containing rst for this function """ def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith(".rst"): found = arg break if found: directory = os.path.dirname(arg) if directory: os.chdir(directory) data = func(*args, **kw) os.chdir(cur_dir) return data return wrapper """ ### Properties Call get/set methods via an instance attributes class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") from property.__doc__ """ import os def find_files(base_dir, recurse=True): """ yeild files found in base_dir """ for name in os.listdir(base_dir): filepath = os.path.join(base_dir, name) if os.path.isdir(filepath) and recurse: for child in find_files(filepath, recurse): yield child else: yield filepath
hiteshagrawal/python
generator-decorator/decorator.py
Python
gpl-2.0
4,681
<?php // ini_set('display_errors','1'); function nzshpcrt_getcategoryform($catid) { global $wpdb,$nzshpcrt_imagesize_info; $product = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `id`=$catid LIMIT 1",ARRAY_A); $output = ''; $output .= "<div class='editing_this_group form_table'>"; $output .= "<p>".str_replace("[categorisation]", htmlentities(stripslashes($product['name'])), TXT_WPSC_EDITING_GROUP)."</p>\n\r"; $output .= "<p><a href='' onclick='return showaddform()' class='add_category_link'><span>".str_replace("&quot;[categorisation]&quot;", "current", TXT_WPSC_ADDNEWCATEGORY)."</span></a></p>"; $output .="<dl>\n\r"; $output .=" <dt>Display Category Shortcode: </dt>\n\r"; $output .=" <dd> [wpsc_products category_url_name='{$product['nice-name']}']</dd>\n\r"; $output .=" <dt>Display Category Template Tag: </dt>\n\r"; $output .=" <dd> &lt;?php echo wpsc_display_products_page(array('category_url_name'=>'{$product['nice-name']}')); ?&gt;</dd>\n\r"; $output .="</dl>\n\r"; //$output .= " [ <a href='#' onclick='return showedit_categorisation_form()'>".TXT_WPSC_EDIT_THIS_GROUP."</a> ]"; $output .= "</div>"; $output .= " <table class='category_forms'>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($product['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_DESCRIPTION.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<textarea name='description' cols='40' rows='8' >".stripslashes($product['description'])."</textarea>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_CATEGORY_PARENT.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= wpsc_parent_category_list($product['group_id'], $product['id'], $product['category_parent']); $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if ($product['display_type'] == 'grid') { $display_type1="selected='selected'"; } else if ($product['display_type'] == 'default') { $display_type2="selected='selected'"; } switch($product['display_type']) { case "default": $product_view1 = "selected ='selected'"; break; case "grid": if(function_exists('product_display_grid')) { $product_view3 = "selected ='selected'"; break; } case "list": if(function_exists('product_display_list')) { $product_view2 = "selected ='selected'"; break; } default: $product_view0 = "selected ='selected'"; break; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_GROUP_IMAGE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='file' name='image' value='' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if(function_exists("getimagesize")) { if($product['image'] != '') { $imagepath = WPSC_CATEGORY_DIR . $product['image']; $imagetype = @getimagesize($imagepath); //previously exif_imagetype() $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".$imagetype[1]."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".$imagetype[0]."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r"; $output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } else { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".get_option('product_image_height')."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".get_option('product_image_width')."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r"; $output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_DELETEIMAGE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='checkbox' name='deleteimage' value='1' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; /* START OF TARGET MARKET SELECTION */ $countrylist = $wpdb->get_results("SELECT id,country,visible FROM `".WPSC_TABLE_CURRENCY_LIST."` ORDER BY country ASC ",ARRAY_A); $selectedCountries = $wpdb->get_col("SELECT countryid FROM `".WPSC_TABLE_CATEGORY_TM."` WHERE categoryid=".$product['id']." AND visible= 1"); // exit('<pre>'.print_r($countrylist,true).'</pre><br /><pre>'.print_r($selectedCountries,true).'</pre>'); $output .= " <tr>\n\r"; $output .= " <td colspan='2'><h4>Target Market Restrictions</h4></td></tr><tr><td>&nbsp;</td></tr><tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_TM.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; if(@extension_loaded('suhosin')) { $output .= "<em>".__("The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature then disable the suhosin extension, if you can not do this, you will need to contact your hosting provider. ",'wpsc')."</em>"; } else { $output .= "<span>Select: <a href='' class='wpsc_select_all'>All</a>&nbsp; <a href='' class='wpsc_select_none'>None</a></span><br />"; $output .= " <div id='resizeable' class='ui-widget-content multiple-select'>\n\r"; foreach($countrylist as $country){ if(in_array($country['id'], $selectedCountries)) /* if($country['visible'] == 1) */{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' checked='".$country['visible']."' />".$country['country']."<br />\n\r"; }else{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' />".$country['country']."<br />\n\r"; } } $output .= " </div><br /><br />"; $output .= " <span class='wpscsmall description'>Select the markets you are selling this category to.<span>\n\r"; } $output .= " </td>\n\r"; $output .= " </tr>\n\r"; //////// $output .= " <tr>\n\r"; $output .= " <td colspan='2' class='category_presentation_settings'>\n\r"; $output .= " <h4>".TXT_WPSC_PRESENTATIONSETTINGS."</h4>\n\r"; $output .= " <span class='small'>".TXT_WPSC_GROUP_PRESENTATION_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " ". TXT_WPSC_CATALOG_VIEW.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <select name='display_type'>\n\r"; $output .= " <option value='' $product_view0 >".TXT_WPSC_PLEASE_SELECT."</option>\n\r"; $output .= " <option value='default' $product_view1 >".TXT_WPSC_DEFAULT."</option>\n\r"; if(function_exists('product_display_list')) { $output .= " <option value='list' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } else { $output .= " <option value='list' disabled='disabled' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } if(function_exists('product_display_grid')) { $output .= " <option value='grid' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } else { $output .= " <option value='grid' disabled='disabled' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; if(function_exists("getimagesize")) { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_THUMBNAIL_SIZE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.": <input type='text' value='".$product['image_height']."' name='product_height' size='6'/> "; $output .= TXT_WPSC_WIDTH.": <input type='text' value='".$product['image_width']."' name='product_width' size='6'/> <br/>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td class='last_row'>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$product['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button-primary' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT_GROUP."' />"; $output .= "<a class='delete_button' href='".add_query_arg('deleteid', $product['id'], 'admin.php?page=wpsc-edit-groups')."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function nzshpcrt_getvariationform($variation_id) { global $wpdb,$nzshpcrt_imagesize_info; $variation_sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."` WHERE `id`='$variation_id' LIMIT 1"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A) ; $variation = $variation_data[0]; $output .= " <table class='category_forms' >\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($variation['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_VARIATION_VALUES.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $variation_values_sql = "SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `variation_id`='$variation_id' ORDER BY `id` ASC"; $variation_values = $wpdb->get_results($variation_values_sql,ARRAY_A); $variation_value_count = count($variation_values); $output .= "<div id='edit_variation_values'>"; $num = 0; foreach($variation_values as $variation_value) { $output .= "<span class='variation_value'>"; $output .= "<input type='text' class='text' name='variation_values[".$variation_value['id']."]' value='".htmlentities(stripslashes($variation_value['name']), ENT_QUOTES, 'UTF-8')."' />"; if($variation_value_count > 1) { $output .= " <a class='image_link' onclick='return remove_variation_value(this,".$variation_value['id'].")' href='#'><img src='".WPSC_URL."/images/trash.gif' alt='".TXT_WPSC_DELETE."' title='".TXT_WPSC_DELETE."' /></a>"; } $output .= "<br />"; $output .= "</span>"; $num++; } $output .= "</div>"; $output .= "<a href='#' onclick='return add_variation_value(\"edit\")'>".TXT_WPSC_ADD."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$variation['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT."' />"; $output .= "<a class='button delete_button' href='admin.php?page=".WPSC_DIR_NAME."/display_variations.php&amp;deleteid=".$variation['id']."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function coupon_edit_form($coupon) { $conditions = unserialize($coupon['condition']); $conditions = $conditions[0]; //exit('<pre>'.print_r($conditions, true).'</pre>'); $start_timestamp = strtotime($coupon['start']); $end_timestamp = strtotime($coupon['expiry']); $id = $coupon['id']; $output = ''; $output .= "<form name='edit_coupon' method='post' action='admin.php?page=".WPSC_DIR_NAME."/display-coupons.php'>\n\r"; $output .= " <input type='hidden' value='true' name='is_edit_coupon' />\n\r"; $output .= "<table class='add-coupon'>\n\r"; $output .= " <tr>\n\r"; $output .= " <th>".TXT_WPSC_COUPON_CODE."</th>\n\r"; $output .= " <th>".TXT_WPSC_DISCOUNT."</th>\n\r"; $output .= " <th>".TXT_WPSC_START."</th>\n\r"; $output .= " <th>".TXT_WPSC_EXPIRY."</th>\n\r"; $output .= " <th>".TXT_WPSC_USE_ONCE."</th>\n\r"; $output .= " <th>".TXT_WPSC_ACTIVE."</th>\n\r"; $output .= " <th>".TXT_WPSC_PERTICKED."</th>\n\r"; $output .= " <th></th>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' size='8' value='".$coupon['coupon_code']."' name='edit_coupon[".$id."][coupon_code]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' style='width:28px;' value='".$coupon['value']."' name=edit_coupon[".$id."][value]' />"; $output .= " <select style='width:20px;' name='edit_coupon[".$id."][is-percentage]'>"; $output .= " <option value='0' ".(($coupon['is-percentage'] == 0) ? "selected='true'" : '')." >$</option>\n\r";// $output .= " <option value='1' ".(($coupon['is-percentage'] == 1) ? "selected='true'" : '')." >%</option>\n\r"; $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_start = explode(" ",$coupon['start']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][start]' value='{$coupon_start[0]}'>"; /* $output .= " <select name='edit_coupon[".$id."][start][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == date("Y", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_expiry = explode(" ",$coupon['expiry']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][expiry]' value='{$coupon_expiry[0]}'>"; /*$output .= " <select name='edit_coupon[".$id."][expiry][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == (date("Y", $end_timestamp))) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>\n\r"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['use-once'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][active]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['active'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][active]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['every_product'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='".$id."' name='edit_coupon[".$id."][id]' />\n\r"; //$output .= " <input type='hidden' value='false' name='add_coupon' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_SUBMIT."' name='edit_coupon[".$id."][submit_coupon]' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_DELETE."' name='edit_coupon[".$id."][delete_coupon]' />\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; if($conditions != null){ $output .= "<tr>"; $output .= "<th>"; $output .= "Conditions"; $output .= "</th>"; $output .= "</tr>"; $output .= "<th>"; $output .= "Delete"; $output .= "</th>"; $output .= "<th>"; $output .= "Property"; $output .= "</th>"; $output .= "<th>"; $output .= "Logic"; $output .= "</th>"; $output .= "<th>"; $output .= "Value"; $output .= "</th>"; $output .= " </tr>\n\r"; $output .= "<tr>"; $output .= "<td>"; $output .= "<input type='hidden' name='coupon_id' value='".$id."' />"; $output .= "<input type='submit' value='Delete' name='delete_condition' />"; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['property']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['logic']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['value']; $output .= "</td>"; $output .= "</tr>"; }elseif($conditions == null){ $output .= wpsc_coupons_conditions( $id); } ?> <!-- <tr><td colspan="8"> <div class="coupon_condition"> <div><img height="16" width="16" class="delete" alt="Delete" src="<?=WPSC_URL?>/images/cross.png"/></button> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <button class="add" type="button"> <img height="16" width="16" alt="Add" src="<?=WPSC_URL?>/images/add.png"/> </button> </span> </div> </div> </tr> --> <?php $output .= "</table>\n\r"; $output .= "</form>\n\r"; echo $output; return $output; } function wpsc_coupons_conditions($id){ ?> <?php $output =' <input type="hidden" name="coupon_id" value="'.$id.'" /> <tr><td colspan="3"><b>Conditions</b></td></tr> <tr><td colspan="8"> <div class="coupon_condition"> <div> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <input type="submit" value="add" name="submit_condition" /> </span> </div> </div> </tr> '; return $output; } function setting_button(){ $itemsFeedURL = "http://www.google.com/base/feeds/items"; $next_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?page=wpsc-edit-products"; $redirect_url = 'https://www.google.com/accounts/AuthSubRequest?session=1'; $redirect_url .= '&next='; $redirect_url .= urlencode($next_url); $redirect_url .= "&scope="; $redirect_url .= urlencode($itemsFeedURL); // $output.="<div><img src='".get_option('siteurl')."/wp-content/plugins/".WPSC_DIR_NAME."/images/settings_button.jpg' onclick='display_settings_button()'>"; $output.="<div style='float: right; margin-top: 0px; position: relative;'> | <a href='#' onclick='display_settings_button(); return false;' style='text-decoration: underline;'>".TXT_WPSC_SETTINGS." &raquo;</a>"; $output.="<span id='settings_button' style='width:180px;background-color:#f1f1f1;position:absolute; right: 10px; border:1px solid black; display:none;'>"; $output.="<ul class='settings_button'>"; $output.="<li><a href='admin.php?page=wpsc-settings'>".TXT_WPSC_SHOP_SETTINGS."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=gateway'>".TXT_WPSC_MONEY_AND_PAYMENT."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=checkout'>".TXT_WPSC_CHECKOUT_PAGE_SETTINGS."</a></li>"; //$output.="<li><a href='?page=".WPSC_DIR_NAME."/instructions.php'>Help/Upgrade</a></li>"; //$output.="<li><a href='{$redirect_url}'>".TXT_WPSC_LOGIN_TO_GOOGLE_BASE."</a></li>"; $output.="</ul>"; // $output.="<div>Checkout Settings</div>"; $output.="</span>&emsp;&emsp;</div>"; return $output; } function wpsc_right_now() { global $wpdb,$nzshpcrt_imagesize_info; $year = date("Y"); $month = date("m"); $start_timestamp = mktime(0, 0, 0, $month, 1, $year); $end_timestamp = mktime(0, 0, 0, ($month+1), 0, $year); $replace_values[":productcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')"); $product_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')"); $replace_values[":productcount:"] .= " ".(($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL); $product_unit = (($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL); $replace_values[":groupcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')"); $group_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')"); $replace_values[":groupcount:"] .= " ".(($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL); $group_unit = (($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL); $replace_values[":salecount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $sales_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $replace_values[":salecount:"] .= " ".(($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL); $sales_unit = (($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL); $replace_values[":monthtotal:"] = nzshpcrt_currency_display(admin_display_total_price($start_timestamp, $end_timestamp),1); $replace_values[":overaltotal:"] = nzshpcrt_currency_display(admin_display_total_price(),1); $variation_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."`"); $variation_unit = (($variation_count == 1) ? TXT_WPSC_VARIATION_SINGULAR : TXT_WPSC_VARIATION_PLURAL); $replace_values[":pendingcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')"); $pending_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')"); $replace_values[":pendingcount:"] .= " " . (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $pending_sales_unit = (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $accept_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('2' ,'3', '4')"); $accept_sales_unit = (($accept_sales == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $replace_values[":theme:"] = get_option('wpsc_selected_theme'); $replace_values[":versionnumber:"] = WPSC_PRESENTABLE_VERSION; if (function_exists('add_object_page')) { $output=""; $output.="<div id='dashboard_right_now' class='postbox'>"; $output.=" <h3 class='hndle'>"; $output.=" <span>".TXT_WPSC_CURRENT_MONTH."</span>"; $output.=" <br class='clear'/>"; $output.=" </h3>"; $output .= "<div class='inside'>"; $output .= "<p class='sub'>".TXT_WPSC_AT_A_GLANCE."</p>"; //$output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>"; $output .= "<div class='table'>"; $output .= "<table>"; $output .= "<tr class='first'>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-products'>".$product_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($product_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$sales_count."</a>"; $output .= "</td>"; $output .= "<td class='last'>"; $output .= ucfirst($sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-groups'>".$group_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($group_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$pending_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t waiting'>".TXT_WPSC_PENDING." "; $output .= ucfirst($pending_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-variations'>".$variation_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($variation_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$accept_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t approved'>".TXT_WPSC_CLOSED." "; $output .= ucfirst($accept_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "</table>"; $output .= "</div>"; $output .= "<div class='versions'>"; $output .= "<p><a class='button rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>".TXT_WPSC_HERE_YOU_CAN_ADD."</p>"; $output .= "</div>"; $output .= "</div>"; $output.="</div>"; } else { $output=""; $output.="<div id='rightnow'>\n\r"; $output.=" <h3 class='reallynow'>\n\r"; $output.=" <a class='rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>\n\r"; $output.=" <span>"._('Right Now')."</span>\n\r"; //$output.=" <br class='clear'/>\n\r"; $output.=" </h3>\n\r"; $output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>\n\r"; $output.=" <p class='youare'>\n\r"; $output.=" ".TXT_WPSC_YOUAREUSING."\n\r"; //$output.=" <a class='rbutton' href='themes.php'>Change Theme</a>\n\r"; //$output.="<span id='wp-version-message'>This is WordPress version 2.6. <a class='rbutton' href='http://wordpress.org/download/'>Update to 2.6.1</a></span>\n\r"; $output.=" </p>\n\r"; $output.="</div>\n\r"; $output.="<br />\n\r"; $output = str_replace(array_keys($replace_values), array_values($replace_values),$output); } return $output; } function wpsc_packing_slip($purchase_id) { global $wpdb; $purch_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `id`='".$purchase_id."'"; $purch_data = $wpdb->get_row($purch_sql,ARRAY_A) ; //echo "<p style='padding-left: 5px;'><strong>".TXT_WPSC_DATE."</strong>:".date("jS M Y", $purch_data['date'])."</p>"; $cartsql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`=".$purchase_id.""; $cart_log = $wpdb->get_results($cartsql,ARRAY_A) ; $j = 0; if($cart_log != null) { echo "<div class='packing_slip'>\n\r"; echo "<h2>".TXT_WPSC_PACKING_SLIP."</h2>\n\r"; echo "<strong>".TXT_WPSC_ORDER." #</strong> ".$purchase_id."<br /><br />\n\r"; echo "<table>\n\r"; $form_sql = "SELECT * FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE `log_id` = '".(int)$purchase_id."'"; $input_data = $wpdb->get_results($form_sql,ARRAY_A); foreach($input_data as $input_row) { $rekeyed_input[$input_row['form_id']] = $input_row; } if($input_data != null) { $form_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `active` = '1'",ARRAY_A); foreach($form_data as $form_field) { switch($form_field['type']) { case 'country': $delivery_region_count = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `".WPSC_TABLE_REGION_TAX."` AS `regions` INNER JOIN `".WPSC_TABLE_CURRENCY_LIST."` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('".$wpdb->escape( $purch_data['billing_country'])."')"); if(is_numeric($purch_data['shipping_region']) && ($delivery_region_count > 0)) { echo " <tr><td>".__('State', 'wpsc').":</td><td>".wpsc_get_region($purch_data['shipping_region'])."</td></tr>\n\r"; } echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['billing_country'])."</td></tr>\n\r"; break; case 'delivery_country': echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['shipping_country'])."</td></tr>\n\r"; break; case 'heading': echo " <tr><td colspan='2'><strong>".wp_kses($form_field['name'], array() ).":</strong></td></tr>\n\r"; break; default: echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".htmlentities(stripslashes($rekeyed_input[$form_field['id']]['value']), ENT_QUOTES)."</td></tr>\n\r"; break; } } } else { echo " <tr><td>".TXT_WPSC_NAME.":</td><td>".$purch_data['firstname']." ".$purch_data['lastname']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_ADDRESS.":</td><td>".$purch_data['address']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_PHONE.":</td><td>".$purch_data['phone']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_EMAIL.":</td><td>".$purch_data['email']."</td></tr>\n\r"; } if(get_option('payment_method') == 2) { $gateway_name = ''; foreach($GLOBALS['nzshpcrt_gateways'] as $gateway) { if($purch_data['gateway'] != 'testmode') { if($gateway['internalname'] == $purch_data['gateway'] ) { $gateway_name = $gateway['name']; } } else { $gateway_name = "Manual Payment"; } } } // echo " <tr><td colspan='2'></td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_PAYMENT_METHOD.":</td><td>".$gateway_name."</td></tr>\n\r"; // //echo " <tr><td>".TXT_WPSC_PURCHASE_NUMBER.":</td><td>".$purch_data['id']."</td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_HOWCUSTOMERFINDUS.":</td><td>".$purch_data['find_us']."</td></tr>\n\r"; // $engrave_line = explode(",",$purch_data['engravetext']); // echo " <tr><td>".TXT_WPSC_ENGRAVE."</td><td></td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_ONE.":</td><td>".$engrave_line[0]."</td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_TWO.":</td><td>".$engrave_line[1]."</td></tr>\n\r"; // if($purch_data['transactid'] != '') { // echo " <tr><td>".TXT_WPSC_TXN_ID.":</td><td>".$purch_data['transactid']."</td></tr>\n\r"; // } echo "</table>\n\r"; echo "<table class='packing_slip'>"; echo "<tr>"; echo " <th>".TXT_WPSC_QUANTITY." </th>"; echo " <th>".TXT_WPSC_NAME."</th>"; echo " <th>".TXT_WPSC_PRICE." </th>"; echo " <th>".TXT_WPSC_SHIPPING." </th>"; echo '<th>Tax</th>'; echo '</tr>'; $endtotal = 0; $all_donations = true; $all_no_shipping = true; $file_link_list = array(); foreach($cart_log as $cart_row) { $alternate = ""; $j++; if(($j % 2) != 0) { $alternate = "class='alt'"; } $productsql= "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`=".$cart_row['prodid'].""; $product_data = $wpdb->get_results($productsql,ARRAY_A); $variation_sql = "SELECT * FROM `".WPSC_TABLE_CART_ITEM_VARIATIONS."` WHERE `cart_id`='".$cart_row['id']."'"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A); $variation_count = count($variation_data); if($variation_count > 1) { $variation_list = " ("; $i = 0; foreach($variation_data as $variation) { if($i > 0) { $variation_list .= ", "; } $value_id = $variation['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list .= $value_data[0]['name']; $i++; } $variation_list .= ")"; } else if($variation_count == 1) { $value_id = $variation_data[0]['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list = " (".$value_data[0]['name'].")"; } else { $variation_list = ''; } if($cart_row['donation'] != 1) { $all_donations = false; } if($cart_row['no_shipping'] != 1) { $shipping = $cart_row['pnp'] * $cart_row['quantity']; $total_shipping += $shipping; $all_no_shipping = false; } else { $shipping = 0; } $price = $cart_row['price'] * $cart_row['quantity']; $gst = $price - ($price / (1+($cart_row['gst'] / 100))); if($gst > 0) { $tax_per_item = $gst / $cart_row['quantity']; } echo "<tr $alternate>"; echo " <td>"; echo $cart_row['quantity']; echo " </td>"; echo " <td>"; echo $product_data[0]['name']; echo stripslashes($variation_list); echo " </td>"; echo " <td>"; echo nzshpcrt_currency_display( $price, 1); echo " </td>"; echo " <td>"; echo nzshpcrt_currency_display($shipping, 1); echo " </td>"; echo '<td>'; echo nzshpcrt_currency_display($cart_row['tax_charged'],1); echo '<td>'; echo '</tr>'; } echo "</table>"; echo "</div>\n\r"; } else { echo "<br />".TXT_WPSC_USERSCARTWASEMPTY; } } function wpsc_product_item_row() { } ?>
alx/SimplePress
wp-content/plugins/wp-e-commerce/admin-form-functions.php
PHP
gpl-2.0
37,491