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
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
package lionse.client.stage; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import lionse.client.Display; import lionse.client.asset.Asset; import lionse.client.net.Header; import lionse.client.net.Server; public class Character implements Renderable { // character format constant values public static final float RESOLUTION = 1.5f; public static final float C_HEAD = 0 * RESOLUTION; public static final float C_FACE = 10 * RESOLUTION; public static final float C_BODY = 24 * RESOLUTION; public static final float C_HAND = 29 * RESOLUTION; public static final float C_LEG = 30 * RESOLUTION; public static LabelStyle NAME_TAG_STYLE; public static float[] SINE_WAVE = { 0, 0.27f, 0.52f, 0.74f, 0.89f, 0.98f, 0.99f, 0.93f, 0.79f, 0.59f, 0.35f, 0.08f, -0.19f, -0.45f, -0.67f, -0.85f, -0.96f, -0.99f, -0.95f, -0.84f, -0.66f, -0.43f, -0.17f }; static { NAME_TAG_STYLE = new LabelStyle(); NAME_TAG_STYLE.font = Asset.Font.get(Asset.NanumGothic); NAME_TAG_STYLE.fontColor = Color.BLACK; } public boolean me = false; // character property public String name; public int head; public int face; public int body; public int clothes; public int weapon; public float speed = 200f; // positioning property public Point position; public Point target; public Point bottom; // character graphics public Label nameTag; // ��dz�� ��� public TalkBalloon talkBalloon; // ��ũ ���߱� ��� public List<Path> path; public int pathIndex = 0; public int direction = 0; public boolean moving = false; private int step = 0; // graphics variables private float stepTime = 0; private int next = -1; // graphics cache private TextureRegion[] texture_head; private TextureRegion[] texture_face; private TextureRegion[] texture_body; private TextureRegion[] texture_hand; private TextureRegion[] texture_leg_stop; private TextureRegion[] texture_leg_step1; private TextureRegion[] texture_leg_step2; private TextureRegion[] texture_leg_step3; private TextureRegion[] texture_leg_step4; // animated character format (sine-wave) private float p_head; private float p_face; private float p_body; private float p_hand; // name, head, face, body, clothes, weapon public Character(String name, int head, int face, int body, int weapon) { this.name = name; this.head = head; this.face = face; this.body = body; this.weapon = weapon; this.position = new Point(); this.bottom = new Point(); this.talkBalloon = new TalkBalloon(this); this.nameTag = new Label(name, NAME_TAG_STYLE); this.path = new ArrayList<Path>(); cache(); } // cache values. if this method is not called when texture value is // changed.noting happens to the graphic public void cache() { texture_head = Asset.Character.get("HEAD"); texture_face = Asset.Character.get("FACE"); texture_body = Asset.Character.get("BODY"); texture_hand = Asset.Character.get("HAND"); texture_leg_stop = Asset.Character.get("LEG_STAND"); texture_leg_step1 = Asset.Character.get("LEG_STEP1"); texture_leg_step2 = Asset.Character.get("LEG_STEP2"); texture_leg_step3 = Asset.Character.get("LEG_STEP3"); texture_leg_step4 = Asset.Character.get("LEG_STEP4"); } public void talk(String message) { talkBalloon.show(message); } @Override public void draw(SpriteBatch spriteBatch, float delta) { // Debugger.log(texture_head.length); // draw leg if (moving) { switch (step) { case 0: spriteBatch.draw(texture_leg_step1[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 1: spriteBatch.draw(texture_leg_step2[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 2: spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 3: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 4: spriteBatch.draw(texture_leg_step4[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 5: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; } } else { spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); } // draw body spriteBatch.draw(texture_body[direction], position.x, Display.HEIGHT - (position.y + p_body)); // draw hands spriteBatch.draw(texture_hand[direction], position.x, Display.HEIGHT - (position.y + p_hand)); // draw face spriteBatch.draw(texture_face[direction], position.x, Display.HEIGHT - (position.y + p_face)); // draw head spriteBatch.draw(texture_head[direction], position.x, Display.HEIGHT - (position.y + p_head)); // draw name tag nameTag.draw(spriteBatch, 1); // draw talk balloon if (talkBalloon.talking) talkBalloon.draw(spriteBatch, delta); } @Override public void update(float delta) { // update time values. stepTime += delta; next += 1; if (next >= SINE_WAVE.length) next = 0; // increase step if moving. if (stepTime > 0.05f && moving) { step += 1; stepTime = 0; if (step > 5) step = 0; } // �̵����̶�� ��ǥ�� ������Ʈ�Ѵ�. // if (moving) { // updatePosition(delta); // �̵� ���� �� ��ũ ������ �߻��Ѵ�. if (me && moving) { updatePosition(delta); } else if (this.path.size() > 0 && !me && this.path.size() > pathIndex) { Path path = this.path.get(pathIndex); if (path.disabled) { pathIndex++; } else { this.direction = path.direction; if (path.target == null) { updatePosition(delta); } else { // moveTo(path, delta); updatePosition(delta); } // ���� ��ǥ�� Ÿ�� ��ǥ�� �˻��ؼ� ���� �ȿ� ������ �Ϸ� if (path.check(position)) { // �Ϸ� ��, ���ÿ��� �����Ͱ� 0�̸� ������ �ʱ�ȭ�Ѵ� (�޸� ���) if (this.path.size() - 1 <= pathIndex) { this.path.clear(); pathIndex = 0; } else { pathIndex++; } // ���̰� �ʹ� ũ�� �� ��� �ϵ弼���Ѵ�. } else if (path.previousDistance > 2000 && path.target != null) { // ������ ���� ���� position.x = path.target.x; position.y = path.target.y; } } } nameTag.setPosition(position.x - (nameTag.getWidth() / 2) + 27, Display.HEIGHT - position.y + 27); if (talkBalloon.talking) talkBalloon.update(delta); // ���� ������ ���� ������ ���� �Ųٱ� ���� ��δ� �������� �̺�Ʈ�� ���� �� �̸� ����� ���´�. // ���� �Ųٴ� ���� move �̺�Ʈ�� ���Դٸ� ���ÿ� �״´�. // ��� ������ �����̹Ƿ�, ��ǥ üũ�� �����ϴ�! ^^ // animation effect. (sine wave) p_head = C_HEAD + SINE_WAVE[next] * 2f; p_face = C_FACE + SINE_WAVE[next] * 2f; p_body = C_BODY + SINE_WAVE[next] * 2; p_hand = C_HAND + SINE_WAVE[next] * 2; } private void updatePosition(float delta) { switch (direction) { case 0: position.x -= speed * delta; position.y += speed * delta / 2; break; case 1: position.x -= speed * delta; break; case 2: position.x -= speed * delta; position.y -= speed * delta / 2; break; case 3: position.y -= speed * delta / 2; break; case 4: position.x += speed * delta; position.y -= speed * delta / 2; break; case 5: position.x += speed * delta; break; case 6: position.x += speed * delta; position.y += speed * delta / 2; break; case 7: position.y += speed * delta / 2; break; } } @Override public Point getPosition() { bottom.x = position.x; bottom.y = position.y + 150; bottom.z = position.z; return bottom; } public void move(int targetDirection) { this.direction = targetDirection; Server.send(Header.MOVE + Server.H_L + direction + Server.H_L + Math.round(speed) + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public void stop() { Server.send(Header.STOP + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public int getDirection(Point point) { int xdet = 0; // -1-����, 0-���� ����, 1-������ int ydet = 0; // -1-�Ʒ���, 0-���� ����, 1-���� if (point.x - position.x > 0) { // �����ʿ� �ִ�. xdet = 1; } else if (point.x == position.x) { // ����. } else {// ���ʿ� �ִ�. xdet = -1; } if (point.y - position.y > 0) { // ���ʿ� �ִ�. ydet = -1; } else if (point.y == position.y) { // ����. } else {// �Ʒ��ʿ� �ִ�. ydet = 1; } if (xdet > 0) { // ������ if (ydet > 0) { // ������ �� return 4; } else if (ydet == 0) { // �׳� ������ return 5; } else { // ������ �Ʒ� return 6; } } else if (xdet == 0) { // y�� ������ if (ydet > 0) { // �� return 3; } else if (ydet == 0) { // �� ������ (����Ʈ ��ũ!) return -1; } else { // �Ʒ� return 7; } } else { // ���� if (ydet > 0) { // ���� �� return 2; } else if (ydet == 0) { // �׳� ���� return 1; } else { // ���� �Ʒ� return 0; } } } }
agemor/lionse
src/lionse/client/stage/Character.java
Java
gpl-2.0
10,099
25.689855
156
0.604257
false
#include <linux/module.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_NFLOG.h> #include <net/netfilter/nf_log.h> #include <net/netfilter/nfnetlink_log.h> MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>"); MODULE_DESCRIPTION("Xtables: packet logging to netlink using NFLOG"); MODULE_LICENSE("GPL"); MODULE_ALIAS("ipt_NFLOG"); MODULE_ALIAS("ip6t_NFLOG"); static unsigned int nflog_tg(struct sk_buff *skb, const struct xt_target_param *par) { const struct xt_nflog_info *info = par->targinfo; struct nf_loginfo li; li.type = NF_LOG_TYPE_ULOG; li.u.ulog.copy_len = info->len; li.u.ulog.group = info->group; li.u.ulog.qthreshold = info->threshold; nfulnl_log_packet(par->family, par->hooknum, skb, par->in, par->out, &li, info->prefix); return XT_CONTINUE; } static bool nflog_tg_check(const struct xt_tgchk_param *par) { const struct xt_nflog_info *info = par->targinfo; if (info->flags & ~XT_NFLOG_MASK) return false; if (info->prefix[sizeof(info->prefix) - 1] != '\0') return false; return true; } static struct xt_target nflog_tg_reg __read_mostly = { .name = "NFLOG", .revision = 0, .family = NFPROTO_UNSPEC, .checkentry = nflog_tg_check, .target = nflog_tg, .targetsize = sizeof(struct xt_nflog_info), .me = THIS_MODULE, }; static int __init nflog_tg_init(void) { return xt_register_target(&nflog_tg_reg); } static void __exit nflog_tg_exit(void) { xt_unregister_target(&nflog_tg_reg); } module_init(nflog_tg_init); module_exit(nflog_tg_exit);
leemgs/OptimusOneKernel-KandroidCommunity
net/netfilter/xt_NFLOG.c
C
gpl-2.0
1,599
23.227273
69
0.682927
false
package com.lami.tuomatuo.mq.zookeeper.server; import com.lami.tuomatuo.mq.zookeeper.jmx.ZKMBeanInfo; /** * This class implements the data tree MBean * * Created by xujiankang on 2017/3/19. */ public class DataTreeBean implements DataTreeMXBean, ZKMBeanInfo{ public DataTree dataTree; public DataTreeBean(DataTree dataTree) { this.dataTree = dataTree; } @Override public int getNodeCount() { return dataTree.getNodeCount(); } @Override public long approximateDataSize() { return dataTree.approximateDataSize(); } @Override public int countEphemerals() { return dataTree.getEphemeralsCount(); } public int getWatchCount(){ return dataTree.getWatchCount(); } @Override public String getName() { return "InMemoryDataTree"; } @Override public boolean isHidden() { return false; } @Override public String getLastZxid() { return "0x" + Long.toHexString(dataTree.lastProcessedZxid); } }
jackkiexu/tuomatuo
tuomatuo-mq/src/main/java/com/lami/tuomatuo/mq/zookeeper/server/DataTreeBean.java
Java
gpl-2.0
1,052
19.627451
67
0.653992
false
/* * linux/arch/arm/kernel/setup.c * * Copyright (C) 1995-2001 Russell King * * 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/module.h> #include <linux/kernel.h> #include <linux/stddef.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/utsname.h> #include <linux/initrd.h> #include <linux/console.h> #include <linux/bootmem.h> #include <linux/seq_file.h> #include <linux/screen_info.h> #include <linux/init.h> #include <linux/kexec.h> #include <linux/of_fdt.h> #include <linux/crash_dump.h> #include <linux/root_dev.h> #include <linux/cpu.h> #include <linux/interrupt.h> #include <linux/smp.h> #include <linux/fs.h> #include <linux/proc_fs.h> #include <linux/memblock.h> #include <asm/unified.h> #include <asm/cpu.h> #include <asm/cputype.h> #include <asm/elf.h> #include <asm/procinfo.h> #include <asm/sections.h> #include <asm/setup.h> #include <asm/smp_plat.h> #include <asm/mach-types.h> #include <asm/cacheflush.h> #include <asm/cachetype.h> #include <asm/tlbflush.h> #include <asm/prom.h> #include <asm/mach/arch.h> #include <asm/mach/irq.h> #include <asm/mach/time.h> #include <asm/traps.h> #include <asm/unwind.h> #if defined(CONFIG_DEPRECATED_PARAM_STRUCT) #include "compat.h" #endif #include "atags.h" #include "tcm.h" #ifndef MEM_SIZE #define MEM_SIZE (16*1024*1024) #endif #if defined(CONFIG_FPE_NWFPE) || defined(CONFIG_FPE_FASTFPE) char fpe_type[8]; static int __init fpe_setup(char *line) { memcpy(fpe_type, line, 8); return 1; } __setup("fpe=", fpe_setup); #endif extern void paging_init(struct machine_desc *desc); extern void sanity_check_meminfo(void); extern void reboot_setup(char *str); unsigned int processor_id; EXPORT_SYMBOL(processor_id); unsigned int __machine_arch_type __read_mostly; EXPORT_SYMBOL(__machine_arch_type); unsigned int cacheid __read_mostly; EXPORT_SYMBOL(cacheid); unsigned int __atags_pointer __initdata; unsigned int system_rev; EXPORT_SYMBOL(system_rev); unsigned int system_serial_low; EXPORT_SYMBOL(system_serial_low); unsigned int system_serial_high; EXPORT_SYMBOL(system_serial_high); unsigned int elf_hwcap __read_mostly; EXPORT_SYMBOL(elf_hwcap); #ifdef MULTI_CPU struct processor processor __read_mostly; #endif #ifdef MULTI_TLB struct cpu_tlb_fns cpu_tlb __read_mostly; #endif #ifdef MULTI_USER struct cpu_user_fns cpu_user __read_mostly; #endif #ifdef MULTI_CACHE struct cpu_cache_fns cpu_cache __read_mostly; #endif #ifdef CONFIG_OUTER_CACHE struct outer_cache_fns outer_cache __read_mostly; EXPORT_SYMBOL(outer_cache); #endif struct stack { u32 irq[3]; u32 abt[3]; u32 und[3]; } ____cacheline_aligned; static struct stack stacks[NR_CPUS]; char elf_platform[ELF_PLATFORM_SIZE]; EXPORT_SYMBOL(elf_platform); static const char *cpu_name; static const char *machine_name; static char __initdata cmd_line[COMMAND_LINE_SIZE]; struct machine_desc *machine_desc __initdata; static char default_command_line[COMMAND_LINE_SIZE] __initdata = CONFIG_CMDLINE; static union { char c[4]; unsigned long l; } endian_test __initdata = { { 'l', '?', '?', 'b' } }; #define ENDIANNESS ((char)endian_test.l) DEFINE_PER_CPU(struct cpuinfo_arm, cpu_data); /* * Standard memory resources */ static struct resource mem_res[] = { { .name = "Video RAM", .start = 0, .end = 0, .flags = IORESOURCE_MEM }, { .name = "Kernel text", .start = 0, .end = 0, .flags = IORESOURCE_MEM }, { .name = "Kernel data", .start = 0, .end = 0, .flags = IORESOURCE_MEM } }; #define video_ram mem_res[0] #define kernel_code mem_res[1] #define kernel_data mem_res[2] static struct resource io_res[] = { { .name = "reserved", .start = 0x3bc, .end = 0x3be, .flags = IORESOURCE_IO | IORESOURCE_BUSY }, { .name = "reserved", .start = 0x378, .end = 0x37f, .flags = IORESOURCE_IO | IORESOURCE_BUSY }, { .name = "reserved", .start = 0x278, .end = 0x27f, .flags = IORESOURCE_IO | IORESOURCE_BUSY } }; #define lp0 io_res[0] #define lp1 io_res[1] #define lp2 io_res[2] static const char *proc_arch[] = { "undefined/unknown", "3", "4", "4T", "5", "5T", "5TE", "5TEJ", "6TEJ", "7", "?(11)", "?(12)", "?(13)", "?(14)", "?(15)", "?(16)", "?(17)", }; int cpu_architecture(void) { int cpu_arch; if ((read_cpuid_id() & 0x0008f000) == 0) { cpu_arch = CPU_ARCH_UNKNOWN; } else if ((read_cpuid_id() & 0x0008f000) == 0x00007000) { cpu_arch = (read_cpuid_id() & (1 << 23)) ? CPU_ARCH_ARMv4T : CPU_ARCH_ARMv3; } else if ((read_cpuid_id() & 0x00080000) == 0x00000000) { cpu_arch = (read_cpuid_id() >> 16) & 7; if (cpu_arch) cpu_arch += CPU_ARCH_ARMv3; } else if ((read_cpuid_id() & 0x000f0000) == 0x000f0000) { unsigned int mmfr0; /* Revised CPUID format. Read the Memory Model Feature * Register 0 and check for VMSAv7 or PMSAv7 */ asm("mrc p15, 0, %0, c0, c1, 4" : "=r" (mmfr0)); if ((mmfr0 & 0x0000000f) >= 0x00000003 || (mmfr0 & 0x000000f0) >= 0x00000030) cpu_arch = CPU_ARCH_ARMv7; else if ((mmfr0 & 0x0000000f) == 0x00000002 || (mmfr0 & 0x000000f0) == 0x00000020) cpu_arch = CPU_ARCH_ARMv6; else cpu_arch = CPU_ARCH_UNKNOWN; } else cpu_arch = CPU_ARCH_UNKNOWN; return cpu_arch; } static int cpu_has_aliasing_icache(unsigned int arch) { int aliasing_icache; unsigned int id_reg, num_sets, line_size; /* arch specifies the register format */ switch (arch) { case CPU_ARCH_ARMv7: asm("mcr p15, 2, %0, c0, c0, 0 @ set CSSELR" : /* No output operands */ : "r" (1)); isb(); asm("mrc p15, 1, %0, c0, c0, 0 @ read CCSIDR" : "=r" (id_reg)); line_size = 4 << ((id_reg & 0x7) + 2); num_sets = ((id_reg >> 13) & 0x7fff) + 1; aliasing_icache = (line_size * num_sets) > PAGE_SIZE; break; case CPU_ARCH_ARMv6: aliasing_icache = read_cpuid_cachetype() & (1 << 11); break; default: /* I-cache aliases will be handled by D-cache aliasing code */ aliasing_icache = 0; } return aliasing_icache; } static void __init cacheid_init(void) { unsigned int cachetype = read_cpuid_cachetype(); unsigned int arch = cpu_architecture(); if (arch >= CPU_ARCH_ARMv6) { if ((cachetype & (7 << 29)) == 4 << 29) { /* ARMv7 register format */ cacheid = CACHEID_VIPT_NONALIASING; if ((cachetype & (3 << 14)) == 1 << 14) cacheid |= CACHEID_ASID_TAGGED; else if (cpu_has_aliasing_icache(CPU_ARCH_ARMv7)) cacheid |= CACHEID_VIPT_I_ALIASING; } else if (cachetype & (1 << 23)) { cacheid = CACHEID_VIPT_ALIASING; } else { cacheid = CACHEID_VIPT_NONALIASING; if (cpu_has_aliasing_icache(CPU_ARCH_ARMv6)) cacheid |= CACHEID_VIPT_I_ALIASING; } } else { cacheid = CACHEID_VIVT; } printk("CPU: %s data cache, %s instruction cache\n", cache_is_vivt() ? "VIVT" : cache_is_vipt_aliasing() ? "VIPT aliasing" : cache_is_vipt_nonaliasing() ? "VIPT nonaliasing" : "unknown", cache_is_vivt() ? "VIVT" : icache_is_vivt_asid_tagged() ? "VIVT ASID tagged" : icache_is_vipt_aliasing() ? "VIPT aliasing" : cache_is_vipt_nonaliasing() ? "VIPT nonaliasing" : "unknown"); } /* * These functions re-use the assembly code in head.S, which * already provide the required functionality. */ extern struct proc_info_list *lookup_processor_type(unsigned int); void __init early_print(const char *str, ...) { extern void printascii(const char *); char buf[256]; va_list ap; va_start(ap, str); vsnprintf(buf, sizeof(buf), str, ap); va_end(ap); #ifdef CONFIG_DEBUG_LL printascii(buf); #endif printk("%s", buf); } static void __init feat_v6_fixup(void) { int id = read_cpuid_id(); if ((id & 0xff0f0000) != 0x41070000) return; /* * HWCAP_TLS is available only on 1136 r1p0 and later, * see also kuser_get_tls_init. */ if ((((id >> 4) & 0xfff) == 0xb36) && (((id >> 20) & 3) == 0)) elf_hwcap &= ~HWCAP_TLS; } static void __init setup_processor(void) { struct proc_info_list *list; /* * locate processor in the list of supported processor * types. The linker builds this table for us from the * entries in arch/arm/mm/proc-*.S */ list = lookup_processor_type(read_cpuid_id()); if (!list) { printk("CPU configuration botched (ID %08x), unable " "to continue.\n", read_cpuid_id()); while (1); } cpu_name = list->cpu_name; #ifdef MULTI_CPU processor = *list->proc; #endif #ifdef MULTI_TLB cpu_tlb = *list->tlb; #endif #ifdef MULTI_USER cpu_user = *list->user; #endif #ifdef MULTI_CACHE cpu_cache = *list->cache; #endif printk("CPU: %s [%08x] revision %d (ARMv%s), cr=%08lx\n", cpu_name, read_cpuid_id(), read_cpuid_id() & 15, proc_arch[cpu_architecture()], cr_alignment); sprintf(init_utsname()->machine, "%s%c", list->arch_name, ENDIANNESS); sprintf(elf_platform, "%s%c", list->elf_name, ENDIANNESS); elf_hwcap = list->elf_hwcap; #ifndef CONFIG_ARM_THUMB elf_hwcap &= ~HWCAP_THUMB; #endif feat_v6_fixup(); cacheid_init(); cpu_proc_init(); } /* * cpu_init - initialise one CPU. * * cpu_init sets up the per-CPU stacks. */ void cpu_init(void) { unsigned int cpu = smp_processor_id(); struct stack *stk = &stacks[cpu]; if (cpu >= NR_CPUS) { printk(KERN_CRIT "CPU%u: bad primary CPU number\n", cpu); BUG(); } /* * Define the placement constraint for the inline asm directive below. * In Thumb-2, msr with an immediate value is not allowed. */ #ifdef CONFIG_THUMB2_KERNEL #define PLC "r" #else #define PLC "I" #endif /* * setup stacks for re-entrant exception handlers */ __asm__ ( "msr cpsr_c, %1\n\t" "add r14, %0, %2\n\t" "mov sp, r14\n\t" "msr cpsr_c, %3\n\t" "add r14, %0, %4\n\t" "mov sp, r14\n\t" "msr cpsr_c, %5\n\t" "add r14, %0, %6\n\t" "mov sp, r14\n\t" "msr cpsr_c, %7" : : "r" (stk), PLC (PSR_F_BIT | PSR_I_BIT | IRQ_MODE), "I" (offsetof(struct stack, irq[0])), PLC (PSR_F_BIT | PSR_I_BIT | ABT_MODE), "I" (offsetof(struct stack, abt[0])), PLC (PSR_F_BIT | PSR_I_BIT | UND_MODE), "I" (offsetof(struct stack, und[0])), PLC (PSR_F_BIT | PSR_I_BIT | SVC_MODE) : "r14"); } void __init dump_machine_table(void) { struct machine_desc *p; early_print("Available machine support:\n\nID (hex)\tNAME\n"); for_each_machine_desc(p) early_print("%08x\t%s\n", p->nr, p->name); early_print("\nPlease check your kernel config and/or bootloader.\n"); while (true) /* can't use cpu_relax() here as it may require MMU setup */; } int __init arm_add_memory(phys_addr_t start, unsigned long size) { struct membank *bank = &meminfo.bank[meminfo.nr_banks]; if (meminfo.nr_banks >= NR_BANKS) { printk(KERN_CRIT "NR_BANKS too low, " "ignoring memory at 0x%08llx\n", (long long)start); return -EINVAL; } /* * Ensure that start/size are aligned to a page boundary. * Size is appropriately rounded down, start is rounded up. */ size -= start & ~PAGE_MASK; bank->start = PAGE_ALIGN(start); bank->size = size & PAGE_MASK; /* * Check whether this memory region has non-zero size or * invalid node number. */ if (bank->size == 0) return -EINVAL; meminfo.nr_banks++; return 0; } /* * Pick out the memory size. We look for mem=size@start, * where start and size are "size[KkMm]" */ static int __init early_mem(char *p) { static int usermem __initdata = 0; unsigned long size; phys_addr_t start; char *endp; /* * If the user specifies memory size, we * blow away any automatically generated * size. */ if (usermem == 0) { usermem = 1; meminfo.nr_banks = 0; } start = PHYS_OFFSET; size = memparse(p, &endp); if (*endp == '@') start = memparse(endp + 1, NULL); arm_add_memory(start, size); return 0; } early_param("mem", early_mem); static void __init setup_ramdisk(int doload, int prompt, int image_start, unsigned int rd_sz) { #ifdef CONFIG_BLK_DEV_RAM extern int rd_size, rd_image_start, rd_prompt, rd_doload; rd_image_start = image_start; rd_prompt = prompt; rd_doload = doload; if (rd_sz) rd_size = rd_sz; #endif } static void __init request_standard_resources(struct machine_desc *mdesc) { struct memblock_region *region; struct resource *res; kernel_code.start = virt_to_phys(_text); kernel_code.end = virt_to_phys(_etext - 1); kernel_data.start = virt_to_phys(_sdata); kernel_data.end = virt_to_phys(_end - 1); for_each_memblock(memory, region) { res = alloc_bootmem_low(sizeof(*res)); res->name = "System RAM"; res->start = __pfn_to_phys(memblock_region_memory_base_pfn(region)); res->end = __pfn_to_phys(memblock_region_memory_end_pfn(region)) - 1; res->flags = IORESOURCE_MEM | IORESOURCE_BUSY; request_resource(&iomem_resource, res); if (kernel_code.start >= res->start && kernel_code.end <= res->end) request_resource(res, &kernel_code); if (kernel_data.start >= res->start && kernel_data.end <= res->end) request_resource(res, &kernel_data); } if (mdesc->video_start) { video_ram.start = mdesc->video_start; video_ram.end = mdesc->video_end; request_resource(&iomem_resource, &video_ram); } /* * Some machines don't have the possibility of ever * possessing lp0, lp1 or lp2 */ if (mdesc->reserve_lp0) request_resource(&ioport_resource, &lp0); if (mdesc->reserve_lp1) request_resource(&ioport_resource, &lp1); if (mdesc->reserve_lp2) request_resource(&ioport_resource, &lp2); } /* * Tag parsing. * * This is the new way of passing data to the kernel at boot time. Rather * than passing a fixed inflexible structure to the kernel, we pass a list * of variable-sized tags to the kernel. The first tag must be a ATAG_CORE * tag for the list to be recognised (to distinguish the tagged list from * a param_struct). The list is terminated with a zero-length tag (this tag * is not parsed in any way). */ static int __init parse_tag_core(const struct tag *tag) { if (tag->hdr.size > 2) { if ((tag->u.core.flags & 1) == 0) root_mountflags &= ~MS_RDONLY; ROOT_DEV = old_decode_dev(tag->u.core.rootdev); } return 0; } __tagtable(ATAG_CORE, parse_tag_core); static int __init parse_tag_mem32(const struct tag *tag) { return arm_add_memory(tag->u.mem.start, tag->u.mem.size); } __tagtable(ATAG_MEM, parse_tag_mem32); #if defined(CONFIG_VGA_CONSOLE) || defined(CONFIG_DUMMY_CONSOLE) struct screen_info screen_info = { .orig_video_lines = 30, .orig_video_cols = 80, .orig_video_mode = 0, .orig_video_ega_bx = 0, .orig_video_isVGA = 1, .orig_video_points = 8 }; static int __init parse_tag_videotext(const struct tag *tag) { screen_info.orig_x = tag->u.videotext.x; screen_info.orig_y = tag->u.videotext.y; screen_info.orig_video_page = tag->u.videotext.video_page; screen_info.orig_video_mode = tag->u.videotext.video_mode; screen_info.orig_video_cols = tag->u.videotext.video_cols; screen_info.orig_video_ega_bx = tag->u.videotext.video_ega_bx; screen_info.orig_video_lines = tag->u.videotext.video_lines; screen_info.orig_video_isVGA = tag->u.videotext.video_isvga; screen_info.orig_video_points = tag->u.videotext.video_points; return 0; } __tagtable(ATAG_VIDEOTEXT, parse_tag_videotext); #endif static int __init parse_tag_ramdisk(const struct tag *tag) { setup_ramdisk((tag->u.ramdisk.flags & 1) == 0, (tag->u.ramdisk.flags & 2) == 0, tag->u.ramdisk.start, tag->u.ramdisk.size); return 0; } __tagtable(ATAG_RAMDISK, parse_tag_ramdisk); static int __init parse_tag_serialnr(const struct tag *tag) { system_serial_low = tag->u.serialnr.low; system_serial_high = tag->u.serialnr.high; return 0; } __tagtable(ATAG_SERIAL, parse_tag_serialnr); static int __init parse_tag_revision(const struct tag *tag) { system_rev = tag->u.revision.rev; return 0; } __tagtable(ATAG_REVISION, parse_tag_revision); static int __init parse_tag_cmdline(const struct tag *tag) { #if defined(CONFIG_CMDLINE_EXTEND) strlcat(default_command_line, " ", COMMAND_LINE_SIZE); strlcat(default_command_line, tag->u.cmdline.cmdline, COMMAND_LINE_SIZE); #elif defined(CONFIG_CMDLINE_FORCE) pr_warning("Ignoring tag cmdline (using the default kernel command line)\n"); #else strlcpy(default_command_line, tag->u.cmdline.cmdline, COMMAND_LINE_SIZE); #endif return 0; } __tagtable(ATAG_CMDLINE, parse_tag_cmdline); /* * Scan the tag table for this tag, and call its parse function. * The tag table is built by the linker from all the __tagtable * declarations. */ static int __init parse_tag(const struct tag *tag) { extern struct tagtable __tagtable_begin, __tagtable_end; struct tagtable *t; for (t = &__tagtable_begin; t < &__tagtable_end; t++) if (tag->hdr.tag == t->tag) { t->parse(tag); break; } return t < &__tagtable_end; } /* * Parse all tags in the list, checking both the global and architecture * specific tag tables. */ static void __init parse_tags(const struct tag *t) { for (; t->hdr.size; t = tag_next(t)) if (!parse_tag(t)) printk(KERN_WARNING "Ignoring unrecognised tag 0x%08x\n", t->hdr.tag); } /* * This holds our defaults. */ static struct init_tags { struct tag_header hdr1; struct tag_core core; struct tag_header hdr2; struct tag_mem32 mem; struct tag_header hdr3; } init_tags __initdata = { { tag_size(tag_core), ATAG_CORE }, { 1, PAGE_SIZE, 0xff }, { tag_size(tag_mem32), ATAG_MEM }, { MEM_SIZE }, { 0, ATAG_NONE } }; static int __init customize_machine(void) { /* customizes platform devices, or adds new ones */ if (machine_desc->init_machine) machine_desc->init_machine(); return 0; } arch_initcall(customize_machine); #ifdef CONFIG_KEXEC static inline unsigned long long get_total_mem(void) { unsigned long total; total = max_low_pfn - min_low_pfn; return total << PAGE_SHIFT; } /** * reserve_crashkernel() - reserves memory are for crash kernel * * This function reserves memory area given in "crashkernel=" kernel command * line parameter. The memory reserved is used by a dump capture kernel when * primary kernel is crashing. */ static void __init reserve_crashkernel(void) { unsigned long long crash_size, crash_base; unsigned long long total_mem; int ret; total_mem = get_total_mem(); ret = parse_crashkernel(boot_command_line, total_mem, &crash_size, &crash_base); if (ret) return; ret = reserve_bootmem(crash_base, crash_size, BOOTMEM_EXCLUSIVE); if (ret < 0) { printk(KERN_WARNING "crashkernel reservation failed - " "memory is in use (0x%lx)\n", (unsigned long)crash_base); return; } printk(KERN_INFO "Reserving %ldMB of memory at %ldMB " "for crashkernel (System RAM: %ldMB)\n", (unsigned long)(crash_size >> 20), (unsigned long)(crash_base >> 20), (unsigned long)(total_mem >> 20)); crashk_res.start = crash_base; crashk_res.end = crash_base + crash_size - 1; insert_resource(&iomem_resource, &crashk_res); } #else static inline void reserve_crashkernel(void) {} #endif /* CONFIG_KEXEC */ static void __init squash_mem_tags(struct tag *tag) { for (; tag->hdr.size; tag = tag_next(tag)) if (tag->hdr.tag == ATAG_MEM) tag->hdr.tag = ATAG_NONE; } static struct machine_desc * __init setup_machine_tags(unsigned int nr) { struct tag *tags = (struct tag *)&init_tags; struct machine_desc *mdesc = NULL, *p; char *from = default_command_line; init_tags.mem.start = PHYS_OFFSET; /* * locate machine in the list of supported machines. */ for_each_machine_desc(p) if (nr == p->nr) { printk("Machine: %s\n", p->name); mdesc = p; break; } if (!mdesc) { early_print("\nError: unrecognized/unsupported machine ID" " (r1 = 0x%08x).\n\n", nr); dump_machine_table(); /* does not return */ } if (__atags_pointer) tags = phys_to_virt(__atags_pointer); else if (mdesc->boot_params) { #ifdef CONFIG_MMU /* * We still are executing with a minimal MMU mapping created * with the presumption that the machine default for this * is located in the first MB of RAM. Anything else will * fault and silently hang the kernel at this point. */ if (mdesc->boot_params < PHYS_OFFSET || mdesc->boot_params >= PHYS_OFFSET + SZ_1M) { printk(KERN_WARNING "Default boot params at physical 0x%08lx out of reach\n", mdesc->boot_params); } else #endif { tags = phys_to_virt(mdesc->boot_params); } } #if defined(CONFIG_DEPRECATED_PARAM_STRUCT) /* * If we have the old style parameters, convert them to * a tag list. */ if (tags->hdr.tag != ATAG_CORE) convert_to_tag_list(tags); #endif if (tags->hdr.tag != ATAG_CORE) { #if defined(CONFIG_OF) /* * If CONFIG_OF is set, then assume this is a reasonably * modern system that should pass boot parameters */ early_print("Warning: Neither atags nor dtb found\n"); #endif tags = (struct tag *)&init_tags; } if (mdesc->fixup) mdesc->fixup(mdesc, tags, &from, &meminfo); if (tags->hdr.tag == ATAG_CORE) { if (meminfo.nr_banks != 0) squash_mem_tags(tags); save_atags(tags); parse_tags(tags); } /* parse_early_param needs a boot_command_line */ strlcpy(boot_command_line, from, COMMAND_LINE_SIZE); return mdesc; } void __init setup_arch(char **cmdline_p) { struct machine_desc *mdesc; unwind_init(); setup_processor(); mdesc = setup_machine_fdt(__atags_pointer); if (!mdesc) mdesc = setup_machine_tags(machine_arch_type); machine_desc = mdesc; machine_name = mdesc->name; #ifdef CONFIG_ZONE_DMA if (mdesc->dma_zone_size) { extern unsigned long arm_dma_zone_size; arm_dma_zone_size = mdesc->dma_zone_size; } #endif if (mdesc->soft_reboot) reboot_setup("s"); init_mm.start_code = (unsigned long) _text; init_mm.end_code = (unsigned long) _etext; init_mm.end_data = (unsigned long) _edata; init_mm.brk = (unsigned long) _end; /* populate cmd_line too for later use, preserving boot_command_line */ strlcpy(cmd_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = cmd_line; parse_early_param(); sanity_check_meminfo(); arm_memblock_init(&meminfo, mdesc); paging_init(mdesc); request_standard_resources(mdesc); unflatten_device_tree(); #ifdef CONFIG_SMP if (is_smp()) smp_init_cpus(); #endif reserve_crashkernel(); cpu_init(); tcm_init(); #ifdef CONFIG_MULTI_IRQ_HANDLER handle_arch_irq = mdesc->handle_irq; #endif #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif early_trap_init(); if (mdesc->init_early) mdesc->init_early(); } static int __init topology_init(void) { int cpu; for_each_possible_cpu(cpu) { struct cpuinfo_arm *cpuinfo = &per_cpu(cpu_data, cpu); cpuinfo->cpu.hotpluggable = 1; register_cpu(&cpuinfo->cpu, cpu); } return 0; } subsys_initcall(topology_init); #ifdef CONFIG_HAVE_PROC_CPU static int __init proc_cpu_init(void) { struct proc_dir_entry *res; res = proc_mkdir("cpu", NULL); if (!res) return -ENOMEM; return 0; } fs_initcall(proc_cpu_init); #endif static const char *hwcap_str[] = { "swp", "half", "thumb", "26bit", "fastmult", "fpa", "vfp", "edsp", "java", "iwmmxt", "crunch", "thumbee", "neon", "vfpv3", "vfpv3d16", "tls", "vfpv4", "idiva", "idivt", NULL }; static int c_show(struct seq_file *m, void *v) { int i; seq_printf(m, "Processor\t: %s rev %d (%s)\n", cpu_name, read_cpuid_id() & 15, elf_platform); #if defined(CONFIG_SMP) for_each_online_cpu(i) { /* * glibc reads /proc/cpuinfo to determine the number of * online processors, looking for lines beginning with * "processor". Give glibc what it expects. */ seq_printf(m, "processor\t: %d\n", i); seq_printf(m, "BogoMIPS\t: %lu.%02lu\n\n", per_cpu(cpu_data, i).loops_per_jiffy / (500000UL/HZ), (per_cpu(cpu_data, i).loops_per_jiffy / (5000UL/HZ)) % 100); } #else /* CONFIG_SMP */ seq_printf(m, "BogoMIPS\t: %lu.%02lu\n", loops_per_jiffy / (500000/HZ), (loops_per_jiffy / (5000/HZ)) % 100); #endif /* dump out the processor features */ seq_puts(m, "Features\t: "); for (i = 0; hwcap_str[i]; i++) if (elf_hwcap & (1 << i)) seq_printf(m, "%s ", hwcap_str[i]); seq_printf(m, "\nCPU implementer\t: 0x%02x\n", read_cpuid_id() >> 24); seq_printf(m, "CPU architecture: %s\n", proc_arch[cpu_architecture()]); if ((read_cpuid_id() & 0x0008f000) == 0x00000000) { /* pre-ARM7 */ seq_printf(m, "CPU part\t: %07x\n", read_cpuid_id() >> 4); } else { if ((read_cpuid_id() & 0x0008f000) == 0x00007000) { /* ARM7 */ seq_printf(m, "CPU variant\t: 0x%02x\n", (read_cpuid_id() >> 16) & 127); } else { /* post-ARM7 */ seq_printf(m, "CPU variant\t: 0x%x\n", (read_cpuid_id() >> 20) & 15); } seq_printf(m, "CPU part\t: 0x%03x\n", (read_cpuid_id() >> 4) & 0xfff); } seq_printf(m, "CPU revision\t: %d\n", read_cpuid_id() & 15); seq_puts(m, "\n"); seq_printf(m, "Hardware\t: %s\n", machine_name); seq_printf(m, "Revision\t: %04x\n", system_rev); seq_printf(m, "Serial\t\t: %08x%08x\n", system_serial_high, system_serial_low); return 0; } static void *c_start(struct seq_file *m, loff_t *pos) { return *pos < 1 ? (void *)1 : NULL; } static void *c_next(struct seq_file *m, void *v, loff_t *pos) { ++*pos; return NULL; } static void c_stop(struct seq_file *m, void *v) { } const struct seq_operations cpuinfo_op = { .start = c_start, .next = c_next, .stop = c_stop, .show = c_show };
GlitchKernel/Glitch
arch/arm/kernel/setup.c
C
gpl-2.0
25,452
22.61039
97
0.652915
false
/** * Copyright (C) SiteSupra SIA, Riga, Latvia, 2015 * * 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. */ YUI.add('itemmanager.itemlist-uploader', function (Y) { //Invoke strict mode "use strict"; //Shortcut var Manager = Supra.Manager, Action = Manager.PageContent; /* * Editable content */ function ItemListUploader (config) { ItemListUploader.superclass.constructor.apply(this, arguments); } ItemListUploader.NAME = 'itemmanager-itemlist-uploader'; ItemListUploader.NS = 'uploader'; ItemListUploader.ATTRS = {}; Y.extend(ItemListUploader, Y.Plugin.Base, { /** * Supra.Uploader instance * @type {Object} * @private */ uploader: null, /** * File uploader ids to item ids * @type {Object} * @private */ ids: null, /** * */ initializer: function () { var itemlist = this.get('host'), container = itemlist.get('contentElement'); this.ids = {}; this.listeners = []; this.listeners.push(itemlist.after('contentElementChange', this.reattachListeners, this)); if (container) { this.reattachListeners(); } }, destructor: function () { this.resetAll(); // Listeners var listeners = this.listeners, i = 0, ii = listeners.length; for (; i < ii; i++) listeners[i].detach(); this.listeners = null; }, /** * Attach drag and drop listeners */ reattachListeners: function () { var itemlist = this.get('host'), container = itemlist.get('contentElement'), //doc = null, target = null; if (this.uploader) { this.uploader.destroy(); this.uploader = null; } if (!container) { return false; } //Create uploader target = itemlist.get('iframe').one('.supra-itemmanager-wrapper'); this.uploader = new Supra.Uploader({ 'dropTarget': target, 'allowBrowse': false, 'allowMultiple': true, 'accept': 'image/*', 'requestUri': Supra.Url.generate('media_library_upload'), 'uploadFolderId': itemlist.get('host').options.imageUploadFolder }); this.uploader.on('file:upload', this.onFileUploadStart, this); this.uploader.on('file:complete', this.onFileUploadEnd, this); this.uploader.on('file:error', this.onFileUploadError, this); }, /** * Reset all iframe content bindings, etc. */ resetAll: function () { var uploader = this.uploader; if (uploader) { uploader.destroy(true); this.uploader = null; } }, /* ------------------------ FILE UPLOAD ------------------------ */ /** * Handle file upload start */ onFileUploadStart: function (e) { var data = e.details[0], itemlist = this.get('host'), item = null; // Prevent item from being opened for editing itemlist.initializing = true; item = itemlist.addItem({'title': e.title.replace(/\..+$/, '')}); itemlist.initializing = false; this.ids[e.id] = item.__suid; }, /** * Handle file upload end */ onFileUploadEnd: function (e) { var data = e.details[0], itemlist = this.get('host'), itemdrop = itemlist.drop; if (e.old_id in this.ids) { itemdrop.updateItemInCollection(data, this.ids[e.old_id]); delete(this.ids[e.old_id]); } else { itemdrop.addItemToCollection(data); } }, /** * Handle file upload error */ onFileUploadError: function (e) { var itemlist = this.get('host'); itemlist.removeItem(this.ids[e.id]); delete(this.ids[e.id]); } }); Supra.ItemManagerItemListUploader = ItemListUploader; //Since this widget has Supra namespace, it doesn't need to be bound to each YUI instance //Make sure this constructor function is called only once delete(this.fn); this.fn = function () {}; }, YUI.version, {requires: ['plugin', 'supra.uploader']});
sitesupra/sitesupra
lib/Supra/Package/Cms/Resources/public/content-manager/itemmanager/modules/itemlist-uploader.js
JavaScript
gpl-2.0
4,508
23.367568
93
0.632875
false
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ // +----------------------------------------------------------------------+ // | Fez - Digital Repository System | // +----------------------------------------------------------------------+ // | Copyright (c) 2005, 2006, 2007 The University of Queensland, | // | Australian Partnership for Sustainable Repositories, | // | eScholarship Project | // | | // | Some of the Fez code was derived from Eventum (Copyright 2003, 2004 | // | MySQL AB - http://dev.mysql.com/downloads/other/eventum/ - 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, write to: | // | | // | Free Software Foundation, Inc. | // | 59 Temple Place - Suite 330 | // | Boston, MA 02111-1307, USA. | // +----------------------------------------------------------------------+ // | Authors: Christiaan Kortekaas <c.kortekaas@library.uq.edu.au>, | // | Matthew Smith <m.smith@library.uq.edu.au> | // +----------------------------------------------------------------------+ // // include_once("config.inc.php"); include_once(APP_INC_PATH . "class.lister.php"); include_once(APP_INC_PATH . "class.auth.php"); if (APP_AUTHOR_PROFILE_REDIRECT == 'ON') { // Send to the new eSpace search profile page when only the author_id is supplied PT: #176474178 if (count($_GET) === 2 && array_key_exists('browse', $_GET) && $_GET['browse'] === 'author_id' && array_key_exists('value', $_GET) && is_numeric($_GET['value']) ) { Lister::authorProfileRedirect($_GET['value']); } } $res = Lister::getList($_GET, true); $pids = array(); if (is_array($res['list'])) { foreach ($res['list'] as $record) { if (array_key_exists('rek_pid', $record)) { $pids[] = $record['rek_pid']; } } } /* * If this is a logged in user we want to save this data for view pages, so when can create * 'prev' and 'next' links */ $username = Auth::getUsername(); if (!empty($username)) { $_SESSION['list'] = $pids; $_SESSION['list_params'] = $_GET; $_SESSION['script_name'] = $_SERVER['SCRIPT_NAME']; $_SESSION['last_page'] = $res['list_info']['last_page']; $_SESSION['view_page'] = $res['list_info']['current_page']; }
uqlibrary/fez
public/list.php
PHP
gpl-2.0
3,603
47.356164
100
0.440466
false
using System.Collections.Generic; using System.Xml.Linq; using UnityEngine; namespace IaS.Xml { public class XmlTrackNode { public const string ElementTrackNode = "node"; private const string AttrTrackNodeId = "id"; private const string AttrTrackNodePosition = "p"; public Vector3 Position { get; private set; } public string Id { get; private set; } public XmlTrackNode Previous { get; private set; } public XmlTrackNode Next { get; private set; } public static XmlTrackNode FromElement(XElement element, Dictionary<string, int> counts) { string id = XmlValueMapper.FromAttribute(element, AttrTrackNodeId).AsIdValue("t_node", counts); Vector3 position = XmlValueMapper.FromAttribute(element, AttrTrackNodePosition).AsVector3().MandatoryValue(); return new XmlTrackNode(id, position); } public XmlTrackNode(string id, Vector3 position) { Id = id; Position = position; } } }
mANDROID99/IaS
Iron_And_steam/Assets/Scripts/Xml/XmlTrackNode.cs
C#
gpl-2.0
1,065
32.21875
121
0.644403
false
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "Movable-Type" authors [ "Andrew Horton", # v0.2 # remove :certainty. # v0.3 # Uses :version=>//. "Brendan Coles <bcoles@gmail.com>", # v0.4 # 2011-07-07 # updated regex. added example urls, google dorks and version/path detection with mt-check.cgi. ] version "0.4" description "Blogging platform" website "http://www.movabletype.org/" # Google results as at 2011-07-07 # # 122 for "Powered by Movable Type" # 89 for inurl:/mt-check.cgi intitle:"Movable Type System Check [mt-check.cgi]" # 26 for inurl:/mt/mt-check.cgi # More examples: # www.movabletype.com/showcase/ # Dorks # dorks [ '"Powered by Movable Type"', 'inurl:/mt-check.cgi intitle:"Movable Type System Check [mt-check.cgi]"' ] # Matches # matches [ # javascript with 'mt' in the filename {:name=>"javascript with 'mt' in the name", :certainty=>50, :regexp=>/<script type="text\/javascript" src="[^"]+mt(-site)?\.js"><\/script>/}, # mt-tags|mt-tb|mt-cp|mt-search|mt-user-login|mt-recommend cgi {:name=>"mt-tags|mt-tb|mt-cp|mt-search|mt-user-login|mt-recommend cgi", :certainty=>75, :regexp=>/"[^"]+\/mt-(tags|tb|cp|search|user-login|recommend)\.[f]?cgi[^"]*"/}, # Meta Generator {:name=>"meta generator tag", :regexp=>/<meta name="generator" content="http:\/\/www\.movabletype\.org\/" \/>/}, # mt-check.cgi # Title { :text=>'<title>Movable Type System Check [mt-check.cgi]</title>' }, # Version Detection # mt-check.cgi { :version=>/<li><strong>Movable Type version:<\/strong> <code>([^<]+)<\/code><\/li>/ }, # Local Path Detection # mt-check.cgi { :filepath=>/<li><strong>Current working directory:<\/strong> <code>([^<]+)<\/code><\/li>/ }, # Powered by link {:name=>"Powered by link", :regexp=>/<a href="http:\/\/sixapart\.com">Powered by Movable Type<\/a>/}, {:name=>"Powered by link", :regexp=>/Powered by <a href="http:\/\/www\.movabletype\.com\/"[^>]*>Movable Type<\/a>/ }, # Version Detection # Meta Generator {:version=>/<meta name="generator" content="Movable Type ([^"]*)/, :name=>"meta generator tag" } ] end =begin # An aggressive plugin could check the following paths for confirmation: # /mt or /mt/mt-check.cgi (discloses versions, paths) # /mt/mt-tags.fcgi # /mt-tb.fcgi # /mt-cp.[f]?cgi # /mt-search.cgi # /mt-user-login.cgi # /mt-recommend.cgi # can't detect: barackobama.com blogs.oracle.com electricartists.com/corporate muledesign.com www.radaronline.com www.theatlantic.com www.thehuffingtonpost.com =end
urbanadventurer/WhatWeb
plugins/movable_type.rb
Ruby
gpl-2.0
2,692
28.26087
154
0.681278
false
import { apiBase, versionApi } from '../commons'; const apiMonitoringBeta = `${apiBase}/beta/monitoring`; const apiMonitoring = `${apiBase}/${versionApi}/monitoring`; export { apiMonitoringBeta, apiMonitoring };
centreon/centreon
tests/e2e/cypress/support/model.ts
TypeScript
gpl-2.0
214
34.666667
60
0.738318
false
require("map/level") local levellist = {} levellist[LEVELTYPE.SURVIVAL] = {} levellist[LEVELTYPE.CAVE] = {} levellist[LEVELTYPE.ADVENTURE] = {} levellist[LEVELTYPE.TEST] = {} levellist[LEVELTYPE.CUSTOM] = {} function AddLevel(type, data) table.insert(levellist[type], Level(data)) end require("map/levels/adventure") require("map/levels/caves") require("map/levels/survival") function GetTypeForLevelID(id) if id == nil or id:lower() == "unknown" then return LEVELTYPE.UNKNOWN end id = id:lower() for type, levels in pairs(levellist) do for idx, level in ipairs(levels) do if level.id:lower() == id then return type end end end return LEVELTYPE.UNKNOWN end AddLevel(LEVELTYPE.TEST, { name="TEST_LEVEL", id="TEST", overrides={ {"world_size", "tiny"}, {"day", "onlynight"}, {"waves", "off"}, {"location", "cave"}, {"boons", "never"}, {"poi", "never"}, {"traps", "never"}, {"protected", "never"}, {"start_setpeice", "CaveStart"}, {"start_node", "BGSinkholeRoom"}, }, tasks={ "CavesStart", "CavesAlternateStart", "FungalBatCave", "BatCaves", "TentacledCave", "LargeFungalComplex", "SingleBatCaveTask", "RabbitsAndFungs", "FungalPlain", "Cavern", }, numoptionaltasks = 1, optionaltasks = { "CaveBase", "MushBase", "SinkBase", "RabbitTown", }, override_triggers = { -- ["RuinsStart"] = { -- {"SeasonColourCube", "caves"}, -- -- {"SeasonColourCube", SEASONS.CAVES}, -- }, -- ["TheLabyrinth"] = { -- {"SeasonColourCube", "caves_ruins"}, -- -- {"SeasonColourCube", { DAY = "images/colour_cubes/ruins_light_cc.tex", -- -- DUSK = "images/colour_cubes/ruins_dim_cc.tex", -- -- NIGHT = "images/colour_cubes/ruins_dark_cc.tex", -- -- }, -- -- }, -- }, -- ["CityInRuins"] = { -- {"SeasonColourCube", "caves_ruins"}, -- -- {"SeasonColourCube", { DAY = "images/colour_cubes/ruins_light_cc.tex", -- -- DUSK = "images/colour_cubes/ruins_dim_cc.tex", -- -- NIGHT = "images/colour_cubes/ruins_dark_cc.tex", -- -- }, -- -- }, -- }, }, }) return { story_levels=levellist[LEVELTYPE.ADVENTURE], sandbox_levels=levellist[LEVELTYPE.SURVIVAL], cave_levels = levellist[LEVELTYPE.CAVE], --free_level=levellist[LEVELTYPE.SURVIVAL][1], test_level=levellist[LEVELTYPE.TEST][1], custom_levels = levellist[LEVELTYPE.CUSTOM], CAMPAIGN_LENGTH=CAMPAIGN_LENGTH, GetTypeForLevelID = GetTypeForLevelID }
czfshine/Don-t-Starve
data/scripts/map/levels.lua
Lua
gpl-2.0
2,569
23.466667
81
0.600623
false
import tests.util.*; import java.util.Map; // Test case for Issue 134: // http://code.google.com/p/checker-framework/issues/detail?id=134 // Handling of generics from different enclosing classes. // TODO: revisit with nested types in 1.3. // @skip-test class GenericTest4 { public interface Foo {} class Outer<O> { O getOuter() { return null; } class Inner<I> { O getInner() { return null; } I setter1(O p) { return null; } O setter2(I p) { return null; } Map<O, I> wow(Map<O, I> p) { return null; } } } class OuterImpl extends Outer<Foo> { void test() { Foo foo = getOuter(); } class InnerImpl extends Inner<@Odd String> { void test() { Foo foo = getInner(); String s = setter1(foo); foo = setter2(s); } void testWow(Map<Foo, String> p) { p = wow(p); } } } // Add uses from outside of both classes. }
biddyweb/checker-framework
framework/tests/framework/GenericTest4.java
Java
gpl-2.0
939
20.837209
66
0.57721
false
<?php /** * Themes shortcode image options go here * * @package Omega * @subpackage Core * @since 1.0 * * @copyright (c) 2014 Oxygenna.com * @license http://wiki.envato.com/support/legal-terms/licensing-terms/ * @version 1.7.3 */ return array( 'title' => __('Image options', 'omega-admin-td'), 'fields' => array( array( 'name' => __('Image Shape', 'omega-admin-td'), 'desc' => __('Choose the shape of the image', 'omega-admin-td'), 'id' => 'image_shape', 'type' => 'select', 'options' => array( 'box-round' => __('Round', 'omega-admin-td'), 'box-rect' => __('Rectangle', 'omega-admin-td'), 'box-square' => __('Square', 'omega-admin-td'), ), 'default' => 'box-round', ), array( 'name' => __('Image Size', 'omega-admin-td'), 'desc' => __('Choose the size of the image', 'omega-admin-td'), 'id' => 'image_size', 'type' => 'select', 'options' => array( 'box-mini' => __('Mini', 'omega-admin-td'), 'no-small' => __('Small', 'omega-admin-td'), 'box-medium' => __('Medium', 'omega-admin-td'), 'box-big' => __('Big', 'omega-admin-td'), 'box-huge' => __('Huge', 'omega-admin-td'), ), 'default' => 'box-medium', ), ) );
rinodung/wordpress-demo
wp-content/themes/omega/inc/options/shortcodes/shortcode-image-options.php
PHP
gpl-2.0
1,670
36
83
0.386826
false
<?php /* Template Name: Products Template * */ ?> <?php get_header(); ?> <div class="wrap-full banner-background cf" style="<?php if( get_field('background_banner')){ echo "background-image: url('". get_field('background_banner')."')"; } ?>"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="products-container cf"> <h1><?php the_title(); ?> <span class="tagline"><?php the_field('tagline'); ?></span></h1> <?php if($_GET['ativo'] == "tilbud") : ?> <div class="price-table-column blue" style="display: block; margin: 0 auto 50px;"> <div class="price-table-header slim"> <span class="price-table-header-value"><h2>Ativo Medlemstilbud</h2></span> </div> <div class="price-table-price-row"> <span class="price-value price-eksl">Månedspris: 350,- <span style="color: #7f7f7f; font-size: 22px; text-decoration: line-through;">450,-</span></span> </div> <div class="price-table-cell"> <div class=""></div> <span class="price-table-cell-value">Vedligeholdelse + Fuld Service</span> <div class="price-table-cell-info">Alt fra pakken til 450,- her under, til en venlig pris :-)</div> </div> <div class="price-table-cell"> <div class=""></div> <span class="price-table-cell-value">TILMELD</span> <div class="price-table-cell-info"> <?php echo do_shortcode("[stripeform serviceid='service350']"); ?> </div> </div> <div class="price-table-footer"></div> </div> <?php endif; ?> <?php // check if any products are created if( have_rows('product') ): // loop through products while( have_rows('product') ): the_row(); ?> <div class="price-table-column <?php the_sub_field('product_color'); ?>"> <div class="price-table-header slim"> <?php if(get_sub_field('product_link')) { ?><a href="<?php the_sub_field('product_link'); ?>"><?php } ?> <span class="price-table-header-value"><h2><?php the_sub_field('product_name'); ?></h2></span> <?php if(get_sub_field('product_link')) { ?></a><?php } ?> </div> <div class="price-table-price-row"> <?php if(get_sub_field('price_label') == 'from') { ?> <span class="price-value price-from price-eksl"><?php the_sub_field('product_price'); ?>,-</span><?php } ?> <?php if(get_sub_field('price_label') == 'more') { ?> <span class="price-readmore"><?php the_sub_field('product_price'); ?></span><?php } ?> <?php if(get_sub_field('price_label') == 'none') { ?> <span class="price-value price-eksl"><?php the_sub_field('product_price'); ?>,-</span><?php } ?> </div> <?php if( get_sub_field('product_description') ): ?> <div class="price-table-description"> <span><?php the_sub_field('product_description'); ?></span> </div> <?php endif; ?> <?php // check if any product items exists if( have_rows('product_items') ): // loop through product items while( have_rows('product_items') ): the_row(); ?> <div class="price-table-cell"> <div class="<?php the_sub_field('class'); ?>"></div> <span class="price-table-cell-value"><?php the_sub_field('label'); ?></span> <div class="price-table-cell-info"><?php echo do_shortcode(get_sub_field('description')); ?></div> </div> <?php endwhile; ?> <?php endif; ?> <div class="price-table-footer"> <?php if(get_sub_field('product_link')) { ?> <a href="<?php the_sub_field('product_link'); ?>"> <span class="price-table-footer-value">Læs mere</span></a> </a><?php } ?> </div> </div> <?php endwhile; ?> <?php endif; ?> </div> <?php endwhile; endif; ?> </div> <?php include (TEMPLATEPATH . '/contact-ribbon.php'); ?> <div id="content"> <div id="inner-content" class="wrap cf"> <main id="main" class="m-all t-2of3 d-5of7 cf" role="main" itemscope itemprop="mainContentOfPage" itemtype="http://schema.org/Blog"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'cf' ); ?> role="article" itemscope itemtype="http://schema.org/BlogPosting"> <section class="entry-content cf" itemprop="articleBody"> <?php the_content(); ?> </section> <?php // end article section ?> <footer class="article-footer cf"> </footer> </article> <?php endwhile; endif; ?> </main> <!-- <?php get_sidebar(); ?> --> </div> </div> <?php get_footer(); ?>
kragej/ativo
themes/bones/page-products.php
PHP
gpl-2.0
5,029
35.427536
172
0.521981
false
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) ------------------------------------------------------------------------- */ #include "omp_compat.h" #include <cmath> #include "pair_lj_charmm_coul_long_omp.h" #include "atom.h" #include "comm.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "suffix.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ PairLJCharmmCoulLongOMP::PairLJCharmmCoulLongOMP(LAMMPS *lmp) : PairLJCharmmCoulLong(lmp), ThrOMP(lmp, THR_PAIR) { suffix_flag |= Suffix::OMP; respa_enable = 0; cut_respa = NULL; } /* ---------------------------------------------------------------------- */ void PairLJCharmmCoulLongOMP::compute(int eflag, int vflag) { ev_init(eflag,vflag); const int nall = atom->nlocal + atom->nghost; const int nthreads = comm->nthreads; const int inum = list->inum; #if defined(_OPENMP) #pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(eflag,vflag) #endif { int ifrom, ito, tid; loop_setup_thr(ifrom, ito, tid, inum, nthreads); ThrData *thr = fix->get_thr(tid); thr->timer(Timer::START); ev_setup_thr(eflag, vflag, nall, eatom, vatom, NULL, thr); if (evflag) { if (eflag) { if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr); else eval<1,1,0>(ifrom, ito, thr); } else { if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr); else eval<1,0,0>(ifrom, ito, thr); } } else { if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr); else eval<0,0,0>(ifrom, ito, thr); } thr->timer(Timer::PAIR); reduce_thr(this, eflag, vflag, thr); } // end of omp parallel region } /* ---------------------------------------------------------------------- */ template <int EVFLAG, int EFLAG, int NEWTON_PAIR> void PairLJCharmmCoulLongOMP::eval(int iifrom, int iito, ThrData * const thr) { const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; const double * _noalias const q = atom->q; const int * _noalias const type = atom->type; const double * _noalias const special_coul = force->special_coul; const double * _noalias const special_lj = force->special_lj; const double qqrd2e = force->qqrd2e; const double inv_denom_lj = 1.0/denom_lj; const int * const ilist = list->ilist; const int * const numneigh = list->numneigh; const int * const * const firstneigh = list->firstneigh; const int nlocal = atom->nlocal; // loop over neighbors of my atoms for (int ii = iifrom; ii < iito; ++ii) { const int i = ilist[ii]; const int itype = type[i]; const double qtmp = q[i]; const double xtmp = x[i].x; const double ytmp = x[i].y; const double ztmp = x[i].z; double fxtmp,fytmp,fztmp; fxtmp=fytmp=fztmp=0.0; const int * const jlist = firstneigh[i]; const int jnum = numneigh[i]; const double * _noalias const lj1i = lj1[itype]; const double * _noalias const lj2i = lj2[itype]; const double * _noalias const lj3i = lj3[itype]; const double * _noalias const lj4i = lj4[itype]; for (int jj = 0; jj < jnum; jj++) { double forcecoul, forcelj, evdwl, ecoul; forcecoul = forcelj = evdwl = ecoul = 0.0; const int sbindex = sbmask(jlist[jj]); const int j = jlist[jj] & NEIGHMASK; const double delx = xtmp - x[j].x; const double dely = ytmp - x[j].y; const double delz = ztmp - x[j].z; const double rsq = delx*delx + dely*dely + delz*delz; const int jtype = type[j]; if (rsq < cut_bothsq) { const double r2inv = 1.0/rsq; if (rsq < cut_coulsq) { if (!ncoultablebits || rsq <= tabinnersq) { const double A1 = 0.254829592; const double A2 = -0.284496736; const double A3 = 1.421413741; const double A4 = -1.453152027; const double A5 = 1.061405429; const double EWALD_F = 1.12837917; const double INV_EWALD_P = 1.0/0.3275911; const double r = sqrt(rsq); const double grij = g_ewald * r; const double expm2 = exp(-grij*grij); const double t = INV_EWALD_P / (INV_EWALD_P + grij); const double erfc = t * (A1+t*(A2+t*(A3+t*(A4+t*A5)))) * expm2; const double prefactor = qqrd2e * qtmp*q[j]/r; forcecoul = prefactor * (erfc + EWALD_F*grij*expm2); if (EFLAG) ecoul = prefactor*erfc; if (sbindex) { const double adjust = (1.0-special_coul[sbindex])*prefactor; forcecoul -= adjust; if (EFLAG) ecoul -= adjust; } } else { union_int_float_t rsq_lookup; rsq_lookup.f = rsq; const int itable = (rsq_lookup.i & ncoulmask) >> ncoulshiftbits; const double fraction = (rsq_lookup.f - rtable[itable]) * drtable[itable]; const double table = ftable[itable] + fraction*dftable[itable]; forcecoul = qtmp*q[j] * table; if (EFLAG) ecoul = qtmp*q[j] * (etable[itable] + fraction*detable[itable]); if (sbindex) { const double table2 = ctable[itable] + fraction*dctable[itable]; const double prefactor = qtmp*q[j] * table2; const double adjust = (1.0-special_coul[sbindex])*prefactor; forcecoul -= adjust; if (EFLAG) ecoul -= adjust; } } } if (rsq < cut_ljsq) { const double r6inv = r2inv*r2inv*r2inv; forcelj = r6inv * (lj1i[jtype]*r6inv - lj2i[jtype]); const double philj = r6inv*(lj3i[jtype]*r6inv-lj4i[jtype]); if (EFLAG) evdwl = philj; if (rsq > cut_lj_innersq) { const double drsq = cut_ljsq - rsq; const double cut2 = (rsq - cut_lj_innersq) * drsq; const double switch1 = drsq * (drsq*drsq + 3.0*cut2) * inv_denom_lj; const double switch2 = 12.0*rsq * cut2 * inv_denom_lj; forcelj = forcelj*switch1 + philj*switch2; if (EFLAG) evdwl *= switch1; } if (sbindex) { const double factor_lj = special_lj[sbindex]; forcelj *= factor_lj; if (EFLAG) evdwl *= factor_lj; } } const double fpair = (forcecoul + forcelj) * r2inv; fxtmp += delx*fpair; fytmp += dely*fpair; fztmp += delz*fpair; if (NEWTON_PAIR || j < nlocal) { f[j].x -= delx*fpair; f[j].y -= dely*fpair; f[j].z -= delz*fpair; } if (EVFLAG) ev_tally_thr(this,i,j,nlocal,NEWTON_PAIR, evdwl,ecoul,fpair,delx,dely,delz,thr); } } f[i].x += fxtmp; f[i].y += fytmp; f[i].z += fztmp; } } /* ---------------------------------------------------------------------- */ double PairLJCharmmCoulLongOMP::memory_usage() { double bytes = memory_usage_thr(); bytes += PairLJCharmmCoulLong::memory_usage(); return bytes; }
pastewka/lammps
src/USER-OMP/pair_lj_charmm_coul_long_omp.cpp
C++
gpl-2.0
7,636
33.242152
87
0.535097
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Backends</title> <link rel="stylesheet" type="text/css" media="screen" href="../general/css/style.css" /> </head> <body> <h1>Backends</h1> <h2>General Information</h2> <p>The NagVis code is separated into several layers. One of these layers is the &quot;data layer&quot;. The data layer is used to handle requests for information from third party sources like the socket of MKLivestatus. We call this layer &quot;backend&quot; in general. There are some components inside NagVis to manage these backends which act as the glue between the single backends and the other layers.</p> <h2>Default backend</h2> <p>At the moment there are a few backends delivered with the NagVis core packages: the most important ones are the mklivestatus and ndomy backends. All backend configuration parameters are described in detail on their own pages.</p> <p>The ndomy backend has been the default backend from NagVis 1.0 to NagVis 1.5. It fetches Nagios information from the NDO MySQL database. Since NagVis 1.5 the default backend has been switched to MKLivestatus backend.</p> <p>In NagVis 1.9, the pgsql backend has been added to fetch the Nagios information from a PostgreSQL database as used by e.g. Icinga 2.</p> <h2>Backend types</h2> <ul> <li><a href=backend_mklivestatus.html>MKLivestatus</a></li> <li><a href=backend_ndomy.html>NDOMy</a></li> <li><a href=backend_nagiosbp.html>NagiosBP</a></li> <li><a href=backend_pgsql.html>PgSQL</a></li> <li>MerlinMy</li> </ul> <h2>Configuring backends</h2> <p>The backends are defined in the main configuration file. See <a href="nagvis_config_format_description.html#backend">main configuration format description</a> on how to define backends.</p> </body> </html>
NagVis/nagvis
docs/en_US/backends.html
HTML
gpl-2.0
2,146
47.772727
109
0.630009
false
MyRaspberry-Utilities ==================== Bash Scripts for Raspberry 24/7
tbhCiro/MyRasperry-Utilities
README.md
Markdown
gpl-2.0
76
18
31
0.605263
false
/* $Id: memuserkernel-r0drv-darwin.cpp $ */ /** @file * IPRT - User & Kernel Memory, Ring-0 Driver, Darwin. */ /* * Copyright (C) 2009 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include "the-darwin-kernel.h" #include "internal/iprt.h" #include <iprt/mem.h> #include <iprt/assert.h> #if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86) # include <iprt/asm-amd64-x86.h> #endif #include <iprt/err.h> RTR0DECL(int) RTR0MemUserCopyFrom(void *pvDst, RTR3PTR R3PtrSrc, size_t cb) { RT_ASSERT_INTS_ON(); int rc = copyin((const user_addr_t)R3PtrSrc, pvDst, cb); if (RT_LIKELY(rc == 0)) return VINF_SUCCESS; return VERR_ACCESS_DENIED; } RTR0DECL(int) RTR0MemUserCopyTo(RTR3PTR R3PtrDst, void const *pvSrc, size_t cb) { RT_ASSERT_INTS_ON(); int rc = copyout(pvSrc, R3PtrDst, cb); if (RT_LIKELY(rc == 0)) return VINF_SUCCESS; return VERR_ACCESS_DENIED; } RTR0DECL(bool) RTR0MemUserIsValidAddr(RTR3PTR R3Ptr) { /* the commpage is above this. */ #ifdef RT_ARCH_X86 return R3Ptr < VM_MAX_ADDRESS; #else return R3Ptr < VM_MAX_PAGE_ADDRESS; #endif } RTR0DECL(bool) RTR0MemKernelIsValidAddr(void *pv) { /* Found no public #define or symbol for checking this, so we'll have to make do with thing found in the debugger and the sources. */ #ifdef RT_ARCH_X86 NOREF(pv); return true; /* Almost anything is a valid kernel address here. */ #elif defined(RT_ARCH_AMD64) return (uintptr_t)pv >= UINT64_C(0xffff800000000000); #else # error "PORTME" #endif } RTR0DECL(bool) RTR0MemAreKrnlAndUsrDifferent(void) { /* As mentioned in RTR0MemKernelIsValidAddr, found no way of checking this at compiler or runtime. */ #ifdef RT_ARCH_X86 return false; #else return true; #endif }
JSansalone/VirtualBox4.1.18
src/VBox/Runtime/r0drv/darwin/memuserkernel-r0drv-darwin.cpp
C++
gpl-2.0
2,937
28.37
80
0.649302
false
<div id="obligee_volumen" class="viz" data-viz="treemap-a" data-graph="treemap-a"> <div class="row"> <div class="col-sm-12"> <h3>Volumen de recursos de revisión, por sujeto obligado y por sentido de la resolución: <span class="year-range">2007 - 2015</span></h3> <p class="lead">Recursos de revisión que se realizan por sujeto obligado, tanto de acceso a la información como de datos personales</p> <!--<a href="#" class="download" download><b></b>Descargar datos</a>--> </div> <div class="col-sm-10 col-sm-offset-1"> <p class="instructions">Da clic sobre un sector para observar la distribución del número de solicitudes por sujeto obligado y tipo de solicitud. Para regresar, da clic sobre el área gris en la parte superior de la gráfica. </p> </div> </div> <section id="treemap-a"></section> <!--source--> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <!--source--> <?php include "templates/source.php";?> <p class="lead info">Distribución de la gráfica</p> <ul class="info row"> <li class="col-sm-3">Primer nivel: <strong>Sector</strong></li> <li class="col-sm-3">Segundo nivel: <strong>Sujeto obligado</strong></li> <li class="col-sm-3">Tercer nivel: <strong>Sentido de la resolución</strong> </li> <li class="col-sm-3">Tamaño: <strong>Número de solicitudes</strong></li> </ul> </div> </div> </div>
GobiernoFacil/mapadai
includes/recursos/obligee/volumen.php
PHP
gpl-2.0
1,410
45.566667
140
0.663565
false
#ifndef LAC_DIFFERENCE_NEIGHBOR_SET_H #define LAC_DIFFERENCE_NEIGHBOR_SET_H 1 #include <utility> #include <list> #include <algorithm> namespace LAC { namespace Difference { template<typename T> struct NeighborSet { typedef T data_t; typedef std::list<T> queue_t; typedef typename queue_t::iterator it_t; typedef typename queue_t::const_iterator const_it_t; NeighborSet(size_t count) : m_count(std::max((size_t)1,count)) {} ~NeighborSet(){} void Append(const T& d){ it_t it = std::lower_bound(m_queue.begin(), m_queue.end(), d); m_queue.insert(it, d); if(m_queue.size() > m_count) m_queue.pop_back(); } const_it_t Begin() const { return m_queue.begin(); } const_it_t End() const { return m_queue.end(); } size_t m_count; queue_t m_queue; }; } } #endif
landmarkacoustics/dissUtils
src/neighbor_set.h
C
gpl-2.0
906
21.230769
71
0.582781
false
package com.carpoolsophia; import java.util.concurrent.ExecutionException; import org.json.JSONException; import org.json.JSONObject; import android.app.Fragment; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import butterknife.InjectView; import butterknife.Views; import com.carpoolsophia.gcloudApi.model.CarpoolSophiaUser; import com.carpoolsophia.service.CarpoolSophiaUserService; import com.carpoolsophia.service.ProfileService; import com.facebook.AccessToken; import com.facebook.AccessTokenUtils; import com.facebook.GraphRequest; import com.facebook.GraphResponse; public class ProfileFragment extends Fragment { private final static String CLASSNAME = ProfileFragment.class.getSimpleName(); @InjectView(R.id.TestLoadFromFB) Button testLoadFromFbBtn; @InjectView(R.id.profile_firstName) EditText profileFirstName; @InjectView(R.id.profile_lastName) EditText profileLastName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile_fragment, container, false); Views.inject(this, view); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ProfileFragment finalThis = this; testLoadFromFbBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.w(ProfileFragment.class.getSimpleName(), "loadFromFB"); CarpoolSophiaUser user; try { user = (new LoadUserFromFbTask(finalThis).execute()).get(); if (user != null) { // Log.w(getClass().getSimpleName(), // "user loaded: "+ModelToJSONParseAdapter.toJSONParse(user)); profileFirstName.setText(user.getFirstName()); profileLastName.setText(user.getLastName()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public void updateProfileInfo(View btn) { Log.w(getClass().getSimpleName(), "updateProfileInfo"); } private class LoadUserFromFbTask extends AsyncTask<CarpoolSophiaUser, Void, CarpoolSophiaUser> { private ProfileFragment profileFragment; public LoadUserFromFbTask(ProfileFragment fragment) { super(); this.profileFragment = fragment; } @SuppressWarnings("serial") protected CarpoolSophiaUser doInBackground(final CarpoolSophiaUser... users) { CarpoolSophiaUser user = CarpoolSophiaUserService.get() .getCurrentCSuser(); AccessToken accessToken = AccessTokenUtils.deserializeToken(user .getAccessToken()); GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { // Log.d(CLASSNAME, "JSONobject: " + object); // Log.d(CLASSNAME, "GraphResponse #1: " + // response.getRawResponse()); } }); GraphResponse response = request.executeAndWait(); Log.d(CLASSNAME, "GraphResponse #2: " + response.getRawResponse()); CarpoolSophiaUser userFromFB = new CarpoolSophiaUser(); try { userFromFB.setFirstName(response.getJSONObject() .getString("first_name")); userFromFB.setLastName(response.getJSONObject().getString("last_name")); } catch (JSONException e) { e.printStackTrace(); } ProfileService.get().refreshCSUser(user, userFromFB); return user; } @Override protected void onPostExecute(CarpoolSophiaUser result) { super.onPostExecute(result); } } }
cernier/carpoolsophia
carpoolsophia/src/main/java/com/carpoolsophia/ProfileFragment.java
Java
gpl-2.0
4,190
30.037037
82
0.698568
false
//--------------------------------------------------------------------------- // NEOPOP : Emulator as in Dreamland // // Copyright (c) 2001-2002 by neopop_uk //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // 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. See also the license.txt file for // additional informations. //--------------------------------------------------------------------------- /* //--------------------------------------------------------------------------- //========================================================================= TLCS900h_registers_mapCodeB0.h //========================================================================= //--------------------------------------------------------------------------- History of changes: =================== 20 JUL 2002 - neopop_uk ======================================= - Cleaned and tidied up for the source release //--------------------------------------------------------------------------- */ ((_u8*)&gprBank[0][0]) + BYTE0,((_u8*)&gprBank[0][0]) + BYTE1, //BANK 0 ((_u8*)&gprBank[0][0]) + BYTE2, ((_u8*)&gprBank[0][0]) + BYTE3, ((_u8*)&gprBank[0][1]) + BYTE0,((_u8*)&gprBank[0][1]) + BYTE1, ((_u8*)&gprBank[0][1]) + BYTE2, ((_u8*)&gprBank[0][1]) + BYTE3, ((_u8*)&gprBank[0][2]) + BYTE0,((_u8*)&gprBank[0][2]) + BYTE1, ((_u8*)&gprBank[0][2]) + BYTE2, ((_u8*)&gprBank[0][2]) + BYTE3, ((_u8*)&gprBank[0][3]) + BYTE0,((_u8*)&gprBank[0][3]) + BYTE1, ((_u8*)&gprBank[0][3]) + BYTE2, ((_u8*)&gprBank[0][3]) + BYTE3, ((_u8*)&gprBank[1][0]) + BYTE0,((_u8*)&gprBank[1][0]) + BYTE1, //BANK 1 ((_u8*)&gprBank[1][0]) + BYTE2, ((_u8*)&gprBank[1][0]) + BYTE3, ((_u8*)&gprBank[1][1]) + BYTE0,((_u8*)&gprBank[1][1]) + BYTE1, ((_u8*)&gprBank[1][1]) + BYTE2, ((_u8*)&gprBank[1][1]) + BYTE3, ((_u8*)&gprBank[1][2]) + BYTE0,((_u8*)&gprBank[1][2]) + BYTE1, ((_u8*)&gprBank[1][2]) + BYTE2, ((_u8*)&gprBank[1][2]) + BYTE3, ((_u8*)&gprBank[1][3]) + BYTE0,((_u8*)&gprBank[1][3]) + BYTE1, ((_u8*)&gprBank[1][3]) + BYTE2, ((_u8*)&gprBank[1][3]) + BYTE3, ((_u8*)&gprBank[2][0]) + BYTE0,((_u8*)&gprBank[2][0]) + BYTE1, //BANK 2 ((_u8*)&gprBank[2][0]) + BYTE2, ((_u8*)&gprBank[2][0]) + BYTE3, ((_u8*)&gprBank[2][1]) + BYTE0,((_u8*)&gprBank[2][1]) + BYTE1, ((_u8*)&gprBank[2][1]) + BYTE2, ((_u8*)&gprBank[2][1]) + BYTE3, ((_u8*)&gprBank[2][2]) + BYTE0,((_u8*)&gprBank[2][2]) + BYTE1, ((_u8*)&gprBank[2][2]) + BYTE2, ((_u8*)&gprBank[2][2]) + BYTE3, ((_u8*)&gprBank[2][3]) + BYTE0,((_u8*)&gprBank[2][3]) + BYTE1, ((_u8*)&gprBank[2][3]) + BYTE2, ((_u8*)&gprBank[2][3]) + BYTE3, ((_u8*)&gprBank[3][0]) + BYTE0,((_u8*)&gprBank[3][0]) + BYTE1, //BANK 3 ((_u8*)&gprBank[3][0]) + BYTE2, ((_u8*)&gprBank[3][0]) + BYTE3, ((_u8*)&gprBank[3][1]) + BYTE0,((_u8*)&gprBank[3][1]) + BYTE1, ((_u8*)&gprBank[3][1]) + BYTE2, ((_u8*)&gprBank[3][1]) + BYTE3, ((_u8*)&gprBank[3][2]) + BYTE0,((_u8*)&gprBank[3][2]) + BYTE1, ((_u8*)&gprBank[3][2]) + BYTE2, ((_u8*)&gprBank[3][2]) + BYTE3, ((_u8*)&gprBank[3][3]) + BYTE0,((_u8*)&gprBank[3][3]) + BYTE1, ((_u8*)&gprBank[3][3]) + BYTE2, ((_u8*)&gprBank[3][3]) + BYTE3, (_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr, //Previous Bank (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, (_u8*)&rErr,(_u8*)&rErr, //Current Bank ((_u8*)&gprBank[0][0]) + BYTE0,((_u8*)&gprBank[0][0]) + BYTE1, ((_u8*)&gprBank[0][0]) + BYTE2, ((_u8*)&gprBank[0][0]) + BYTE3, ((_u8*)&gprBank[0][1]) + BYTE0,((_u8*)&gprBank[0][1]) + BYTE1, ((_u8*)&gprBank[0][1]) + BYTE2, ((_u8*)&gprBank[0][1]) + BYTE3, ((_u8*)&gprBank[0][2]) + BYTE0,((_u8*)&gprBank[0][2]) + BYTE1, ((_u8*)&gprBank[0][2]) + BYTE2, ((_u8*)&gprBank[0][2]) + BYTE3, ((_u8*)&gprBank[0][3]) + BYTE0,((_u8*)&gprBank[0][3]) + BYTE1, ((_u8*)&gprBank[0][3]) + BYTE2, ((_u8*)&gprBank[0][3]) + BYTE3, ((_u8*)&gpr[0]) + BYTE0, ((_u8*)&gpr[0]) + BYTE1, ((_u8*)&gpr[0]) + BYTE2, ((_u8*)&gpr[0]) + BYTE3, ((_u8*)&gpr[1]) + BYTE0, ((_u8*)&gpr[1]) + BYTE1, ((_u8*)&gpr[1]) + BYTE2, ((_u8*)&gpr[1]) + BYTE3, ((_u8*)&gpr[2]) + BYTE0, ((_u8*)&gpr[2]) + BYTE1, ((_u8*)&gpr[2]) + BYTE2, ((_u8*)&gpr[2]) + BYTE3, ((_u8*)&gpr[3]) + BYTE0, ((_u8*)&gpr[3]) + BYTE1, ((_u8*)&gpr[3]) + BYTE2, ((_u8*)&gpr[3]) + BYTE3 //=============================================================================
Cpasjuste/neopop-sdl
Core/TLCS-900h/TLCS900h_registers_mapCodeB0.h
C
gpl-2.0
6,424
60.180952
385
0.44396
false
<!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.11"/> <title>ShipCAD: ShipCADlib/subdivbase.cpp File 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="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </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 id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">ShipCAD </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_f0b6ef187c5b1483641b038f81654ac4.html">ShipCADlib</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">subdivbase.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &lt;iostream&gt;</code><br /> <code>#include &quot;<a class="el" href="subdivbase_8h_source.html">subdivbase.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="subdivsurface_8h_source.html">subdivsurface.h</a>&quot;</code><br /> </div> <p><a href="subdivbase_8cpp_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:a84a51d41cc05085431b75e5148141ca9"><td class="memItemLeft" align="right" valign="top">ostream &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="subdivbase_8cpp.html#a84a51d41cc05085431b75e5148141ca9">operator&lt;&lt;</a> (ostream &amp;os, const <a class="el" href="classShipCAD_1_1SubdivisionBase.html">ShipCAD::SubdivisionBase</a> &amp;base)</td></tr> <tr class="separator:a84a51d41cc05085431b75e5148141ca9"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="a84a51d41cc05085431b75e5148141ca9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ostream&amp; operator&lt;&lt; </td> <td>(</td> <td class="paramtype">ostream &amp;&#160;</td> <td class="paramname"><em>os</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="classShipCAD_1_1SubdivisionBase.html">ShipCAD::SubdivisionBase</a> &amp;&#160;</td> <td class="paramname"><em>base</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="subdivbase_8cpp_source.html#l00062">62</a> of file <a class="el" href="subdivbase_8cpp_source.html">subdivbase.cpp</a>.</p> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Feb 25 2018 15:36:00 for ShipCAD by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
gpgreen/ShipCAD
doc/html/subdivbase_8cpp.html
HTML
gpl-2.0
6,049
41.598592
398
0.640767
false
/* * fs/fs-writeback.c * * Copyright (C) 2002, Linus Torvalds. * * Contains all the functions related to writing back and waiting * upon dirty inodes against superblocks, and writing back dirty * pages against inodes. ie: data writeback. Writeout of the * inode itself is not handled here. * * 10Apr2002 Andrew Morton * Split out of fs/inode.c * Additions for address_space-based writeback */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/writeback.h> #include <linux/blkdev.h> #include <linux/backing-dev.h> #include <linux/buffer_head.h> #include <linux/tracepoint.h> #include <trace/events/vfs.h> #include "internal.h" /* * Passed into wb_writeback(), essentially a subset of writeback_control */ struct wb_writeback_work { long nr_pages; struct super_block *sb; unsigned long *older_than_this; enum writeback_sync_modes sync_mode; unsigned int tagged_writepages:1; unsigned int for_kupdate:1; unsigned int range_cyclic:1; unsigned int for_background:1; enum wb_reason reason; /* why was writeback initiated? */ struct list_head list; /* pending work list */ struct completion *done; /* set if the caller waits */ }; /* * Include the creation of the trace points after defining the * wb_writeback_work structure so that the definition remains local to this * file. */ #define CREATE_TRACE_POINTS #include <trace/events/writeback.h> /* * We don't actually have pdflush, but this one is exported though /proc... */ int nr_pdflush_threads; /** * writeback_in_progress - determine whether there is writeback in progress * @bdi: the device's backing_dev_info structure. * * Determine whether there is writeback waiting to be handled against a * backing device. */ int writeback_in_progress(struct backing_dev_info *bdi) { return test_bit(BDI_writeback_running, &bdi->state); } static inline struct backing_dev_info *inode_to_bdi(struct inode *inode) { struct super_block *sb = inode->i_sb; if (strcmp(sb->s_type->name, "bdev") == 0) return inode->i_mapping->backing_dev_info; return sb->s_bdi; } static inline struct inode *wb_inode(struct list_head *head) { return list_entry(head, struct inode, i_wb_list); } /* Wakeup flusher thread or forker thread to fork it. Requires bdi->wb_lock. */ static void bdi_wakeup_flusher(struct backing_dev_info *bdi) { if (bdi->wb.task) { wake_up_process(bdi->wb.task); } else { /* * The bdi thread isn't there, wake up the forker thread which * will create and run it. */ wake_up_process(default_backing_dev_info.wb.task); } } static void bdi_queue_work(struct backing_dev_info *bdi, struct wb_writeback_work *work) { trace_writeback_queue(bdi, work); spin_lock_bh(&bdi->wb_lock); list_add_tail(&work->list, &bdi->work_list); if (!bdi->wb.task) trace_writeback_nothread(bdi, work); bdi_wakeup_flusher(bdi); spin_unlock_bh(&bdi->wb_lock); } static void __bdi_start_writeback(struct backing_dev_info *bdi, long nr_pages, bool range_cyclic, enum wb_reason reason) { struct wb_writeback_work *work; /* * This is WB_SYNC_NONE writeback, so if allocation fails just * wakeup the thread for old dirty data writeback */ work = kzalloc(sizeof(*work), GFP_ATOMIC); if (!work) { if (bdi->wb.task) { trace_writeback_nowork(bdi); wake_up_process(bdi->wb.task); } return; } work->sync_mode = WB_SYNC_NONE; work->nr_pages = nr_pages; work->range_cyclic = range_cyclic; work->reason = reason; bdi_queue_work(bdi, work); } /** * bdi_start_writeback - start writeback * @bdi: the backing device to write from * @nr_pages: the number of pages to write * @reason: reason why some writeback work was initiated * * Description: * This does WB_SYNC_NONE opportunistic writeback. The IO is only * started when this function returns, we make no guarantees on * completion. Caller need not hold sb s_umount semaphore. * */ void bdi_start_writeback(struct backing_dev_info *bdi, long nr_pages, enum wb_reason reason) { __bdi_start_writeback(bdi, nr_pages, true, reason); } /** * bdi_start_background_writeback - start background writeback * @bdi: the backing device to write from * * Description: * This makes sure WB_SYNC_NONE background writeback happens. When * this function returns, it is only guaranteed that for given BDI * some IO is happening if we are over background dirty threshold. * Caller need not hold sb s_umount semaphore. */ void bdi_start_background_writeback(struct backing_dev_info *bdi) { /* * We just wake up the flusher thread. It will perform background * writeback as soon as there is no other work to do. */ trace_writeback_wake_background(bdi); spin_lock_bh(&bdi->wb_lock); bdi_wakeup_flusher(bdi); spin_unlock_bh(&bdi->wb_lock); } /* * Remove the inode from the writeback list it is on. */ void inode_wb_list_del(struct inode *inode) { struct backing_dev_info *bdi = inode_to_bdi(inode); spin_lock(&bdi->wb.list_lock); list_del_init(&inode->i_wb_list); spin_unlock(&bdi->wb.list_lock); } /* * Redirty an inode: set its when-it-was dirtied timestamp and move it to the * furthest end of its superblock's dirty-inode list. * * Before stamping the inode's ->dirtied_when, we check to see whether it is * already the most-recently-dirtied inode on the b_dirty list. If that is * the case then the inode must have been redirtied while it was being written * out and we don't reset its dirtied_when. */ static void redirty_tail(struct inode *inode, struct bdi_writeback *wb) { assert_spin_locked(&wb->list_lock); if (!list_empty(&wb->b_dirty)) { struct inode *tail; tail = wb_inode(wb->b_dirty.next); if (time_before(inode->dirtied_when, tail->dirtied_when)) inode->dirtied_when = jiffies; } list_move(&inode->i_wb_list, &wb->b_dirty); } /* * requeue inode for re-scanning after bdi->b_io list is exhausted. */ static void requeue_io(struct inode *inode, struct bdi_writeback *wb) { assert_spin_locked(&wb->list_lock); list_move(&inode->i_wb_list, &wb->b_more_io); } static void inode_sync_complete(struct inode *inode) { /* * Prevent speculative execution through * spin_unlock(&wb->list_lock); */ smp_mb(); wake_up_bit(&inode->i_state, __I_SYNC); } static bool inode_dirtied_after(struct inode *inode, unsigned long t) { bool ret = time_after(inode->dirtied_when, t); #ifndef CONFIG_64BIT /* * For inodes being constantly redirtied, dirtied_when can get stuck. * It _appears_ to be in the future, but is actually in distant past. * This test is necessary to prevent such wrapped-around relative times * from permanently stopping the whole bdi writeback. */ ret = ret && time_before_eq(inode->dirtied_when, jiffies); #endif return ret; } /* * Move expired dirty inodes from @delaying_queue to @dispatch_queue. */ static int move_expired_inodes(struct list_head *delaying_queue, struct list_head *dispatch_queue, struct wb_writeback_work *work) { LIST_HEAD(tmp); struct list_head *pos, *node; struct super_block *sb = NULL; struct inode *inode; int do_sb_sort = 0; int moved = 0; while (!list_empty(delaying_queue)) { inode = wb_inode(delaying_queue->prev); if (work->older_than_this && inode_dirtied_after(inode, *work->older_than_this)) break; if (sb && sb != inode->i_sb) do_sb_sort = 1; sb = inode->i_sb; list_move(&inode->i_wb_list, &tmp); moved++; } /* just one sb in list, splice to dispatch_queue and we're done */ if (!do_sb_sort) { list_splice(&tmp, dispatch_queue); goto out; } /* Move inodes from one superblock together */ while (!list_empty(&tmp)) { sb = wb_inode(tmp.prev)->i_sb; list_for_each_prev_safe(pos, node, &tmp) { inode = wb_inode(pos); if (inode->i_sb == sb) list_move(&inode->i_wb_list, dispatch_queue); } } out: return moved; } /* * Queue all expired dirty inodes for io, eldest first. * Before * newly dirtied b_dirty b_io b_more_io * =============> gf edc BA * After * newly dirtied b_dirty b_io b_more_io * =============> g fBAedc * | * +--> dequeue for IO */ static void queue_io(struct bdi_writeback *wb, struct wb_writeback_work *work) { int moved; assert_spin_locked(&wb->list_lock); list_splice_init(&wb->b_more_io, &wb->b_io); moved = move_expired_inodes(&wb->b_dirty, &wb->b_io, work); trace_writeback_queue_io(wb, work, moved); } static int write_inode(struct inode *inode, struct writeback_control *wbc) { if (inode->i_sb->s_op->write_inode && !is_bad_inode(inode)) return inode->i_sb->s_op->write_inode(inode, wbc); return 0; } /* * Wait for writeback on an inode to complete. */ static void inode_wait_for_writeback(struct inode *inode, struct bdi_writeback *wb) { DEFINE_WAIT_BIT(wq, &inode->i_state, __I_SYNC); wait_queue_head_t *wqh; wqh = bit_waitqueue(&inode->i_state, __I_SYNC); while (inode->i_state & I_SYNC) { spin_unlock(&inode->i_lock); spin_unlock(&wb->list_lock); __wait_on_bit(wqh, &wq, inode_wait, TASK_UNINTERRUPTIBLE); spin_lock(&wb->list_lock); spin_lock(&inode->i_lock); } } /* * Write out an inode's dirty pages. Called under wb->list_lock and * inode->i_lock. Either the caller has an active reference on the inode or * the inode has I_WILL_FREE set. * * If `wait' is set, wait on the writeout. * * The whole writeout design is quite complex and fragile. We want to avoid * starvation of particular inodes when others are being redirtied, prevent * livelocks, etc. */ static int writeback_single_inode(struct inode *inode, struct bdi_writeback *wb, struct writeback_control *wbc) { struct address_space *mapping = inode->i_mapping; long nr_to_write = wbc->nr_to_write; unsigned dirty; int ret; assert_spin_locked(&wb->list_lock); assert_spin_locked(&inode->i_lock); if (!atomic_read(&inode->i_count)) WARN_ON(!(inode->i_state & (I_WILL_FREE|I_FREEING))); else WARN_ON(inode->i_state & I_WILL_FREE); if (inode->i_state & I_SYNC) { /* * If this inode is locked for writeback and we are not doing * writeback-for-data-integrity, move it to b_more_io so that * writeback can proceed with the other inodes on s_io. * * We'll have another go at writing back this inode when we * completed a full scan of b_io. */ if (wbc->sync_mode != WB_SYNC_ALL) { requeue_io(inode, wb); trace_writeback_single_inode_requeue(inode, wbc, nr_to_write); return 0; } /* * It's a data-integrity sync. We must wait. */ inode_wait_for_writeback(inode, wb); } BUG_ON(inode->i_state & I_SYNC); /* Set I_SYNC, reset I_DIRTY_PAGES */ inode->i_state |= I_SYNC; inode->i_state &= ~I_DIRTY_PAGES; spin_unlock(&inode->i_lock); spin_unlock(&wb->list_lock); ret = do_writepages(mapping, wbc); /* * Make sure to wait on the data before writing out the metadata. * This is important for filesystems that modify metadata on data * I/O completion. */ if (wbc->sync_mode == WB_SYNC_ALL) { int err = filemap_fdatawait(mapping); if (ret == 0) ret = err; } /* * Some filesystems may redirty the inode during the writeback * due to delalloc, clear dirty metadata flags right before * write_inode() */ spin_lock(&inode->i_lock); dirty = inode->i_state & I_DIRTY; inode->i_state &= ~(I_DIRTY_SYNC | I_DIRTY_DATASYNC); spin_unlock(&inode->i_lock); /* Don't write the inode if only I_DIRTY_PAGES was set */ if (dirty & (I_DIRTY_SYNC | I_DIRTY_DATASYNC)) { int err = write_inode(inode, wbc); if (ret == 0) ret = err; } spin_lock(&wb->list_lock); spin_lock(&inode->i_lock); inode->i_state &= ~I_SYNC; if (!(inode->i_state & I_FREEING)) { /* * Sync livelock prevention. Each inode is tagged and synced in * one shot. If still dirty, it will be redirty_tail()'ed below. * Update the dirty time to prevent enqueue and sync it again. */ if ((inode->i_state & I_DIRTY) && (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)) inode->dirtied_when = jiffies; if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) { /* * We didn't write back all the pages. nfs_writepages() * sometimes bales out without doing anything. */ inode->i_state |= I_DIRTY_PAGES; if (wbc->nr_to_write <= 0) { /* * slice used up: queue for next turn */ requeue_io(inode, wb); } else { /* * Writeback blocked by something other than * congestion. Delay the inode for some time to * avoid spinning on the CPU (100% iowait) * retrying writeback of the dirty page/inode * that cannot be performed immediately. */ redirty_tail(inode, wb); } } else if (inode->i_state & I_DIRTY) { /* * Filesystems can dirty the inode during writeback * operations, such as delayed allocation during * submission or metadata updates after data IO * completion. */ redirty_tail(inode, wb); } else { /* * The inode is clean. At this point we either have * a reference to the inode or it's on it's way out. * No need to add it back to the LRU. */ list_del_init(&inode->i_wb_list); } } inode_sync_complete(inode); trace_writeback_single_inode(inode, wbc, nr_to_write); return ret; } static long writeback_chunk_size(struct backing_dev_info *bdi, struct wb_writeback_work *work) { long pages; /* * WB_SYNC_ALL mode does livelock avoidance by syncing dirty * inodes/pages in one big loop. Setting wbc.nr_to_write=LONG_MAX * here avoids calling into writeback_inodes_wb() more than once. * * The intended call sequence for WB_SYNC_ALL writeback is: * * wb_writeback() * writeback_sb_inodes() <== called only once * write_cache_pages() <== called once for each inode * (quickly) tag currently dirty pages * (maybe slowly) sync all tagged pages */ if (work->sync_mode == WB_SYNC_ALL || work->tagged_writepages) pages = LONG_MAX; else { pages = min(bdi->avg_write_bandwidth / 2, global_dirty_limit / DIRTY_SCOPE); pages = min(pages, work->nr_pages); pages = round_down(pages + MIN_WRITEBACK_PAGES, MIN_WRITEBACK_PAGES); } return pages; } /* * Write a portion of b_io inodes which belong to @sb. * * If @only_this_sb is true, then find and write all such * inodes. Otherwise write only ones which go sequentially * in reverse order. * * Return the number of pages and/or inodes written. */ static long writeback_sb_inodes(struct super_block *sb, struct bdi_writeback *wb, struct wb_writeback_work *work) { struct writeback_control wbc = { .sync_mode = work->sync_mode, .tagged_writepages = work->tagged_writepages, .for_kupdate = work->for_kupdate, .for_background = work->for_background, .range_cyclic = work->range_cyclic, .range_start = 0, .range_end = LLONG_MAX, }; unsigned long start_time = jiffies; long write_chunk; long wrote = 0; /* count both pages and inodes */ while (!list_empty(&wb->b_io)) { struct inode *inode = wb_inode(wb->b_io.prev); if (inode->i_sb != sb) { if (work->sb) { /* * We only want to write back data for this * superblock, move all inodes not belonging * to it back onto the dirty list. */ redirty_tail(inode, wb); continue; } /* * The inode belongs to a different superblock. * Bounce back to the caller to unpin this and * pin the next superblock. */ break; } /* * Don't bother with new inodes or inodes beeing freed, first * kind does not need peridic writeout yet, and for the latter * kind writeout is handled by the freer. */ spin_lock(&inode->i_lock); if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) { spin_unlock(&inode->i_lock); redirty_tail(inode, wb); continue; } __iget(inode); write_chunk = writeback_chunk_size(wb->bdi, work); wbc.nr_to_write = write_chunk; wbc.pages_skipped = 0; writeback_single_inode(inode, wb, &wbc); work->nr_pages -= write_chunk - wbc.nr_to_write; wrote += write_chunk - wbc.nr_to_write; if (!(inode->i_state & I_DIRTY)) wrote++; if (wbc.pages_skipped) { /* * writeback is not making progress due to locked * buffers. Skip this inode for now. */ redirty_tail(inode, wb); } spin_unlock(&inode->i_lock); spin_unlock(&wb->list_lock); iput(inode); cond_resched(); spin_lock(&wb->list_lock); /* * bail out to wb_writeback() often enough to check * background threshold and other termination conditions. */ if (wrote) { if (time_is_before_jiffies(start_time + HZ / 10UL)) break; if (work->nr_pages <= 0) break; } } return wrote; } static long __writeback_inodes_wb(struct bdi_writeback *wb, struct wb_writeback_work *work) { unsigned long start_time = jiffies; long wrote = 0; while (!list_empty(&wb->b_io)) { struct inode *inode = wb_inode(wb->b_io.prev); struct super_block *sb = inode->i_sb; if (!grab_super_passive(sb)) { /* * grab_super_passive() may fail consistently due to * s_umount being grabbed by someone else. Don't use * requeue_io() to avoid busy retrying the inode/sb. */ redirty_tail(inode, wb); continue; } wrote += writeback_sb_inodes(sb, wb, work); drop_super(sb); /* refer to the same tests at the end of writeback_sb_inodes */ if (wrote) { if (time_is_before_jiffies(start_time + HZ / 10UL)) break; if (work->nr_pages <= 0) break; } } /* Leave any unwritten inodes on b_io */ return wrote; } long writeback_inodes_wb(struct bdi_writeback *wb, long nr_pages, enum wb_reason reason) { struct wb_writeback_work work = { .nr_pages = nr_pages, .sync_mode = WB_SYNC_NONE, .range_cyclic = 1, .reason = reason, }; spin_lock(&wb->list_lock); if (list_empty(&wb->b_io)) queue_io(wb, &work); __writeback_inodes_wb(wb, &work); spin_unlock(&wb->list_lock); return nr_pages - work.nr_pages; } static bool over_bground_thresh(struct backing_dev_info *bdi) { unsigned long background_thresh, dirty_thresh; global_dirty_limits(&background_thresh, &dirty_thresh); if (global_page_state(NR_FILE_DIRTY) + global_page_state(NR_UNSTABLE_NFS) > background_thresh) return true; if (bdi_stat(bdi, BDI_RECLAIMABLE) > bdi_dirty_limit(bdi, background_thresh)) return true; return false; } /* * Called under wb->list_lock. If there are multiple wb per bdi, * only the flusher working on the first wb should do it. */ static void wb_update_bandwidth(struct bdi_writeback *wb, unsigned long start_time) { __bdi_update_bandwidth(wb->bdi, 0, 0, 0, 0, 0, start_time); } /* * Explicit flushing or periodic writeback of "old" data. * * Define "old": the first time one of an inode's pages is dirtied, we mark the * dirtying-time in the inode's address_space. So this periodic writeback code * just walks the superblock inode list, writing back any inodes which are * older than a specific point in time. * * Try to run once per dirty_writeback_interval. But if a writeback event * takes longer than a dirty_writeback_interval interval, then leave a * one-second gap. * * older_than_this takes precedence over nr_to_write. So we'll only write back * all dirty pages if they are all attached to "old" mappings. */ static long wb_writeback(struct bdi_writeback *wb, struct wb_writeback_work *work) { unsigned long wb_start = jiffies; long nr_pages = work->nr_pages; unsigned long oldest_jif; struct inode *inode; long progress; oldest_jif = jiffies; work->older_than_this = &oldest_jif; spin_lock(&wb->list_lock); for (;;) { /* * Stop writeback when nr_pages has been consumed */ if (work->nr_pages <= 0) break; /* * Background writeout and kupdate-style writeback may * run forever. Stop them if there is other work to do * so that e.g. sync can proceed. They'll be restarted * after the other works are all done. */ if ((work->for_background || work->for_kupdate) && !list_empty(&wb->bdi->work_list)) break; /* * For background writeout, stop when we are below the * background dirty threshold */ if (work->for_background && !over_bground_thresh(wb->bdi)) break; if (work->for_kupdate) { oldest_jif = jiffies - msecs_to_jiffies(dirty_expire_interval * 10); work->older_than_this = &oldest_jif; } trace_writeback_start(wb->bdi, work); if (list_empty(&wb->b_io)) queue_io(wb, work); if (work->sb) progress = writeback_sb_inodes(work->sb, wb, work); else progress = __writeback_inodes_wb(wb, work); trace_writeback_written(wb->bdi, work); wb_update_bandwidth(wb, wb_start); /* * Did we write something? Try for more * * Dirty inodes are moved to b_io for writeback in batches. * The completion of the current batch does not necessarily * mean the overall work is done. So we keep looping as long * as made some progress on cleaning pages or inodes. */ if (progress) continue; /* * No more inodes for IO, bail */ if (list_empty(&wb->b_more_io)) break; /* * Nothing written. Wait for some inode to * become available for writeback. Otherwise * we'll just busyloop. */ if (!list_empty(&wb->b_more_io)) { trace_writeback_wait(wb->bdi, work); inode = wb_inode(wb->b_more_io.prev); spin_lock(&inode->i_lock); inode_wait_for_writeback(inode, wb); spin_unlock(&inode->i_lock); } } spin_unlock(&wb->list_lock); return nr_pages - work->nr_pages; } /* * Return the next wb_writeback_work struct that hasn't been processed yet. */ static struct wb_writeback_work * get_next_work_item(struct backing_dev_info *bdi) { struct wb_writeback_work *work = NULL; spin_lock_bh(&bdi->wb_lock); if (!list_empty(&bdi->work_list)) { work = list_entry(bdi->work_list.next, struct wb_writeback_work, list); list_del_init(&work->list); } spin_unlock_bh(&bdi->wb_lock); return work; } /* * Add in the number of potentially dirty inodes, because each inode * write can dirty pagecache in the underlying blockdev. */ static unsigned long get_nr_dirty_pages(void) { return global_page_state(NR_FILE_DIRTY) + global_page_state(NR_UNSTABLE_NFS) + get_nr_dirty_inodes(); } static long wb_check_background_flush(struct bdi_writeback *wb) { if (over_bground_thresh(wb->bdi)) { struct wb_writeback_work work = { .nr_pages = LONG_MAX, .sync_mode = WB_SYNC_NONE, .for_background = 1, .range_cyclic = 1, .reason = WB_REASON_BACKGROUND, }; return wb_writeback(wb, &work); } return 0; } static long wb_check_old_data_flush(struct bdi_writeback *wb) { unsigned long expired; long nr_pages; /* * When set to zero, disable periodic writeback */ if (!dirty_writeback_interval) return 0; expired = wb->last_old_flush + msecs_to_jiffies(dirty_writeback_interval * 10); if (time_before(jiffies, expired)) return 0; wb->last_old_flush = jiffies; nr_pages = get_nr_dirty_pages(); if (nr_pages) { struct wb_writeback_work work = { .nr_pages = nr_pages, .sync_mode = WB_SYNC_NONE, .for_kupdate = 1, .range_cyclic = 1, .reason = WB_REASON_PERIODIC, }; return wb_writeback(wb, &work); } return 0; } /* * Retrieve work items and do the writeback they describe */ long wb_do_writeback(struct bdi_writeback *wb, int force_wait) { struct backing_dev_info *bdi = wb->bdi; struct wb_writeback_work *work; long wrote = 0; set_bit(BDI_writeback_running, &wb->bdi->state); while ((work = get_next_work_item(bdi)) != NULL) { /* * Override sync mode, in case we must wait for completion * because this thread is exiting now. */ if (force_wait) work->sync_mode = WB_SYNC_ALL; trace_writeback_exec(bdi, work); wrote += wb_writeback(wb, work); /* * Notify the caller of completion if this is a synchronous * work item, otherwise just free it. */ if (work->done) complete(work->done); else kfree(work); } /* * Check for periodic writeback, kupdated() style */ wrote += wb_check_old_data_flush(wb); wrote += wb_check_background_flush(wb); clear_bit(BDI_writeback_running, &wb->bdi->state); return wrote; } /* * Handle writeback of dirty data for the device backed by this bdi. Also * wakes up periodically and does kupdated style flushing. */ int bdi_writeback_thread(void *data) { struct bdi_writeback *wb = data; struct backing_dev_info *bdi = wb->bdi; long pages_written; current->flags |= PF_SWAPWRITE; set_freezable(); wb->last_active = jiffies; /* * Our parent may run at a different priority, just set us to normal */ set_user_nice(current, 0); trace_writeback_thread_start(bdi); while (!kthread_should_stop()) { /* * Remove own delayed wake-up timer, since we are already awake * and we'll take care of the preriodic write-back. */ del_timer(&wb->wakeup_timer); pages_written = wb_do_writeback(wb, 0); trace_writeback_pages_written(pages_written); if (pages_written) wb->last_active = jiffies; set_current_state(TASK_INTERRUPTIBLE); if (!list_empty(&bdi->work_list) || kthread_should_stop()) { __set_current_state(TASK_RUNNING); continue; } if (wb_has_dirty_io(wb) && dirty_writeback_interval) schedule_timeout(msecs_to_jiffies(dirty_writeback_interval * 10)); else { /* * We have nothing to do, so can go sleep without any * timeout and save power. When a work is queued or * something is made dirty - we will be woken up. */ schedule(); } try_to_freeze(); } /* Flush any work that raced with us exiting */ if (!list_empty(&bdi->work_list)) wb_do_writeback(wb, 1); trace_writeback_thread_stop(bdi); return 0; } /* * Start writeback of `nr_pages' pages. If `nr_pages' is zero, write back * the whole world. */ void wakeup_flusher_threads(long nr_pages, enum wb_reason reason) { struct backing_dev_info *bdi; if (!nr_pages) { nr_pages = global_page_state(NR_FILE_DIRTY) + global_page_state(NR_UNSTABLE_NFS); } rcu_read_lock(); list_for_each_entry_rcu(bdi, &bdi_list, bdi_list) { if (!bdi_has_dirty_io(bdi)) continue; __bdi_start_writeback(bdi, nr_pages, false, reason); } rcu_read_unlock(); } static noinline void block_dump___mark_inode_dirty(struct inode *inode) { if (inode->i_ino || strcmp(inode->i_sb->s_id, "bdev")) { struct dentry *dentry; const char *name = "?"; dentry = d_find_alias(inode); if (dentry) { spin_lock(&dentry->d_lock); name = (const char *) dentry->d_name.name; } printk(KERN_DEBUG "%s(%d): dirtied inode %lu (%s) on %s\n", current->comm, task_pid_nr(current), inode->i_ino, name, inode->i_sb->s_id); if (dentry) { spin_unlock(&dentry->d_lock); dput(dentry); } } } /** * __mark_inode_dirty - internal function * @inode: inode to mark * @flags: what kind of dirty (i.e. I_DIRTY_SYNC) * Mark an inode as dirty. Callers should use mark_inode_dirty or * mark_inode_dirty_sync. * * Put the inode on the super block's dirty list. * * CAREFUL! We mark it dirty unconditionally, but move it onto the * dirty list only if it is hashed or if it refers to a blockdev. * If it was not hashed, it will never be added to the dirty list * even if it is later hashed, as it will have been marked dirty already. * * In short, make sure you hash any inodes _before_ you start marking * them dirty. * * Note that for blockdevs, inode->dirtied_when represents the dirtying time of * the block-special inode (/dev/hda1) itself. And the ->dirtied_when field of * the kernel-internal blockdev inode represents the dirtying time of the * blockdev's pages. This is why for I_DIRTY_PAGES we always use * page->mapping->host, so the page-dirtying time is recorded in the internal * blockdev inode. */ void __mark_inode_dirty(struct inode *inode, int flags) { struct super_block *sb = inode->i_sb; struct backing_dev_info *bdi = NULL; /* * Don't do this for I_DIRTY_PAGES - that doesn't actually * dirty the inode itself */ if (flags & (I_DIRTY_SYNC | I_DIRTY_DATASYNC)) { if (sb->s_op->dirty_inode) sb->s_op->dirty_inode(inode, flags); } /* * make sure that changes are seen by all cpus before we test i_state * -- mikulas */ smp_mb(); /* avoid the locking if we can */ if ((inode->i_state & flags) == flags) return; trace_dirty_inode(inode, current); if (unlikely(block_dump)) block_dump___mark_inode_dirty(inode); spin_lock(&inode->i_lock); if ((inode->i_state & flags) != flags) { const int was_dirty = inode->i_state & I_DIRTY; inode->i_state |= flags; /* * If the inode is being synced, just update its dirty state. * The unlocker will place the inode on the appropriate * superblock list, based upon its state. */ if (inode->i_state & I_SYNC) goto out_unlock_inode; /* * Only add valid (hashed) inodes to the superblock's * dirty list. Add blockdev inodes as well. */ if (!S_ISBLK(inode->i_mode)) { if (inode_unhashed(inode)) goto out_unlock_inode; } if (inode->i_state & I_FREEING) goto out_unlock_inode; /* * If the inode was already on b_dirty/b_io/b_more_io, don't * reposition it (that would break b_dirty time-ordering). */ if (!was_dirty) { bool wakeup_bdi = false; bdi = inode_to_bdi(inode); if (bdi_cap_writeback_dirty(bdi)) { WARN(!test_bit(BDI_registered, &bdi->state), "bdi-%s not registered\n", bdi->name); /* * If this is the first dirty inode for this * bdi, we have to wake-up the corresponding * bdi thread to make sure background * write-back happens later. */ if (!wb_has_dirty_io(&bdi->wb)) wakeup_bdi = true; } spin_unlock(&inode->i_lock); spin_lock(&bdi->wb.list_lock); inode->dirtied_when = jiffies; list_move(&inode->i_wb_list, &bdi->wb.b_dirty); spin_unlock(&bdi->wb.list_lock); if (wakeup_bdi) bdi_wakeup_thread_delayed(bdi); return; } } out_unlock_inode: spin_unlock(&inode->i_lock); } EXPORT_SYMBOL(__mark_inode_dirty); /* * Write out a superblock's list of dirty inodes. A wait will be performed * upon no inodes, all inodes or the final one, depending upon sync_mode. * * If older_than_this is non-NULL, then only write out inodes which * had their first dirtying at a time earlier than *older_than_this. * * If `bdi' is non-zero then we're being asked to writeback a specific queue. * This function assumes that the blockdev superblock's inodes are backed by * a variety of queues, so all inodes are searched. For other superblocks, * assume that all inodes are backed by the same queue. * * The inodes to be written are parked on bdi->b_io. They are moved back onto * bdi->b_dirty as they are selected for writing. This way, none can be missed * on the writer throttling path, and we get decent balancing between many * throttled threads: we don't want them all piling up on inode_sync_wait. */ static void wait_sb_inodes(struct super_block *sb) { struct inode *inode, *old_inode = NULL; /* * We need to be protected against the filesystem going from * r/o to r/w or vice versa. */ WARN_ON(!rwsem_is_locked(&sb->s_umount)); spin_lock(&inode_sb_list_lock); /* * Data integrity sync. Must wait for all pages under writeback, * because there may have been pages dirtied before our sync * call, but which had writeout started before we write it out. * In which case, the inode may not be on the dirty list, but * we still have to wait for that writeout. */ list_for_each_entry(inode, &sb->s_inodes, i_sb_list) { struct address_space *mapping = inode->i_mapping; spin_lock(&inode->i_lock); if ((inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) || (mapping->nrpages == 0)) { spin_unlock(&inode->i_lock); continue; } __iget(inode); spin_unlock(&inode->i_lock); spin_unlock(&inode_sb_list_lock); /* * We hold a reference to 'inode' so it couldn't have been * removed from s_inodes list while we dropped the * inode_sb_list_lock. We cannot iput the inode now as we can * be holding the last reference and we cannot iput it under * inode_sb_list_lock. So we keep the reference and iput it * later. */ iput(old_inode); old_inode = inode; filemap_fdatawait(mapping); cond_resched(); spin_lock(&inode_sb_list_lock); } spin_unlock(&inode_sb_list_lock); iput(old_inode); } /** * writeback_inodes_sb_nr - writeback dirty inodes from given super_block * @sb: the superblock * @nr: the number of pages to write * @reason: reason why some writeback work initiated * * Start writeback on some inodes on this super_block. No guarantees are made * on how many (if any) will be written, and this function does not wait * for IO completion of submitted IO. */ void writeback_inodes_sb_nr(struct super_block *sb, unsigned long nr, enum wb_reason reason) { DECLARE_COMPLETION_ONSTACK(done); struct wb_writeback_work work = { .sb = sb, .sync_mode = WB_SYNC_NONE, .tagged_writepages = 1, .done = &done, .nr_pages = nr, .reason = reason, }; WARN_ON(!rwsem_is_locked(&sb->s_umount)); bdi_queue_work(sb->s_bdi, &work); wait_for_completion(&done); } EXPORT_SYMBOL(writeback_inodes_sb_nr); /** * writeback_inodes_sb - writeback dirty inodes from given super_block * @sb: the superblock * @reason: reason why some writeback work was initiated * * Start writeback on some inodes on this super_block. No guarantees are made * on how many (if any) will be written, and this function does not wait * for IO completion of submitted IO. */ void writeback_inodes_sb(struct super_block *sb, enum wb_reason reason) { return writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason); } EXPORT_SYMBOL(writeback_inodes_sb); /** * writeback_inodes_sb_if_idle - start writeback if none underway * @sb: the superblock * @reason: reason why some writeback work was initiated * * Invoke writeback_inodes_sb if no writeback is currently underway. * Returns 1 if writeback was started, 0 if not. */ int writeback_inodes_sb_if_idle(struct super_block *sb, enum wb_reason reason) { if (!writeback_in_progress(sb->s_bdi)) { down_read(&sb->s_umount); writeback_inodes_sb(sb, reason); up_read(&sb->s_umount); return 1; } else return 0; } EXPORT_SYMBOL(writeback_inodes_sb_if_idle); /** * writeback_inodes_sb_if_idle - start writeback if none underway * @sb: the superblock * @nr: the number of pages to write * @reason: reason why some writeback work was initiated * * Invoke writeback_inodes_sb if no writeback is currently underway. * Returns 1 if writeback was started, 0 if not. */ int writeback_inodes_sb_nr_if_idle(struct super_block *sb, unsigned long nr, enum wb_reason reason) { if (!writeback_in_progress(sb->s_bdi)) { down_read(&sb->s_umount); writeback_inodes_sb_nr(sb, nr, reason); up_read(&sb->s_umount); return 1; } else return 0; } EXPORT_SYMBOL(writeback_inodes_sb_nr_if_idle); /** * sync_inodes_sb - sync sb inode pages * @sb: the superblock * * This function writes and waits on any dirty inode belonging to this * super_block. */ void sync_inodes_sb(struct super_block *sb) { DECLARE_COMPLETION_ONSTACK(done); struct wb_writeback_work work = { .sb = sb, .sync_mode = WB_SYNC_ALL, .nr_pages = LONG_MAX, .range_cyclic = 0, .done = &done, .reason = WB_REASON_SYNC, }; WARN_ON(!rwsem_is_locked(&sb->s_umount)); bdi_queue_work(sb->s_bdi, &work); wait_for_completion(&done); wait_sb_inodes(sb); } EXPORT_SYMBOL(sync_inodes_sb); /** * write_inode_now - write an inode to disk * @inode: inode to write to disk * @sync: whether the write should be synchronous or not * * This function commits an inode to disk immediately if it is dirty. This is * primarily needed by knfsd. * * The caller must either have a ref on the inode or must have set I_WILL_FREE. */ int write_inode_now(struct inode *inode, int sync) { struct bdi_writeback *wb = &inode_to_bdi(inode)->wb; int ret; struct writeback_control wbc = { .nr_to_write = LONG_MAX, .sync_mode = sync ? WB_SYNC_ALL : WB_SYNC_NONE, .range_start = 0, .range_end = LLONG_MAX, }; if (!mapping_cap_writeback_dirty(inode->i_mapping)) wbc.nr_to_write = 0; might_sleep(); spin_lock(&wb->list_lock); spin_lock(&inode->i_lock); ret = writeback_single_inode(inode, wb, &wbc); spin_unlock(&inode->i_lock); spin_unlock(&wb->list_lock); if (sync) inode_sync_wait(inode); return ret; } EXPORT_SYMBOL(write_inode_now); /** * sync_inode - write an inode and its pages to disk. * @inode: the inode to sync * @wbc: controls the writeback mode * * sync_inode() will write an inode and its pages to disk. It will also * correctly update the inode on its superblock's dirty inode lists and will * update inode->i_state. * * The caller must have a ref on the inode. */ int sync_inode(struct inode *inode, struct writeback_control *wbc) { struct bdi_writeback *wb = &inode_to_bdi(inode)->wb; int ret; spin_lock(&wb->list_lock); spin_lock(&inode->i_lock); ret = writeback_single_inode(inode, wb, wbc); spin_unlock(&inode->i_lock); spin_unlock(&wb->list_lock); return ret; } EXPORT_SYMBOL(sync_inode); /** * sync_inode_metadata - write an inode to disk * @inode: the inode to sync * @wait: wait for I/O to complete. * * Write an inode to disk and adjust its dirty state after completion. * * Note: only writes the actual inode, no associated data or other metadata. */ int sync_inode_metadata(struct inode *inode, int wait) { struct writeback_control wbc = { .sync_mode = wait ? WB_SYNC_ALL : WB_SYNC_NONE, .nr_to_write = 0, /* metadata-only */ }; return sync_inode(inode, &wbc); } EXPORT_SYMBOL(sync_inode_metadata);
xplodwild/packaged-linux-linaro-3.2-ci
fs/fs-writeback.c
C
gpl-2.0
38,100
26.021277
79
0.666089
false
/* * Copyright (C) 2011-2012 ArkCORE2 <http://www.arkania.net/> * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "ScriptedEscortAI.h" #include "violet_hold.h" #define GOSSIP_START_EVENT "Get your people to safety, we'll keep the Blue Dragonflight's forces at bay." #define GOSSIP_ITEM_1 "Activate the crystals when we get in trouble, right" #define GOSSIP_I_WANT_IN "I'm not fighting, so send me in now!" #define SPAWN_TIME 20000 enum PortalCreatures { CREATURE_AZURE_INVADER_1 = 30661, CREATURE_AZURE_INVADER_2 = 30961, CREATURE_AZURE_SPELLBREAKER_1 = 30662, CREATURE_AZURE_SPELLBREAKER_2 = 30962, CREATURE_AZURE_BINDER_1 = 30663, CREATURE_AZURE_BINDER_2 = 30918, CREATURE_AZURE_MAGE_SLAYER_1 = 30664, CREATURE_AZURE_MAGE_SLAYER_2 = 30963, CREATURE_AZURE_CAPTAIN = 30666, CREATURE_AZURE_SORCEROR = 30667, CREATURE_AZURE_RAIDER = 30668, CREATURE_AZURE_STALKER = 32191 }; enum AzureInvaderSpells { SPELL_CLEAVE = 15496, SPELL_IMPALE = 58459, H_SPELL_IMPALE = 59256, SPELL_BRUTAL_STRIKE = 58460, SPELL_SUNDER_ARMOR = 58461 }; enum AzureSellbreakerSpells { SPELL_ARCANE_BLAST = 58462, H_SPELL_ARCANE_BLAST = 59257, SPELL_SLOW = 25603, SPELL_CHAINS_OF_ICE = 58464, SPELL_CONE_OF_COLD = 58463, H_SPELL_CONE_OF_COLD = 59258 }; enum AzureBinderSpells { SPELL_ARCANE_BARRAGE = 58456, H_SPELL_ARCANE_BARRAGE = 59248, SPELL_ARCANE_EXPLOSION = 58455, H_SPELL_ARCANE_EXPLOSION = 59245, SPELL_FROST_NOVA = 58458, H_SPELL_FROST_NOVA = 59253, SPELL_FROSTBOLT = 58457, H_SPELL_FROSTBOLT = 59251, }; enum AzureMageSlayerSpells { SPELL_ARCANE_EMPOWERMENT = 58469, SPELL_SPELL_LOCK = 30849 }; enum AzureCaptainSpells { SPELL_MORTAL_STRIKE = 32736, SPELL_WHIRLWIND_OF_STEEL = 41057 }; enum AzureSorcerorSpells { SPELL_ARCANE_STREAM = 60181, H_SPELL_ARCANE_STREAM = 60204, SPELL_MANA_DETONATION = 60182, H_SPELL_MANA_DETONATION = 60205 }; enum AzureRaiderSpells { SPELL_CONCUSSION_BLOW = 52719, SPELL_MAGIC_REFLECTION = 60158 }; enum AzureStalkerSpells { SPELL_BACKSTAB = 58471, SPELL_TACTICAL_BLINK = 58470 }; enum AzureSaboteurSpells { SABOTEUR_SHIELD_DISRUPTION = 58291, SABOTEUR_SHIELD_EFFECT = 45775 }; enum TrashDoorSpell { SPELL_DESTROY_DOOR_SEAL = 58040 }; enum Spells { SPELL_PORTAL_CHANNEL = 58012, SPELL_CRYSTALL_ACTIVATION = 57804 }; enum eSinclari { SAY_SINCLARI_1 = -1608045 }; float FirstPortalWPs [6][3] = { {1877.670288f, 842.280273f, 43.333591f}, {1877.338867f, 834.615356f, 38.762287f}, {1872.161011f, 823.854309f, 38.645401f}, {1864.860474f, 815.787170f, 38.784843f}, {1858.953735f, 810.048950f, 44.008759f}, {1843.707153f, 805.807739f, 44.135197f} //{1825.736084f, 807.305847f, 44.363785f} }; float SecondPortalFirstWPs [9][3] = { {1902.561401f, 853.334656f, 47.106117f}, {1895.486084f, 855.376404f, 44.334591f}, {1882.805176f, 854.993286f, 43.333591f}, {1877.670288f, 842.280273f, 43.333591f}, {1877.338867f, 834.615356f, 38.762287f}, {1872.161011f, 823.854309f, 38.645401f}, {1864.860474f, 815.787170f, 38.784843f}, {1858.953735f, 810.048950f, 44.008759f}, {1843.707153f, 805.807739f, 44.135197f} //{1825.736084f, 807.305847f, 44.363785f} }; float SecondPortalSecondWPs [8][3] = { {1929.392212f, 837.614990f, 47.136166f}, {1928.290649f, 824.750427f, 45.474411f}, {1915.544922f, 826.919373f, 38.642811f}, {1900.933960f, 818.855652f, 38.801647f}, {1886.810547f, 813.536621f, 38.490490f}, {1869.079712f, 808.701538f, 38.689003f}, {1860.843384f, 806.645020f, 44.008789f}, {1843.707153f, 805.807739f, 44.135197f} //{1825.736084f, 807.305847f, 44.363785f} }; float ThirdPortalWPs [8][3] = { {1934.049438f, 815.778503f, 52.408699f}, {1928.290649f, 824.750427f, 45.474411f}, {1915.544922f, 826.919373f, 38.642811f}, {1900.933960f, 818.855652f, 38.801647f}, {1886.810547f, 813.536621f, 38.490490f}, {1869.079712f, 808.701538f, 38.689003f}, {1860.843384f, 806.645020f, 44.008789f}, {1843.707153f, 805.807739f, 44.135197f} //{1825.736084f, 807.305847f, 44.363785f} }; float FourthPortalWPs [9][3] = { {1921.658447f, 761.657043f, 50.866741f}, {1910.559814f, 755.780457f, 47.701447f}, {1896.664673f, 752.920898f, 47.667004f}, {1887.398804f, 763.633240f, 47.666851f}, {1879.020386f, 775.396973f, 38.705990f}, {1872.439087f, 782.568604f, 38.808292f}, {1863.573364f, 791.173584f, 38.743660f}, {1857.811890f, 796.765564f, 43.950329f}, {1845.577759f, 800.681152f, 44.104248f} //{1827.100342f, 801.605957f, 44.363358f} }; float FifthPortalWPs [6][3] = { {1887.398804f, 763.633240f, 47.666851f}, {1879.020386f, 775.396973f, 38.705990f}, {1872.439087f, 782.568604f, 38.808292f}, {1863.573364f, 791.173584f, 38.743660f}, {1857.811890f, 796.765564f, 43.950329f}, {1845.577759f, 800.681152f, 44.104248f} //{1827.100342f, 801.605957f, 44.363358f} }; float SixthPoralWPs [4][3] = { {1888.861084f, 805.074768f, 38.375790f}, {1869.793823f, 804.135804f, 38.647018f}, {1861.541504f, 804.149780f, 43.968292f}, {1843.567017f, 804.288208f, 44.139091f} //{1826.889648f, 803.929993f, 44.363239f} }; const float SaboteurFinalPos1[3][3] = { {1892.502319f, 777.410767f, 38.630402f}, {1891.165161f, 762.969421f, 47.666920f}, {1893.168091f, 740.919189f, 47.666920f} }; const float SaboteurFinalPos2[3][3] = { {1882.242676f, 834.818726f, 38.646786f}, {1879.220825f, 842.224854f, 43.333641f}, {1873.842896f, 863.892456f, 43.333641f} }; const float SaboteurFinalPos3[2][3] = { {1904.298340f, 792.400391f, 38.646782f}, {1935.716919f, 758.437073f, 30.627895f} }; const float SaboteurFinalPos4[3] = { 1855.006104f, 760.641724f, 38.655266f }; const float SaboteurFinalPos5[3] = { 1906.667358f, 841.705566f, 38.637894f }; const float SaboteurFinalPos6[5][3] = { {1911.437012f, 821.289246f, 38.684128f}, {1920.734009f, 822.978027f, 41.525414f}, {1928.262939f, 830.836609f, 44.668266f}, {1929.338989f, 837.593933f, 47.137596f}, {1931.063354f, 848.468445f, 47.190434f} }; const Position MovePosition = {1806.955566f, 803.851807f, 44.363323f, 0.0f}; const Position playerTeleportPosition = {1830.531006f, 803.939758f, 44.340508f, 6.281611f}; const Position sinclariOutsidePosition = {1817.315674f, 804.060608f, 44.363998f, 0.0f}; class npc_sinclari_vh : public CreatureScript { public: npc_sinclari_vh() : CreatureScript("npc_sinclari_vh") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*Sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF+1: player->CLOSE_GOSSIP_MENU(); CAST_AI(npc_sinclari_vh::npc_sinclariAI, (creature->AI()))->uiPhase = 1; if (InstanceScript* instance = creature->GetInstanceScript()) instance->SetData(DATA_MAIN_EVENT_PHASE, SPECIAL); break; case GOSSIP_ACTION_INFO_DEF+2: player->SEND_GOSSIP_MENU(13854, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+3: player->NearTeleportTo(playerTeleportPosition.GetPositionX(), playerTeleportPosition.GetPositionY(), playerTeleportPosition.GetPositionZ(), playerTeleportPosition.GetOrientation(), true); player->CLOSE_GOSSIP_MENU(); break; } return true; } bool OnGossipHello(Player* player, Creature* creature) { if (InstanceScript* instance = creature->GetInstanceScript()) { switch (instance->GetData(DATA_MAIN_EVENT_PHASE)) { case NOT_STARTED: case FAIL: // Allow to start event if not started or wiped player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(13853, creature->GetGUID()); break; case IN_PROGRESS: // Allow to teleport inside if event is in progress player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_I_WANT_IN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); player->SEND_GOSSIP_MENU(13853, creature->GetGUID()); break; default: player->SEND_GOSSIP_MENU(13910, creature->GetGUID()); } } return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_sinclariAI(creature); } struct npc_sinclariAI : public ScriptedAI { npc_sinclariAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint8 uiPhase; uint32 uiTimer; void Reset() { uiPhase = 0; uiTimer = 0; me->SetReactState(REACT_AGGRESSIVE); std::list<Creature*> GuardList; me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f); if (!GuardList.empty()) { for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr) { if (Creature* pGuard = *itr) { pGuard->DisappearAndDie(); pGuard->Respawn(); pGuard->SetVisible(true); pGuard->SetReactState(REACT_AGGRESSIVE); } } } } void UpdateAI(const uint32 uiDiff) { ScriptedAI::UpdateAI(uiDiff); if (uiPhase) { if (uiTimer <= uiDiff) { switch (uiPhase) { case 1: DoScriptText(SAY_SINCLARI_1, me); uiTimer = 4000; uiPhase = 2; break; case 2: { std::list<Creature*> GuardList; me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f); if (!GuardList.empty()) for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr) { if (Creature* pGuard = *itr) { pGuard->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); pGuard->GetMotionMaster()->MovePoint(0, MovePosition); } } uiTimer = 6000; uiPhase = 3; break; } case 3: { std::list<Creature*> GuardList; me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f); if (!GuardList.empty()) for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr) { if (Creature* pGuard = *itr) { pGuard->SetVisible(false); pGuard->SetReactState(REACT_PASSIVE); } } uiTimer = 2000; uiPhase = 4; break; } case 4: me->GetMotionMaster()->MovePoint(0, sinclariOutsidePosition); uiTimer = 4000; uiPhase = 5; break; case 5: if (instance) instance->SetData(DATA_MAIN_EVENT_PHASE, IN_PROGRESS); me->SetReactState(REACT_PASSIVE); uiTimer = 0; uiPhase = 0; break; } } else uiTimer -= uiDiff; } if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; class mob_azure_saboteur : public CreatureScript { public: mob_azure_saboteur() : CreatureScript("mob_azure_saboteur") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_saboteurAI (creature); } struct mob_azure_saboteurAI : public npc_escortAI { mob_azure_saboteurAI(Creature* c):npc_escortAI(c) { instance = c->GetInstanceScript(); bHasGotMovingPoints = false; uiBoss = 0; Reset(); } InstanceScript* instance; bool bHasGotMovingPoints; uint32 uiBoss; void Reset() { if (instance && !uiBoss) uiBoss = instance->GetData(DATA_WAVE_COUNT) == 6 ? instance->GetData(DATA_FIRST_BOSS) : instance->GetData(DATA_SECOND_BOSS); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_NON_ATTACKABLE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void WaypointReached(uint32 uiWPointId) { switch (uiBoss) { case 1: if (uiWPointId == 2) FinishPointReached(); break; case 2: if (uiWPointId == 2) FinishPointReached(); break; case 3: if (uiWPointId == 1) FinishPointReached(); break; case 4: if (uiWPointId == 0) FinishPointReached(); break; case 5: if (uiWPointId == 0) FinishPointReached(); break; case 6: if (uiWPointId == 4) FinishPointReached(); break; } } void UpdateAI(const uint32 diff) { if (instance && instance->GetData(DATA_MAIN_EVENT_PHASE) != IN_PROGRESS) me->CastStop(); npc_escortAI::UpdateAI(diff); if (!bHasGotMovingPoints) { bHasGotMovingPoints = true; switch (uiBoss) { case 1: for (int i=0;i<3;i++) AddWaypoint(i, SaboteurFinalPos1[i][0], SaboteurFinalPos1[i][1], SaboteurFinalPos1[i][2], 0); me->SetHomePosition(SaboteurFinalPos1[2][0], SaboteurFinalPos1[2][1], SaboteurFinalPos1[2][2], 4.762346f); break; case 2: for (int i=0;i<3;i++) AddWaypoint(i, SaboteurFinalPos2[i][0], SaboteurFinalPos2[i][1], SaboteurFinalPos2[i][2], 0); me->SetHomePosition(SaboteurFinalPos2[2][0], SaboteurFinalPos2[2][1], SaboteurFinalPos2[2][2], 1.862674f); break; case 3: for (int i=0;i<2;i++) AddWaypoint(i, SaboteurFinalPos3[i][0], SaboteurFinalPos3[i][1], SaboteurFinalPos3[i][2], 0); me->SetHomePosition(SaboteurFinalPos3[1][0], SaboteurFinalPos3[1][1], SaboteurFinalPos3[1][2], 5.500638f); break; case 4: AddWaypoint(0, SaboteurFinalPos4[0], SaboteurFinalPos4[1], SaboteurFinalPos4[2], 0); me->SetHomePosition(SaboteurFinalPos4[0], SaboteurFinalPos4[1], SaboteurFinalPos4[2], 3.991108f); break; case 5: AddWaypoint(0, SaboteurFinalPos5[0], SaboteurFinalPos5[1], SaboteurFinalPos5[2], 0); me->SetHomePosition(SaboteurFinalPos5[0], SaboteurFinalPos5[1], SaboteurFinalPos5[2], 1.100841f); break; case 6: for (int i=0;i<5;i++) AddWaypoint(i, SaboteurFinalPos6[i][0], SaboteurFinalPos6[i][1], SaboteurFinalPos6[i][2], 0); me->SetHomePosition(SaboteurFinalPos6[4][0], SaboteurFinalPos6[4][1], SaboteurFinalPos6[4][2], 0.983031f); break; } SetDespawnAtEnd(false); Start(true, true); } } void FinishPointReached() { me->CastSpell(me, SABOTEUR_SHIELD_DISRUPTION, false); me->DisappearAndDie(); Creature* pSaboPort = Unit::GetCreature((*me), instance->GetData64(DATA_SABOTEUR_PORTAL)); if (pSaboPort) pSaboPort->DisappearAndDie(); instance->SetData(DATA_START_BOSS_ENCOUNTER, 1); } }; }; class npc_teleportation_portal_vh : public CreatureScript { public: npc_teleportation_portal_vh() : CreatureScript("npc_teleportation_portal_vh") { } CreatureAI* GetAI(Creature* creature) const { return new npc_teleportation_portalAI(creature); } struct npc_teleportation_portalAI : public ScriptedAI { npc_teleportation_portalAI(Creature* c) : ScriptedAI(c), listOfMobs(me) { instance = c->GetInstanceScript(); uiTypeOfMobsPortal = urand(0, 1); // 0 - elite mobs 1 - portal guardian or portal keeper with regular mobs bPortalGuardianOrKeeperOrEliteSpawn = false; } uint32 uiSpawnTimer; bool bPortalGuardianOrKeeperOrEliteSpawn; uint8 uiTypeOfMobsPortal; SummonList listOfMobs; InstanceScript* instance; void Reset() { uiSpawnTimer = 10000; bPortalGuardianOrKeeperOrEliteSpawn = false; } void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit* /*who*/) {} void UpdateAI(const uint32 diff) { if (!instance) //Massive usage of instance, global check return; if (instance->GetData(DATA_REMOVE_NPC) == 1) { me->DespawnOrUnsummon(); instance->SetData(DATA_REMOVE_NPC, 0); } uint8 uiWaveCount = instance->GetData(DATA_WAVE_COUNT); if ((uiWaveCount == 6) || (uiWaveCount == 12)) //Don't spawn mobs on boss encounters return; switch (uiTypeOfMobsPortal) { // spawn elite mobs and then set portals visibility to make it look like it dissapeard case 0: if (!bPortalGuardianOrKeeperOrEliteSpawn) { if (uiSpawnTimer <= diff) { bPortalGuardianOrKeeperOrEliteSpawn = true; uint8 k = uiWaveCount < 12 ? 2 : 3; for (uint8 i = 0; i < k; ++i) { uint32 entry = RAND(CREATURE_AZURE_CAPTAIN, CREATURE_AZURE_RAIDER, CREATURE_AZURE_STALKER, CREATURE_AZURE_SORCEROR); DoSummon(entry, me, 2.0f, 20000, TEMPSUMMON_DEAD_DESPAWN); } me->SetVisible(false); } else uiSpawnTimer -= diff; } else { // if all spawned elites have died kill portal if (listOfMobs.empty()) { me->Kill(me, false); me->RemoveCorpse(); } } break; // spawn portal guardian or portal keeper with regular mobs case 1: if (uiSpawnTimer <= diff) { if (bPortalGuardianOrKeeperOrEliteSpawn) { uint8 k = instance->GetData(DATA_WAVE_COUNT) < 12 ? 3 : 4; for (uint8 i = 0; i < k; ++i) { uint32 entry = RAND(CREATURE_AZURE_INVADER_1, CREATURE_AZURE_INVADER_2, CREATURE_AZURE_SPELLBREAKER_1, CREATURE_AZURE_SPELLBREAKER_2, CREATURE_AZURE_MAGE_SLAYER_1, CREATURE_AZURE_MAGE_SLAYER_2, CREATURE_AZURE_BINDER_1, CREATURE_AZURE_BINDER_2); DoSummon(entry, me, 2.0f, 20000, TEMPSUMMON_DEAD_DESPAWN); } } else { bPortalGuardianOrKeeperOrEliteSpawn = true; uint32 entry = RAND(CREATURE_PORTAL_GUARDIAN, CREATURE_PORTAL_KEEPER); if (Creature* pPortalKeeper = DoSummon(entry, me, 2.0f, 0, TEMPSUMMON_DEAD_DESPAWN)) me->CastSpell(pPortalKeeper, SPELL_PORTAL_CHANNEL, false); } uiSpawnTimer = SPAWN_TIME; } else uiSpawnTimer -= diff; if (bPortalGuardianOrKeeperOrEliteSpawn && !me->IsNonMeleeSpellCasted(false)) { me->Kill(me, false); me->RemoveCorpse(); } break; } } void JustDied(Unit* /*killer*/) { if (instance) instance->SetData(DATA_WAVE_COUNT, instance->GetData(DATA_WAVE_COUNT)+1); } void JustSummoned(Creature* summoned) { listOfMobs.Summon(summoned); if (summoned) instance->SetData64(DATA_ADD_TRASH_MOB, summoned->GetGUID()); } void SummonedMobDied(Creature* summoned) { listOfMobs.Despawn(summoned); if (summoned) instance->SetData64(DATA_DEL_TRASH_MOB, summoned->GetGUID()); } }; }; struct violet_hold_trashAI : public npc_escortAI { violet_hold_trashAI(Creature* c):npc_escortAI(c) { instance = c->GetInstanceScript(); bHasGotMovingPoints = false; if (instance) portalLocationID = instance->GetData(DATA_PORTAL_LOCATION); Reset(); } public: InstanceScript* instance; bool bHasGotMovingPoints; uint32 portalLocationID; uint32 secondPortalRouteID; void WaypointReached(uint32 uiPointId) { switch (portalLocationID) { case 0: if (uiPointId == 5) CreatureStartAttackDoor(); break; case 1: if ((uiPointId == 8 && secondPortalRouteID == 0) || (uiPointId == 7 && secondPortalRouteID == 1)) CreatureStartAttackDoor(); break; case 2: if (uiPointId == 7) CreatureStartAttackDoor(); break; case 3: if (uiPointId == 8) CreatureStartAttackDoor(); break; case 4: if (uiPointId == 5) CreatureStartAttackDoor(); break; case 5: if (uiPointId == 3) CreatureStartAttackDoor(); break; } } void UpdateAI(const uint32) { if (instance && instance->GetData(DATA_MAIN_EVENT_PHASE) != IN_PROGRESS) me->CastStop(); if (!bHasGotMovingPoints) { bHasGotMovingPoints = true; switch (portalLocationID) { case 0: for (int i=0;i<6;i++) AddWaypoint(i, FirstPortalWPs[i][0]+irand(-1, 1), FirstPortalWPs[i][1]+irand(-1, 1), FirstPortalWPs[i][2]+irand(-1, 1), 0); me->SetHomePosition(FirstPortalWPs[5][0], FirstPortalWPs[5][1], FirstPortalWPs[5][2], 3.149439f); break; case 1: secondPortalRouteID = urand(0, 1); switch (secondPortalRouteID) { case 0: for (int i=0;i<9;i++) AddWaypoint(i, SecondPortalFirstWPs[i][0]+irand(-1, 1), SecondPortalFirstWPs[i][1]+irand(-1, 1), SecondPortalFirstWPs[i][2], 0); me->SetHomePosition(SecondPortalFirstWPs[8][0]+irand(-1, 1), SecondPortalFirstWPs[8][1]+irand(-1, 1), SecondPortalFirstWPs[8][2]+irand(-1, 1), 3.149439f); break; case 1: for (int i=0;i<8;i++) AddWaypoint(i, SecondPortalSecondWPs[i][0]+irand(-1, 1), SecondPortalSecondWPs[i][1]+irand(-1, 1), SecondPortalSecondWPs[i][2], 0); me->SetHomePosition(SecondPortalSecondWPs[7][0], SecondPortalSecondWPs[7][1], SecondPortalSecondWPs[7][2], 3.149439f); break; } break; case 2: for (int i=0;i<8;i++) AddWaypoint(i, ThirdPortalWPs[i][0]+irand(-1, 1), ThirdPortalWPs[i][1]+irand(-1, 1), ThirdPortalWPs[i][2], 0); me->SetHomePosition(ThirdPortalWPs[7][0], ThirdPortalWPs[7][1], ThirdPortalWPs[7][2], 3.149439f); break; case 3: for (int i=0;i<9;i++) AddWaypoint(i, FourthPortalWPs[i][0]+irand(-1, 1), FourthPortalWPs[i][1]+irand(-1, 1), FourthPortalWPs[i][2], 0); me->SetHomePosition(FourthPortalWPs[8][0], FourthPortalWPs[8][1], FourthPortalWPs[8][2], 3.149439f); break; case 4: for (int i=0;i<6;i++) AddWaypoint(i, FifthPortalWPs[i][0]+irand(-1, 1), FifthPortalWPs[i][1]+irand(-1, 1), FifthPortalWPs[i][2], 0); me->SetHomePosition(FifthPortalWPs[5][0], FifthPortalWPs[5][1], FifthPortalWPs[5][2], 3.149439f); break; case 5: for (int i=0;i<4;i++) AddWaypoint(i, SixthPoralWPs[i][0]+irand(-1, 1), SixthPoralWPs[i][1]+irand(-1, 1), SixthPoralWPs[i][2], 0); me->SetHomePosition(SixthPoralWPs[3][0], SixthPoralWPs[3][1], SixthPoralWPs[3][2], 3.149439f); break; } SetDespawnAtEnd(false); Start(true, true); } } void JustDied(Unit* /*unit*/) { if (Creature* portal = Unit::GetCreature((*me), instance->GetData64(DATA_TELEPORTATION_PORTAL))) CAST_AI(npc_teleportation_portal_vh::npc_teleportation_portalAI, portal->AI())->SummonedMobDied(me); if (instance) instance->SetData(DATA_NPC_PRESENCE_AT_DOOR_REMOVE, 1); } void CreatureStartAttackDoor() { me->SetReactState(REACT_PASSIVE); DoCast(SPELL_DESTROY_DOOR_SEAL); if (instance) instance->SetData(DATA_NPC_PRESENCE_AT_DOOR_ADD, 1); } }; class mob_azure_invader : public CreatureScript { public: mob_azure_invader() : CreatureScript("mob_azure_invader") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_invaderAI (creature); } struct mob_azure_invaderAI : public violet_hold_trashAI { mob_azure_invaderAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiCleaveTimer; uint32 uiImpaleTimer; uint32 uiBrutalStrikeTimer; uint32 uiSunderArmorTimer; void Reset() { uiCleaveTimer = 5000; uiImpaleTimer = 4000; uiBrutalStrikeTimer = 5000; uiSunderArmorTimer = 4000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (me->GetEntry() == CREATURE_AZURE_INVADER_1) { if (uiCleaveTimer <= diff) { DoCast(me->getVictim(), SPELL_CLEAVE); uiCleaveTimer = 5000; } else uiCleaveTimer -= diff; if (uiImpaleTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, SPELL_IMPALE); uiImpaleTimer = 4000; } else uiImpaleTimer -= diff; } if (me->GetEntry() == CREATURE_AZURE_INVADER_2) { if (uiBrutalStrikeTimer <= diff) { DoCast(me->getVictim(), SPELL_BRUTAL_STRIKE); uiBrutalStrikeTimer = 5000; } else uiBrutalStrikeTimer -= diff; if (uiSunderArmorTimer <= diff) { DoCast(me->getVictim(), SPELL_SUNDER_ARMOR); uiSunderArmorTimer = urand(8000, 10000); } else uiSunderArmorTimer -= diff; DoMeleeAttackIfReady(); } DoMeleeAttackIfReady(); } }; }; class mob_azure_binder : public CreatureScript { public: mob_azure_binder() : CreatureScript("mob_azure_binder") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_binderAI (creature); } struct mob_azure_binderAI : public violet_hold_trashAI { mob_azure_binderAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiArcaneExplosionTimer; uint32 uiArcainBarrageTimer; uint32 uiFrostNovaTimer; uint32 uiFrostboltTimer; void Reset() { uiArcaneExplosionTimer = 5000; uiArcainBarrageTimer = 4000; uiFrostNovaTimer = 5000; uiFrostboltTimer = 4000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (me->GetEntry() == CREATURE_AZURE_BINDER_1) { if (uiArcaneExplosionTimer <= diff) { DoCast(DUNGEON_MODE(SPELL_ARCANE_EXPLOSION, H_SPELL_ARCANE_EXPLOSION)); uiArcaneExplosionTimer = 5000; } else uiArcaneExplosionTimer -= diff; if (uiArcainBarrageTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, DUNGEON_MODE(SPELL_ARCANE_BARRAGE, H_SPELL_ARCANE_BARRAGE)); uiArcainBarrageTimer = 6000; } else uiArcainBarrageTimer -= diff; } if (me->GetEntry() == CREATURE_AZURE_BINDER_2) { if (uiFrostNovaTimer <= diff) { DoCast(DUNGEON_MODE(SPELL_FROST_NOVA, H_SPELL_FROST_NOVA)); uiFrostNovaTimer = 5000; } else uiFrostNovaTimer -= diff; if (uiFrostboltTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, DUNGEON_MODE(SPELL_FROSTBOLT, H_SPELL_FROSTBOLT)); uiFrostboltTimer = 6000; } else uiFrostboltTimer -= diff; } DoMeleeAttackIfReady(); } }; }; class mob_azure_mage_slayer : public CreatureScript { public: mob_azure_mage_slayer() : CreatureScript("mob_azure_mage_slayer") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_mage_slayerAI (creature); } struct mob_azure_mage_slayerAI : public violet_hold_trashAI { mob_azure_mage_slayerAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiArcaneEmpowermentTimer; uint32 uiSpellLockTimer; void Reset() { uiArcaneEmpowermentTimer = 5000; uiSpellLockTimer = 5000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (me->GetEntry() == CREATURE_AZURE_MAGE_SLAYER_1) { if (uiArcaneEmpowermentTimer <= diff) { DoCast(me, SPELL_ARCANE_EMPOWERMENT); uiArcaneEmpowermentTimer = 14000; } else uiArcaneEmpowermentTimer -= diff; } if (me->GetEntry() == CREATURE_AZURE_MAGE_SLAYER_2) { if (uiSpellLockTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, SPELL_SPELL_LOCK); uiSpellLockTimer = 9000; } else uiSpellLockTimer -= diff; } DoMeleeAttackIfReady(); } }; }; class mob_azure_raider : public CreatureScript { public: mob_azure_raider() : CreatureScript("mob_azure_raider") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_raiderAI (creature); } struct mob_azure_raiderAI : public violet_hold_trashAI { mob_azure_raiderAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiConcussionBlowTimer; uint32 uiMagicReflectionTimer; void Reset() { uiConcussionBlowTimer = 5000; uiMagicReflectionTimer = 8000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (uiConcussionBlowTimer <= diff) { DoCast(me->getVictim(), SPELL_CONCUSSION_BLOW); uiConcussionBlowTimer = 5000; } else uiConcussionBlowTimer -= diff; if (uiMagicReflectionTimer <= diff) { DoCast(SPELL_MAGIC_REFLECTION); uiMagicReflectionTimer = urand(10000, 15000); } else uiMagicReflectionTimer -= diff; DoMeleeAttackIfReady(); } }; }; class mob_azure_stalker : public CreatureScript { public: mob_azure_stalker() : CreatureScript("mob_azure_stalker") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_stalkerAI (creature); } struct mob_azure_stalkerAI : public violet_hold_trashAI { mob_azure_stalkerAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiBackstabTimer; uint32 uiTacticalBlinkTimer; bool TacticalBlinkCasted; void Reset() { uiBackstabTimer = 1300; uiTacticalBlinkTimer = 8000; TacticalBlinkCasted =false; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (!TacticalBlinkCasted) { if (uiTacticalBlinkTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 40, true); if (target) DoCast(target, SPELL_TACTICAL_BLINK); uiTacticalBlinkTimer = 6000; TacticalBlinkCasted = true; } else uiTacticalBlinkTimer -= diff; } else { if (uiBackstabTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_NEAREST, 0, 10, true); DoCast(target, SPELL_BACKSTAB); TacticalBlinkCasted = false; uiBackstabTimer =1300; } else uiBackstabTimer -= diff; } DoMeleeAttackIfReady(); } }; }; class mob_azure_spellbreaker : public CreatureScript { public: mob_azure_spellbreaker() : CreatureScript("mob_azure_spellbreaker") { } struct mob_azure_spellbreakerAI : public violet_hold_trashAI { mob_azure_spellbreakerAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiArcaneBlastTimer; uint32 uiSlowTimer; uint32 uiChainsOfIceTimer; uint32 uiConeOfColdTimer; void Reset() { uiArcaneBlastTimer = 5000; uiSlowTimer = 4000; uiChainsOfIceTimer = 5000; uiConeOfColdTimer = 4000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (me->GetEntry() == CREATURE_AZURE_SPELLBREAKER_1) { if (uiArcaneBlastTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, DUNGEON_MODE(SPELL_ARCANE_BLAST, H_SPELL_ARCANE_BLAST)); uiArcaneBlastTimer = 6000; } else uiArcaneBlastTimer -= diff; if (uiSlowTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, SPELL_SLOW); uiSlowTimer = 5000; } else uiSlowTimer -= diff; } if (me->GetEntry() == CREATURE_AZURE_SPELLBREAKER_2) { if (uiChainsOfIceTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, SPELL_CHAINS_OF_ICE); uiChainsOfIceTimer = 7000; } else uiChainsOfIceTimer -= diff; if (uiConeOfColdTimer <= diff) { DoCast(DUNGEON_MODE(SPELL_CONE_OF_COLD, H_SPELL_CONE_OF_COLD)); uiConeOfColdTimer = 5000; } else uiConeOfColdTimer -= diff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new mob_azure_spellbreakerAI (creature); } }; class mob_azure_captain : public CreatureScript { public: mob_azure_captain() : CreatureScript("mob_azure_captain") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_captainAI (creature); } struct mob_azure_captainAI : public violet_hold_trashAI { mob_azure_captainAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiMortalStrikeTimer; uint32 uiWhirlwindTimer; void Reset() { uiMortalStrikeTimer = 5000; uiWhirlwindTimer = 8000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (uiMortalStrikeTimer <= diff) { DoCast(me->getVictim(), SPELL_MORTAL_STRIKE); uiMortalStrikeTimer = 5000; } else uiMortalStrikeTimer -= diff; if (uiWhirlwindTimer <= diff) { DoCast(me, SPELL_WHIRLWIND_OF_STEEL); uiWhirlwindTimer = 8000; } else uiWhirlwindTimer -= diff; DoMeleeAttackIfReady(); } }; }; class mob_azure_sorceror : public CreatureScript { public: mob_azure_sorceror() : CreatureScript("mob_azure_sorceror") { } CreatureAI* GetAI(Creature* creature) const { return new mob_azure_sorcerorAI (creature); } struct mob_azure_sorcerorAI : public violet_hold_trashAI { mob_azure_sorcerorAI(Creature* c) : violet_hold_trashAI(c) { instance = c->GetInstanceScript(); } uint32 uiArcaneStreamTimer; uint32 uiArcaneStreamTimerStartingValueHolder; uint32 uiManaDetonationTimer; void Reset() { uiArcaneStreamTimer = 4000; uiArcaneStreamTimerStartingValueHolder = uiArcaneStreamTimer; uiManaDetonationTimer = 5000; } void UpdateAI(const uint32 diff) { violet_hold_trashAI::UpdateAI(diff); npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (uiArcaneStreamTimer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); if (target) DoCast(target, DUNGEON_MODE(SPELL_ARCANE_STREAM, H_SPELL_ARCANE_STREAM)); uiArcaneStreamTimer = urand(0, 5000)+5000; uiArcaneStreamTimerStartingValueHolder = uiArcaneStreamTimer; } else uiArcaneStreamTimer -= diff; if (uiManaDetonationTimer <= diff && uiArcaneStreamTimer >=1500 && uiArcaneStreamTimer <= uiArcaneStreamTimerStartingValueHolder/2) { DoCast(DUNGEON_MODE(SPELL_MANA_DETONATION, H_SPELL_MANA_DETONATION)); uiManaDetonationTimer = urand(2000, 6000); } else uiManaDetonationTimer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_violet_hold() { new npc_sinclari_vh(); new npc_teleportation_portal_vh(); new mob_azure_invader(); new mob_azure_spellbreaker(); new mob_azure_binder(); new mob_azure_mage_slayer(); new mob_azure_captain(); new mob_azure_sorceror(); new mob_azure_raider(); new mob_azure_stalker(); new mob_azure_saboteur(); }
alideny/ChgMangos_CTM
src/server/scripts/Northrend/VioletHold/violet_hold.cpp
C++
gpl-2.0
45,090
33.108169
276
0.517787
false
/* Hey EMACS -*- linux-c -*- */ /* $Id: toolbar.h 4392 2011-08-01 09:24:05Z debrouxl $ */ /* TiLP - Tilp Is a Linking Program * Copyright (C) 1999-2006 Romain Lievin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GTOOLBAR_H #define GTOOLBAR_H void toolbar_refresh_buttons(void); void toolbar_set_button(int sr); #endif
debrouxl/strip_tilp_nspire
src/toolbar.h
C
gpl-2.0
1,022
35.5
75
0.722114
false
(function ($, window, document) { "use strict"; $(document).on( 'ready', function(){ var $body = $('body'), $topbar = $( document.getElementById('topbar') ), $products_sliders = $('.products-slider-wrapper, .categories-slider-wrapper'); /************************* * SHOP STYLE SWITCHER *************************/ $('#list-or-grid').on( 'click', 'a', function(){ var trigger = $(this), view = trigger.attr( 'class' ).replace('-view', ''); $( 'ul.products li' ).removeClass( 'list grid' ).addClass( view ); trigger.parent().find( 'a' ).removeClass( 'active' ); trigger.addClass( 'active' ); $.cookie( yit_shop_view_cookie, view ); return false; }); /************************* * Fix Product Name and Price *************************/ var padding_nameprice = function () { $('li.product .product-wrapper .info-product.slideup').each(function () { $(this).find('h3').css( 'padding-' + ( ! yit.isRtl ? 'right' : 'left' ), $(this).find('span.price').width() + 10 ); }); }; if( $(window).width() > 1199 ){ padding_nameprice(); } $(document).on('yith-wcan-ajax-filtered', padding_nameprice ); /************************* * ADD TO CART *************************/ var product, product_onsale; var add_to_cart = function() { $('ul.products').on('click', 'li.product .add_to_cart_button', function () { product = $(this).parents('li.product'); product_onsale = product.find('.product-wrapper > .onsale'); if( typeof yit.load_gif != 'undefined' ) { product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else{ product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } }); } add_to_cart(); $(document).on('yith-wcan-ajax-filtered', add_to_cart ); $body.on('added_to_cart', function () { if( typeof product_onsale === 'undefined' && typeof product === 'undefined' ) return; $( '.products-slider.swiper .swiper-slide .opacity .swiper-product-informations span.product-add-to-cart a.added_to_cart.wc-forward') .addClass( 'btn btn-flat' ) .prev('a').remove(); if ( product_onsale.length ) { product_onsale.remove(); } product.find('.thumb-wrapper').append('<div class="added_to_cart_box"><div class="added_to_cart_label">' + yit.added_to_cart + '</div></div>'); product.find('.added_to_cart_label').append(product.find('a.added_to_cart')); product.find('.product-wrapper div:first-child').addClass('nohover'); setTimeout( function(){ product.find('.added_to_cart_box').fadeOut(2000, function(){ $(this).remove(); }); product.find('.product-wrapper div:first-child').removeClass('nohover'); }, 3000 ); if (product.find('.product-wrapper > .added_to_cart_ico').length == 0) { setTimeout(function() { product.find('.product-wrapper').append('<span class="added_to_cart_ico">' + yit.added_to_cart_ico + '</span>'); }, 4000); } product.find('.thumb-wrapper').unblock(); }); /************************* * PRODUCTS SLIDER *************************/ if( $.fn.owlCarousel && $.fn.imagesLoaded && $products_sliders.length ) { var product_slider = function(t) { t.imagesLoaded(function(){ var cols = t.data('columns') ? t.data('columns') : 4; var autoplay = (t.attr('data-autoplay')=='true') ? 3000 : false; var owl = t.find('.products').owlCarousel({ items : cols, responsiveClass : true, responsive:{ 0 : { items: 2 }, 479 : { items: 3 }, 767 : { items: 4 }, 992 : { items: cols } }, autoplay : autoplay, autoplayTimeout : 2000, autoplayHoverPause: true, loop : true, rtl: yit.isRtl == true }); // Custom Navigation Events t.on('click', '.es-nav-next', function () { owl.trigger('next.owl.carousel'); }); t.on('click', '.es-nav-prev', function () { owl.trigger('prev.owl.carousel'); }); }); }; // initialize slider in only visible tabs $products_sliders.each(function(){ var t = $(this); if( ! t.closest('.panel.group').length || t.closest('.panel.group').hasClass('showing') ){ product_slider( t ); } }); $('.tabs-container').on( 'yit_tabopened', function( e, tab ) { product_slider( tab.find( $products_sliders ) ); }); } /************************* * VARIATIONS SELECT *************************/ var variations_select = function(){ // variations select if( $.fn.selectbox ) { var form = $('form.variations_form'); var select = form.find('select:not(.yith_wccl_custom)'); if( form.data('wccl') ) { select = select.filter(function(){ return $(this).data('type') == 'select' }); } select.selectbox({ effect: 'fade', onOpen: function() { //$('.variations select').trigger('focusin'); } }); var update_select = function(event){ // console.log(event); select.selectbox("detach"); select.selectbox("attach"); }; // fix variations select form.on( 'woocommerce_update_variation_values', update_select); form.find('.reset_variations').on('click.yit', update_select); } }; variations_select(); /************************* * TOPBAR INDICATORS *************************/ $topbar.find('#lang_sel .lang_sel_sel').append('<span class="sf-sub-indicator"> +</span>'); $topbar.find('#wcml_currency_switcher > ul > li a.sbSelector').append('<span class="sf-sub-indicator"> +</span>'); /************************* * PRODUCT TABS *************************/ $('.single-product-tabs.vertical').on('click', 'ul.tabs li .tab_name', function () { var tab_trigger = $(this), panel = tab_trigger.siblings('.panel'), container = tab_trigger.closest('.single-product-tabs'); if ( ! tab_trigger.hasClass('active') ) { //remove opened tab container.find('.tab_name.active').siblings('div.panel').slideToggle('slow'); container.find('.tab_name.active').removeClass('active'); //open tab tab_trigger.addClass('active'); } else { tab_trigger.removeClass('active'); } panel.slideToggle('slow'); }); /************************* * INQUIRY FORM *************************/ var inquiry_form = function(){ if ( $('#inquiry-form .product-inquiry').length ) { $(document).on('click', '#inquiry-form .product-inquiry', function(event){ event.stopImmediatePropagation('click'); $(this).next('form.contact-form').slideToggle('slow'); }); } }; inquiry_form(); $(document).on('yit_quick_view_loaded', inquiry_form); if( $( 'body').hasClass( 'single-product' ) ) { setTimeout( function() { if( $.trim( $( 'div.user-message').html() ) != '' || $.trim( $( '.contact-form li div.msg-error' ).text() ) != '' ) { $('form.contact-form').slideToggle('slow'); } }, 200 ); } /************************* * Wishlist *************************/ var wishlist_share = function() { if ( $('#wishlist-share div.share-text').length ) { $(document).on('click', '#wishlist-share div.share-text', function(){ $(this).next('div.share-link-container').slideToggle('slow'); }); } }; wishlist_share(); $(document).on('yit_quick_view_loaded', wishlist_share); /************************* * Update Calculate Shipping Select *************************/ var wc_version = 2.2; if (typeof yit_woocommerce != 'undefined') wc_version = parseFloat(yit_woocommerce.version); if ( wc_version < 2.3 && $.fn.selectbox ) { $('#calc_shipping_state').next('.sbHolder').addClass('stateHolder'); $body.on('country_to_state_changing', function(){ $('.stateHolder').remove(); $('#calc_shipping_state').show().attr('sb', ''); $('select#calc_shipping_state').selectbox({ effect: 'fade', classHolder: 'stateHolder sbHolder' }); }); } /************************* * Login Form *************************/ // $('#login-form').on('submit', function(){ // var a = $('#reg_password').val(); // var b = $('#reg_password_retype').val(); // if(!(a==b)){ // $('#reg_password_retype').addClass('invalid'); // return false; // }else{ // $('#reg_password_retype').removeClass('invalid'); // return true; // } // }); /************************* * PRODUCT QUICK VIEW *************************/ function quick_view_trigger() { $('div.quick-view a.trigger').yit_quick_view({ item_container: 'li.product', loader : 'div.single-product.woocommerce', assets : yit_quick_view.assets, before : function (trigger, item) { // add loading in the button if( typeof yit.load_gif != 'undefined' ) { trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else{ trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } item.find('.thumb-wrapper').addClass('hover'); }, openDialog : function (trigger, item) { // remove loading from button trigger.parent().unblock(); item.find('.thumb-wrapper').removeClass('hover'); }, completed : function (trigger, item, html, overlay) { var data = $('<div>' + html + '</div>'), title = data.find('h1.product_title').html(), price = data.find('p.price').html(), rating = data.find('div.star-rating').html(), container = document.getElementById('wrapper'), wrapper = $(overlay).find('.main .container'); // add main class to dialog container $(overlay).addClass('product-quick-view'); // head $('<p />').addClass('price').html(price).prependTo(wrapper.find('.head')); $('<div />').addClass('star-rating').html(rating).prependTo(wrapper.find('.head')); $('<h4 />').html(title).prependTo(wrapper.find('.head')); //prettyPhoto if ( typeof $.prettyPhoto != 'undefined' ) { data.find( "a[rel^='thumbnails'], a.zoom" ).prettyPhoto({ social_tools : false, theme : 'pp_woocommerce', horizontal_padding: 40, opacity : 0.9, deeplinking : false }); } // quantity fields $('div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)').addClass('buttons_added').append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />'); variations_select(); // add to cart $('form.cart', overlay).on('submit', function (e) { e.preventDefault(); var form = $(this), button = form.find('button'), product_url = item.find('a.thumb').attr('href'); if( typeof yit.load_gif != 'undefined' ) { button.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else if (typeof( woocommerce_params.plugin_url ) != 'undefined') { button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.plugin_url + '/assets/images/ajax-loader.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } else { button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) { var message = $( '.woocommerce-message', result ), cart_dropdown = $( '#header .yit_cart_widget', result); if( typeof wc_cart_fragments_params != 'undefined') { // update fragments var $supports_html5_storage; try { $supports_html5_storage = ( 'sessionStorage' in window && window.sessionStorage !== null ); window.sessionStorage.setItem('wc', 'test'); window.sessionStorage.removeItem('wc'); } catch (err) { $supports_html5_storage = false; } $.ajax({ url : wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'), type : 'POST', success: function (data) { if (data && data.fragments) { $.each(data.fragments, function (key, value) { $(key).replaceWith(value); }); if ($supports_html5_storage) { sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(data.fragments)); sessionStorage.setItem('wc_cart_hash', data.cart_hash); } $(document.body).trigger('wc_fragments_refreshed'); } } }); } // add message $('div.product', overlay).before(message); // remove loading button.unblock(); }); }); // others $('#wishlist-share').find('.share-link-container').hide(); $('#inquiry-form').find('form.contact-form').hide(); }, action : 'yit_load_product_quick_view' }); } if ($.fn.yit_quick_view && typeof yit_quick_view != 'undefined') { quick_view_trigger(); $(document).on('yith-wcan-ajax-filtered', quick_view_trigger); } /************************* * WISHLIST LABEL *************************/ $( '.yith-wcwl-add-button .add_to_wishlist').on( 'click', function() { var feedback = $(this).closest('.yith-wcwl-add-to-wishlist').find('.yith-wcwl-wishlistaddedbrowse span.feedback'); feedback.fadeIn(); setTimeout( function(){ feedback.fadeOut('slow'); }, 4000 ); }); /************************* * Widget Woo Price Filter *************************/ if( yit.price_filter_slider == 'no' || typeof yit.price_filter_slider == 'undefined' ) { var removePriceFilterSlider = function() { $( 'input#min_price, input#max_price' ).show(); $('form > div.price_slider_wrapper').find( 'div.price_slider, div.price_label' ).hide(); }; removePriceFilterSlider(); } /***************************** * TERMS AND CONDITIONS POPUP *****************************/ if ($.fn.yit_quick_view ) { var term_popup = function() { $('p.terms a').yit_quick_view({ item_container: 'p.terms', loader: '#primary .content', loadPage: true, before: function( trigger, item ) { // add loading in the button if( typeof yit.load_gif != 'undefined' ) { item.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}}); } else { item.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}}); } }, completed: function( trigger, item, html, overlay ) { var data = $('<div>' + html + '</div>'), title = trigger.text(), container = document.getElementById( 'wrapper' ), wrapper = $(overlay).find('.main .container'); // head $('<h4 />').html(title).prependTo( wrapper.find('.head') ); $(overlay).addClass('terms-popup'); $(overlay).find('.content').removeClass('col-sm-12 col-sm-9'); }, openDialog: function( trigger, item ) { item.unblock(); } }); }; $body.on('updated_checkout', term_popup); term_popup(); } }); })( jQuery, window, document );
lieison/IndustriasFenix
wp-content/themes/bishop/theme/assets/js/woocommerce.js
JavaScript
gpl-2.0
21,939
40.113244
267
0.407767
false
package com.yh.admin.bo; import java.util.Date; import com.yh.platform.core.bo.BaseBo; public class UserAgent extends BaseBo { private static final long serialVersionUID = 2715416587055228708L; private Long userAgentOid; private Long systemPositionOid; private String userId; // 被代理人 private String agentUserId; // 指定的代理人 private Date effectiveDate; // 有效开始期 private Date expiredDt; private String isActive; public Long getSystemPositionOid() { return systemPositionOid; } public void setSystemPositionOid(Long systemPositionOid) { this.systemPositionOid = systemPositionOid; } public Long getUserAgentOid() { return userAgentOid; } public void setUserAgentOid(Long userAgentOid) { this.userAgentOid = userAgentOid; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAgentUserId() { return agentUserId; } public void setAgentUserId(String agentUserId) { this.agentUserId = agentUserId; } public Date getExpiredDt() { return expiredDt; } public void setExpiredDt(Date expiredDt) { this.expiredDt = expiredDt; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public Date getEffectiveDate() { return effectiveDate; } public void setEffectiveDate(Date effectiveDate) { this.effectiveDate = effectiveDate; } }
meijmOrg/Repo-test
freelance-admin/src/java/com/yh/admin/bo/UserAgent.java
Java
gpl-2.0
1,512
18.76
67
0.72942
false
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\File; use PHPExiftool\Driver\AbstractTag; class PreviewPNG extends AbstractTag { protected $Id = 'PreviewPNG'; protected $Name = 'PreviewPNG'; protected $FullName = 'Extra'; protected $GroupName = 'File'; protected $g0 = 'File'; protected $g1 = 'File'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Preview PNG'; protected $flag_Binary = true; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/File/PreviewPNG.php
PHP
gpl-2.0
725
16.682927
74
0.663448
false
<?php /** * @version $Id: blog.php 20960 2011-03-12 14:14:00Z chdemko $ * @package Chola.Site * @subpackage com_content * @copyright Copyright (C) 2005 - 2011 Cholalabs Software LLP. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT.'/helpers'); ?> <div class="blog<?php echo $this->pageclass_sfx;?>"> <?php if ($this->params->get('show_page_heading', 1)) : ?> <h1> <?php echo $this->escape($this->params->get('page_heading')); ?> </h1> <?php endif; ?> <?php if ($this->params->get('show_category_title', 1) OR $this->params->get('page_subheading')) : ?> <h2> <?php echo $this->escape($this->params->get('page_subheading')); ?> <?php if ($this->params->get('show_category_title')) : ?> <span class="subheading-category"><?php echo $this->category->title;?></span> <?php endif; ?> </h2> <?php endif; ?> <?php if ($this->params->get('show_description', 1) || $this->params->def('show_description_image', 1)) : ?> <div class="category-desc"> <?php if ($this->params->get('show_description_image') && $this->category->getParams()->get('image')) : ?> <img src="<?php echo $this->category->getParams()->get('image'); ?>"/> <?php endif; ?> <?php if ($this->params->get('show_description') && $this->category->description) : ?> <?php echo JHtml::_('content.prepare', $this->category->description); ?> <?php endif; ?> <div class="clr"></div> </div> <?php endif; ?> <?php $leadingcount=0 ; ?> <?php if (!empty($this->lead_items)) : ?> <div class="items-leading"> <?php foreach ($this->lead_items as &$item) : ?> <div class="leading-<?php echo $leadingcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"> <?php $this->item = &$item; echo $this->loadTemplate('item'); ?> </div> <?php $leadingcount++; ?> <?php endforeach; ?> </div> <?php endif; ?> <?php $introcount=(count($this->intro_items)); $counter=0; ?> <?php if (!empty($this->intro_items)) : ?> <?php foreach ($this->intro_items as $key => &$item) : ?> <?php $key= ($key-$leadingcount)+1; $rowcount=( ((int)$key-1) % (int) $this->columns) +1; $row = $counter / $this->columns ; if ($rowcount==1) : ?> <div class="items-row cols-<?php echo (int) $this->columns;?> <?php echo 'row-'.$row ; ?>"> <?php endif; ?> <div class="item column-<?php echo $rowcount;?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"> <?php $this->item = &$item; echo $this->loadTemplate('item'); ?> </div> <?php $counter++; ?> <?php if (($rowcount == $this->columns) or ($counter ==$introcount)): ?> <span class="row-separator"></span> </div> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($this->link_items)) : ?> <?php echo $this->loadTemplate('links'); ?> <?php endif; ?> <?php if (!empty($this->children[$this->category->id])&& $this->maxLevel != 0) : ?> <div class="cat-children"> <h3> <?php echo JTEXT::_('JGLOBAL_SUBCATEGORIES'); ?> </h3> <?php echo $this->loadTemplate('children'); ?> </div> <?php endif; ?> <?php if (($this->params->def('show_pagination', 1) == 1 || ($this->params->get('show_pagination') == 2)) && ($this->pagination->get('pages.total') > 1)) : ?> <div class="pagination"> <?php if ($this->params->def('show_pagination_results', 1)) : ?> <p class="counter"> <?php echo $this->pagination->getPagesCounter(); ?> </p> <?php endif; ?> <?php echo $this->pagination->getPagesLinks(); ?> </div> <?php endif; ?> </div>
cholalabs/CholaApps2.0
components/com_content/views/category/tmpl/blog.php
PHP
gpl-2.0
3,631
28.048
159
0.585238
false
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'Anti-bot enabled on this chat' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'Anti-bot disabled on this chat' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '[/!]antibot enable: Enable Anti-bot on current chat', '[/!]antibot disable: Disable Anti-bot on current chat', '[/!]antibot allow <botId>: Allow <botId> on this chat', '[/!]antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^[/!]antibot (allow) (%d+)$', '^[/!]antibot (disallow) (%d+)$', '^[/!]antibot (enable)$', '^[/!]antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
mamaddeveloper/DeveloperMMD_bot
plugins/anti-bot.lua
Lua
gpl-2.0
3,087
26.5625
78
0.646906
false
/* Cabal - Legacy Game Implementations * * Cabal is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ // Based on the ScummVM (GPLv2+) file of the same name #ifdef ENABLE_HE #include "scumm/he/floodfill_he.h" #include "scumm/he/intern_he.h" #include "scumm/resource.h" #include "scumm/scumm.h" namespace Scumm { static bool floodFillPixelCheck(int x, int y, const FloodFillState *ffs) { int diffColor = ffs->color1 - ffs->color2; if (x >= 0 && x < ffs->dst_w && y >= 0 && y < ffs->dst_h) { uint8 color = *(ffs->dst + y * ffs->dst_w + x); diffColor = color - ffs->color1; } return diffColor == 0; } static void floodFillProcessRect(FloodFillState *ffs, const Common::Rect *r) { Common::Rect *dr = &ffs->dstBox; if (dr->right >= dr->left && dr->top <= dr->bottom) { int rw = r->right - r->left + 1; int rh = r->bottom - r->top + 1; assert(r->top + rh <= ffs->dst_h); assert(r->left + rw <= ffs->dst_w); uint8 *dst = ffs->dst + r->top * ffs->dst_w + r->left; if (rw <= 1) { --rh; while (rh >= 0) { *dst = ffs->color2; dst += ffs->dst_w; --rh; } } else { --rh; while (rh >= 0) { memset(dst, ffs->color2, rw); dst += ffs->dst_w; --rh; } } dr->extend(*r); } else { *dr = *r; } } static void floodFillAddLine(FloodFillLine **ffl, int y, int x1, int x2, int dy) { (*ffl)->y = y; (*ffl)->x1 = x1; (*ffl)->x2 = x2; (*ffl)->inc = dy; (*ffl)++; } static void floodFillProcess(int x, int y, FloodFillState *ffs, FloodFillPixelCheckCallback pixelCheckCallback) { ffs->dstBox.left = ffs->dstBox.top = 12345; ffs->dstBox.right = ffs->dstBox.bottom = -12345; FloodFillLine **fillLineCur = &ffs->fillLineTableCur; FloodFillLine **fillLineEnd = &ffs->fillLineTableEnd; assert(*fillLineCur < *fillLineEnd); if (ffs->srcBox.top <= y + 1 && ffs->srcBox.bottom >= y + 1) { (*fillLineCur)->y = y; (*fillLineCur)->x1 = x; (*fillLineCur)->x2 = x; (*fillLineCur)->inc = 1; (*fillLineCur)++; } assert(*fillLineCur < *fillLineEnd); if (ffs->srcBox.top <= y && ffs->srcBox.bottom >= y) { (*fillLineCur)->y = y + 1; (*fillLineCur)->x1 = x; (*fillLineCur)->x2 = x; (*fillLineCur)->inc = -1; (*fillLineCur)++; } assert(ffs->fillLineTable <= *fillLineCur); FloodFillLine **fillLineStart = fillLineCur; while (ffs->fillLineTable < *fillLineStart) { Common::Rect r; int x_start; FloodFillLine *fflCur = --(*fillLineCur); int dy = fflCur->inc; int x_end = fflCur->x2; int x1 = fflCur->x1; int x2 = fflCur->x1 + 1; r.bottom = r.top = y = fflCur->y + fflCur->inc; r.left = x2; r.right = x1; x = x1; while (ffs->srcBox.left <= x) { if (!(*pixelCheckCallback)(x, y, ffs)) { break; } r.left = x; --x; } if (r.right >= r.left && r.top <= r.bottom) { floodFillProcessRect(ffs, &r); } if (x >= x1) goto skip; x_start = x + 1; if (x1 > x_start) { assert(*fillLineEnd > *fillLineCur); if (ffs->srcBox.top <= y - dy && ffs->srcBox.bottom >= y - dy) { --x1; floodFillAddLine(fillLineCur, y, x_start, x1, -dy); } } x = x2; while (x_start <= x_end) { r.left = x; r.top = y; r.right = x - 1; r.bottom = y; while (ffs->srcBox.right >= x) { if (!(*pixelCheckCallback)(x, y, ffs)) { break; } r.right = x; ++x; } if (r.right >= r.left && r.top <= r.bottom) { floodFillProcessRect(ffs, &r); } assert(ffs->fillLineTableCur < ffs->fillLineTableEnd); if (ffs->srcBox.top <= y + dy && ffs->srcBox.bottom >= y + dy) { floodFillAddLine(&ffs->fillLineTableCur, y, x_start, x - 1, dy); } x_start = x_end + 1; if (x > x_start) { assert(ffs->fillLineTableCur < ffs->fillLineTableEnd); if (ffs->srcBox.top <= y - dy && ffs->srcBox.bottom >= y - dy) { floodFillAddLine(&ffs->fillLineTableCur, y, x_start, x - 1, -dy); } } skip: ++x; while (x <= x_end) { if ((*pixelCheckCallback)(x, y, ffs)) { break; } ++x; } x_start = x; } } } void floodFill(FloodFillParameters *ffp, ScummEngine_v90he *vm) { uint8 *dst; VirtScreen *vs = &vm->_virtscr[kMainVirtScreen]; if (ffp->flags & 0x8000) { dst = vs->getBackPixels(0, vs->topline); } else { dst = vs->getPixels(0, vs->topline); } uint8 color = ffp->flags & 0xFF; Common::Rect r; r.left = r.top = 12345; r.right = r.bottom = -12345; FloodFillState *ffs = new FloodFillState; ffs->fillLineTableCount = vs->getHeight() * 2; ffs->fillLineTable = new FloodFillLine[ffs->fillLineTableCount]; ffs->color2 = color; ffs->dst = dst; ffs->dst_w = vs->getWidth(); ffs->dst_h = vs->getHeight(); ffs->srcBox = ffp->box; ffs->fillLineTableCur = &ffs->fillLineTable[0]; ffs->fillLineTableEnd = &ffs->fillLineTable[ffs->fillLineTableCount]; if (ffp->x < 0 || ffp->y < 0 || ffp->x >= vs->getWidth() || ffp->y >= vs->getHeight()) { ffs->color1 = color; } else { ffs->color1 = *(dst + ffp->y * vs->getWidth() + ffp->x); } debug(5, "floodFill() x=%d y=%d color1=%d ffp->flags=0x%X", ffp->x, ffp->y, ffs->color1, ffp->flags); if (ffs->color1 != color) { floodFillProcess(ffp->x, ffp->y, ffs, floodFillPixelCheck); r = ffs->dstBox; } r.debugPrint(5, "floodFill() dirty_rect"); delete[] ffs->fillLineTable; delete ffs; vm->VAR(119) = 1; if (r.left <= r.right && r.top <= r.bottom) { if (ffp->flags & 0x8000) { vm->restoreBackgroundHE(r); } else { ++r.bottom; vm->markRectAsDirty(kMainVirtScreen, r); } } } void Wiz::fillWizFlood(const WizParameters *params) { if (params->processFlags & kWPFClipBox2) { int px = params->box2.left; int py = params->box2.top; uint8 *dataPtr = _vm->getResourceAddress(rtImage, params->img.resNum); if (dataPtr) { int state = 0; if (params->processFlags & kWPFNewState) { state = params->img.state; } uint8 *wizh = _vm->findWrappedBlock(MKTAG('W','I','Z','H'), dataPtr, state, 0); assert(wizh); int c = READ_LE_UINT32(wizh + 0x0); int w = READ_LE_UINT32(wizh + 0x4); int h = READ_LE_UINT32(wizh + 0x8); assert(c == 0); Common::Rect imageRect(w, h); if (params->processFlags & kWPFClipBox) { if (!imageRect.intersects(params->box)) { return; } imageRect.clip(params->box); } uint8 color = _vm->VAR(93); if (params->processFlags & kWPFFillColor) { color = params->fillColor; } if (imageRect.contains(px, py)) { uint8 *wizd = _vm->findWrappedBlock(MKTAG('W','I','Z','D'), dataPtr, state, 0); assert(wizd); FloodFillState *ffs = new FloodFillState; ffs->fillLineTableCount = h * 2; ffs->fillLineTable = new FloodFillLine[ffs->fillLineTableCount]; ffs->color2 = color; ffs->dst = wizd; ffs->dst_w = w; ffs->dst_h = h; ffs->srcBox = imageRect; ffs->fillLineTableCur = &ffs->fillLineTable[0]; ffs->fillLineTableEnd = &ffs->fillLineTable[ffs->fillLineTableCount]; if (px < 0 || py < 0 || px >= w || py >= h) { ffs->color1 = color; } else { ffs->color1 = *(wizd + py * w + px); } debug(0, "floodFill() x=%d y=%d color1=%d", px, py, ffs->color1); if (ffs->color1 != color) { floodFillProcess(px, py, ffs, floodFillPixelCheck); } delete[] ffs->fillLineTable; delete ffs; } } } _vm->_res->setModified(rtImage, params->img.resNum); } } // End of namespace Scumm #endif // ENABLE_HE
project-cabal/cabal
engines/scumm/he/floodfill_he.cpp
C++
gpl-2.0
8,174
26.614865
113
0.608637
false
/* Copyright (c) 2014, Oracle and/or its affiliates. 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; 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ DROP PROCEDURE IF EXISTS ps_setup_show_enabled_consumers; DELIMITER $$ CREATE DEFINER='root'@'localhost' PROCEDURE ps_setup_show_enabled_consumers () COMMENT ' Description ----------- Shows all currently enabled consumers. Parameters ----------- None Example ----------- mysql> CALL sys.ps_setup_show_enabled_consumers(); +---------------------------+ | enabled_consumers | +---------------------------+ | events_statements_current | | global_instrumentation | | thread_instrumentation | | statements_digest | +---------------------------+ 4 rows in set (0.05 sec) ' SQL SECURITY INVOKER DETERMINISTIC READS SQL DATA BEGIN SELECT name AS enabled_consumers FROM performance_schema.setup_consumers WHERE enabled = 'YES'; END$$ DELIMITER ;
syaroslavtsev/mysql-sys
procedures/ps_setup_show_enabled_consumers.sql
SQL
gpl-2.0
1,784
30.857143
79
0.58296
false
if (Meteor.isServer) { var //// A lookup-table whose keys are generated each time an ‘you.register’ form is rendered using the `babelslug()` method. //// The key is a babelslug, followed by hyphen, followed by a Meteor connection ID (like a session ID for anon users). //// The value is the unix timestamp in milliseconds, which allows us to clear out old and unused babelslugs. //// Two examples are shown here: recentBabelslugs = { // @todo for a multi-servo project, move this functionality to a shared mongoDB collection // 'MagentaMouse-KukNJw4d4vjGzzrQa': 1409341347912, // 'BlueChessCat-YYJWMWTPq7RFWdKr6': 1409341399283 } //// Clear out stale elements in the `recentBabelslugs` lookup-table. , recentBabelslugsHousekeeping = function () { var key , now = Date.now() ; for (key in recentBabelslugs) { if (15 * 60 * 1000 < now - recentBabelslugs[key]) { // allow a user 15 minutes to fill in the registration form delete recentBabelslugs[key]; } } } //// Check how many times a given `username` exists in the user database. If all’s well, this should only ever return `0` or `1`. , usernameCount = function (username) { return Meteor.users.find({ 'profile.username': username }).count(); } //// BabelSlug, from Rich Plastow’s work, 2014-02-09. , ucs2 = [ [ // animal { en:'slug' ,es:'babosa' ,ru:'\u0441\u043B\u0438\u0437\u043D\u044F\u043A',fr:'limace' ,zh:'\u86DE\u8753',ar:'\u064A\u0631\u0642\u0627\u0646\u0629' } , { en:'mouse' ,es:'rat\u00F3n',ru:'\u043C\u044B\u0448\u044C' ,fr:'souris' ,zh:'\u9F20\u6807',ar:'\u0641\u0623\u0631' } , { en:'cow' ,es:'vaca' ,ru:'\u043A\u043E\u0440\u043E\u0432\u0430' ,fr:'vache' ,zh:'\u725B' ,ar:'\u0628\u0642\u0631\u0629' } , { en:'cat' ,es:'gato' ,ru:'\u043A\u043E\u0448\u043A\u0430' ,fr:'chat' ,zh:'\u732B' ,ar:'\u0642\u0637' } , { en:'rabbit',es:'conejo' ,ru:'\u043A\u0440\u043E\u043B\u0438\u043A' ,fr:'lapin' ,zh:'\u5154' ,ar:'\u0623\u0631\u0646\u0628' } , { en:'deer' ,es:'ciervo' ,ru:'\u043E\u043B\u0435\u043D\u044C' ,fr:'cerf' ,zh:'\u9E7F' ,ar:'\u0623\u064A\u0644' } , { en:'bear' ,es:'oso' ,ru:'\u043C\u0435\u0434\u0432\u0435\u0434\u044C',fr:'ours' ,zh:'\u718A' ,ar:'\u062F\u064F\u0628\u0651' } , { en:'frog' ,es:'rana' ,ru:'\u043B\u044F\u0433\u0443\u0448\u043A\u0430',fr:'grenouille',zh:'\u9752\u86D9',ar:'\u0636\u0641\u062F\u0639' } ] // , [ // texture // { en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' } // , { en:'dotted' ,es:'punteado',ru:[1087,1091,1085,1082,1090,1080,1088,1085,1099,1081],fr:'pointill\u00E9',zh:[26001,28857],ar:[1605,1606,1602,1591] } // , { en:'striped',es:'rayas' ,ru:[1087,1086,1083,1086,1089,1072,1090,1099,1081] ,fr:'ray\u00E9' ,zh:[26465,32441],ar:[1605,1602,1604,1605] } // , { en:'chess' ,es:'ajedrez' ,ru:[1096,1072,1093,1084,1072,1090,1099] ,fr:'\u00E9checs' ,zh:[26827] ,ar:[1588,1591,1585,1606,1580] } // ] , [ // color1 { en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' } , { en:'red' ,es:'rojo' ,ru:[1082,1088,1072,1089,1085,1099,1081] ,fr:'rouge' ,zh:[32418] ,ar:[1571,1581,1605,1585] } , { en:'orange' ,es:'naranja' ,ru:[1086,1088,1072,1085,1078,1077,1074,1099,1081],fr:'orange' ,zh:[27225] ,ar:[1575,1604,1576,1585,1578,1602,1575,1604,1610] } , { en:'yellow' ,es:'amarillo',ru:[1078,1077,1083,1090,1099,1081] ,fr:'jaune' ,zh:[40644] ,ar:[1571,1589,1601,1585] } , { en:'green' ,es:'verde' ,ru:[1079,1077,1083,1077,1085,1099,1081] ,fr:'vert' ,zh:[32511] ,ar:[1571,1582,1590,1585] } // , { en:'cyan' ,es:'cian' ,ru:[1075,1086,1083,1091,1073,1086,1081] ,fr:'cyan' ,zh:[38738] ,ar:[1587,1605,1575,1608,1610] } , { en:'blue' ,es:'azul' ,ru:[1089,1080,1085,1080,1081] ,fr:'bleu' ,zh:[34013] ,ar:[1571,1586,1585,1602] } , { en:'purple' ,es:'magenta' ,ru:[1087,1091,1088,1087,1091,1088,1085,1099,1081],fr:'magenta',zh:[27915,32418],ar:[1571,1585,1580,1608,1575,1606,1610] } // @todo translate purple (these are for magenta) ] , [ // emotion @todo convert remaining languages from 2014-Work/BabelSlug/README.md { en:'-' ,es:'-' ,fr:'-' } , { en:'happy' ,es:'feliz' ,fr:'heureux' } // , { en:'sad' ,es:'triste' ,fr:'triste' } , { en:'laughing' ,es:'risa' ,fr:'rire' } , { en:'sleepy' ,es:'soñoliento' ,fr:'somnolent' } , { en:'surprised',es:'sorprendido',fr:'étonné' } // , { en:'playful' ,es:'juguetón' ,fr:'espiègle' } , { en:'confused' ,es:'confundido' ,fr:'embrouillé' } ] ] //// Prepare an empty cache, which may contain HTML entities converted from `ucs2`, if required. , html = (function () { var i, j, l, m ,html = {}; for (i=0, l=ucs2.length; i<l; i++) { html[i] = []; for (j=0, m=ucs2[i].length; j<m; j++) { html[i][j] = {}; } } return html } ()) // !!!! `numberToPhrase()`, then `i` becomes `num`, and then `ucs2` becomes an array, and `i` is iterator !!!! , numberToPhrase = function (number, options) { var key, len, rem, word , num = ~~(number < 0 ? -number : number) // ensure `num` is a positive whole number, or zero , opt = options || {} , l18n = ucs2[0][0][opt.l18n] ? opt.l18n : 'en' // set to English if the localization option is invalid or unspecified , phrase = [] ; for (key in ucs2) { len = ucs2[key].length; rem = num % len; if (! opt.format || 'ucs2' === opt.format) { word = ucs2[key][rem][l18n]; // console.log('key ' + key + ' format ' + 'ucs2' + ' word ' + word); } else if ('html' === opt.format) { word = html[key][rem][l18n]; if (! word) { word = html[key][rem][l18n] = ucs2[key][rem][l18n].replace(/[\u00A0-\u2666]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); // console.log('ADD TO CACHE key ' + key + ' format ' + 'html' + ' word ' + word); } else { // console.log('GET IN CACHE key ' + key + ' format ' + 'html' + ' word ' + word); } } else { // @todo format error } if ('-' !== word) { phrase.unshift(word); } num = ~~(num / len); // prepare for the next part in `ucs2` if (0 === num) { break; } // low numbers don't need to step through every section in `ucs2` } return phrase.join('-'); } ; Meteor.methods({ babelslug: function () { var i, key, babelslug; if (this.isSimulation) { return; } // clientside stub (return value is ignored) //// Housekeeping on the `recentBabelslugs` lut. recentBabelslugsHousekeeping(); //// Try, 200 times, to find a username which has not been taken. @todo this is quite brute-force ... can we come up with a more elegant solution? for (i=200; i>0; i--) { babelslug = numberToPhrase( Math.floor(Math.random() * 50000) ); if ( 3 === babelslug.split('-').length && ! recentBabelslugs[babelslug] && ! usernameCount(babelslug) ) { break; } // we are only using three-part usernames at present } if (! i) { throw new Meteor.Error(500, "Cannot generate a username! Please email " + Config.about.webmaster); } // @todo check `(! i)` can ever be truthy recentBabelslugs[babelslug] = { // later, when the form is submitted, we will check that the babelslug value is expected now: Date.now() // allows `recentBabelslugsHousekeeping()` to find stale babelslugs , cid: this.connection.id } return babelslug + '_' + this.connection.id; // @todo is `this.connection.id` ever some unexpected value, for example `null`? } }); Accounts.onCreateUser(function (options, user) { var babelslug, connectionId; //// Housekeeping on the `recentBabelslugs` lut. recentBabelslugsHousekeeping(); //// Validate the value of `<input id="AT_field_you-babelslug" ...>`. babelslug = options.profile['you-babelslug'].split('_')[0]; connectionId = options.profile['you-babelslug'].split('_')[1]; if (! babelslug || ! connectionId) { throw new Meteor.Error(500, "The ‘username’ field is invalid."); // @todo better error-code than 500? } if (! recentBabelslugs[babelslug]) { throw new Meteor.Error(500, "Your registration form expired after 15 minutes. Please refresh the browser and try again."); // The ‘username’ value is unexpected, so this may actually be a hack attempt } if ( usernameCount(babelslug) ) { throw new Meteor.Error(500, "The ‘username’ is already in use."); // prevent two `Meteor.user` records having the same username, which could happen on a multi-servo project, until we change `recentBabelslugs` to a shared mongoDB collection @todo } //// Remove the babelslug, as it’s not needed any more. delete recentBabelslugs[babelslug]; //// Record the username (‘info@loop.coop’ gets a special username). options.profile = options.profile || {}; options.profile.username = 'info@loop.coop' === options.email ? 'red-cat' : babelslug; //// Record other registration data. if (options.profile['you-age-group-code']) { options.profile.agc = options.profile['you-age-group-code']; } if (options.profile['you-based-in-code']) { options.profile.bic = options.profile['you-based-in-code']; } if (options.profile['you-hear-about-code']) { options.profile.hac = options.profile['you-hear-about-code']; } if (options.profile['you-hear-about-text']) { options.profile.hat = options.profile['you-hear-about-text']; } if (options.profile['you-newsletter-opt']) { options.profile.nlo = options.profile['you-newsletter-opt']; } //// The registration is valid, so record it as usual. http://docs.meteor.com/#accounts_oncreateuser user.profile = options.profile; return user; }); }
loopdotcoop/looptopia
you/you.create-user.js
JavaScript
gpl-2.0
11,763
60.418848
257
0.511551
false
#pragma once #include <string> class GameSettings { private: int m_nFPS = 60; std::string m_strPath = "../Settings.ini"; private: GameSettings(); void Load(); void Save(); static GameSettings& GetInstance(); public: static int FPS(); };
sam1018/PacMan
PacMan/PacMan/GameSettings.h
C
gpl-2.0
269
13.157895
46
0.620818
false
package org.rebecalang.modeltransformer.ros.timedrebeca; import java.util.HashMap; import java.util.Map; import org.rebecalang.compiler.modelcompiler.corerebeca.CoreRebecaTypeSystem; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.BinaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.CastExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.DotPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Expression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.FieldDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Literal; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.MsgsrvDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.NonDetExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PlusSubExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PrimaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.ReactiveClassDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecInstantiationPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecaModel; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TermPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TernaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.UnaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.VariableDeclarator; import org.rebecalang.compiler.modelcompiler.timedrebeca.TimedRebecaTypeSystem; import org.rebecalang.compiler.utils.CodeCompilationException; import org.rebecalang.compiler.utils.ExceptionContainer; import org.rebecalang.compiler.utils.Pair; import org.rebecalang.modeltransformer.StatementTransformingException; import org.rebecalang.modeltransformer.ros.Utilities; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class TimedRebeca2ROSExpressionTransformer { public final static String NEW_LINE = "\r\n"; public final static String TAB = "\t"; static Integer i = 0; private String modelName; private ReactiveClassDeclaration rc; private RebecaModel rebecaModel; private Map <Pair<String, String>, String> methodCalls = new HashMap<Pair<String, String>, String>(); @Autowired TimedRebecaTypeSystem timedRebecaTypeSystem; @Autowired ExceptionContainer exceptionContainer; public void prepare(String modelName, ReactiveClassDeclaration rc, RebecaModel rebecaModel) { this.modelName = modelName; this.rebecaModel = rebecaModel; this.rc = rc; } public String translate(Expression expression) { String retValue = ""; if (expression instanceof TernaryExpression) { TernaryExpression tExpression = (TernaryExpression)expression; Expression condition = tExpression.getCondition(); retValue = "(" + (translate(condition)) + ")"; retValue += " ? " + "(" + translate(tExpression.getLeft()) + ")"; retValue += " : " + "(" + translate(tExpression.getRight()) + ")"; } else if (expression instanceof BinaryExpression) { BinaryExpression bExpression = (BinaryExpression) expression; String op = bExpression.getOperator(); retValue = translate(bExpression.getLeft()) + " " + op + " " + translate(bExpression.getRight()); } else if (expression instanceof UnaryExpression) { UnaryExpression uExpression = (UnaryExpression) expression; retValue = uExpression.getOperator() + " " + translate(uExpression.getExpression()); } else if (expression instanceof CastExpression) { exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " + "\"cast\" expression.", expression.getLineNumber(), expression.getCharacter())); } else if (expression instanceof NonDetExpression) { NonDetExpression nonDetExpression = (NonDetExpression)expression; int numberOfChoices = nonDetExpression.getChoices().size(); retValue += nonDetExpression.getType().getTypeName(); retValue += "int numberOfChoices = " + Integer.toString(numberOfChoices) + ";" + NEW_LINE; retValue += "int choice = " + "rand() % " + Integer.toString(numberOfChoices) + ";" + NEW_LINE; int index = numberOfChoices; for (Expression nonDetChoice : ((NonDetExpression)expression).getChoices()) { retValue += "if (" + "choice ==" + Integer.toString(numberOfChoices - index) + ")" + NEW_LINE; retValue += ((NonDetExpression)nonDetChoice); index ++; } } else if (expression instanceof Literal) { Literal lExpression = (Literal) expression; retValue = lExpression.getLiteralValue(); if (retValue.equals("null")) retValue = "\"dummy\""; } else if (expression instanceof PlusSubExpression) { retValue = translate(((PlusSubExpression)expression).getValue()) + ((PlusSubExpression)expression).getOperator(); } else if (expression instanceof PrimaryExpression) { PrimaryExpression pExpression = (PrimaryExpression) expression; retValue = translatePrimaryExpression(pExpression); } else { exceptionContainer.addException( new StatementTransformingException("Unknown translation rule for expression type " + expression.getClass(), expression.getLineNumber(), expression.getCharacter())); } return retValue; } protected String translatePrimaryExpression(PrimaryExpression pExpression) { String retValue = ""; if (pExpression instanceof DotPrimary) { DotPrimary dotPrimary = (DotPrimary) pExpression; retValue = translateDotPrimary(dotPrimary); } else if (pExpression instanceof TermPrimary) { retValue = translatePrimaryTermExpression((TermPrimary) pExpression); } else if (pExpression instanceof RebecInstantiationPrimary) { RebecInstantiationPrimary rip = (RebecInstantiationPrimary) pExpression; boolean hasMoreVariable = false; String args = ""; try { ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) timedRebecaTypeSystem.getMetaData(rip.getType()); if (!rcd.getStatevars().isEmpty()) { args += " , "; for (FieldDeclaration fd : rcd.getStatevars()) { for (VariableDeclarator vd : fd.getVariableDeclarators()) { hasMoreVariable = true; String typeInit = fd.getType() == CoreRebecaTypeSystem.BOOLEAN_TYPE ? "false" : fd.getType().canTypeCastTo(CoreRebecaTypeSystem.INT_TYPE) ? "0" : "\"dummy\""; args += "(" + rcd.getName() + "-" + vd.getVariableName() + " |-> " + typeInit + ") " ; } } } if (!hasMoreVariable) args += "emptyValuation"; } catch (CodeCompilationException e) { e.printStackTrace(); } args += ","; hasMoreVariable = false; String typeName = rip.getType().getTypeName(); for (Expression expression : rip.getBindings()) { args += " arg(" + translate(expression) + ")"; hasMoreVariable = true; } for (Expression expression : rip.getArguments()) { args += " arg(" + translate(expression) + ")"; hasMoreVariable = true; } if (!hasMoreVariable) args += "noArg"; retValue = " new (" + typeName + args + ")"; } else { exceptionContainer.addException(new StatementTransformingException("Unknown translation rule for initializer type " + pExpression.getClass(), pExpression.getLineNumber(), pExpression.getCharacter())); } return retValue; } private String translateDotPrimary(DotPrimary dotPrimary) { String retValue = ""; if (!(dotPrimary.getLeft() instanceof TermPrimary) || !(dotPrimary.getRight() instanceof TermPrimary)) { exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " + "nested record access expression.", dotPrimary.getLineNumber(), dotPrimary.getCharacter())); } else { // TODO: Modified by Ehsan as the return vlaue type of message servers is always set to MSGSRV_TYPE // if(TypesUtilities.getInstance().getSuperType(dotPrimary.getRight().getType()) == TypesUtilities.MSGSRV_TYPE) { if(dotPrimary.getRight().getType() == CoreRebecaTypeSystem.MSGSRV_TYPE) { retValue = mapToROSPublishing(dotPrimary); } } return retValue; } private String mapToROSPublishing(DotPrimary dotPrimary) { String retValue = ""; /* map to ROS Publishing */ retValue = modelName + "::" + ((TermPrimary)dotPrimary.getRight()).getName() + " " + "pubMsg" + i.toString() + ";" + NEW_LINE; /* fill the ROS message fields with the arguments to be published */ int argumentIndex = 0; for (Expression expression : ((TermPrimary)dotPrimary.getRight()).getParentSuffixPrimary().getArguments()) { ReactiveClassDeclaration toClass = null; TermPrimary toRebec = (TermPrimary)dotPrimary.getLeft(); toClass = Utilities.findKnownReactiveClass(rc, toRebec.getName(), rebecaModel); String toMsgsrvName = ((TermPrimary)dotPrimary.getRight()).getName(); MsgsrvDeclaration toMsgsrv = Utilities.findTheMsgsrv(toClass, toMsgsrvName); String argumentName = toMsgsrv.getFormalParameters().get(argumentIndex).getName(); retValue += "pubMsg" + i.toString() + "." + argumentName + " = " + translate(expression) + ";" + NEW_LINE; argumentIndex ++; } retValue += "pubMsg" + i.toString() + "." + "sender" + "=" + "sender" + ";" + NEW_LINE; retValue += ((TermPrimary) dotPrimary.getLeft()).getName() + "_" + ((TermPrimary)dotPrimary.getRight()).getName() + "_pub" + "." + "publish(" + "pubMsg" + i.toString() + ")" + ";" + NEW_LINE; i ++; /* to prevent from repeated names */ /* end of publishing */ /* storing the name of callee rebec and the name of called msgsrv in order to declare publishers */ Pair<String, String> methodCall = new Pair<String, String>( ((TermPrimary)dotPrimary.getLeft()).getName(), ((TermPrimary)dotPrimary.getRight()).getName() ); methodCalls.put(methodCall, ""); //ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) TransformingContext.getInstance().lookupInContext("current-reactive-class"); //retValue = ((TermPrimary) dotPrimary.getLeft()).getName(); //String typeName = TypesUtilities.getTypeName(((TermPrimary) dotPrimary.getLeft()).getType()); //System.out.println(typeName); return retValue; } private String translatePrimaryTermExpression(TermPrimary pExpression) { String retValue = ""; if(pExpression.getName().equals("assertion") || pExpression.getName().equals("after") || pExpression.getName().equals("deadline")){ return retValue; } if(pExpression.getName().equals("delay")) retValue += "sleep"; else if(pExpression.getName().equals("sender")) return "thisMsg.sender"; else retValue += pExpression.getName(); if( pExpression.getParentSuffixPrimary() != null) { retValue += "("; for(Expression argument: pExpression.getParentSuffixPrimary().getArguments()) { retValue += translate(argument) + ","; } if(! pExpression.getParentSuffixPrimary().getArguments().isEmpty()) { retValue = retValue.substring(0, retValue.length() - 1); } retValue += ")"; } //To support movement in ROS if (retValue.compareTo("Move(1,0)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(0,1)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(-1,0)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(0,-1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(1,1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(1,-1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(-1,1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(-1,-1)")==0) { //ROSCode to publish on CM_Vel topic } /* to support arrays */ for(Expression ex: pExpression.getIndices()) { retValue += "[" + translate(ex) + "]"; } return retValue; } public Map <Pair<String, String>, String> getMethodCalls() { return methodCalls; } }
rebeca-lang/org.rebecalang.modeltransformer
src/main/java/org/rebecalang/modeltransformer/ros/timedrebeca/TimedRebeca2ROSExpressionTransformer.java
Java
gpl-2.0
12,240
41.800699
138
0.724837
false
/* * Copyright (C) 2007 Red Hat, Inc. All rights reserved. * * This file is part of LVM2. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License v.2.1. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _LVM_UTIL_H #define _LVM_UTIL_H #define min(a, b) ({ typeof(a) _a = (a); \ typeof(b) _b = (b); \ (void) (&_a == &_b); \ _a < _b ? _a : _b; }) #define max(a, b) ({ typeof(a) _a = (a); \ typeof(b) _b = (b); \ (void) (&_a == &_b); \ _a > _b ? _a : _b; }) #define uninitialized_var(x) x = x #define KERNEL_VERSION(major, minor, release) (((major) << 16) + ((minor) << 8) + (release)) #endif
SteamMOD/android_bootable_steam_device-mapper
lib/misc/util.h
C
gpl-2.0
958
28.9375
92
0.588727
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Mon Jul 03 11:07:20 PDT 2000 --> <TITLE> : Class Ins_dup2 </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" ID="NavBarCell1Rev"> &nbsp;<FONT ID="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT ID="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../ojvm/loading/instructions/Ins_dup_x2.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../ojvm/loading/instructions/Ins_dup2_x1.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Ins_dup2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;<A HREF="#fields_inherited_from_class_ojvm.loading.instructions.Instruction">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> ojvm.loading.instructions</FONT> <BR> Class Ins_dup2</H2> <PRE> java.lang.Object | +--<A HREF="../../../ojvm/loading/instructions/Instruction.html">ojvm.loading.instructions.Instruction</A> | +--<B>ojvm.loading.instructions.Ins_dup2</B> </PRE> <HR> <DL> <DT>public class <B>Ins_dup2</B><DT>extends <A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></DL> <P> The encapsulation of a dup2 instruction. <P> <HR> <P> <!-- ======== INNER CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <A NAME="fields_inherited_from_class_ojvm.loading.instructions.Instruction"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor"> <TD><B>Fields inherited from class ojvm.loading.instructions.<A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></B></TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD><CODE><A HREF="../../../ojvm/loading/instructions/Instruction.html#length">length</A>, <A HREF="../../../ojvm/loading/instructions/Instruction.html#OPCODE">OPCODE</A>, <A HREF="../../../ojvm/loading/instructions/Instruction.html#opcodeName">opcodeName</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" ID="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#Ins_dup2(ojvm.loading.instructions.InstructionInputStream)">Ins_dup2</A></B>(<A HREF="../../../ojvm/loading/instructions/InstructionInputStream.html">InstructionInputStream</A>&nbsp;classFile)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" ID="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#accept(ojvm.operations.InstructionVisitor)">accept</A></B>(<A HREF="../../../ojvm/operations/InstructionVisitor.html">InstructionVisitor</A>&nbsp;iv)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#toString()">toString</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_ojvm.loading.instructions.Instruction"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor"> <TD><B>Methods inherited from class ojvm.loading.instructions.<A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></B></TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD><CODE><A HREF="../../../ojvm/loading/instructions/Instruction.html#getLength()">getLength</A>, <A HREF="../../../ojvm/loading/instructions/Instruction.html#isActualInstruction()">isActualInstruction</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" ID="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" ID="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="Ins_dup2(ojvm.loading.instructions.InstructionInputStream)"><!-- --></A><H3> Ins_dup2</H3> <PRE> public <B>Ins_dup2</B>(<A HREF="../../../ojvm/loading/instructions/InstructionInputStream.html">InstructionInputStream</A>&nbsp;classFile)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" ID="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="accept(ojvm.operations.InstructionVisitor)"><!-- --></A><H3> accept</H3> <PRE> public void <B>accept</B>(<A HREF="../../../ojvm/operations/InstructionVisitor.html">InstructionVisitor</A>&nbsp;iv) throws <A HREF="../../../ojvm/data/JavaException.html">JavaException</A></PRE> <DL> <DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../ojvm/loading/instructions/Instruction.html#accept(ojvm.operations.InstructionVisitor)">accept</A> in class <A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></DL> </DD> </DL> <HR> <A NAME="toString()"><!-- --></A><H3> toString</H3> <PRE> public java.lang.String <B>toString</B>()</PRE> <DL> <DD><DL> <DT><B>Overrides:</B><DD>toString in class java.lang.Object</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" ID="NavBarCell1Rev"> &nbsp;<FONT ID="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT ID="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../ojvm/loading/instructions/Ins_dup_x2.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../ojvm/loading/instructions/Ins_dup2_x1.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Ins_dup2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;<A HREF="#fields_inherited_from_class_ojvm.loading.instructions.Instruction">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> </BODY> </HTML>
adum/bitbath
hackjvm/src/doc/ojvm/loading/instructions/Ins_dup2.html
HTML
gpl-2.0
10,883
40.380228
270
0.627768
false
#!/usr/bin/perl =head1 NAME TMI pokal_sent.pl =head1 SYNOPSIS TBD =head1 AUTHOR admin@socapro.com =head1 CHANGELOG 2015-06-09 Thomas: Added Session Management =head1 COPYRIGHT Copyright (c) 2015, SocaPro Inc. Created 2015-06-09 =cut use lib '/tmapp/tmsrc/cgi-bin/'; use TMSession; my $session = TMSession::getSession(tmi_login => 1); my $trainer = $session->getUser(); my $leut = $trainer; use CGI; print "Content-type: text/html\n\n"; $query = new CGI; $url = $query->param('url'); $tip[1] = $query->param('30....'); $tip[2] = $query->param('31....'); $tip[3] = $query->param('32....'); $tip[4] = $query->param('33....'); $tip[5] = $query->param('34....'); $tip[6] = $query->param('35....'); $tip[7] = $query->param('36....'); $tip[8] = $query->param('37....'); $tip[9] = $query->param('38....'); $tip[10] = $query->param('39....'); $tips = $query->param('tips'); $pokal = $query->param('pokal'); open(D7,"/tmdata/tmi/pokal/tip_status.txt"); $tip_status = <D7> ; chomp $tip_status; close(D7); if ( $tip_status != 1 ) { print "<title>Pokal Tipabgabe</title><font face=verdana size=2><br><br><br><br><br><b>Die Tipabgabefrist ist bereits abgelaufen ...\n"; exit ; } print "Content-type: text/html\n\n"; print "<title>Pokal Tipabgabe</title><body bgcolor=white text=black>\n"; print "<form name=Testform action=/cgi-mod/tmi/login.pl method=post></form>"; print "<script language=JavaScript>"; print" function AbGehts()"; print" {"; print" document.Testform.submit();"; print" }"; print" window.setTimeout(\"AbGehts()\",7000);"; print" </script>"; print "<p align=left><body bgcolor=white text=black link=darkred link=darkred>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n"; require "/tmapp/tmsrc/cgi-bin/tag.pl" ; $agb = 0; for ($x=1 ; $x<=10 ; $x++ ) { if ( $tip[$x] ne "0&0" ) { $abg++ } $reihe = $reihe . $tip[$x] . '.' ; } if ( $abg != $tips ) { print "<font face=verdana size=2><br><br><br><br><br><b>Die Anzahl Ihrer abgegebenen Tips ist nicht korrekt ...<br>Sie haben $abg Tips anstatt der korrekten $tips Tips abgegeben .<br>Bitte kehren Sie zur Tipabgabe zurueck und korregieren Sie Ihre Tipabgabe .\n"; exit ; } $rf ="0"; $rx = "x" ; my $liga = 0; if ( $liga > 9 ) { $rf = "" } $suche = '&'.$trainer.'&' ; $s = 0; open(D2,"/tmdata/tmi/history.txt"); while(<D2>) { $s++; if ($_ =~ /$suche/) { @lor = split (/&/, $_); $liga = $s ; } } close(D2); $id_verein = 0; $y = 0; for ( $x = 1; $x < 19; $x++ ) { $y++; chomp $lor[$y]; $data[$x] = $lor[$y]; $teams[$x] = $lor[$y]; $team[$x] = $lor[$y]; $y++; chomp $lor[$y]; $datb[$x] = $lor[$y]; if ( $datb[$x] eq $trainer ) {$id = $x } if ( $datb[$x] eq $trainer ) {$id_verein = (($liga-1)*18)+ $x } if ( $datb[$x] eq $trainer ) {$verein = $data[$x] } $y++; chomp $lor[$y]; $datc[$x] = $lor[$y]; if ( $datb[$x] eq $trainer ) {$recipient = $datc[$x] } } $rr = 0; $li=0; $liga=0; open(D2,"/tmdata/tmi/history.txt"); while(<D2>) { $li++; @vereine = split (/&/, $_); $y = 0; for ( $x = 1; $x < 19; $x++ ) { $rr++; $y++; chomp $verein[$y]; $teams[$rr] = $vereine[$y]; $team[$rr] = $vereine[$y]; $y++; chomp $verein[$y]; $datb[$rr] = $vereine[$y]; $y++; chomp $verein[$y]; $datc[$rr] = $vereine[$y]; } } close(D2); my $url = "/tmdata/tmi/pokal/tips/" ; if ( $id_verein<10 ) { $url = $url . '0' } if ( $id_verein<100 ) { $url = $url . '0' } if ( $id_verein<1000 ) { $url = $url . '0' } open(D7,"/tmdata/tmi/pokal/pokal_datum.txt"); $spielrunde_ersatz = <D7> ; chomp $spielrunde_ersatz; close(D7); $runde = $spielrunde_ersatz; $url=$url.$id_verein. '-' . $pokal . '-' . $runde . '.txt' ; open(D2,">$url"); print D2 "$reihe\n"; close (D2) ; print "<font face=verdana size=2><br><br><br><b>&nbsp;&nbsp;Ihre Tipabgabe wurde registriert .<br>&nbsp;&nbsp;Sie werden zu Ihrem LogIn Bereich weitergeleitet ...\n";
tipmaster/tipmaster
tmsrc/cgi-bin/tmi/pokal/pokal_sent.pl
Perl
gpl-2.0
3,837
20.082418
262
0.576492
false
/* * The ManaPlus Client * Copyright (C) 2013-2015 The ManaPlus Developers * * This file is part of The ManaPlus Client. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utils/fuzzer.h" #ifdef USE_FUZZER #include "client.h" #include "logger.h" #include "settings.h" #include "utils/stringutils.h" #include "debug.h" namespace { Logger *fuzz = nullptr; int fuzzRand = 50; } // namespace void Fuzzer::init() { fuzz = new Logger; fuzz->setLogFile(settings.localDataDir + "/fuzzer.log"); unsigned int sr = time(nullptr); fuzz->log("Srand: %u", sr); srand(sr); } bool Fuzzer::conditionTerminate(const char *const name) { if ((rand() % 100) <= fuzzRand) { fuzz->log("deleted: %s", name); return true; } fuzz->log("passed: %s", name); return false; } #endif
Rawng/ManaPlus
src/utils/fuzzer.cpp
C++
gpl-2.0
1,441
23.016667
73
0.671062
false
<?php /** * HTML attribute filters. * Most of these functions filter the generic values from the framework found in hoot/functions/attr.php * Attributes for non-generic structural elements (mostly theme specific) can be loaded in this file. * * @package hoot * @subpackage responsive-brix * @since responsive-brix 1.0 */ /* Modify Original Filters from Framework */ add_filter( 'hoot_attr_content', 'hoot_theme_attr_content' ); add_filter( 'hoot_attr_sidebar', 'hoot_theme_attr_sidebar', 10, 2 ); /* New Theme Filters */ add_filter( 'hoot_attr_page_wrapper', 'hoot_theme_attr_page_wrapper' ); add_filter( 'hoot_attr_page_template_content', 'hoot_theme_page_template_content', 10, 2 ); /* Misc Filters */ add_filter( 'hoot_attr_social_icons_icon', 'hoot_theme_attr_social_icons_icon', 10, 2 ); /** * Modify Main content container of the page attributes. * * @since 1.0 * @access public * @param array $attr * @return array */ function hoot_theme_attr_content( $attr ) { $layout_class = hoot_main_layout_class( 'content' ); if ( !empty( $layout_class ) ) { if ( isset( $attr['class'] ) ) $attr['class'] .= ' ' . $layout_class; else $attr['class'] = $layout_class; } return $attr; } /** * Modify Sidebar attributes. * * @since 1.0 * @access public * @param array $attr * @param string $context * @return array */ function hoot_theme_attr_sidebar( $attr, $context ) { if ( !empty( $context ) && $context == 'primary' ) { $layout_class = hoot_main_layout_class( 'primary-sidebar' ); if ( !empty( $layout_class ) ) { if ( isset( $attr['class'] ) ) $attr['class'] .= ' ' . $layout_class; else $attr['class'] = $layout_class; } } return $attr; } /** * Page wrapper attributes. * * @since 1.0 * @access public * @param array $attr * @return array */ function hoot_theme_attr_page_wrapper( $attr ) { $site_layout = hoot_get_mod( 'site_layout' ); $attr['class'] = ( $site_layout == 'boxed' ) ? 'grid site-boxed' : 'site-stretch'; $attr['class'] .= ' page-wrapper'; return $attr; } /** * Main content container of the page attributes when a page template is being displayed * * @since 1.0 * @access public * @param array $attr * @param string $context * @return array */ function hoot_theme_page_template_content( $attr, $context ) { if ( is_page_template() && $context == 'none' ) { $attr['id'] = 'content'; $attr['class'] = 'content sidebar-none'; $attr['role'] = 'main'; $attr['itemprop'] = 'mainContentOfPage'; $template_slug = basename( get_page_template(), '.php' ); $attr['class'] .= ' ' . sanitize_html_class( 'content-' . $template_slug ); } elseif ( function_exists( 'hoot_attr_content' ) ) { // Get page attributes for main content container of a non-template regular page $attr = apply_filters( "hoot_attr_content", $attr, $context ); } return $attr; } /** * Social Icons Widget - Icons * * @since 2.0 * @access public * @param array $attr * @param string $context * @return array */ function hoot_theme_attr_social_icons_icon( $attr, $context ) { $attr['class'] = 'social-icons-icon'; if ( $context != 'email' ) $attr['target'] = '_blank'; return $attr; }
BellarmineBTDesigns/mashariki
wp-content/themes/responsive-brix/hoot-theme/attr.php
PHP
gpl-2.0
3,197
24.584
104
0.636534
false
var iconhead={ title:"Icon Heading Shortcode", id :'oscitas-form-iconhead', pluginName: 'iconhead', setRowColors:false }; (function() { _create_tinyMCE_options(iconhead,800); })(); function create_oscitas_iconhead(pluginObj){ if(jQuery(pluginObj.hashId).length){ jQuery(pluginObj.hashId).remove(); } // creates a form to be displayed everytime the button is clicked // you should achieve this using AJAX instead of direct html code like this var iconhead_fa=''; /*if(ebs.ebs_fa_inclusion==1){ iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>'; }*/ iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>'; // creates a form to be displayed everytime the button is clicked // you should achieve this using AJAX instead of direct html code like this var form = jQuery('<div id="'+pluginObj.id+'" class="oscitas-container" title="'+pluginObj.title+'"><table id="gallery-table" class="form-table">\ <tr>\ <th><label for="oscitas-heading-icon">Select Icon:</label></th>\ <td><div id="click_icon_list" class="oscitas-icon-div"><span id="osc_show_icon"></span><span class="show-drop"></span></div><input type="hidden" id="oscitas-iconhead-icon" value=""><input type="hidden" id="oscitas-iconhead-icontype" value="">\ <div id="osc_show_iconlist" class="oscitas-icon" style="display:none;width:100%"><h4>Glyphicons</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsicons+'</ul>'+iconhead_fa+'</div>\ </td>\ </tr>\ <tr>\ <th><label for="oscitas-iconhead-iconcolor">Icon Color:</label></th>\ <td><input type="text" name="label" id="oscitas-iconhead-iconcolor" class="color" value="" /><br />\ </td>\ </tr>\ <tr>\ <th><label for="oscitas-iconhead-headingtype">Heading Type:</label></th>\ <td><select name="oscitas-iconhead-headingtype" id="oscitas-iconhead-headingtype">\ <option value="h1">H1</option>\ <option value="h2">H2</option>\ <option value="h3">H3</option>\ <option value="h4">H4</option>\ <option value="h5">H5</option>\ <option value="h6">H6</option>\ </select><br />\ </td>\ </tr>\ <tr>\ <th><label for="oscitas-iconhead-heading">Heading:</label></th>\ <td><input type="text" name="oscitas-iconhead-heading" id="oscitas-iconhead-heading" value="Heading"/><br />\ </td>\ </tr>\ <tr>\ <th><label for="oscitas-iconhead-class">Custom Class:</label></th>\ <td><input type="text" name="line" id="oscitas-iconhead-class" value=""/><br />\ </td>\ </tr>\ </table>\ <p class="submit">\ <input type="button" id="oscitas-iconhead-submit" class="button-primary" value="Insert Icon Heading" name="submit" />\ </p>\ </div>'); var table = form.find('table'); jQuery('.glyphicon').css('display','inline'); form.appendTo('body').hide(); form.find('.color').wpColorPicker(); table.find('#click_icon_list').click(function(){ if(!jQuery(this).hasClass('osc_icon_showing')){ jQuery(this).addClass('osc_icon_showing') table.find('#osc_show_iconlist').show(); } else{ jQuery(this).removeClass('osc_icon_showing') table.find('#osc_show_iconlist').hide(); } }); table.find('.oscitas-heading-icon li').click(function(){ var val=jQuery(this).attr('data-value'); var type=jQuery(this).attr('type'); table.find('.oscitas-heading-icon li').removeClass('osc_icon_selected'); jQuery(this).addClass('osc_icon_selected'); table.find('#click_icon_list').removeClass('osc_icon_showing'); table.find('#osc_show_iconlist').hide(); table.find('#osc_show_icon').removeClass().addClass(type).addClass(val); table.find('#oscitas-iconhead-icon').val(val); table.find('#oscitas-iconhead-icontype').val(type); }); // // handles the click event of the submit button form.find('#oscitas-iconhead-submit').click(function() { // defines the options and their default values // again, this is not the most elegant way to do this // but well, this gets the job done nonetheless var type=jQuery('#oscitas-iconhead-headingtype').val(); var cusclass='',style=''; if(table.find('#oscitas-iconhead-icon').val()!=''){ style=' style="' + table.find('#oscitas-iconhead-icon').val()+'"' ; } if(table.find('#oscitas-iconhead-icontype').val()!=''){ style+=' icontype="' + table.find('#oscitas-iconhead-icontype').val()+'"' ; } if(table.find('#oscitas-iconhead-iconcolor').val()!=''){ cusclass+= ' color="'+table.find('#oscitas-iconhead-iconcolor').val()+'"'; } if(table.find('#oscitas-iconhead-class').val()!=''){ cusclass+= ' class="'+table.find('#oscitas-iconhead-class').val()+'"'; } var shortcode = '[iconheading type="'+type+'"'; shortcode += style+cusclass ; shortcode += ']'+table.find('#oscitas-iconhead-heading').val()+'[/iconheading]' ; // inserts the shortcode into the active editor tinyMCE.activeEditor.execCommand('mceInsertContent',0 , shortcode); // closes Dialoguebox close_dialogue(pluginObj.hashId); }); }
wjmendez/easy-bootstrap-shortcodes
shortcode/iconhead/iconhead_plugin.js
JavaScript
gpl-2.0
5,742
44.571429
247
0.588123
false
using System; using System.Threading.Tasks; using System.Windows.Threading; using Disp = System.Windows.Threading.Dispatcher; using Op = System.Windows.Threading.DispatcherOperation; using DO = System.Windows.Threading.DispatcherObject; using static System.Array; namespace AphidUI { public static class DispatcherObjectExtension { public static void Invoke(this Disp dispatcher, Action action) => dispatcher.Invoke(action, Empty<object>()); public static void Sync(this Disp dispatcher, Action action) => dispatcher.Invoke(action, Empty<object>()); public static Op BeginInvoke(this Disp dispatcher, Action action, params object[] args) => dispatcher.BeginInvoke(action, args); public static Op Async(this Disp dispatcher, Action action, params object[] args) => dispatcher.BeginInvoke(action, args); public static Task Run(this Disp dispatcher, Action action, params object[] args) => dispatcher.BeginInvoke(action, args).Task; public static TResult Invoke<TResult>(this Disp dispatcher, Func<TResult> action) => (TResult)dispatcher.Invoke(action, Empty<object>()); public static TResult Sync<TResult>(this Disp dispatcher, Func<TResult> action) => (TResult)dispatcher.Invoke(action, Empty<object>()); public static Op BeginInvoke(this DO @do, Action action, params object[] args) => @do.Dispatcher.BeginInvoke(action, args); public static Op Async(this DO @do, Action action, params object[] args) => @do.Dispatcher.BeginInvoke(action, args); public static Task Run(this DO @do, Action action, params object[] args) => @do.BeginInvoke(action, args).Task; public static Task Run<TArg>(this DO @do, Action<TArg> action, TArg arg0) => @do.Dispatcher.BeginInvoke(action, new object[] { arg0 }).Task; public static void Invoke(this DO @do, Action action) => @do.Dispatcher.Invoke(action, Empty<object>()); public static void Sync(this DO @do, Action action) => @do.Dispatcher.Invoke(action, Empty<object>()); public static TResult Invoke<TResult>(this DO @do, Func<TResult> action) => (TResult)@do.Dispatcher.Invoke(action, Empty<object>()); public static TResult Sync<TResult>(this DO @do, Func<TResult> action) => (TResult)@do.Dispatcher.Invoke(action, Empty<object>()); public static DispatcherProcessingDisabled DisableProcessing(this DO @do) => @do.Dispatcher.DisableProcessing(); } }
John-Leitch/Aphid
AphidUI/DispatcherObjectExtension.cs
C#
gpl-2.0
2,708
42.360656
98
0.651146
false
<?php /** * @desc Modify from component Media Manager of Joomla * */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die( 'Restricted access' ); jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); /** * Weblinks Weblink Controller * * @package Joomla * @subpackage Weblinks * @since 1.5 */ class JaextmanagerControllerFile extends JaextmanagerController { /** * Upload a file * * @since 1.5 */ function upload() { global $mainframe; // Check for request forgeries JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' ); $file = JRequest::getVar( 'Filedata', '', 'files', 'array' ); $folder = JRequest::getVar( 'folder', '', '', 'path' ); $format = JRequest::getVar( 'format', 'html', '', 'cmd'); $return = JRequest::getVar( 'return-url', null, 'post', 'base64' ); $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { $filepath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.strtolower($file['name'])); if (!RepoHelper::canUpload( $file, $err )) { if ($format == 'json') { jimport('joomla.error.log'); $log = &JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Invalid: '.$filepath.': '.$err)); header('HTTP/1.0 415 Unsupported Media Type'); jexit('Error. Unsupported Media Type!'); } else { JError::raiseNotice(100, JText::_($err)); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return).'&folder='.$folder); } return; } } if (JFile::exists($filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log = &JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'File already exists: '.$filepath)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { JError::raiseNotice(100, JText::_('Error. File already exists')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return).'&folder='.$folder); } return; } } if (!JFile::upload($file['tmp_name'], $filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log = &JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Cannot upload: '.$filepath)); header('HTTP/1.0 400 Bad Request'); jexit('Error. Unable to upload file'); } else { JError::raiseWarning(100, JText::_('Error. Unable to upload file')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return).'&folder='.$folder); } return; } } else { if ($format == 'json') { jimport('joomla.error.log'); $log = &JLog::getInstance(); $log->addEntry(array('comment' => $folder)); jexit('Upload complete'); } else { $mainframe->enqueueMessage(JText::_('Upload complete')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return).'&folder='.$folder); } return; } } } else { $mainframe->redirect('index.php', 'Invalid Request', 'error'); } } /** * Deletes paths from the current path * * @param string $listFolder The image directory to delete a file from * @since 1.5 */ function delete() { global $mainframe; JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' ); // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Get some data from the request $tmpl = JRequest::getCmd( 'tmpl' ); $paths = JRequest::getVar( 'rm', array(), '', 'array' ); $folder = JRequest::getVar( 'folder', '', '', 'path'); // Initialize variables $msg = array(); $ret = true; if (count($paths)) { foreach ($paths as $path) { if ($path !== JFile::makeSafe($path)) { JError::raiseWarning(100, JText::_('Unable to delete:').htmlspecialchars($path, ENT_COMPAT, 'UTF-8').' '.JText::_('WARNFILENAME')); continue; } $fullPath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.$path); if (is_file($fullPath)) { $ret |= !JFile::delete($fullPath); } else if (is_dir($fullPath)) { $files = JFolder::files($fullPath, '.', true); $canDelete = true; foreach ($files as $file) { if ($file != 'index.html') { $canDelete = false; } } if ($canDelete) { $ret |= !JFolder::delete($fullPath); } else { //allow remove folder not empty on local repository $ret2 = JFolder::delete($fullPath); $ret |= !$ret2; if($ret2 == false) { JError::raiseWarning(100, JText::_('Unable to delete:').$fullPath); } } } } } if ($ret) { JError::raiseNotice(200, JText::_('Successfully delete a seleted item(s).')); } if ($tmpl == 'component') { // We are inside the iframe $mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder.'&tmpl=component'); } else { $mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder); } } function download() { global $mainframe; JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' ); // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Get some data from the request $tmpl = JRequest::getCmd( 'tmpl' ); $paths = JRequest::getVar( 'rm', array(), '', 'array' ); $folder = JRequest::getVar( 'folder', '', '', 'path'); // Initialize variables $msg = array(); $ret = true; if (count($paths)) { foreach ($paths as $path) { $fullPath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.$path); if(is_file($fullPath) && JFile::getExt($fullPath) == 'zip') { // Set headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$fullPath"); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: binary"); // Read the file from disk readfile($fullPath); exit(); } } } if ($tmpl == 'component') { // We are inside the iframe $mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder.'&tmpl=component'); } else { $mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder); } } }
rlee1962/diylegalcenter
administrator/components/com_jaextmanager/controllers/file.php
PHP
gpl-2.0
6,634
27.718615
136
0.601146
false
# Rshell A simple command shell designed by Trevor Smith and Chianh Wu. ## What it does (currently) This shell will handle standard command line programs and their arguments. Similarly, these commands can be linked with `&&`,`||`, or `;`. We are orking on adding precidence via parentheses. The shell itself will also handle comments starting with the `#` symbol. There is also a built in function that will test if a file or directory exits, and can be executed via `test` with flags `-e` to check existance, `-f` to check for a regular file, and `-d` to check if it is a directory. Also, `test` can be represented as `[]` (e.g. `test -e /home/user/` = `[ -e /home/user/ ]`); note also that this is white space sensetive `[-e /home/user/]` will not work. ## How to Run - `$ git clone https://github.com/tsmit019/rshell.git` - `$ cd rshell` - `$ git checkout hw4` - `$ make` - `$ bin/rshell` ## If you want to run test - `$ git clone https://github.com/tsmit019/rshell.git` - `$ cd rshell` - `$ git checkout hw4` - `$ make` - `$ cd tests` From here you can chose any of the `.sh` and run them. Make sure they are executable by checking using `ls -l`. If they are not executable, then type `chmod 711 *.sh` to make all the `.sh` files executable. ## Bugs Input redirection and output redirection work most of the time except for when they are the first set of commands (e.g. `cat < test.txt` will through an out of range. I have looked for the reason for a while and have not been able to identify why). But, if you use the redirects after a connector (e.g. `echo hhallllllllu && cat < test` or `ls -al; echo why does this not work > sad.txt`) then it works perfectly fine. Same for piping. I don't quite know. Nested redirects dont quite work as intended e.g. `cat < test.txt > test_clone.txt` will not write to test_clone.txt but just execute the `cat < test.txt`. If you give a command that is parenthese, connector, then command (e.g. `(echo a && echo b) || echo c`) you get a out of range error that I was not able to resolve. Similarly, any connector directly after a closing parenthese will cause this behavior and I am unsure why. I will try and fix this by the next release. Similarly, commands with connectors right after each other will through a similar out of range error. E.g `echo a && ||` will give you out of range.
tsmit019/rshell
README.md
Markdown
gpl-2.0
2,347
57.675
207
0.714955
false
--- name: Feature request about: Please consider reporting directly to https://github.com/magento/community-features --- <!--- Important: This repository is intended only for Magento 2 Technical Issues. Enter Feature Requests at https://github.com/magento/community-features. Project stakeholders monitor and manage requests. Feature requests entered using this form may be moved to the forum. Fields marked with (*) are required. Please don't remove the template. --> ### Description (*) <!--- Describe the feature you would like to add. --> ### Expected behavior (*) <!--- What is the expected behavior of this feature? How is it going to work? --> ### Benefits <!--- How do you think this feature would improve Magento? --> ### Additional information <!--- What other information can you provide about the desired feature? -->
kunj1988/Magento2
.github/ISSUE_TEMPLATE/feature_request.md
Markdown
gpl-2.0
836
38.809524
337
0.73445
false
<!DOCTYPE html> <html> <h1>muppets_mug5</h1> <p> BOLD: 2/2 correct and 0/2false</p> <p> SIFT: 0/2 correct and 2/2false</p><br> <img src = "../../../BVD_M01/muppets_mug/muppets_mug5.jpg" alt = "muppets_mug5.html" style= " width:320px;height:240px;"> <h1> Falsely compared to: </h1><br> <img src = "../../../" alt = "" style= " width:320px;height:240px;"> <img src = "../../../" alt = "" style= " width:320px;height:240px;"> </html>
MarcGroef/ros-vision
catkin_ws/Reports/BOLD_SIFT_1CAN-10fold-10%/muppets_mug/muppets_mug5.html
HTML
gpl-2.0
431
60.714286
157
0.600928
false
/** @mainpage SOIL Jonathan Dummer 2007-07-26-10.36 Simple OpenGL Image Library A tiny c library for uploading images as textures into OpenGL. Also saving and loading of images is supported. I'm using Sean's Tool Box image loader as a base: http://www.nothings.org/ I'm upgrading it to load TGA and DDS files, and a direct path for loading DDS files straight into OpenGL textures, when applicable. Image Formats: - BMP load & save - TGA load & save - DDS load & save - PNG load - JPG load OpenGL Texture Features: - resample to power-of-two sizes - MIPmap generation - compressed texture S3TC formats (if supported) - can pre-multiply alpha for you, for better compositing - can flip image about the y-axis (except pre-compressed DDS files) Thanks to: * Sean Barret - for the awesome stb_image * Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts * everybody at gamedev.net **/ #ifndef HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY #define HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY #ifdef __cplusplus extern "C" { #endif /** The format of images that may be loaded (force_channels). SOIL_LOAD_AUTO leaves the image in whatever format it was found. SOIL_LOAD_L forces the image to load as Luminous (greyscale) SOIL_LOAD_LA forces the image to load as Luminous with Alpha SOIL_LOAD_RGB forces the image to load as Red Green Blue SOIL_LOAD_RGBA forces the image to load as Red Green Blue Alpha **/ enum { SOIL_LOAD_AUTO = 0, SOIL_LOAD_L = 1, SOIL_LOAD_LA = 2, SOIL_LOAD_RGB = 3, SOIL_LOAD_RGBA = 4 }; /** Passed in as reuse_texture_ID, will cause SOIL to register a new texture ID using glGenTextures(). If the value passed into reuse_texture_ID > 0 then SOIL will just re-use that texture ID (great for reloading image assets in-game!) **/ enum { SOIL_CREATE_NEW_ID = 0 }; /** flags you can pass into SOIL_load_OGL_texture() and SOIL_create_OGL_texture(). (note that if SOIL_FLAG_DDS_LOAD_DIRECT is used the rest of the flags with the exception of SOIL_FLAG_TEXTURE_REPEATS will be ignored while loading already-compressed DDS files.) SOIL_FLAG_POWER_OF_TWO: force the image to be POT SOIL_FLAG_MIPMAPS: generate mipmaps for the texture SOIL_FLAG_TEXTURE_REPEATS: otherwise will clamp SOIL_FLAG_MULTIPLY_ALPHA: for using (GL_ONE,GL_ONE_MINUS_SRC_ALPHA) blending SOIL_FLAG_INVERT_Y: flip the image vertically SOIL_FLAG_COMPRESS_TO_DXT: if the card can display them, will convert RGB to DXT1, RGBA to DXT5 SOIL_FLAG_DDS_LOAD_DIRECT: will load DDS files directly without _ANY_ additional processing SOIL_FLAG_NTSC_SAFE_RGB: clamps RGB components to the range [16,235] SOIL_FLAG_CoCg_Y: Google YCoCg; RGB=>CoYCg, RGBA=>CoCgAY SOIL_FLAG_TEXTURE_RECTANGE: uses ARB_texture_rectangle ; pixel indexed & no repeat or MIPmaps or cubemaps **/ enum { SOIL_FLAG_POWER_OF_TWO = 1, SOIL_FLAG_MIPMAPS = 2, SOIL_FLAG_TEXTURE_REPEATS = 4, SOIL_FLAG_MULTIPLY_ALPHA = 8, SOIL_FLAG_INVERT_Y = 16, SOIL_FLAG_COMPRESS_TO_DXT = 32, SOIL_FLAG_DDS_LOAD_DIRECT = 64, SOIL_FLAG_NTSC_SAFE_RGB = 128, SOIL_FLAG_CoCg_Y = 256, SOIL_FLAG_TEXTURE_RECTANGLE = 512 }; /** The types of images that may be saved. (TGA supports uncompressed RGB / RGBA) (BMP supports uncompressed RGB) (DDS supports DXT1 and DXT5) **/ enum { SOIL_SAVE_TYPE_TGA = 0, SOIL_SAVE_TYPE_BMP = 1, SOIL_SAVE_TYPE_DDS = 2 }; /** Defines the order of faces in a DDS cubemap. I recommend that you use the same order in single image cubemap files, so they will be interchangeable with DDS cubemaps when using SOIL. **/ #define SOIL_DDS_CUBEMAP_FACE_ORDER "EWUDNS" /** The types of internal fake HDR representations SOIL_HDR_RGBE: RGB * pow( 2.0, A - 128.0 ) SOIL_HDR_RGBdivA: RGB / A SOIL_HDR_RGBdivA2: RGB / (A*A) **/ enum { SOIL_HDR_RGBE = 0, SOIL_HDR_RGBdivA = 1, SOIL_HDR_RGBdivA2 = 2 }; /** Loads an image from disk into an OpenGL texture. \param filename the name of the file to upload as a texture \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_texture ( const char *filename, int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads 6 images from disk into an OpenGL cubemap texture. \param x_pos_file the name of the file to upload as the +x cube face \param x_neg_file the name of the file to upload as the -x cube face \param y_pos_file the name of the file to upload as the +y cube face \param y_neg_file the name of the file to upload as the -y cube face \param z_pos_file the name of the file to upload as the +z cube face \param z_neg_file the name of the file to upload as the -z cube face \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_cubemap ( const char *x_pos_file, const char *x_neg_file, const char *y_pos_file, const char *y_neg_file, const char *z_pos_file, const char *z_neg_file, int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads 1 image from disk and splits it into an OpenGL cubemap texture. \param filename the name of the file to upload as a texture \param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc. \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_single_cubemap ( const char *filename, const char face_order[6], int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads an HDR image from disk into an OpenGL texture. \param filename the name of the file to upload as a texture \param fake_HDR_format SOIL_HDR_RGBE, SOIL_HDR_RGBdivA, SOIL_HDR_RGBdivA2 \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_HDR_texture ( const char *filename, int fake_HDR_format, int rescale_to_max, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads an image from RAM into an OpenGL texture. \param buffer the image data in RAM just as if it were still in a file \param buffer_length the size of the buffer in bytes \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \param width \param height \param channels \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_texture_and_info_from_memory ( const unsigned char *const buffer, int buffer_length, int force_channels, unsigned int reuse_texture_ID, unsigned int flags, int *width, int *height, int *channels ); /** Loads an image from RAM into an OpenGL texture. \param buffer the image data in RAM just as if it were still in a file \param buffer_length the size of the buffer in bytes \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_texture_from_memory ( const unsigned char *const buffer, int buffer_length, int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads 6 images from memory into an OpenGL cubemap texture. \param x_pos_buffer the image data in RAM to upload as the +x cube face \param x_pos_buffer_length the size of the above buffer \param x_neg_buffer the image data in RAM to upload as the +x cube face \param x_neg_buffer_length the size of the above buffer \param y_pos_buffer the image data in RAM to upload as the +x cube face \param y_pos_buffer_length the size of the above buffer \param y_neg_buffer the image data in RAM to upload as the +x cube face \param y_neg_buffer_length the size of the above buffer \param z_pos_buffer the image data in RAM to upload as the +x cube face \param z_pos_buffer_length the size of the above buffer \param z_neg_buffer the image data in RAM to upload as the +x cube face \param z_neg_buffer_length the size of the above buffer \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_cubemap_from_memory ( const unsigned char *const x_pos_buffer, int x_pos_buffer_length, const unsigned char *const x_neg_buffer, int x_neg_buffer_length, const unsigned char *const y_pos_buffer, int y_pos_buffer_length, const unsigned char *const y_neg_buffer, int y_neg_buffer_length, const unsigned char *const z_pos_buffer, int z_pos_buffer_length, const unsigned char *const z_neg_buffer, int z_neg_buffer_length, int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Loads 1 image from RAM and splits it into an OpenGL cubemap texture. \param buffer the image data in RAM just as if it were still in a file \param buffer_length the size of the buffer in bytes \param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc. \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_load_OGL_single_cubemap_from_memory ( const unsigned char *const buffer, int buffer_length, const char face_order[6], int force_channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Creates a 2D OpenGL texture from raw image data. Note that the raw data is _NOT_ freed after the upload (so the user can load various versions). \param data the raw data to be uploaded as an OpenGL texture \param width the width of the image in pixels \param height the height of the image in pixels \param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_create_OGL_texture ( const unsigned char *const data, int width, int height, int channels, unsigned int reuse_texture_ID, unsigned int flags ); /** Creates an OpenGL cubemap texture by splitting up 1 image into 6 parts. \param data the raw data to be uploaded as an OpenGL texture \param width the width of the image in pixels \param height the height of the image in pixels \param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA \param face_order the order of the faces in the file, and combination of NSWEUD, for North, South, Up, etc. \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT \return 0-failed, otherwise returns the OpenGL texture handle **/ unsigned int SOIL_create_OGL_single_cubemap ( const unsigned char *const data, int width, int height, int channels, const char face_order[6], unsigned int reuse_texture_ID, unsigned int flags ); /** Captures the OpenGL window (RGB) and saves it to disk \return 0 if it failed, otherwise returns 1 **/ int SOIL_save_screenshot ( const char *filename, int image_type, int x, int y, int width, int height ); /** Loads an image from disk into an array of unsigned chars. Note that *channels return the original channel count of the image. If force_channels was other than SOIL_LOAD_AUTO, the resulting image has force_channels, but *channels may be different (if the original image had a different channel count). \return 0 if failed, otherwise returns 1 **/ unsigned char* SOIL_load_image ( const char *filename, int *width, int *height, int *channels, int force_channels ); /** Loads an image from memory into an array of unsigned chars. Note that *channels return the original channel count of the image. If force_channels was other than SOIL_LOAD_AUTO, the resulting image has force_channels, but *channels may be different (if the original image had a different channel count). \return 0 if failed, otherwise returns 1 **/ unsigned char* SOIL_load_image_from_memory ( const unsigned char *const buffer, int buffer_length, int *width, int *height, int *channels, int force_channels ); /** Saves an image from an array of unsigned chars (RGBA) to disk \return 0 if failed, otherwise returns 1 **/ int SOIL_save_image ( const char *filename, int image_type, int width, int height, int channels, const unsigned char *const data ); /** Frees the image data (note, this is just C's "free()"...this function is present mostly so C++ programmers don't forget to use "free()" and call "delete []" instead [8^) **/ void SOIL_free_image_data ( unsigned char *img_data ); /** This function resturn a pointer to a string describing the last thing that happened inside SOIL. It can be used to determine why an image failed to load. **/ const char* SOIL_last_result ( void ); #ifdef __cplusplus } #endif #endif /* HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY */
cheeseEater/ihge
src/core/soil/SOIL.h
C
gpl-2.0
16,510
33.969499
202
0.718474
false
/* Google HTML5 slides template Authors: Luke Mahé (code) Marcin Wichary (code and design) Dominic Mazzoni (browser compatibility) Charles Chen (ChromeVox support) URL: http://code.google.com/p/html5slides/ */ /* Framework */ html { height: 100%; } body { margin: 0; padding: 0; display: block !important; height: 100%; min-height: 740px; overflow-x: hidden; overflow-y: auto; background: rgb(215, 215, 215); background: -o-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190)); background: -moz-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190)); background: -webkit-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190)); background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 500, from(rgb(240, 240, 240)), to(rgb(190, 190, 190))); -webkit-font-smoothing: antialiased; } .slides { width: 100%; height: 100%; left: 0; top: 0; position: absolute; -webkit-transform: translate3d(0, 0, 0); } .slides > article { display: block; position: absolute; overflow: hidden; width: 900px; height: 700px; left: 50%; top: 50%; margin-left: -450px; margin-top: -350px; padding: 40px 60px; box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; border-radius: 10px; -o-border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; background-color: white; box-shadow: 0 2px 6px rgba(0, 0, 0, .1); border: 1px solid rgba(0, 0, 0, .3); transition: transform .3s ease-out; -o-transition: -o-transform .3s ease-out; -moz-transition: -moz-transform .3s ease-out; -webkit-transition: -webkit-transform .3s ease-out; } .slides.layout-widescreen > article { margin-left: -550px; width: 1100px; } .slides.layout-faux-widescreen > article { margin-left: -550px; width: 1100px; padding: 40px 160px; } .slides.template-default > article:not(.nobackground):not(.biglogo) { background: url(images/google-logo-small.jpg) 710px 625px no-repeat; background-color: white; } .slides.template-io2011 > article:not(.nobackground):not(.biglogo) { background: url(images/colorbar.png) 0 600px repeat-x, url(images/googleio-logo.jpg) 640px 625px no-repeat; background-size: 100%, 225px; background-color: white; } .slides.layout-widescreen > article:not(.nobackground):not(.biglogo), .slides.layout-faux-widescreen > article:not(.nobackground):not(.biglogo) { background-position-x: 0, 840px; } /* Clickable/tappable areas */ .slide-area { z-index: 1000; position: absolute; left: 0; top: 0; width: 150px; height: 700px; left: 50%; top: 50%; cursor: pointer; margin-top: -350px; tap-highlight-color: transparent; -o-tap-highlight-color: transparent; -moz-tap-highlight-color: transparent; -webkit-tap-highlight-color: transparent; } #prev-slide-area { margin-left: -550px; } #next-slide-area { margin-left: 400px; } .slides.layout-widescreen #prev-slide-area, .slides.layout-faux-widescreen #prev-slide-area { margin-left: -650px; } .slides.layout-widescreen #next-slide-area, .slides.layout-faux-widescreen #next-slide-area { margin-left: 500px; } /* Slide styles */ .slides.template-default article.biglogo { background: white url(images/google-logo.jpg) 50% 50% no-repeat; } .slides.template-io2011 article.biglogo { background: white url(images/googleio-logo.jpg) 50% 50% no-repeat; background-size: 600px; } /* Slides */ .slides > article { display: none; } .slides > article.far-past { display: block; transform: translate(-2040px); -o-transform: translate(-2040px); -moz-transform: translate(-2040px); -webkit-transform: translate3d(-2040px, 0, 0); } .slides > article.past { display: block; transform: translate(-1020px); -o-transform: translate(-1020px); -moz-transform: translate(-1020px); -webkit-transform: translate3d(-1020px, 0, 0); } .slides > article.current { display: block; transform: translate(0); -o-transform: translate(0); -moz-transform: translate(0); -webkit-transform: translate3d(0, 0, 0); } .slides > article.next { display: block; transform: translate(1020px); -o-transform: translate(1020px); -moz-transform: translate(1020px); -webkit-transform: translate3d(1020px, 0, 0); } .slides > article.far-next { display: block; transform: translate(2040px); -o-transform: translate(2040px); -moz-transform: translate(2040px); -webkit-transform: translate3d(2040px, 0, 0); } .slides.layout-widescreen > article.far-past, .slides.layout-faux-widescreen > article.far-past { display: block; transform: translate(-2260px); -o-transform: translate(-2260px); -moz-transform: translate(-2260px); -webkit-transform: translate3d(-2260px, 0, 0); } .slides.layout-widescreen > article.past, .slides.layout-faux-widescreen > article.past { display: block; transform: translate(-1130px); -o-transform: translate(-1130px); -moz-transform: translate(-1130px); -webkit-transform: translate3d(-1130px, 0, 0); } .slides.layout-widescreen > article.current, .slides.layout-faux-widescreen > article.current { display: block; transform: translate(0); -o-transform: translate(0); -moz-transform: translate(0); -webkit-transform: translate3d(0, 0, 0); } .slides.layout-widescreen > article.next, .slides.layout-faux-widescreen > article.next { display: block; transform: translate(1130px); -o-transform: translate(1130px); -moz-transform: translate(1130px); -webkit-transform: translate3d(1130px, 0, 0); } .slides.layout-widescreen > article.far-next, .slides.layout-faux-widescreen > article.far-next { display: block; transform: translate(2260px); -o-transform: translate(2260px); -moz-transform: translate(2260px); -webkit-transform: translate3d(2260px, 0, 0); } /* Styles for slides */ .slides > article { font-family: 'Open Sans', Arial, sans-serif; color: rgb(102, 102, 102); text-shadow: 0 1px 1px rgba(0, 0, 0, .1); font-size: 30px; line-height: 36px; letter-spacing: -1px; } b { font-weight: 600; } .blue { color: rgb(0, 102, 204); } .yellow { color: rgb(255, 211, 25); } .green { color: rgb(0, 138, 53); } .red { color: rgb(255, 0, 0); } .black { color: black; } .white { color: white; } a { color: rgb(0, 102, 204); } a:visited { color: rgba(0, 102, 204, .75); } a:hover { color: black; } p { margin: 0; padding: 0; margin-top: 20px; } p:first-child { margin-top: 0; } h1 { font-size: 60px; line-height: 60px; padding: 0; margin: 0; margin-top: 200px; padding-right: 40px; font-weight: 600; letter-spacing: -3px; color: rgb(51, 51, 51); } h2 { font-size: 45px; line-height: 45px; position: absolute; bottom: 150px; padding: 0; margin: 0; padding-right: 40px; font-weight: 600; letter-spacing: -2px; color: rgb(51, 51, 51); } h3 { font-size: 30px; line-height: 36px; padding: 0; margin: 0; padding-right: 40px; font-weight: 600; letter-spacing: -1px; color: rgb(51, 51, 51); } article.fill h3 { background: rgba(0, 0, 0, .35); padding-top: .2em; padding-bottom: .3em; margin-top: -.2em; margin-left: -60px; padding-left: 60px; margin-right: -60px; padding-right: 60px; } ul { list-style: none; margin: 0; padding: 0; margin-top: 40px; margin-left: .75em; } ul:first-child { margin-top: 0; } ul ul { margin-top: .5em; } li { padding: 0; margin: 0; margin-bottom: .5em; } li::before { content: '·'; width: .75em; margin-left: -.75em; position: absolute; } pre { font-family: 'Droid Sans Mono', 'Courier New', monospace; font-size: 20px; line-height: 28px; padding: 5px 10px; letter-spacing: -1px; margin-top: 40px; margin-bottom: 40px; color: black; background: rgb(240, 240, 240); border: 1px solid rgb(224, 224, 224); box-shadow: inset 0 2px 6px rgba(0, 0, 0, .1); overflow: hidden; } code { font-size: 95%; font-family: 'Droid Sans Mono', 'Courier New', monospace; color: black; } iframe { width: 100%; height: 620px; background: white; border: 1px solid rgb(192, 192, 192); margin: -1px; /*box-shadow: inset 0 2px 6px rgba(0, 0, 0, .1);*/ } h3 + iframe { margin-top: 40px; height: 540px; } article.fill iframe { position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 0; margin: 0; border-radius: 10px; -o-border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; z-index: -1; } article.fill img { position: absolute; left: 0; top: 0; min-width: 100%; min-height: 100%; border-radius: 10px; -o-border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; z-index: -1; } img.centered { margin: 0 auto; display: block; } table { width: 100%; border-collapse: collapse; margin-top: 40px; } th { font-weight: 600; text-align: left; } td, th { border: 1px solid rgb(224, 224, 224); padding: 5px 10px; vertical-align: top; } .source { position: absolute; left: 60px; top: 644px; padding-right: 175px; font-size: 15px; letter-spacing: 0; line-height: 18px; } q { display: block; font-size: 60px; line-height: 72px; margin-left: 20px; margin-top: 100px; margin-right: 150px; } q::before { content: '“'; position: absolute; display: inline-block; margin-left: -2.1em; width: 2em; text-align: right; font-size: 90px; color: rgb(192, 192, 192); } q::after { content: '”'; position: absolute; margin-left: .1em; font-size: 90px; color: rgb(192, 192, 192); } div.author { text-align: right; font-size: 40px; margin-top: 20px; margin-right: 150px; } div.author::before { content: '—'; } /* Size variants */ article.smaller p, article.smaller ul { font-size: 20px; line-height: 24px; letter-spacing: 0; } article.smaller table { font-size: 20px; line-height: 24px; letter-spacing: 0; } article.smaller pre { font-size: 15px; line-height: 20px; letter-spacing: 0; } article.smaller q { font-size: 40px; line-height: 48px; } article.smaller q::before, article.smaller q::after { font-size: 60px; } /* Builds */ .build > * { transition: opacity 0.5s ease-in-out 0.2s; -o-transition: opacity 0.5s ease-in-out 0.2s; -moz-transition: opacity 0.5s ease-in-out 0.2s; -webkit-transition: opacity 0.5s ease-in-out 0.2s; } .to-build { opacity: 0; } /* Pretty print */ .prettyprint .str, /* string content */ .prettyprint .atv { /* a markup attribute value */ color: rgb(0, 138, 53); } .prettyprint .kwd, /* a keyword */ .prettyprint .tag { /* a markup tag name */ color: rgb(0, 102, 204); } .prettyprint .com { /* a comment */ color: rgb(127, 127, 127); font-style: italic; } .prettyprint .lit { /* a literal value */ color: rgb(127, 0, 0); } .prettyprint .pun, /* punctuation, lisp open bracket, lisp close bracket */ .prettyprint .opn, .prettyprint .clo { color: rgb(127, 127, 127); } .prettyprint .typ, /* a type name */ .prettyprint .atn, /* a markup attribute name */ .prettyprint .dec, .prettyprint .var { /* a declaration; a variable name */ color: rgb(127, 0, 127); } .mylogo{ width: 200px; height: 80px; background: white; position: absolute; bottom: 0; right: 0; }
Urinx/Web.Page
Demo/ppt3.0/Presentation.google_files/styles.css
CSS
gpl-2.0
11,441
17.441935
115
0.649173
false
/* Linux PINMUX.C */ #include <asm/arch/am_regs.h> #include <asm/arch/am_eth_reg.h> #include <asm/arch/pinmux.h> int clear_mio_mux(unsigned mux_index, unsigned mux_mask) { unsigned mux_reg[] = {PERIPHS_PIN_MUX_0, PERIPHS_PIN_MUX_1, PERIPHS_PIN_MUX_2,PERIPHS_PIN_MUX_3, PERIPHS_PIN_MUX_4,PERIPHS_PIN_MUX_5,PERIPHS_PIN_MUX_6,PERIPHS_PIN_MUX_7,PERIPHS_PIN_MUX_8, PERIPHS_PIN_MUX_9,PERIPHS_PIN_MUX_10,PERIPHS_PIN_MUX_11,PERIPHS_PIN_MUX_12}; if (mux_index < 13) { CLEAR_CBUS_REG_MASK(mux_reg[mux_index], mux_mask); return 0; } return -1; } int set_mio_mux(unsigned mux_index, unsigned mux_mask) { unsigned mux_reg[] = {PERIPHS_PIN_MUX_0, PERIPHS_PIN_MUX_1, PERIPHS_PIN_MUX_2,PERIPHS_PIN_MUX_3, PERIPHS_PIN_MUX_4,PERIPHS_PIN_MUX_5,PERIPHS_PIN_MUX_6,PERIPHS_PIN_MUX_7,PERIPHS_PIN_MUX_8, PERIPHS_PIN_MUX_9,PERIPHS_PIN_MUX_10,PERIPHS_PIN_MUX_11,PERIPHS_PIN_MUX_12}; if (mux_index < 13) { SET_CBUS_REG_MASK(mux_reg[mux_index], mux_mask); return 0; } return -1; } /* call it before pinmux init; call it before soft reset; */ void clearall_pinmux(void) { int i; for(i=0;i<13;i++) clear_mio_mux(i,0xffffffff); return; } /*ETH PINMUX SETTING More details can get from am_eth_pinmux.h */ int eth_set_pinmux(int bank_id,int clk_in_out_id,unsigned long ext_msk) { int ret=0; switch(bank_id) { case ETH_BANK0_GPIOX46_X54: if(ext_msk>0) set_mio_mux(ETH_BANK0_REG1,ext_msk); else set_mio_mux(ETH_BANK0_REG1,ETH_BANK0_REG1_VAL); break; case ETH_BANK1_GPIOX59_X67: if(ext_msk>0) set_mio_mux(ETH_BANK1_REG1,ext_msk); else set_mio_mux(ETH_BANK1_REG1,ETH_BANK1_REG1_VAL); break; default: printf("UNknow pinmux setting of ethernet!error bankid=%d,must be 0-2\n",bank_id); ret=-1; } switch(clk_in_out_id) { case ETH_CLK_IN_GPIOX45_REG3_11: set_mio_mux(3,1<<11); break; case ETH_CLK_IN_GPIOX55_REG3_0: set_mio_mux(3,1); break; case ETH_CLK_IN_GPIOX58_REG3_24: set_mio_mux(3,1<<24); break; case ETH_CLK_IN_GPIOX68_REG3_13: set_mio_mux(3,1<<13); break; case ETH_CLK_OUT_GPIOX45_REG3_12: set_mio_mux(3,1<<12); break; case ETH_CLK_OUT_GPIOX55_REG3_1: set_mio_mux(3,1<<1); break; case ETH_CLK_OUT_GPIOX58_REG3_25: set_mio_mux(3,1<<25); break; case ETH_CLK_OUT_GPIOX68_REG3_14: set_mio_mux(3,1<<14); break; default: printf("UNknow clk_in_out_id setting of ethernet!error clk_in_out_id=%d,must be 0-7\n",clk_in_out_id); ret=-1; } return ret; }
bogdanov-d-a/Amlogic-reff16-uboot
arch/arm/cpu/aml_meson/m2/pinmux.c
C
gpl-2.0
2,559
24.336634
106
0.644002
false
<?php /** * @version $Id: helper.php 20228 2011-01-10 00:52:54Z eddieajau $ * @package Joomla.Site * @subpackage mod_stats * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; /** * @package Joomla.Site * @subpackage mod_stats * @since 1.5 */ class modStatsHelper { static function &getList(&$params) { $app = JFactory::getApplication(); $db = JFactory::getDbo(); $rows = array(); $query = $db->getQuery(true); $serverinfo = $params->get('serverinfo'); $siteinfo = $params->get('siteinfo'); $counter = $params->get('counter'); $increase = $params->get('increase'); $i = 0; if ($serverinfo) { $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_OS'); $rows[$i]->data = substr(php_uname(), 0, 7); $i++; $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_PHP'); $rows[$i]->data = phpversion(); $i++; $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_MYSQL'); $rows[$i]->data = $db->getVersion(); $i++; $rows[$i] = new stdClass; $rows[$i]->title = JTEXT::_('MOD_STATS_TIME'); $rows[$i]->data = JHTML::_('date','now', 'H:i'); $i++; $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_CACHING'); $rows[$i]->data = $app->getCfg('caching') ? JText::_('JENABLED'):JText::_('JDISABLED'); $i++; $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_GZIP'); $rows[$i]->data = $app->getCfg('gzip') ? JText::_('JENABLED'):JText::_('JDISABLED'); $i++; } if ($siteinfo) { $query->select('COUNT(id) AS count_users'); $query->from('#__users'); $db->setQuery($query); $users = $db->loadResult(); $query->clear(); $query->select('COUNT(id) AS count_items'); $query->from('#__content'); $query->where('state = 1'); $db->setQuery($query); $items = $db->loadResult(); $query->clear(); $query->select('COUNT(id) AS count_links '); $query->from('#__weblinks'); $query->where('state = 1'); $db->setQuery($query); $links = $db->loadResult(); if ($users) { $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_USERS'); $rows[$i]->data = $users; $i++; } if ($items) { $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_ARTICLES'); $rows[$i]->data = $items; $i++; } if ($links) { $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_WEBLINKS'); $rows[$i]->data = $links; $i++; } } if ($counter) { $query->clear(); $query->select('SUM(hits) AS count_hits'); $query->from('#__content'); $query->where('state = 1'); $db->setQuery($query); $hits = $db->loadResult(); if ($hits) { $rows[$i] = new stdClass; $rows[$i]->title = JText::_('MOD_STATS_ARTICLES_VIEW_HITS'); $rows[$i]->data = $hits + $increase; $i++; } } return $rows; } }
emelynelisboa/studiosummo
modules/mod_stats/helper.php
PHP
gpl-2.0
3,177
23.432
90
0.525024
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:26:30 PST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.handler.component.HttpShardHandler (Solr 5.0.0 API)</title> <meta name="date" content="2015-02-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.handler.component.HttpShardHandler (Solr 5.0.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/component/HttpShardHandler.html" title="class in org.apache.solr.handler.component">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/HttpShardHandler.html" target="_top">Frames</a></li> <li><a href="HttpShardHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.handler.component.HttpShardHandler" class="title">Uses of Class<br>org.apache.solr.handler.component.HttpShardHandler</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.handler.component.HttpShardHandler</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/component/HttpShardHandler.html" title="class in org.apache.solr.handler.component">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/HttpShardHandler.html" target="_top">Frames</a></li> <li><a href="HttpShardHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
annieweng/solr_example
solr-5.0.0/docs/solr-core/org/apache/solr/handler/component/class-use/HttpShardHandler.html
HTML
gpl-2.0
4,943
36.732824
163
0.599434
false
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2002 by Alan Korr * * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "config.h" #include "hwcompat.h" #include "kernel.h" #include "lcd.h" #include "system.h" /*** definitions ***/ #define LCD_SET_LOWER_COLUMN_ADDRESS ((char)0x00) #define LCD_SET_HIGHER_COLUMN_ADDRESS ((char)0x10) #define LCD_SET_INTERNAL_REGULATOR_RESISTOR_RATIO ((char)0x20) #define LCD_SET_POWER_CONTROL_REGISTER ((char)0x28) #define LCD_SET_DISPLAY_START_LINE ((char)0x40) #define LCD_SET_CONTRAST_CONTROL_REGISTER ((char)0x81) #define LCD_SET_SEGMENT_REMAP ((char)0xA0) #define LCD_SET_LCD_BIAS ((char)0xA2) #define LCD_SET_ENTIRE_DISPLAY_OFF ((char)0xA4) #define LCD_SET_ENTIRE_DISPLAY_ON ((char)0xA5) #define LCD_SET_NORMAL_DISPLAY ((char)0xA6) #define LCD_SET_REVERSE_DISPLAY ((char)0xA7) #define LCD_SET_MULTIPLEX_RATIO ((char)0xA8) #define LCD_SET_BIAS_TC_OSC ((char)0xA9) #define LCD_SET_1OVER4_BIAS_RATIO ((char)0xAA) #define LCD_SET_INDICATOR_OFF ((char)0xAC) #define LCD_SET_INDICATOR_ON ((char)0xAD) #define LCD_SET_DISPLAY_OFF ((char)0xAE) #define LCD_SET_DISPLAY_ON ((char)0xAF) #define LCD_SET_PAGE_ADDRESS ((char)0xB0) #define LCD_SET_COM_OUTPUT_SCAN_DIRECTION ((char)0xC0) #define LCD_SET_TOTAL_FRAME_PHASES ((char)0xD2) #define LCD_SET_DISPLAY_OFFSET ((char)0xD3) #define LCD_SET_READ_MODIFY_WRITE_MODE ((char)0xE0) #define LCD_SOFTWARE_RESET ((char)0xE2) #define LCD_NOP ((char)0xE3) #define LCD_SET_END_OF_READ_MODIFY_WRITE_MODE ((char)0xEE) /* LCD command codes */ #define LCD_CNTL_RESET 0xe2 /* Software reset */ #define LCD_CNTL_POWER 0x2f /* Power control */ #define LCD_CNTL_CONTRAST 0x81 /* Contrast */ #define LCD_CNTL_OUTSCAN 0xc8 /* Output scan direction */ #define LCD_CNTL_SEGREMAP 0xa1 /* Segment remap */ #define LCD_CNTL_DISPON 0xaf /* Display on */ #define LCD_CNTL_PAGE 0xb0 /* Page address */ #define LCD_CNTL_HIGHCOL 0x10 /* Upper column address */ #define LCD_CNTL_LOWCOL 0x00 /* Lower column address */ /** globals **/ static int xoffset; /* needed for flip */ /*** hardware configuration ***/ int lcd_default_contrast(void) { return (HW_MASK & LCD_CONTRAST_BIAS) ? 31 : 49; } void lcd_set_contrast(int val) { lcd_write_command(LCD_CNTL_CONTRAST); lcd_write_command(val); } void lcd_set_invert_display(bool yesno) { if (yesno) lcd_write_command(LCD_SET_REVERSE_DISPLAY); else lcd_write_command(LCD_SET_NORMAL_DISPLAY); } /* turn the display upside down (call lcd_update() afterwards) */ void lcd_set_flip(bool yesno) { #ifdef HAVE_DISPLAY_FLIPPED if (!yesno) #else if (yesno) #endif { lcd_write_command(LCD_SET_SEGMENT_REMAP); lcd_write_command(LCD_SET_COM_OUTPUT_SCAN_DIRECTION); xoffset = 132 - LCD_WIDTH; /* 132 colums minus the 112 we have */ } else { lcd_write_command(LCD_SET_SEGMENT_REMAP | 0x01); lcd_write_command(LCD_SET_COM_OUTPUT_SCAN_DIRECTION | 0x08); xoffset = 0; } } void lcd_init_device(void) { /* Initialize PB0-3 as output pins */ PBCR2 &= 0xff00; /* MD = 00 */ PBIOR |= 0x000f; /* IOR = 1 */ /* inits like the original firmware */ lcd_write_command(LCD_SOFTWARE_RESET); lcd_write_command(LCD_SET_INTERNAL_REGULATOR_RESISTOR_RATIO + 4); lcd_write_command(LCD_SET_1OVER4_BIAS_RATIO + 0); /* force 1/4 bias: 0 */ lcd_write_command(LCD_SET_POWER_CONTROL_REGISTER + 7); /* power control register: op-amp=1, regulator=1, booster=1 */ lcd_write_command(LCD_SET_DISPLAY_ON); lcd_write_command(LCD_SET_NORMAL_DISPLAY); lcd_set_flip(false); lcd_write_command(LCD_SET_DISPLAY_START_LINE + 0); lcd_set_contrast(lcd_default_contrast()); lcd_write_command(LCD_SET_PAGE_ADDRESS); lcd_write_command(LCD_SET_LOWER_COLUMN_ADDRESS + 0); lcd_write_command(LCD_SET_HIGHER_COLUMN_ADDRESS + 0); lcd_clear_display(); lcd_update(); } /*** Update functions ***/ /* Performance function that works with an external buffer note that by and bheight are in 8-pixel units! */ void lcd_blit_mono(const unsigned char *data, int x, int by, int width, int bheight, int stride) { /* Copy display bitmap to hardware */ while (bheight--) { lcd_write_command (LCD_CNTL_PAGE | (by++ & 0xf)); lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset)>>4) & 0xf)); lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf)); lcd_write_data(data, width); data += stride; } } /* Helper function for lcd_grey_phase_blit(). */ void lcd_grey_data(unsigned char *values, unsigned char *phases, int count); /* Performance function that works with an external buffer note that by and bheight are in 8-pixel units! */ void lcd_blit_grey_phase(unsigned char *values, unsigned char *phases, int x, int by, int width, int bheight, int stride) { stride <<= 3; /* 8 pixels per block */ while (bheight--) { lcd_write_command (LCD_CNTL_PAGE | (by++ & 0xf)); lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset)>>4) & 0xf)); lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf)); lcd_grey_data(values, phases, width); values += stride; phases += stride; } } /* Update the display. This must be called after all other LCD functions that change the display. */ void lcd_update(void) { int y; /* Copy display bitmap to hardware */ for (y = 0; y < LCD_FBHEIGHT; y++) { lcd_write_command (LCD_CNTL_PAGE | (y & 0xf)); lcd_write_command (LCD_CNTL_HIGHCOL | ((xoffset >> 4) & 0xf)); lcd_write_command (LCD_CNTL_LOWCOL | (xoffset & 0xf)); lcd_write_data (FBADDR(0, y), LCD_WIDTH); } } /* Update a fraction of the display. */ void lcd_update_rect(int x, int y, int width, int height) { int ymax; /* The Y coordinates have to work on even 8 pixel rows */ ymax = (y + height-1) >> 3; y >>= 3; if(x + width > LCD_WIDTH) width = LCD_WIDTH - x; if (width <= 0) return; /* nothing left to do, 0 is harmful to lcd_write_data() */ if(ymax >= LCD_FBHEIGHT) ymax = LCD_FBHEIGHT-1; /* Copy specified rectange bitmap to hardware */ for (; y <= ymax; y++) { lcd_write_command (LCD_CNTL_PAGE | (y & 0xf)); lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset) >> 4) & 0xf)); lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf)); lcd_write_data (FBADDR(x,y), width); } }
renolui/RenoStudio
Player/firmware/target/sh/archos/lcd-archos-bitmap.c
C
gpl-2.0
7,922
34.366071
80
0.561979
false
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pt.jkaiui.core.messages; import java.util.regex.Matcher; import java.util.regex.Pattern; import pt.jkaiui.core.KaiString; import pt.jkaiui.manager.I_InMessage; /** * * @author yuu@akron */ public class ConnectedArena extends Message implements I_InMessage { public ConnectedArena() { } public Message parse(String s) { Pattern p = Pattern.compile("KAI_CLIENT_CONNECTED_ARENA;"); Matcher m = p.matcher(s); if (m.matches()){ ConnectedArena msg = new ConnectedArena(); return msg; } return null; } }
yuuakron/jKaiUI_Custom
src/pt/jkaiui/core/messages/ConnectedArena.java
Java
gpl-2.0
731
21.151515
68
0.614227
false
#ifndef NO_OGL //OpenGL library #pragma comment( lib, "OpenGL32" ) // MFC #include "stdafx.h" //GUI #include "MainWnd.h" #include "FullscreenSettings.h" // Internals #include "../System.h" #include "../gba/GBA.h" #include "../gba/Globals.h" #include "../Util.h" #include "../gb/gbGlobals.h" #include "../common/memgzio.h" //Math #include <cmath> #include <sys/stat.h> // OpenGL #include <gl/GL.h> // main include file #include <GL/glu.h> #include "glFont.h" #include <gl/glext.h> typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)( int ); extern int Init_2xSaI(u32); extern void winlog(const char *,...); extern int systemSpeed; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef MMX extern "C" bool cpu_mmx; extern bool detectMMX(); #endif class OpenGLDisplay : public IDisplay { private: HDC hDC; HGLRC hRC; GLuint texture; int width,height; float size; u8 *filterData; RECT destRect; bool failed; GLFONT font; int pitch; u8 *data; DWORD currentAdapter; void initializeMatrices( int w, int h ); bool initializeTexture( int w, int h ); void updateFiltering( int value ); void setVSync( int interval = 1 ); void calculateDestRect( int w, int h ); void initializeFont(); public: OpenGLDisplay(); virtual ~OpenGLDisplay(); virtual DISPLAY_TYPE getType() { return OPENGL; }; virtual void EnableOpenGL(); virtual void DisableOpenGL(); virtual bool initialize(); virtual void cleanup(); virtual void clear(); virtual void render(); virtual bool changeRenderSize( int w, int h ); virtual void resize( int w, int h ); virtual void setOption( const char *, int ); virtual bool selectFullScreenMode( VIDEO_MODE &mode ); }; #include "gzglfont.h" //Load GL font void OpenGLDisplay::initializeFont() { int ret; z_stream strm; char *buf = (char *)malloc(GZGLFONT_SIZE); /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit2(&strm, 16+MAX_WBITS); if (ret != Z_OK) return; strm.avail_in = sizeof(gzglfont); strm.next_in = gzglfont; strm.avail_out = GZGLFONT_SIZE; strm.next_out = (Bytef *)buf; ret = inflate(&strm, Z_NO_FLUSH); if (ret==Z_STREAM_END) { glGenTextures( 1, &texture ); glFontCreate(&font, (char *)buf, texture); texture=0; } free(buf); (void)inflateEnd(&strm); } //OpenGL class constructor OpenGLDisplay::OpenGLDisplay() { hDC = NULL; hRC = NULL; texture = 0; width = 0; height = 0; size = 0.0f; failed = false; filterData = NULL; currentAdapter = 0; } //OpenGL class destroyer OpenGLDisplay::~OpenGLDisplay() { cleanup(); } //Set OpenGL PFD and contexts void OpenGLDisplay::EnableOpenGL() { PIXELFORMATDESCRIPTOR pfd; // get the device context (DC) hDC = GetDC( theApp.m_pMainWnd->GetSafeHwnd() ); // set the pixel format for the DC ZeroMemory( &pfd, sizeof( pfd ) ); pfd.nSize = sizeof( pfd ); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; SetPixelFormat (GetDC (theApp.m_pMainWnd->GetSafeHwnd()), ChoosePixelFormat ( GetDC (theApp.m_pMainWnd->GetSafeHwnd()), &pfd), &pfd); wglMakeCurrent (GetDC (theApp.m_pMainWnd->GetSafeHwnd()), wglCreateContext(GetDC (theApp.m_pMainWnd->GetSafeHwnd()) ) ); } //Remove contexts void OpenGLDisplay::DisableOpenGL() { wglMakeCurrent( NULL, NULL ); wglDeleteContext( hRC ); ReleaseDC( theApp.m_pMainWnd->GetSafeHwnd(), hDC ); } //Remove resources used void OpenGLDisplay::cleanup() { if(texture != 0) { glDeleteTextures(1, &texture); texture = 0; } DisableOpenGL(); if(filterData) { free(filterData); filterData = NULL; } width = 0; height = 0; size = 0.0f; DISPLAY_DEVICE dev; ZeroMemory( &dev, sizeof(dev) ); dev.cb = sizeof(dev); EnumDisplayDevices( NULL, currentAdapter, &dev, 0 ); // restore default video mode ChangeDisplaySettingsEx( dev.DeviceName, NULL, NULL, 0, NULL ); } //init renderer bool OpenGLDisplay::initialize() { switch( theApp.cartridgeType ) { case IMAGE_GBA: theApp.sizeX = 240; theApp.sizeY = 160; break; case IMAGE_GB: if ( gbBorderOn ) { theApp.sizeX = 256; theApp.sizeY = 224; } else { theApp.sizeX = 160; theApp.sizeY = 144; } break; } switch(theApp.videoOption) { case VIDEO_1X: theApp.surfaceSizeX = theApp.sizeX; theApp.surfaceSizeY = theApp.sizeY; break; case VIDEO_2X: theApp.surfaceSizeX = theApp.sizeX * 2; theApp.surfaceSizeY = theApp.sizeY * 2; break; case VIDEO_3X: theApp.surfaceSizeX = theApp.sizeX * 3; theApp.surfaceSizeY = theApp.sizeY * 3; break; case VIDEO_4X: theApp.surfaceSizeX = theApp.sizeX * 4; theApp.surfaceSizeY = theApp.sizeY * 4; break; case VIDEO_5X: theApp.surfaceSizeX = theApp.sizeX * 5; theApp.surfaceSizeY = theApp.sizeY * 5; break; case VIDEO_6X: theApp.surfaceSizeX = theApp.sizeX * 6; theApp.surfaceSizeY = theApp.sizeY * 6; break; case VIDEO_320x240: case VIDEO_640x480: case VIDEO_800x600: case VIDEO_1024x768: case VIDEO_1280x1024: case VIDEO_OTHER: { if( theApp.fullScreenStretch ) { theApp.surfaceSizeX = theApp.fsWidth; theApp.surfaceSizeY = theApp.fsHeight; } else { float scaleX = (float)theApp.fsWidth / (float)theApp.sizeX; float scaleY = (float)theApp.fsHeight / (float)theApp.sizeY; float min = ( scaleX < scaleY ) ? scaleX : scaleY; if( theApp.maxScale ) min = ( min > (float)theApp.maxScale ) ? (float)theApp.maxScale : min; theApp.surfaceSizeX = (int)((float)theApp.sizeX * min); theApp.surfaceSizeY = (int)((float)theApp.sizeY * min); } } break; } theApp.rect.left = 0; theApp.rect.top = 0; theApp.rect.right = theApp.sizeX; theApp.rect.bottom = theApp.sizeY; theApp.dest.left = 0; theApp.dest.top = 0; theApp.dest.right = theApp.surfaceSizeX; theApp.dest.bottom = theApp.surfaceSizeY; DWORD style = WS_POPUP | WS_VISIBLE; DWORD styleEx = 0; if( theApp.videoOption <= VIDEO_6X ) style |= WS_OVERLAPPEDWINDOW; else styleEx = 0; if( theApp.videoOption <= VIDEO_6X ) AdjustWindowRectEx( &theApp.dest, style, TRUE, styleEx ); else AdjustWindowRectEx( &theApp.dest, style, FALSE, styleEx ); int winSizeX = theApp.dest.right - theApp.dest.left; int winSizeY = theApp.dest.bottom - theApp.dest.top; int x = 0, y = 0; if( theApp.videoOption <= VIDEO_6X ) { x = theApp.windowPositionX; y = theApp.windowPositionY; } else { winSizeX = theApp.fsWidth; winSizeY = theApp.fsHeight; } theApp.updateMenuBar(); theApp.adjustDestRect(); currentAdapter = theApp.fsAdapter; DISPLAY_DEVICE dev; ZeroMemory( &dev, sizeof(dev) ); dev.cb = sizeof(dev); EnumDisplayDevices( NULL, currentAdapter, &dev, 0 ); if( theApp.videoOption >= VIDEO_320x240 ) { // enter full screen mode DEVMODE mode; ZeroMemory( &mode, sizeof(mode) ); mode.dmSize = sizeof(mode); mode.dmBitsPerPel = theApp.fsColorDepth; mode.dmPelsWidth = theApp.fsWidth; mode.dmPelsHeight = theApp.fsHeight; mode.dmDisplayFrequency = theApp.fsFrequency; mode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY; LONG ret = ChangeDisplaySettingsEx( dev.DeviceName, &mode, NULL, CDS_FULLSCREEN, NULL ); if( ret != DISP_CHANGE_SUCCESSFUL ) { systemMessage( 0, "Can not change display mode!" ); failed = true; } } else { // restore default mode ChangeDisplaySettingsEx( dev.DeviceName, NULL, NULL, 0, NULL ); } EnableOpenGL(); initializeFont(); glPushAttrib( GL_ENABLE_BIT ); glDisable( GL_DEPTH_TEST ); glDisable( GL_CULL_FACE ); glEnable( GL_TEXTURE_2D ); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); initializeMatrices( theApp.surfaceSizeX, theApp.surfaceSizeY ); setVSync( theApp.vsync ); #ifdef MMX if(!theApp.disableMMX) cpu_mmx = theApp.detectMMX(); else cpu_mmx = 0; #endif systemRedShift = 3; systemGreenShift = 11; systemBlueShift = 19; systemColorDepth = 32; theApp.fsColorDepth = 32; Init_2xSaI(32); utilUpdateSystemColorMaps(theApp.cartridgeType == IMAGE_GBA && gbColorOption == 1); theApp.updateFilter(); theApp.updateIFB(); pitch = theApp.filterWidth * (systemColorDepth>>3) + 4; data = pix + ( theApp.sizeX + 1 ) * 4; if(failed) return false; return true; } //clear colour buffer void OpenGLDisplay::clear() { glClearColor(0.0,0.0,0.0,1.0); glClear( GL_COLOR_BUFFER_BIT ); } //main render func void OpenGLDisplay::render() { clear(); pitch = theApp.filterWidth * (systemColorDepth>>3) + 4; data = pix + ( theApp.sizeX + 1 ) * 4; // apply pixel filter if(theApp.filterFunction) { data = filterData; theApp.filterFunction( pix + pitch, pitch, (u8*)theApp.delta, (u8*)filterData, width * 4 , theApp.filterWidth, theApp.filterHeight); } // Texturemap complete texture to surface // so we have free scaling and antialiasing if( theApp.filterFunction ) { glPixelStorei( GL_UNPACK_ROW_LENGTH, width); } else { glPixelStorei( GL_UNPACK_ROW_LENGTH, theApp.sizeX + 1 ); } glTexSubImage2D(GL_TEXTURE_2D,0,0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,data ); glBegin( GL_QUADS ); glTexCoord2f( 0.0f, 0.0f ); glVertex3i( 0, 0, 0 ); glTexCoord2f( (float)(width) / size, 0.0f ); glVertex3i( theApp.surfaceSizeX, 0, 0 ); glTexCoord2f( (float)(width) / size, (float)(height) / size ); glVertex3i( theApp.surfaceSizeX, theApp.surfaceSizeY, 0 ); glTexCoord2f( 0.0f, (float)(height) / size ); glVertex3i( 0, theApp.surfaceSizeY, 0 ); glEnd(); if( theApp.showSpeed ) { // && ( theApp.videoOption > VIDEO_6X ) ) { char buffer[30]; if( theApp.showSpeed == 1 ) { sprintf( buffer, "%3d%%", systemSpeed ); } else { sprintf( buffer, "%3d%%(%d, %d fps)", systemSpeed, systemFrameSkip, theApp.showRenderedFrames ); } glFontBegin(&font); glPushMatrix(); float fontscale = (float)theApp.surfaceSizeX / 100.0f; glScalef(fontscale, fontscale, fontscale); glColor4f(1.0f, 0.25f, 0.25f, 1.0f); glFontTextOut(buffer, (theApp.surfaceSizeX-(strlen(buffer)*11))/(fontscale*2), (theApp.surfaceSizeY-20)/fontscale, 0); glPopMatrix(); glFontEnd(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBindTexture( GL_TEXTURE_2D, texture ); } if( theApp.screenMessage ) { if( ( ( GetTickCount() - theApp.screenMessageTime ) < 3000 ) && !theApp.disableStatusMessage ) { glFontBegin(&font); glPushMatrix(); float fontscale = (float)theApp.surfaceSizeX / 100.0f; glScalef(fontscale, fontscale, fontscale); glColor4f(1.0f, 0.25f, 0.25f, 1.0f); glFontTextOut((char *)((const char *)theApp.screenMessageBuffer), (theApp.surfaceSizeX-(theApp.screenMessageBuffer.GetLength()*11))/(fontscale*2), (theApp.surfaceSizeY-40)/fontscale, 0); glPopMatrix(); glFontEnd(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBindTexture( GL_TEXTURE_2D, texture ); } else { theApp.screenMessage = false; } } glFlush(); SwapBuffers( hDC ); // since OpenGL draws on the back buffer, // we have to swap it to the front buffer to see the content } //resize screen void OpenGLDisplay::resize( int w, int h ) { initializeMatrices( w, h ); } //update filtering methods void OpenGLDisplay::updateFiltering( int value ) { switch( value ) { case 0: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); break; case 1: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ); } //init projection matrixes and viewports void OpenGLDisplay::initializeMatrices( int w, int h ) { if( theApp.fullScreenStretch ) { glViewport( 0, 0, w, h ); } else { calculateDestRect( w, h ); glViewport( destRect.left, destRect.top, destRect.right - destRect.left, destRect.bottom - destRect.top ); } glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( /* left */ 1.0f, /* right */ (GLdouble)(w - 1), /* bottom */ (GLdouble)(h - 1), /* top */ 1.0f, 0.0f, 1.0f ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } //init font texture bool OpenGLDisplay::initializeTexture( int w, int h ) { // size = 2^n // w = 24 > size = 256 = 2^8 // w = 255 > size = 256 = 2^8 // w = 256 > size = 512 = 2^9 // w = 300 > size = 512 = 2^9 // OpenGL textures have to be square and a power of 2 // We could use methods that allow tex's to not be powers of two // but that requires extra OGL extensions float n1 = log10( (float)w ) / log10( 2.0f ); float n2 = log10( (float)h ) / log10( 2.0f ); float n = ( n1 > n2 ) ? n1 : n2; if( ((float)((int)n)) != n ) { // round up n = ((float)((int)n)) + 1.0f; } size = pow( 2.0f, n ); glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); updateFiltering( theApp.glFilter ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)size, (GLsizei)size, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); width = w; height = h; //return ( glGetError() == GL_NO_ERROR) ? true : false; // Workaround: We usually get GL_INVALID_VALUE, but somehow it works nevertheless // In consequence, we must not treat it as an error or else the app behaves as if an error occured. // This in the end results in theApp->input not being created = no input when switching from D3D to OGL return true; } //turn vsync on or off void OpenGLDisplay::setVSync( int interval ) { const char *extensions = (const char *)glGetString( GL_EXTENSIONS ); if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) { winlog( "Error: WGL_EXT_swap_control extension not supported on your computer.\n" ); return; } else { PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = NULL; wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); if( wglSwapIntervalEXT ) { wglSwapIntervalEXT( interval ); } } } //change render size for fonts and filter data bool OpenGLDisplay::changeRenderSize( int w, int h ) { if( (width != w) || (height != h) ) { if( texture != 0 ) { glDeleteTextures( 1, &texture ); texture = 0; } if( !initializeTexture( w, h ) ) { failed = true; return false; } if (filterData) free(filterData); filterData = (u8 *)malloc(4*w*h); } return true; } //calculate RECTs void OpenGLDisplay::calculateDestRect( int w, int h ) { float scaleX = (float)w / (float)width; float scaleY = (float)h / (float)height; float min = (scaleX < scaleY) ? scaleX : scaleY; if( theApp.maxScale && (min > theApp.maxScale) ) { min = (float)theApp.maxScale; } destRect.left = 0; destRect.top = 0; destRect.right = (LONG)(width * min); destRect.bottom = (LONG)(height * min); if( destRect.right != w ) { LONG diff = (w - destRect.right) / 2; destRect.left += diff; destRect.right += diff; } if( destRect.bottom != h ) { LONG diff = (h - destRect.bottom) / 2; destRect.top += diff; destRect.bottom += diff; } } //config options void OpenGLDisplay::setOption( const char *option, int value ) { if( !_tcscmp( option, _T("vsync") ) ) { setVSync( value ); } if( !_tcscmp( option, _T("glFilter") ) ) { updateFiltering( value ); } if( !_tcscmp( option, _T("maxScale") ) ) { initializeMatrices( theApp.dest.right-theApp.dest.left, theApp.dest.bottom-theApp.dest.top ); } if( !_tcscmp( option, _T("fullScreenStretch") ) ) { initializeMatrices( theApp.dest.right-theApp.dest.left, theApp.dest.bottom-theApp.dest.top ); } } //set fullscreen mode bool OpenGLDisplay::selectFullScreenMode( VIDEO_MODE &mode ) { FullscreenSettings dlg; dlg.setAPI( this->getType() ); INT_PTR ret = dlg.DoModal(); if( ret == IDOK ) { mode.adapter = dlg.m_device; switch( dlg.m_colorDepth ) { case 30: // TODO: support return false; break; case 24: mode.bitDepth = 32; break; case 16: case 15: mode.bitDepth = 16; break; } mode.width = dlg.m_width; mode.height = dlg.m_height; mode.frequency = dlg.m_refreshRate; return true; } else { return false; } } IDisplay *newOpenGLDisplay() { return new OpenGLDisplay(); } #endif // #ifndef NO_OGL
wowzaman12/vba
trunk/src/win32/OpenGL.cpp
C++
gpl-2.0
16,390
22.788099
189
0.673337
false
/* asn.h * * Copyright (C) 2006-2016 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL 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-1335, USA */ #ifndef WOLF_CRYPT_ASN_H #define WOLF_CRYPT_ASN_H #include <wolfssl/wolfcrypt/types.h> #ifndef NO_ASN #include <wolfssl/wolfcrypt/integer.h> #ifndef NO_RSA #include <wolfssl/wolfcrypt/rsa.h> #endif /* fips declare of RsaPrivateKeyDecode @wc_fips */ #if defined(HAVE_FIPS) && !defined(NO_RSA) #include <cyassl/ctaocrypt/rsa.h> #endif #ifndef NO_DH #include <wolfssl/wolfcrypt/dh.h> #endif #ifndef NO_DSA #include <wolfssl/wolfcrypt/dsa.h> #endif #ifndef NO_SHA #include <wolfssl/wolfcrypt/sha.h> #endif #ifndef NO_MD5 #include <wolfssl/wolfcrypt/md5.h> #endif #include <wolfssl/wolfcrypt/sha256.h> #include <wolfssl/wolfcrypt/asn_public.h> /* public interface */ #ifdef HAVE_ECC #include <wolfssl/wolfcrypt/ecc.h> #endif #ifdef __cplusplus extern "C" { #endif enum { ISSUER = 0, SUBJECT = 1, EXTERNAL_SERIAL_SIZE = 32, BEFORE = 0, AFTER = 1 }; /* ASN Tags */ enum ASN_Tags { ASN_BOOLEAN = 0x01, ASN_INTEGER = 0x02, ASN_BIT_STRING = 0x03, ASN_OCTET_STRING = 0x04, ASN_TAG_NULL = 0x05, ASN_OBJECT_ID = 0x06, ASN_ENUMERATED = 0x0a, ASN_UTF8STRING = 0x0c, ASN_SEQUENCE = 0x10, ASN_SET = 0x11, ASN_UTC_TIME = 0x17, ASN_OTHER_TYPE = 0x00, ASN_RFC822_TYPE = 0x01, ASN_DNS_TYPE = 0x02, ASN_DIR_TYPE = 0x04, ASN_GENERALIZED_TIME = 0x18, CRL_EXTENSIONS = 0xa0, ASN_EXTENSIONS = 0xa3, ASN_LONG_LENGTH = 0x80 }; enum ASN_Flags{ ASN_CONSTRUCTED = 0x20, ASN_CONTEXT_SPECIFIC = 0x80 }; enum DN_Tags { ASN_COMMON_NAME = 0x03, /* CN */ ASN_SUR_NAME = 0x04, /* SN */ ASN_SERIAL_NUMBER = 0x05, /* serialNumber */ ASN_COUNTRY_NAME = 0x06, /* C */ ASN_LOCALITY_NAME = 0x07, /* L */ ASN_STATE_NAME = 0x08, /* ST */ ASN_ORG_NAME = 0x0a, /* O */ ASN_ORGUNIT_NAME = 0x0b /* OU */ }; enum PBES { PBE_MD5_DES = 0, PBE_SHA1_DES = 1, PBE_SHA1_DES3 = 2, PBE_SHA1_RC4_128 = 3, PBES2 = 13 /* algo ID */ }; enum ENCRYPTION_TYPES { DES_TYPE = 0, DES3_TYPE = 1, RC4_TYPE = 2 }; enum ECC_TYPES { ECC_PREFIX_0 = 160, ECC_PREFIX_1 = 161 }; enum Misc_ASN { ASN_NAME_MAX = 256, MAX_SALT_SIZE = 64, /* MAX PKCS Salt length */ MAX_IV_SIZE = 64, /* MAX PKCS Iv length */ MAX_KEY_SIZE = 64, /* MAX PKCS Key length */ PKCS5 = 5, /* PKCS oid tag */ PKCS5v2 = 6, /* PKCS #5 v2.0 */ PKCS12 = 12, /* PKCS #12 */ MAX_UNICODE_SZ = 256, ASN_BOOL_SIZE = 2, /* including type */ ASN_ECC_HEADER_SZ = 2, /* String type + 1 byte len */ ASN_ECC_CONTEXT_SZ = 2, /* Content specific type + 1 byte len */ #ifdef NO_SHA KEYID_SIZE = SHA256_DIGEST_SIZE, #else KEYID_SIZE = SHA_DIGEST_SIZE, #endif RSA_INTS = 8, /* RSA ints in private key */ DSA_INTS = 5, /* DSA ints in private key */ MIN_DATE_SIZE = 13, MAX_DATE_SIZE = 32, ASN_GEN_TIME_SZ = 15, /* 7 numbers * 2 + Zulu tag */ MAX_ENCODED_SIG_SZ = 512, MAX_SIG_SZ = 256, MAX_ALGO_SZ = 20, MAX_SEQ_SZ = 5, /* enum(seq | con) + length(4) */ MAX_SET_SZ = 5, /* enum(set | con) + length(4) */ MAX_OCTET_STR_SZ = 5, /* enum(set | con) + length(4) */ MAX_EXP_SZ = 5, /* enum(contextspec|con|exp) + length(4) */ MAX_PRSTR_SZ = 5, /* enum(prstr) + length(4) */ MAX_VERSION_SZ = 5, /* enum + id + version(byte) + (header(2))*/ MAX_ENCODED_DIG_SZ = 73, /* sha512 + enum(bit or octet) + length(4) */ MAX_RSA_INT_SZ = 517, /* RSA raw sz 4096 for bits + tag + len(4) */ MAX_NTRU_KEY_SZ = 610, /* NTRU 112 bit public key */ MAX_NTRU_ENC_SZ = 628, /* NTRU 112 bit DER public encoding */ MAX_LENGTH_SZ = 4, /* Max length size for DER encoding */ MAX_RSA_E_SZ = 16, /* Max RSA public e size */ MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */ MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */ MAX_DER_DIGEST_SZ = MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, /* Maximum DER digest size */ #ifdef WOLFSSL_CERT_GEN #ifdef WOLFSSL_CERT_REQ /* Max encoded cert req attributes length */ MAX_ATTRIB_SZ = MAX_SEQ_SZ * 3 + (11 + MAX_SEQ_SZ) * 2 + MAX_PRSTR_SZ + CTC_NAME_SIZE, /* 11 is the OID size */ #endif #if defined(WOLFSSL_ALT_NAMES) || defined(WOLFSSL_CERT_EXT) MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + CTC_MAX_ALT_SIZE, #else MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + MAX_CA_SZ, #endif /* Max total extensions, id + len + others */ #endif #ifdef WOLFSSL_CERT_EXT MAX_KID_SZ = 45, /* Max encoded KID length (SHA-256 case) */ MAX_KEYUSAGE_SZ = 18, /* Max encoded Key Usage length */ MAX_OID_SZ = 32, /* Max DER length of OID*/ MAX_OID_STRING_SZ = 64, /* Max string length representation of OID*/ MAX_CERTPOL_NB = CTC_MAX_CERTPOL_NB,/* Max number of Cert Policy */ MAX_CERTPOL_SZ = CTC_MAX_CERTPOL_SZ, #endif OCSP_NONCE_EXT_SZ = 37, /* OCSP Nonce Extension size */ MAX_OCSP_EXT_SZ = 58, /* Max OCSP Extension length */ MAX_OCSP_NONCE_SZ = 16, /* OCSP Nonce size */ EIGHTK_BUF = 8192, /* Tmp buffer size */ MAX_PUBLIC_KEY_SZ = MAX_NTRU_ENC_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2, /* use bigger NTRU size */ HEADER_ENCRYPTED_KEY_SIZE = 88,/* Extra header size for encrypted key */ TRAILING_ZERO = 1 /* Used for size of zero pad */ }; enum Oid_Types { oidHashType = 0, oidSigType = 1, oidKeyType = 2, oidCurveType = 3, oidBlkType = 4, oidOcspType = 5, oidCertExtType = 6, oidCertAuthInfoType = 7, oidCertPolicyType = 8, oidCertAltNameType = 9, oidCertKeyUseType = 10, oidKdfType = 11, oidIgnoreType }; enum Hash_Sum { MD2h = 646, MD5h = 649, SHAh = 88, SHA256h = 414, SHA384h = 415, SHA512h = 416 }; enum Block_Sum { DESb = 69, DES3b = 652 }; enum Key_Sum { DSAk = 515, RSAk = 645, NTRUk = 274, ECDSAk = 518 }; enum Ecc_Sum { ECC_256R1 = 526, ECC_384R1 = 210, ECC_521R1 = 211, ECC_160R1 = 184, ECC_192R1 = 520, ECC_224R1 = 209 }; enum KDF_Sum { PBKDF2_OID = 660 }; enum Extensions_Sum { BASIC_CA_OID = 133, ALT_NAMES_OID = 131, CRL_DIST_OID = 145, AUTH_INFO_OID = 69, AUTH_KEY_OID = 149, SUBJ_KEY_OID = 128, CERT_POLICY_OID = 146, KEY_USAGE_OID = 129, /* 2.5.29.15 */ INHIBIT_ANY_OID = 168, /* 2.5.29.54 */ EXT_KEY_USAGE_OID = 151, /* 2.5.29.37 */ NAME_CONS_OID = 144 /* 2.5.29.30 */ }; enum CertificatePolicy_Sum { CP_ANY_OID = 146 /* id-ce 32 0 */ }; enum SepHardwareName_Sum { HW_NAME_OID = 79 /* 1.3.6.1.5.5.7.8.4 from RFC 4108*/ }; enum AuthInfo_Sum { AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1 */ AIA_CA_ISSUER_OID = 117 /* 1.3.6.1.5.5.7.48.2 */ }; enum ExtKeyUsage_Sum { /* From RFC 5280 */ EKU_ANY_OID = 151, /* 2.5.29.37.0, anyExtendedKeyUsage */ EKU_SERVER_AUTH_OID = 71, /* 1.3.6.1.5.5.7.3.1, id-kp-serverAuth */ EKU_CLIENT_AUTH_OID = 72, /* 1.3.6.1.5.5.7.3.2, id-kp-clientAuth */ EKU_OCSP_SIGN_OID = 79 /* 1.3.6.1.5.5.7.3.9, OCSPSigning */ }; enum VerifyType { NO_VERIFY = 0, VERIFY = 1 }; #ifdef WOLFSSL_CERT_EXT enum KeyIdType { SKID_TYPE = 0, AKID_TYPE = 1 }; #endif /* Key usage extension bits */ #define KEYUSE_DIGITAL_SIG 0x0080 #define KEYUSE_CONTENT_COMMIT 0x0040 #define KEYUSE_KEY_ENCIPHER 0x0020 #define KEYUSE_DATA_ENCIPHER 0x0010 #define KEYUSE_KEY_AGREE 0x0008 #define KEYUSE_KEY_CERT_SIGN 0x0004 #define KEYUSE_CRL_SIGN 0x0002 #define KEYUSE_ENCIPHER_ONLY 0x0001 #define KEYUSE_DECIPHER_ONLY 0x8000 #define EXTKEYUSE_ANY 0x08 #define EXTKEYUSE_OCSP_SIGN 0x04 #define EXTKEYUSE_CLIENT_AUTH 0x02 #define EXTKEYUSE_SERVER_AUTH 0x01 typedef struct DNS_entry DNS_entry; struct DNS_entry { DNS_entry* next; /* next on DNS list */ char* name; /* actual DNS name */ }; typedef struct Base_entry Base_entry; struct Base_entry { Base_entry* next; /* next on name base list */ char* name; /* actual name base */ int nameSz; /* name length */ byte type; /* Name base type (DNS or RFC822) */ }; struct DecodedName { char* fullName; int fullNameLen; int entryCount; int cnIdx; int cnLen; int snIdx; int snLen; int cIdx; int cLen; int lIdx; int lLen; int stIdx; int stLen; int oIdx; int oLen; int ouIdx; int ouLen; int emailIdx; int emailLen; int uidIdx; int uidLen; int serialIdx; int serialLen; }; typedef struct DecodedCert DecodedCert; typedef struct DecodedName DecodedName; typedef struct Signer Signer; #ifdef WOLFSSL_TRUST_PEER_CERT typedef struct TrustedPeerCert TrustedPeerCert; #endif /* WOLFSSL_TRUST_PEER_CERT */ struct DecodedCert { byte* publicKey; word32 pubKeySize; int pubKeyStored; word32 certBegin; /* offset to start of cert */ word32 sigIndex; /* offset to start of signature */ word32 sigLength; /* length of signature */ word32 signatureOID; /* sum of algorithm object id */ word32 keyOID; /* sum of key algo object id */ int version; /* cert version, 1 or 3 */ DNS_entry* altNames; /* alt names list of dns entries */ #ifndef IGNORE_NAME_CONSTRAINTS DNS_entry* altEmailNames; /* alt names list of RFC822 entries */ Base_entry* permittedNames; /* Permitted name bases */ Base_entry* excludedNames; /* Excluded name bases */ #endif /* IGNORE_NAME_CONSTRAINTS */ byte subjectHash[KEYID_SIZE]; /* hash of all Names */ byte issuerHash[KEYID_SIZE]; /* hash of all Names */ #ifdef HAVE_OCSP byte issuerKeyHash[KEYID_SIZE]; /* hash of the public Key */ #endif /* HAVE_OCSP */ byte* signature; /* not owned, points into raw cert */ char* subjectCN; /* CommonName */ int subjectCNLen; /* CommonName Length */ char subjectCNEnc; /* CommonName Encoding */ int subjectCNStored; /* have we saved a copy we own */ char issuer[ASN_NAME_MAX]; /* full name including common name */ char subject[ASN_NAME_MAX]; /* full name including common name */ int verify; /* Default to yes, but could be off */ byte* source; /* byte buffer holder cert, NOT owner */ word32 srcIdx; /* current offset into buffer */ word32 maxIdx; /* max offset based on init size */ void* heap; /* for user memory overrides */ byte serial[EXTERNAL_SERIAL_SIZE]; /* raw serial number */ int serialSz; /* raw serial bytes stored */ byte* extensions; /* not owned, points into raw cert */ int extensionsSz; /* length of cert extensions */ word32 extensionsIdx; /* if want to go back and parse later */ byte* extAuthInfo; /* Authority Information Access URI */ int extAuthInfoSz; /* length of the URI */ byte* extCrlInfo; /* CRL Distribution Points */ int extCrlInfoSz; /* length of the URI */ byte extSubjKeyId[KEYID_SIZE]; /* Subject Key ID */ byte extSubjKeyIdSet; /* Set when the SKID was read from cert */ byte extAuthKeyId[KEYID_SIZE]; /* Authority Key ID */ byte extAuthKeyIdSet; /* Set when the AKID was read from cert */ #ifndef IGNORE_NAME_CONSTRAINTS byte extNameConstraintSet; #endif /* IGNORE_NAME_CONSTRAINTS */ byte isCA; /* CA basic constraint true */ byte weOwnAltNames; /* altNames haven't been given to copy */ byte extKeyUsageSet; word16 extKeyUsage; /* Key usage bitfield */ byte extExtKeyUsageSet; /* Extended Key Usage */ byte extExtKeyUsage; /* Extended Key usage bitfield */ #ifdef OPENSSL_EXTRA byte extBasicConstSet; byte extBasicConstCrit; byte extBasicConstPlSet; word32 pathLength; /* CA basic constraint path length, opt */ byte extSubjAltNameSet; byte extSubjAltNameCrit; byte extAuthKeyIdCrit; #ifndef IGNORE_NAME_CONSTRAINTS byte extNameConstraintCrit; #endif /* IGNORE_NAME_CONSTRAINTS */ byte extSubjKeyIdCrit; byte extKeyUsageCrit; byte extExtKeyUsageCrit; byte* extExtKeyUsageSrc; word32 extExtKeyUsageSz; word32 extExtKeyUsageCount; byte* extAuthKeyIdSrc; word32 extAuthKeyIdSz; byte* extSubjKeyIdSrc; word32 extSubjKeyIdSz; #endif #ifdef HAVE_ECC word32 pkCurveOID; /* Public Key's curve OID */ #endif /* HAVE_ECC */ byte* beforeDate; int beforeDateLen; byte* afterDate; int afterDateLen; #ifdef HAVE_PKCS7 byte* issuerRaw; /* pointer to issuer inside source */ int issuerRawLen; #endif #ifndef IGNORE_NAME_CONSTRAINT byte* subjectRaw; /* pointer to subject inside source */ int subjectRawLen; #endif #if defined(WOLFSSL_CERT_GEN) /* easy access to subject info for other sign */ char* subjectSN; int subjectSNLen; char subjectSNEnc; char* subjectC; int subjectCLen; char subjectCEnc; char* subjectL; int subjectLLen; char subjectLEnc; char* subjectST; int subjectSTLen; char subjectSTEnc; char* subjectO; int subjectOLen; char subjectOEnc; char* subjectOU; int subjectOULen; char subjectOUEnc; char* subjectEmail; int subjectEmailLen; #endif /* WOLFSSL_CERT_GEN */ #ifdef OPENSSL_EXTRA DecodedName issuerName; DecodedName subjectName; #endif /* OPENSSL_EXTRA */ #ifdef WOLFSSL_SEP int deviceTypeSz; byte* deviceType; int hwTypeSz; byte* hwType; int hwSerialNumSz; byte* hwSerialNum; #ifdef OPENSSL_EXTRA byte extCertPolicySet; byte extCertPolicyCrit; #endif /* OPENSSL_EXTRA */ #endif /* WOLFSSL_SEP */ #ifdef WOLFSSL_CERT_EXT char extCertPolicies[MAX_CERTPOL_NB][MAX_CERTPOL_SZ]; int extCertPoliciesNb; #endif /* WOLFSSL_CERT_EXT */ }; extern const char* BEGIN_CERT; extern const char* END_CERT; extern const char* BEGIN_CERT_REQ; extern const char* END_CERT_REQ; extern const char* BEGIN_DH_PARAM; extern const char* END_DH_PARAM; extern const char* BEGIN_X509_CRL; extern const char* END_X509_CRL; extern const char* BEGIN_RSA_PRIV; extern const char* END_RSA_PRIV; extern const char* BEGIN_PRIV_KEY; extern const char* END_PRIV_KEY; extern const char* BEGIN_ENC_PRIV_KEY; extern const char* END_ENC_PRIV_KEY; extern const char* BEGIN_EC_PRIV; extern const char* END_EC_PRIV; extern const char* BEGIN_DSA_PRIV; extern const char* END_DSA_PRIV; extern const char* BEGIN_PUB_KEY; extern const char* END_PUB_KEY; #ifdef NO_SHA #define SIGNER_DIGEST_SIZE SHA256_DIGEST_SIZE #else #define SIGNER_DIGEST_SIZE SHA_DIGEST_SIZE #endif /* CA Signers */ /* if change layout change PERSIST_CERT_CACHE functions too */ struct Signer { word32 pubKeySize; word32 keyOID; /* key type */ word16 keyUsage; byte* publicKey; int nameLen; char* name; /* common name */ #ifndef IGNORE_NAME_CONSTRAINTS Base_entry* permittedNames; Base_entry* excludedNames; #endif /* IGNORE_NAME_CONSTRAINTS */ byte subjectNameHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ #ifndef NO_SKID byte subjectKeyIdHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ #endif Signer* next; }; #ifdef WOLFSSL_TRUST_PEER_CERT /* used for having trusted peer certs rather then CA */ struct TrustedPeerCert { int nameLen; char* name; /* common name */ #ifndef IGNORE_NAME_CONSTRAINTS Base_entry* permittedNames; Base_entry* excludedNames; #endif /* IGNORE_NAME_CONSTRAINTS */ byte subjectNameHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ #ifndef NO_SKID byte subjectKeyIdHash[SIGNER_DIGEST_SIZE]; /* sha hash of names in certificate */ #endif word32 sigLen; byte* sig; struct TrustedPeerCert* next; }; #endif /* WOLFSSL_TRUST_PEER_CERT */ /* not for public consumption but may use for testing sometimes */ #ifdef WOLFSSL_TEST_CERT #define WOLFSSL_TEST_API WOLFSSL_API #else #define WOLFSSL_TEST_API WOLFSSL_LOCAL #endif WOLFSSL_TEST_API void FreeAltNames(DNS_entry*, void*); #ifndef IGNORE_NAME_CONSTRAINTS WOLFSSL_TEST_API void FreeNameSubtrees(Base_entry*, void*); #endif /* IGNORE_NAME_CONSTRAINTS */ WOLFSSL_TEST_API void InitDecodedCert(DecodedCert*, byte*, word32, void*); WOLFSSL_TEST_API void FreeDecodedCert(DecodedCert*); WOLFSSL_TEST_API int ParseCert(DecodedCert*, int type, int verify, void* cm); WOLFSSL_LOCAL int ParseCertRelative(DecodedCert*,int type,int verify,void* cm); WOLFSSL_LOCAL int DecodeToKey(DecodedCert*, int verify); WOLFSSL_LOCAL Signer* MakeSigner(void*); WOLFSSL_LOCAL void FreeSigner(Signer*, void*); WOLFSSL_LOCAL void FreeSignerTable(Signer**, int, void*); #ifdef WOLFSSL_TRUST_PEER_CERT WOLFSSL_LOCAL void FreeTrustedPeer(TrustedPeerCert*, void*); WOLFSSL_LOCAL void FreeTrustedPeerTable(TrustedPeerCert**, int, void*); #endif /* WOLFSSL_TRUST_PEER_CERT */ WOLFSSL_LOCAL int ToTraditional(byte* buffer, word32 length); WOLFSSL_LOCAL int ToTraditionalEnc(byte* buffer, word32 length,const char*,int); WOLFSSL_LOCAL int ValidateDate(const byte* date, byte format, int dateType); /* ASN.1 helper functions */ WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx); WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len, word32 maxIdx); WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx); WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx, int* version); WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx); WOLFSSL_LOCAL int GetObjectId(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx); WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, word32 oidType, word32 maxIdx); WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output); WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output); WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output); WOLFSSL_LOCAL word32 SetImplicit(byte tag,byte number,word32 len,byte* output); WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output); WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output); WOLFSSL_LOCAL word32 SetAlgoID(int algoOID,byte* output,int type,int curveSz); WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header); WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output); WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx); #ifdef HAVE_ECC /* ASN sig helpers */ WOLFSSL_LOCAL int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s); WOLFSSL_LOCAL int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s); #endif #ifdef WOLFSSL_CERT_GEN enum cert_enums { NAME_ENTRIES = 8, JOINT_LEN = 2, EMAIL_JOINT_LEN = 9, RSA_KEY = 10, NTRU_KEY = 11, ECC_KEY = 12 }; #ifndef WOLFSSL_PEMCERT_TODER_DEFINED #ifndef NO_FILESYSTEM /* forward from wolfSSL */ WOLFSSL_API int wolfSSL_PemCertToDer(const char* fileName,unsigned char* derBuf,int derSz); #define WOLFSSL_PEMCERT_TODER_DEFINED #endif #endif #endif /* WOLFSSL_CERT_GEN */ /* for pointer use */ typedef struct CertStatus CertStatus; #ifdef HAVE_OCSP enum Ocsp_Response_Status { OCSP_SUCCESSFUL = 0, /* Response has valid confirmations */ OCSP_MALFORMED_REQUEST = 1, /* Illegal confirmation request */ OCSP_INTERNAL_ERROR = 2, /* Internal error in issuer */ OCSP_TRY_LATER = 3, /* Try again later */ OCSP_SIG_REQUIRED = 5, /* Must sign the request (4 is skipped) */ OCSP_UNAUTHROIZED = 6 /* Request unauthorized */ }; enum Ocsp_Cert_Status { CERT_GOOD = 0, CERT_REVOKED = 1, CERT_UNKNOWN = 2 }; enum Ocsp_Sums { OCSP_BASIC_OID = 117, OCSP_NONCE_OID = 118 }; typedef struct OcspRequest OcspRequest; typedef struct OcspResponse OcspResponse; struct CertStatus { CertStatus* next; byte serial[EXTERNAL_SERIAL_SIZE]; int serialSz; int status; byte thisDate[MAX_DATE_SIZE]; byte nextDate[MAX_DATE_SIZE]; byte thisDateFormat; byte nextDateFormat; byte* rawOcspResponse; word32 rawOcspResponseSz; }; struct OcspResponse { int responseStatus; /* return code from Responder */ byte* response; /* Pointer to beginning of OCSP Response */ word32 responseSz; /* length of the OCSP Response */ byte producedDate[MAX_DATE_SIZE]; /* Date at which this response was signed */ byte producedDateFormat; /* format of the producedDate */ byte* issuerHash; byte* issuerKeyHash; byte* cert; word32 certSz; byte* sig; /* Pointer to sig in source */ word32 sigSz; /* Length in octets for the sig */ word32 sigOID; /* OID for hash used for sig */ CertStatus* status; /* certificate status to fill out */ byte* nonce; /* pointer to nonce inside ASN.1 response */ int nonceSz; /* length of the nonce string */ byte* source; /* pointer to source buffer, not owned */ word32 maxIdx; /* max offset based on init size */ }; struct OcspRequest { byte issuerHash[KEYID_SIZE]; byte issuerKeyHash[KEYID_SIZE]; byte* serial; /* copy of the serial number in source cert */ int serialSz; byte* url; /* copy of the extAuthInfo in source cert */ int urlSz; byte nonce[MAX_OCSP_NONCE_SZ]; int nonceSz; }; WOLFSSL_LOCAL void InitOcspResponse(OcspResponse*, CertStatus*, byte*, word32); WOLFSSL_LOCAL int OcspResponseDecode(OcspResponse*, void*); WOLFSSL_LOCAL int InitOcspRequest(OcspRequest*, DecodedCert*, byte); WOLFSSL_LOCAL void FreeOcspRequest(OcspRequest*); WOLFSSL_LOCAL int EncodeOcspRequest(OcspRequest*, byte*, word32); WOLFSSL_LOCAL word32 EncodeOcspRequestExtensions(OcspRequest*, byte*, word32); WOLFSSL_LOCAL int CompareOcspReqResp(OcspRequest*, OcspResponse*); #endif /* HAVE_OCSP */ /* for pointer use */ typedef struct RevokedCert RevokedCert; #ifdef HAVE_CRL struct RevokedCert { byte serialNumber[EXTERNAL_SERIAL_SIZE]; int serialSz; RevokedCert* next; }; typedef struct DecodedCRL DecodedCRL; struct DecodedCRL { word32 certBegin; /* offset to start of cert */ word32 sigIndex; /* offset to start of signature */ word32 sigLength; /* length of signature */ word32 signatureOID; /* sum of algorithm object id */ byte* signature; /* pointer into raw source, not owned */ byte issuerHash[SIGNER_DIGEST_SIZE]; /* issuer hash */ byte crlHash[SIGNER_DIGEST_SIZE]; /* raw crl data hash */ byte lastDate[MAX_DATE_SIZE]; /* last date updated */ byte nextDate[MAX_DATE_SIZE]; /* next update date */ byte lastDateFormat; /* format of last date */ byte nextDateFormat; /* format of next date */ RevokedCert* certs; /* revoked cert list */ int totalCerts; /* number on list */ }; WOLFSSL_LOCAL void InitDecodedCRL(DecodedCRL*); WOLFSSL_LOCAL int ParseCRL(DecodedCRL*, const byte* buff, word32 sz, void* cm); WOLFSSL_LOCAL void FreeDecodedCRL(DecodedCRL*); #endif /* HAVE_CRL */ #ifdef __cplusplus } /* extern "C" */ #endif #endif /* !NO_ASN */ #endif /* WOLF_CRYPT_ASN_H */
lchristina26/wolfssl
wolfssl/wolfcrypt/asn.h
C
gpl-2.0
26,993
31.798299
102
0.589671
false
/* * Customer code to add GPIO control during WLAN start/stop * Copyright (C) 1999-2010, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: dhd_custom_gpio.c,v 1.1.4.8.4.4 2011/01/20 20:23:09 Exp $ */ #include <typedefs.h> #include <linuxver.h> #include <osl.h> #include <bcmutils.h> #include <dngl_stats.h> #include <dhd.h> #include <wlioctl.h> #include <wl_iw.h> #define WL_ERROR(x) printf x #define WL_TRACE(x) #ifdef CUSTOMER_HW_SAMSUNG extern void bcm_wlan_power_off(int); extern void bcm_wlan_power_on(int); extern void wlan_setup_power(int, int); #endif /* CUSTOMER_HW_SAMSUNG */ #ifdef CUSTOMER_HW extern void bcm_wlan_power_off(int); extern void bcm_wlan_power_on(int); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW2 int wifi_set_carddetect(int on); int wifi_set_power(int on, unsigned long msec); int wifi_get_irq_number(unsigned long *irq_flags_ptr); int wifi_get_mac_addr(unsigned char *buf); void *wifi_get_country_code(char *ccode); #endif #if defined(OOB_INTR_ONLY) #if defined(BCMLXSDMMC) extern int sdioh_mmc_irq(int irq); #endif /* (BCMLXSDMMC) */ #ifdef CUSTOMER_HW3 #include <mach/gpio.h> #endif /* Customer specific Host GPIO defintion */ /* Customer specific Host GPIO defintion */ #ifdef CUSTOMER_HW_SAMSUNG static int dhd_oob_gpio_num = IRQ_EINT(20); #else static int dhd_oob_gpio_num = -1; /* GG 19 */ #endif module_param(dhd_oob_gpio_num, int, 0644); MODULE_PARM_DESC(dhd_oob_gpio_num, "DHD oob gpio number"); int dhd_customer_oob_irq_map(unsigned long *irq_flags_ptr) { int host_oob_irq = 0; #ifdef CUSTOMER_HW2 host_oob_irq = wifi_get_irq_number(irq_flags_ptr); #else /* for NOT CUSTOMER_HW2 */ #if defined(CUSTOM_OOB_GPIO_NUM) if (dhd_oob_gpio_num < 0) { dhd_oob_gpio_num = CUSTOM_OOB_GPIO_NUM; } #endif if (dhd_oob_gpio_num < 0) { WL_ERROR(("%s: ERROR customer specific Host GPIO is NOT defined \n", __FUNCTION__)); return (dhd_oob_gpio_num); } WL_ERROR(("%s: customer specific Host GPIO number is (%d)\n", __FUNCTION__, dhd_oob_gpio_num)); #if defined CUSTOMER_HW host_oob_irq = MSM_GPIO_TO_INT(dhd_oob_gpio_num); #elif defined CUSTOMER_HW3 gpio_request(dhd_oob_gpio_num, "oob irq"); host_oob_irq = gpio_to_irq(dhd_oob_gpio_num); gpio_direction_input(dhd_oob_gpio_num); #elif defined CUSTOMER_HW_SAMSUNG host_oob_irq = dhd_oob_gpio_num; #endif /* CUSTOMER_HW */ #endif /* CUSTOMER_HW2 */ return (host_oob_irq); } #endif /* defined(OOB_INTR_ONLY) */ /* Customer function to control hw specific wlan gpios */ void dhd_customer_gpio_wlan_ctrl(int onoff) { switch (onoff) { case WLAN_RESET_OFF: WL_TRACE(("%s: call customer specific GPIO to insert WLAN RESET\n", __FUNCTION__)); #ifdef CUSTOMER_HW_SAMSUNG //bcm_wlan_power_off(2); wlan_setup_power(0, 2); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW bcm_wlan_power_off(2); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW2 wifi_set_power(0, 0); #endif WL_ERROR(("=========== WLAN placed in RESET ========\n")); break; case WLAN_RESET_ON: WL_TRACE(("%s: callc customer specific GPIO to remove WLAN RESET\n", __FUNCTION__)); #ifdef CUSTOMER_HW_SAMSUNG //bcm_wlan_power_on(2); wlan_setup_power(1, 2); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW bcm_wlan_power_on(2); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW2 wifi_set_power(1, 0); #endif WL_ERROR(("=========== WLAN going back to live ========\n")); break; case WLAN_POWER_OFF: WL_TRACE(("%s: call customer specific GPIO to turn off WL_REG_ON\n", __FUNCTION__)); #ifdef CUSTOMER_HW_SAMSUNG //bcm_wlan_power_off(1); wlan_setup_power(0, 1); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW bcm_wlan_power_off(1); #endif /* CUSTOMER_HW */ break; case WLAN_POWER_ON: WL_TRACE(("%s: call customer specific GPIO to turn on WL_REG_ON\n", __FUNCTION__)); #ifdef CUSTOMER_HW_SAMSUNG //bcm_wlan_power_on(1); wlan_setup_power(1, 1); #endif /* CUSTOMER_HW */ #ifdef CUSTOMER_HW bcm_wlan_power_on(1); /* Lets customer power to get stable */ OSL_DELAY(50); #endif /* CUSTOMER_HW */ break; } } #ifdef GET_CUSTOM_MAC_ENABLE /* Function to get custom MAC address */ int dhd_custom_get_mac_address(unsigned char *buf) { int ret = 0; WL_TRACE(("%s Enter\n", __FUNCTION__)); if (!buf) return -EINVAL; /* Customer access to MAC address stored outside of DHD driver */ #ifdef CUSTOMER_HW2 ret = wifi_get_mac_addr(buf); #endif #ifdef EXAMPLE_GET_MAC /* EXAMPLE code */ { struct ether_addr ea_example = {{0x00, 0x11, 0x22, 0x33, 0x44, 0xFF}}; bcopy((char *)&ea_example, buf, sizeof(struct ether_addr)); } #endif /* EXAMPLE_GET_MAC */ return ret; } #endif /* GET_CUSTOM_MAC_ENABLE */ /* Customized Locale table : OPTIONAL feature */ const struct cntry_locales_custom translate_custom_table[] = { /* Table should be filled out based on custom platform regulatory requirement */ #ifdef EXAMPLE_TABLE {"", "XY", 4}, /* universal */ {"US", "US", 69}, /* input ISO "US" to : US regrev 69 */ {"CA", "US", 69}, /* input ISO "CA" to : US regrev 69 */ {"EU", "EU", 5}, /* European union countries */ {"AT", "EU", 5}, {"BE", "EU", 5}, {"BG", "EU", 5}, {"CY", "EU", 5}, {"CZ", "EU", 5}, {"DK", "EU", 5}, {"EE", "EU", 5}, {"FI", "EU", 5}, {"FR", "EU", 5}, {"DE", "EU", 5}, {"GR", "EU", 5}, {"HU", "EU", 5}, {"IE", "EU", 5}, {"IT", "EU", 5}, {"LV", "EU", 5}, {"LI", "EU", 5}, {"LT", "EU", 5}, {"LU", "EU", 5}, {"MT", "EU", 5}, {"NL", "EU", 5}, {"PL", "EU", 5}, {"PT", "EU", 5}, {"RO", "EU", 5}, {"SK", "EU", 5}, {"SI", "EU", 5}, {"ES", "EU", 5}, {"SE", "EU", 5}, {"GB", "EU", 5}, /* input ISO "GB" to : EU regrev 05 */ {"IL", "IL", 0}, {"CH", "CH", 0}, {"TR", "TR", 0}, {"NO", "NO", 0}, {"KR", "XY", 3}, {"AU", "XY", 3}, {"CN", "XY", 3}, /* input ISO "CN" to : XY regrev 03 */ {"TW", "XY", 3}, {"AR", "XY", 3}, {"MX", "XY", 3} #endif /* EXAMPLE_TABLE */ }; /* Customized Locale convertor * input : ISO 3166-1 country abbreviation * output: customized cspec */ void get_customized_country_code(char *country_iso_code, wl_country_t *cspec) { #ifdef CUSTOMER_HW2 struct cntry_locales_custom *cloc_ptr; if (!cspec) return; cloc_ptr = wifi_get_country_code(country_iso_code); if (cloc_ptr) { strlcpy(cspec->ccode, cloc_ptr->custom_locale, WLC_CNTRY_BUF_SZ); cspec->rev = cloc_ptr->custom_locale_rev; } return; #else int size, i; size = ARRAYSIZE(translate_custom_table); if (cspec == 0) return; if (size == 0) return; for (i = 0; i < size; i++) { if (strcmp(country_iso_code, translate_custom_table[i].iso_abbrev) == 0) { memcpy(cspec->ccode, translate_custom_table[i].custom_locale, WLC_CNTRY_BUF_SZ); cspec->rev = translate_custom_table[i].custom_locale_rev; return; } } memcpy(cspec->ccode, translate_custom_table[0].custom_locale, WLC_CNTRY_BUF_SZ); cspec->rev = translate_custom_table[0].custom_locale_rev; return; #endif }
sdadier/gb_kernel_2.6.32.9-mtd
Kernel/drivers/net/wireless/bcm4329/dhd_custom_gpio.c
C
gpl-2.0
8,018
25.637874
83
0.64006
false
// Test for method java.util.IllegalFormatPrecisionException.getClass().getFields() // Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com> // This file is part of Mauve. // Mauve 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, or (at your option) // any later version. // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301 USA. // Tags: JDK1.5 package gnu.testlet.java.util.IllegalFormatPrecisionException.classInfo; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.util.IllegalFormatPrecisionException; import java.util.Map; import java.util.HashMap; /** * Test for method java.util.IllegalFormatPrecisionException.getClass().getFields() */ public class getFields implements Testlet { /** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { // map of fields which should exists Map<String, String> testedFields = null; // map of fields for (Open)JDK6 Map<String, String> testedFields_jdk6 = new HashMap<String, String>(); // map of fields for (Open)JDK7 Map<String, String> testedFields_jdk7 = new HashMap<String, String>(); // map for fields declared in (Open)JDK6 // --- empty --- // map for fields declared in (Open)JDK7 // --- empty --- // create instance of a class IllegalFormatPrecisionException final Object o = new IllegalFormatPrecisionException(42); // get a runtime class of an object "o" final Class c = o.getClass(); // get the right map containing field signatures testedFields = getJavaVersion() < 7 ? testedFields_jdk6 : testedFields_jdk7; // get all fields for this class java.lang.reflect.Field[] fields = c.getFields(); // expected number of fields final int expectedNumberOfFields = testedFields.size(); // basic check for a number of fields harness.check(fields.length, expectedNumberOfFields); } /** * Returns version of Java. The input could have the following form: "1.7.0_06" * and we are interested only in "7" in this case. * * @return Java version */ protected int getJavaVersion() { String javaVersionStr = System.getProperty("java.version"); String[] parts = javaVersionStr.split("\\."); return Integer.parseInt(parts[1]); } }
niloc132/mauve-gwt
src/main/java/gnu/testlet/java/util/IllegalFormatPrecisionException/classInfo/getFields.java
Java
gpl-2.0
3,040
31
84
0.678618
false
# Turn Off the Lights Browser Extension <img alt="Turn Off the Lights Browser Extension Logo" src="https://github.com/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/blob/master/src/icons/icon48.png" align="left" style="padding: 0 10px 5px 0"> **Turn Off the Lights** is a popular browser extension that works on all major web browsers such as Google Chrome, Firefox, Opera, Safari, Yandex, Maxthon, Brave, Vivaldi, Cốc Cốc, and Microsoft Edge. ![Chrome Web Store](https://img.shields.io/chrome-web-store/d/bfbmjmiodbnnpllbbbfblcplfjjepjdn.svg?color=#44cc12&style=flat-square) ![Chrome Web Store](https://img.shields.io/chrome-web-store/rating/bfbmjmiodbnnpllbbbfblcplfjjepjdn?color=#44cc12&style=flat-square) ![Chrome Web Store](https://img.shields.io/chrome-web-store/v/bfbmjmiodbnnpllbbbfblcplfjjepjdn.svg?color=#44cc12&style=flat-square) Project<br> [![CodeQL](https://github.com/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/actions/workflows/codeql-analysis.yml) [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/turnoffthelights/Turn-Off-the-Lights-Chrome-extension.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/context:javascript) Using Turn Off the Lights to dims the web page and reduces the eye strain caused by the bright screen. And it will highlight the video player on that web page such as on YouTube. **[Join our growing community on Facebook](https://www.facebook.com/turnoffthelight) to stay up to date!** **[Join our growing Translators community on Crowdin](https://www.crowdin.com/project/turnoffthelights) to stay up to date!** **[Please use and enjoy it, and if you can make a donation of any amount, I'd appreciate it immensely](https://www.turnoffthelights.com/donate.html)** <div style="text-align:center"> <img alt="Turn Off the Lights Browser extension Screenshot in Google Chrome" src="https://www.turnoffthelights.com/images/turnoffthelights-twitter.png"> </div> ## Features * Turn the lights back on, by clicking on it * Support multiple video sites: YouTube, HTML5 video,... and more * Customize your YouTube: * Auto HD: Set videos to play in HD automatically. Users can select from highres > 8K > 5K> 4K > 1080p > 720p > 480p > 360p > 240p > 144p > default * Auto Wide: Automatically plays the video on the widest mode ,... and more * Easter Eggs: * Shortcut key: T -> Do you like a real movie theater feeling? * Option to make the screen dark when the user clicks on the play button * Option to turn on/off the fade in and fade out effects * Custom colors * Option to Flash Detection * Option to Show Dimness Level Bar * Option Eye Protection for when it's night. And with whitelist/blacklist filter * Option atmosphere lighting that shows a glow around the video player * Option to show the dark layer on the top of the window * Options to shortcut keys: * Ctrl + Shift + L to toggle the lights * Alt + F8 to restore the default opacity value * Alt + F9 to save the current opacity value * Alt + F10 to enable/disable the Eye Protection feature * Alt + (arrow up) to increase the opacity * Alt + (arrow down) to decrease the opacity * Alt + * to toggle the lights on all open tabs * Option Camera Motion * Option Speech Recognition * Option for Mouse Wheel Volume Control for each HTML5 video player * Option to add a filter to the current HTML5 video player (grayscale, sepia, invert, contrast, saturate, hue rotation and brightness) * Option to show the Audio Visualization effect on top of the current HTML5 video (Blocks, Frequency and Music Tunnel) * Option to loop the current HTML5 video player * Option to place the Night Mode switch to toggle YouTube in black or white theme. And with whitelist/blacklist filter * Time stamp: Activate the Night Mode within the chosen time * Blackout: Dims the web page and activates the Night Mode * Option to stop YouTube and HTML5 videos from automatically playing. ## Installation #### Loading it in Chrome: 1. Open your Google Chrome web browser, browse to [chrome://extensions](chrome://extensions) 1. If you have already Turn Off the Lights Chrome extension installed, disable it 1. Check **Developer mode** in the top of the Extensions page 1. Click **Load unpacked extension...** 1. Choose the sub-directory **src** (where manifest.json resides) #### Store hyperlinks: The Browser extension is available in the following stores: * [Google Chrome in the Chrome web store](https://chrome.google.com/webstore/detail/turn-off-the-lights/bfbmjmiodbnnpllbbbfblcplfjjepjdn) * [Opera in the Opera Extension gallery](https://addons.opera.com/extensions/details/turn-off-the-lights/) * [Firefox in the Firefox Extension gallery](https://addons.mozilla.org/firefox/addon/turn-off-the-lights/) * [Safari in the Safari Extension gallery](https://itunes.apple.com/us/app/turn-off-the-lights-for-safari/id1273998507?ls=1&mt=12&at=1010lwtb) * Available for Yandex: See Yandex built-in extension * [Maxthon in the Maxthon Extension gallery](http://extension.maxthon.com/detail/index.php?view_id=1813) * [Microsoft Edge in the Windows Store](https://microsoftedge.microsoft.com/addons/detail/turn-off-the-lights/fmamkbgpnienhphflfdamlhnljffjdgm)
turnoffthelights/Turn-Off-the-Lights-Chrome-extension
.github/README.md
Markdown
gpl-2.0
5,391
66.3375
262
0.772044
false
/** ============================================================================ * @file zsp800m_map.c * * @path $(APUDRV)/gpp/src/arch/ZSP800M/ * * @desc Defines the configuration mapping information for the APU DRIVER * driver. * * @ver 0.01.00.00 * ============================================================================ * Copyright (C) 2011-2012, Nufront Incorporated - http://www.nufront.com/ * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any kind, * whether express or implied; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * ============================================================================ */ /* ----------------------------------- APU DRIVER Headers */ #include <apudrv.h> #include <_apudrv.h> #if defined (POOL_COMPONENT) #include <pooldefs.h> #endif /* if defined (POOL_COMPONENT) */ #if defined (MSGQ_COMPONENT) #include <msgqdefs.h> #endif /* if defined (MSGQ_COMPONENT) */ #include <cfgmap.h> #if defined (__cplusplus) EXTERN "C" { #endif /* defined (__cplusplus) */ /** ============================================================================ * @name ZSP800MMAP_DspObjects * * @desc Array of configuration mapping objects for the DSPs in the system. * ============================================================================ */ EXTERN DSP_Interface ZSP800M_Interface ; CONST CFGMAP_Dsp ZSP800MMAP_DspObjects [] = { { "ZSP800M", /* NAME : Name of the DSP */ &ZSP800M_Interface /* INTERFACE : DSP interface table */ } } ; /** ============================================================================ * @name ZSP800MMAP_LoaderObjects * * @desc Array of configuration mapping objects for the DSP executable * loaders in the system. * ============================================================================ */ EXTERN KFILE_Interface KFILEPSEUDO_Interface ; EXTERN KFILE_Interface KFILEDEF_Interface ; CONST CFGMAP_Loader ZSP800MMAP_LoaderObjects [] = { { "BIN", NULL,//&BINFILE_Interface, &KFILEDEF_Interface } } ; #if (!defined (ONLY_PROC_COMPONENT)) /** ============================================================================ * @name ZSP800MMAP_LinkDrvObjects * * @desc Array of configuration mapping objects for the link drivers in the * system. * ============================================================================ */ EXTERN DRV_Interface SHMDRV_Interface ; CONST CFGMAP_LinkDrv ZSP800MMAP_LinkDrvObjects [] = { { "SHMDRV", /* NAME : Name of the link driver */ &SHMDRV_Interface /* INTERFACE : Link driver interface table */ } } ; /** ============================================================================ * @name ZSP800MMAP_IpsObjects * * @desc Array of configuration mapping objects for the IPS components in the * system. * ============================================================================ */ EXTERN FnIpsInit IPS_init ; EXTERN FnIpsExit IPS_exit ; #if defined (DDSP_DEBUG) EXTERN FnIpsDebug IPS_debug ; #endif /* if defined (DDSP_DEBUG) */ CONST CFGMAP_Ips ZSP800MMAP_IpsObjects [] = { { "IPS", /* NAME : Name of the IPS */ (FnIpsInit) &IPS_init, /* FXN_INIT : Init function for the IPS */ (FnIpsExit) &IPS_exit, /* FXN_EXIT : Exit function for the IPS */ #if defined (DDSP_DEBUG) (FnIpsDebug) &IPS_debug /* FXN_DEBUG : Debug function for the IPS */ #endif /* if defined (DDSP_DEBUG) */ } } ; #endif /* if (!defined (ONLY_PROC_COMPONENT)) */ #if defined (POOL_COMPONENT) /** ============================================================================ * @name ZSP800MMAP_PoolObjects * * @desc Array of configuration mapping objects for the POOLs in the system. * ============================================================================ */ EXTERN FnPoolInit SMAPOOL_init ; EXTERN FnPoolExit SMAPOOL_exit ; EXTERN POOL_Interface SMAPOOL_Interface ; #if defined (PCPY_LINK) EXTERN FnPoolInit BUFPOOL_init ; EXTERN FnPoolExit BUFPOOL_exit ; EXTERN POOL_Interface BUFPOOL_Interface ; #endif /* if defined (PCPY_LINK) */ CONST CFGMAP_Pool ZSP800MMAP_PoolObjects [] = { { "SMAPOOL", /* NAME : Name of the pool */ (FnPoolInit) &SMAPOOL_init, /* FXN_INIT : Init function for the pool */ (FnPoolExit) &SMAPOOL_exit, /* FXN_EXIT : Exit function for the pool */ &SMAPOOL_Interface /* INTERFACE : Pool interface table */ }, #if defined (PCPY_LINK) { "BUFPOOL", /* NAME : Name of the pool */ (FnPoolInit) &BUFPOOL_init, /* FXN_INIT : Init function for the pool */ (FnPoolExit) &BUFPOOL_exit, /* FXN_EXIT : Exit function for the pool */ &BUFPOOL_Interface /* INTERFACE : Pool interface table */ } #endif /* if defined (PCPY_LINK) */ } ; #endif /* if defined (POOL_COMPONENT) */ #if defined (CHNL_COMPONENT) /** ============================================================================ * @name ZSP800MMAP_DataDrvObjects * * @desc Array of configuration mapping objects for the Data drivers in the * system. * ============================================================================ */ EXTERN DATA_Interface ZCPYDATA_Interface ; CONST CFGMAP_DataDrv ZSP800MMAP_DataDrvObjects [] = { { "ZCPYDATA", /* NAME : Name of the data driver */ &ZCPYDATA_Interface /* INTERFACE : Data transfer interface table */ } } ; #endif /* if defined (CHNL_COMPONENT) */ #if defined (MSGQ_COMPONENT) /** ============================================================================ * @name ZSP800MMAP_MqtObjects * * @desc Array of configuration mapping objects for the Message Queue * Transports in the system. * ============================================================================ */ EXTERN MQT_Interface ZCPYMQT_Interface ; CONST CFGMAP_Mqt ZSP800MMAP_MqtObjects [] = { { "ZCPYMQT", /* NAME : Name of the Message Queue Transport */ &ZCPYMQT_Interface /* INTERFACE : MQT Interface table */ } } ; #endif /* if defined (MSGQ_COMPONENT) */ /** ============================================================================ * @name ZSP800MMAP_Config * * @desc APU DRIVER configuration mapping structure. * ============================================================================ */ CFGMAP_Object ZSP800MMAP_Config = { 1, /* NUMDSPS : Number of types of DSPs */ (CFGMAP_Dsp *) ZSP800MMAP_DspObjects, /* DSPOBJECTS : Array of DSP configuration mapping objects */ 1, /* NUMLOADERS : Number of types of DSP executable loaders */ (CFGMAP_Loader *) ZSP800MMAP_LoaderObjects, /* LOADERS : Array of DSP executable loader configuration mapping objects */ #if (!defined (ONLY_PROC_COMPONENT)) 1, /* NUMLINKDRVS : Number of types of link drivers */ (CFGMAP_LinkDrv *) ZSP800MMAP_LinkDrvObjects, /* LINKDRVOBJECTS : Array of Link Driver configuration mapping objects */ 1, /* NUMIPS : Number of types of IPS */ (CFGMAP_Ips *) ZSP800MMAP_IpsObjects, /* IPSOBJECTS : Array of IPS configuration mapping objects */ #else 0, /* NUMLINKDRVS : Number of types of link drivers */ NULL, /* LINKDRVOBJECTS : Array of Link Driver configuration mapping objects */ 0, /* NUMIPS : Number of types of IPS */ NULL, /* IPSOBJECTS : Array of IPS configuration mapping objects */ #endif /* if (!defined (ONLY_PROC_COMPONENT)) */ #if defined (POOL_COMPONENT) 1, /* NUMPOOLS : Number of types of POOLs */ (CFGMAP_Pool *) ZSP800MMAP_PoolObjects, /* POOLOBJECTS : Array of POOL configuration mapping objects */ #endif /* if defined (POOL_COMPONENT) */ #if defined (CHNL_COMPONENT) 1, /* NUMDATADRIVERS : Number of types of Data drivers */ (CFGMAP_DataDrv *) ZSP800MMAP_DataDrvObjects, /* DATADRIVERS : Array of Data driver configuration mapping objects */ #endif /* if defined (CHNL_COMPONENT) */ #if defined (MSGQ_COMPONENT) 1, /* NUMMQTS : Number of types of MQTs */ (CFGMAP_Mqt *) ZSP800MMAP_MqtObjects /* MQTOBJECTS : Array of MQT configuration mapping objects */ #endif /* if defined (MSGQ_COMPONENT) */ } ; #if defined (__cplusplus) } #endif /* defined (__cplusplus) */
adamdmcbride/Nufront_linux_kernel
drivers/char/apu/gpp/src/arch/ZSP800M/zsp800m_map.c
C
gpl-2.0
9,567
39.710638
133
0.486882
false
<?php $consumer_key = $_GET['1']; $consumer_secret = $_GET['2']; $oauth_access_token = $_GET['3']; $oauth_access_token_secret = $_GET['4']; switch($_GET['url']) { case 'timeline': $rest = 'statuses/user_timeline' ; $params = Array('count' => $_GET['count'], 'include_rts' => $_GET['include_rts'], 'exclude_replies' => $_GET['exclude_replies'], 'screen_name' => $_GET['screen_name']); break; case 'search': $rest = "search/tweets"; $params = Array('q' => $_GET['q'], 'count' => $_GET['count'], 'include_rts' => $_GET['include_rts']); break; case 'list': $rest = "lists/statuses"; $params = Array('list_id' => $_GET['list_id'], 'count' => $_GET['count'], 'include_rts' => $_GET['include_rts']); break; default: $rest = 'statuses/user_timeline' ; $params = Array('count' => '20'); break; } $auth = new dcsnt_TwitterOAuth($consumer_key,$consumer_secret,$oauth_access_token,$oauth_access_token_secret); $get = $auth->get( $rest, $params ); if( ! $get ) { echo 'An error occurs while reading the feed, please check your connection or settings'; } if( isset( $get->errors ) ) { // foreach( $get->errors as $key => $val ) echo $val; echo 'errors'; //print_r($get->errors); } else { echo $get; } /* * Abraham Williams (abraham@abrah.am) http://abrah.am * * The first PHP Library to support OAuth for Twitter's REST API. */ /** * Twitter OAuth class */ class dcsnt_TwitterOAuth { /* Contains the last HTTP status code returned. */ public $http_code; /* Contains the last API call. */ public $url; /* Set up the API root URL. */ public $host = "https://api.twitter.com/1.1/"; /* Set timeout default. */ public $timeout = 30; /* Set connect timeout. */ public $connecttimeout = 30; /* Verify SSL Cert. */ public $ssl_verifypeer = FALSE; /* Respons format. */ public $format = 'json'; /* Decode returned json data. */ public $decode_json = false; /* Contains the last HTTP headers returned. */ public $http_info; /* Set the useragnet. */ public $useragent = 'TwitterOAuth v0.2.0-beta2'; /* Immediately retry the API call if the response was not successful. */ //public $retry = TRUE; /** * Set API URLS */ function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; } function authenticateURL() { return 'https://api.twitter.com/oauth/authenticate'; } function authorizeURL() { return 'https://api.twitter.com/oauth/authorize'; } function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; } /** * Debug helpers */ function lastStatusCode() { return $this->http_status; } function lastAPICall() { return $this->last_api_call; } /** * construct TwitterOAuth object */ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { $this->sha1_method = new dcsnt_OAuthSignatureMethod_HMAC_SHA1(); $this->consumer = new dcsnt_OAuthConsumer($consumer_key, $consumer_secret); if (!empty($oauth_token) && !empty($oauth_token_secret)) { $this->token = new dcsnt_OAuthConsumer($oauth_token, $oauth_token_secret); } else { $this->token = NULL; } } /** * Get a request_token from Twitter * * @returns a key/value array containing oauth_token and oauth_token_secret */ function getRequestToken($oauth_callback = NULL) { $parameters = array(); if (!empty($oauth_callback)) { $parameters['oauth_callback'] = $oauth_callback; } $request = $this->dcsnt_OAuthRequest($this->requestTokenURL(), 'GET', $parameters); $token = dcsnt_OAuthUtil::parse_parameters($request); $this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * Get the authorize URL * * @returns a string */ function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) { if (is_array($token)) { $token = $token['oauth_token']; } if (empty($sign_in_with_twitter)) { return $this->authorizeURL() . "?oauth_token={$token}"; } else { return $this->authenticateURL() . "?oauth_token={$token}"; } } /** * Exchange request token and secret for an access token and * secret, to sign API calls. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham") */ function getAccessToken($oauth_verifier = FALSE) { $parameters = array(); if (!empty($oauth_verifier)) { $parameters['oauth_verifier'] = $oauth_verifier; } $request = $this->dcsnt_OAuthRequest($this->accessTokenURL(), 'GET', $parameters); $token = dcsnt_OAuthUtil::parse_parameters($request); $this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * One time exchange of username and password for access token and secret. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham", * "x_auth_expires" => "0") */ function getXAuthToken($username, $password) { $parameters = array(); $parameters['x_auth_username'] = $username; $parameters['x_auth_password'] = $password; $parameters['x_auth_mode'] = 'client_auth'; $request = $this->dcsnt_OAuthRequest($this->accessTokenURL(), 'POST', $parameters); $token = dcsnt_OAuthUtil::parse_parameters($request); $this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * GET wrapper for dcsnt_OAuthRequest. */ function get($url, $parameters = array()) { $response = $this->dcsnt_OAuthRequest($url, 'GET', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * POST wrapper for dcsnt_OAuthRequest. */ function post($url, $parameters = array()) { $response = $this->dcsnt_OAuthRequest($url, 'POST', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * DELETE wrapper for oAuthReqeust. */ function delete($url, $parameters = array()) { $response = $this->dcsnt_OAuthRequest($url, 'DELETE', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * Format and sign an OAuth / API request */ function dcsnt_OAuthRequest($url, $method, $parameters) { if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) { $url = "{$this->host}{$url}.{$this->format}"; } $request = dcsnt_OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); $request->sign_request($this->sha1_method, $this->consumer, $this->token); switch ($method) { case 'GET': return $this->http($request->to_url(), 'GET'); default: return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata()); } } /** * Make an HTTP request * * @return API results */ function http($url, $method, $postfields = NULL) { $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); curl_setopt($ci, CURLOPT_HEADER, FALSE); switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); $this->url = $url; curl_close ($ci); return $response; } /** * Get the header info to store. */ function getHeader($ch, $header) { $i = strpos($header, ':'); if (!empty($i)) { $key = str_replace('-', '_', strtolower(substr($header, 0, $i))); $value = trim(substr($header, $i + 2)); $this->http_header[$key] = $value; } return strlen($header); } } // vim: foldmethod=marker /* Generic exception class */ class dcsnt_OAuthException extends Exception { // pass } class dcsnt_OAuthConsumer { public $key; public $secret; function __construct($key, $secret, $callback_url=NULL) { $this->key = $key; $this->secret = $secret; $this->callback_url = $callback_url; } function __toString() { return "OAuthConsumer[key=$this->key,secret=$this->secret]"; } } class dcsnt_OAuthToken { // access tokens and request tokens public $key; public $secret; /** * key = the token * secret = the token secret */ function __construct($key, $secret) { $this->key = $key; $this->secret = $secret; } /** * generates the basic string serialization of a token that a server * would respond to request_token and access_token calls with */ function to_string() { return "oauth_token=" . dcsnt_OAuthUtil::urlencode_rfc3986($this->key) . "&oauth_token_secret=" . dcsnt_OAuthUtil::urlencode_rfc3986($this->secret); } function __toString() { return $this->to_string(); } } /** * A class for implementing a Signature Method * See section 9 ("Signing Requests") in the spec */ abstract class dcsnt_OAuthSignatureMethod { /** * Needs to return the name of the Signature Method (ie HMAC-SHA1) * @return string */ abstract public function get_name(); /** * Build up the signature * NOTE: The output of this function MUST NOT be urlencoded. * the encoding is handled in dcsnt_OAuthRequest when the final * request is serialized * @param dcsnt_OAuthRequest $request * @param OAuthConsumer $consumer * @param dcsnt_OAuthToken $token * @return string */ abstract public function build_signature($request, $consumer, $token); /** * Verifies that a given signature is correct * @param dcsnt_OAuthRequest $request * @param OAuthConsumer $consumer * @param dcsnt_OAuthToken $token * @param string $signature * @return bool */ public function check_signature($request, $consumer, $token, $signature) { $built = $this->build_signature($request, $consumer, $token); return $built == $signature; } } /** * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] * where the Signature Base String is the text and the key is the concatenated values (each first * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' * character (ASCII code 38) even if empty. * - Chapter 9.2 ("HMAC-SHA1") */ class dcsnt_OAuthSignatureMethod_HMAC_SHA1 extends dcsnt_OAuthSignatureMethod { function get_name() { return "HMAC-SHA1"; } public function build_signature($request, $consumer, $token) { $base_string = $request->get_signature_base_string(); $request->base_string = $base_string; $key_parts = array( $consumer->secret, ($token) ? $token->secret : "" ); $key_parts = dcsnt_OAuthUtil::urlencode_rfc3986($key_parts); $key = implode('&', $key_parts); return base64_encode(hash_hmac('sha1', $base_string, $key, true)); } } /** * The PLAINTEXT method does not provide any security protection and SHOULD only be used * over a secure channel such as HTTPS. It does not use the Signature Base String. * - Chapter 9.4 ("PLAINTEXT") */ class dcsnt_OAuthSignatureMethod_PLAINTEXT extends dcsnt_OAuthSignatureMethod { public function get_name() { return "PLAINTEXT"; } /** * oauth_signature is set to the concatenated encoded values of the Consumer Secret and * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is * empty. The result MUST be encoded again. * - Chapter 9.4.1 ("Generating Signatures") * * Please note that the second encoding MUST NOT happen in the SignatureMethod, as * dcsnt_OAuthRequest handles this! */ public function build_signature($request, $consumer, $token) { $key_parts = array( $consumer->secret, ($token) ? $token->secret : "" ); $key_parts = dcsnt_OAuthUtil::urlencode_rfc3986($key_parts); $key = implode('&', $key_parts); $request->base_string = $key; return $key; } } /** * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a * verified way to the Service Provider, in a manner which is beyond the scope of this * specification. * - Chapter 9.3 ("RSA-SHA1") */ abstract class dcsnt_OAuthSignatureMethod_RSA_SHA1 extends dcsnt_OAuthSignatureMethod { public function get_name() { return "RSA-SHA1"; } // Up to the SP to implement this lookup of keys. Possible ideas are: // (1) do a lookup in a table of trusted certs keyed off of consumer // (2) fetch via http using a url provided by the requester // (3) some sort of specific discovery code based on request // // Either way should return a string representation of the certificate protected abstract function fetch_public_cert(&$request); // Up to the SP to implement this lookup of keys. Possible ideas are: // (1) do a lookup in a table of trusted certs keyed off of consumer // // Either way should return a string representation of the certificate protected abstract function fetch_private_cert(&$request); public function build_signature($request, $consumer, $token) { $base_string = $request->get_signature_base_string(); $request->base_string = $base_string; // Fetch the private key cert based on the request $cert = $this->fetch_private_cert($request); // Pull the private key ID from the certificate $privatekeyid = openssl_get_privatekey($cert); // Sign using the key $ok = openssl_sign($base_string, $signature, $privatekeyid); // Release the key resource openssl_free_key($privatekeyid); return base64_encode($signature); } public function check_signature($request, $consumer, $token, $signature) { $decoded_sig = base64_decode($signature); $base_string = $request->get_signature_base_string(); // Fetch the public key cert based on the request $cert = $this->fetch_public_cert($request); // Pull the public key ID from the certificate $publickeyid = openssl_get_publickey($cert); // Check the computed signature against the one passed in the query $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); // Release the key resource openssl_free_key($publickeyid); return $ok == 1; } } class dcsnt_OAuthRequest { private $parameters; private $http_method; private $http_url; // for debug purposes public $base_string; public static $version = '1.0'; public static $POST_INPUT = 'php://input'; function __construct($http_method, $http_url, $parameters=NULL) { @$parameters or $parameters = array(); $parameters = array_merge( dcsnt_OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); $this->parameters = $parameters; $this->http_method = $http_method; $this->http_url = $http_url; } /** * attempt to build up a request from what was passed to the server */ public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https'; @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']; @$http_method or $http_method = $_SERVER['REQUEST_METHOD']; // We weren't handed any parameters, so let's find the ones relevant to // this request. // If you run XML-RPC or similar you should use this to provide your own // parsed parameter-list if (!$parameters) { // Find request headers $request_headers = dcsnt_OAuthUtil::get_headers(); // Parse the query-string to find GET parameters $parameters = dcsnt_OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); // It's a POST request of the proper content-type, so parse POST // parameters and add those overriding any duplicates from GET if ($http_method == "POST" && @strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded") ) { $post_data = dcsnt_OAuthUtil::parse_parameters( file_get_contents(self::$POST_INPUT) ); $parameters = array_merge($parameters, $post_data); } // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") { $header_parameters = dcsnt_OAuthUtil::split_header( $request_headers['Authorization'] ); $parameters = array_merge($parameters, $header_parameters); } } return new dcsnt_OAuthRequest($http_method, $http_url, $parameters); } /** * pretty much a helper function to set up the request */ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { @$parameters or $parameters = array(); $defaults = array("oauth_version" => dcsnt_OAuthRequest::$version, "oauth_nonce" => dcsnt_OAuthRequest::generate_nonce(), "oauth_timestamp" => dcsnt_OAuthRequest::generate_timestamp(), "oauth_consumer_key" => $consumer->key); if ($token) $defaults['oauth_token'] = $token->key; $parameters = array_merge($defaults, $parameters); return new dcsnt_OAuthRequest($http_method, $http_url, $parameters); } public function set_parameter($name, $value, $allow_duplicates = true) { if ($allow_duplicates && isset($this->parameters[$name])) { // We have already added parameter(s) with this name, so add to the list if (is_scalar($this->parameters[$name])) { // This is the first duplicate, so transform scalar (string) // into an array so we can add the duplicates $this->parameters[$name] = array($this->parameters[$name]); } $this->parameters[$name][] = $value; } else { $this->parameters[$name] = $value; } } public function get_parameter($name) { return isset($this->parameters[$name]) ? $this->parameters[$name] : null; } public function get_parameters() { return $this->parameters; } public function unset_parameter($name) { unset($this->parameters[$name]); } /** * The request parameters, sorted and concatenated into a normalized string. * @return string */ public function get_signable_parameters() { // Grab all parameters $params = $this->parameters; // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") if (isset($params['oauth_signature'])) { unset($params['oauth_signature']); } return dcsnt_OAuthUtil::build_http_query($params); } /** * Returns the base string of this request * * The base string defined as the method, the url * and the parameters (normalized), each urlencoded * and the concated with &. */ public function get_signature_base_string() { $parts = array( $this->get_normalized_http_method(), $this->get_normalized_http_url(), $this->get_signable_parameters() ); $parts = dcsnt_OAuthUtil::urlencode_rfc3986($parts); return implode('&', $parts); } /** * just uppercases the http method */ public function get_normalized_http_method() { return strtoupper($this->http_method); } /** * parses the url and rebuilds it to be * scheme://host/path */ public function get_normalized_http_url() { $parts = parse_url($this->http_url); $port = @$parts['port']; $scheme = $parts['scheme']; $host = $parts['host']; $path = @$parts['path']; $port or $port = ($scheme == 'https') ? '443' : '80'; if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) { $host = "$host:$port"; } return "$scheme://$host$path"; } /** * builds a url usable for a GET request */ public function to_url() { $post_data = $this->to_postdata(); $out = $this->get_normalized_http_url(); if ($post_data) { $out .= '?'.$post_data; } return $out; } /** * builds the data one would send in a POST request */ public function to_postdata() { return dcsnt_OAuthUtil::build_http_query($this->parameters); } /** * builds the Authorization: header */ public function to_header($realm=null) { $first = true; if($realm) { $out = 'Authorization: OAuth realm="' . dcsnt_OAuthUtil::urlencode_rfc3986($realm) . '"'; $first = false; } else $out = 'Authorization: OAuth'; $total = array(); foreach ($this->parameters as $k => $v) { if (substr($k, 0, 5) != "oauth") continue; if (is_array($v)) { throw new dcsnt_OAuthException('Arrays not supported in headers'); } $out .= ($first) ? ' ' : ','; $out .= dcsnt_OAuthUtil::urlencode_rfc3986($k) . '="' . dcsnt_OAuthUtil::urlencode_rfc3986($v) . '"'; $first = false; } return $out; } public function __toString() { return $this->to_url(); } public function sign_request($signature_method, $consumer, $token) { $this->set_parameter( "oauth_signature_method", $signature_method->get_name(), false ); $signature = $this->build_signature($signature_method, $consumer, $token); $this->set_parameter("oauth_signature", $signature, false); } public function build_signature($signature_method, $consumer, $token) { $signature = $signature_method->build_signature($this, $consumer, $token); return $signature; } /** * util function: current timestamp */ private static function generate_timestamp() { return time(); } /** * util function: current nonce */ private static function generate_nonce() { $mt = microtime(); $rand = mt_rand(); return md5($mt . $rand); // md5s look nicer than numbers } } class dcsnt_OAuthServer { protected $timestamp_threshold = 300; // in seconds, five minutes protected $version = '1.0'; // hi blaine protected $signature_methods = array(); protected $data_store; function __construct($data_store) { $this->data_store = $data_store; } public function add_signature_method($signature_method) { $this->signature_methods[$signature_method->get_name()] = $signature_method; } // high level functions /** * process a request_token request * returns the request token on success */ public function fetch_request_token(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); // no token required for the initial token request $token = NULL; $this->check_signature($request, $consumer, $token); // Rev A change $callback = $request->get_parameter('oauth_callback'); $new_token = $this->data_store->new_request_token($consumer, $callback); return $new_token; } /** * process an access_token request * returns the access token on success */ public function fetch_access_token(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); // requires authorized request token $token = $this->get_token($request, $consumer, "request"); $this->check_signature($request, $consumer, $token); // Rev A change $verifier = $request->get_parameter('oauth_verifier'); $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); return $new_token; } /** * verify an api call, checks all the parameters */ public function verify_request(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); $token = $this->get_token($request, $consumer, "access"); $this->check_signature($request, $consumer, $token); return array($consumer, $token); } // Internals from here /** * version 1 */ private function get_version(&$request) { $version = $request->get_parameter("oauth_version"); if (!$version) { // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. // Chapter 7.0 ("Accessing Protected Ressources") $version = '1.0'; } if ($version !== $this->version) { throw new dcsnt_OAuthException("OAuth version '$version' not supported"); } return $version; } /** * figure out the signature with some defaults */ private function get_signature_method(&$request) { $signature_method = @$request->get_parameter("oauth_signature_method"); if (!$signature_method) { // According to chapter 7 ("Accessing Protected Ressources") the signature-method // parameter is required, and we can't just fallback to PLAINTEXT throw new dcsnt_OAuthException('No signature method parameter. This parameter is required'); } if (!in_array($signature_method, array_keys($this->signature_methods))) { throw new dcsnt_OAuthException( "Signature method '$signature_method' not supported " . "try one of the following: " . implode(", ", array_keys($this->signature_methods)) ); } return $this->signature_methods[$signature_method]; } /** * try to find the consumer for the provided request's consumer key */ private function get_consumer(&$request) { $consumer_key = @$request->get_parameter("oauth_consumer_key"); if (!$consumer_key) { throw new dcsnt_OAuthException("Invalid consumer key"); } $consumer = $this->data_store->lookup_consumer($consumer_key); if (!$consumer) { throw new dcsnt_OAuthException("Invalid consumer"); } return $consumer; } /** * try to find the token for the provided request's token key */ private function get_token(&$request, $consumer, $token_type="access") { $token_field = @$request->get_parameter('oauth_token'); $token = $this->data_store->lookup_token( $consumer, $token_type, $token_field ); if (!$token) { throw new dcsnt_OAuthException("Invalid $token_type token: $token_field"); } return $token; } /** * all-in-one function to check the signature on a request * should guess the signature method appropriately */ private function check_signature(&$request, $consumer, $token) { // this should probably be in a different method $timestamp = @$request->get_parameter('oauth_timestamp'); $nonce = @$request->get_parameter('oauth_nonce'); $this->check_timestamp($timestamp); $this->check_nonce($consumer, $token, $nonce, $timestamp); $signature_method = $this->get_signature_method($request); $signature = $request->get_parameter('oauth_signature'); $valid_sig = $signature_method->check_signature( $request, $consumer, $token, $signature ); if (!$valid_sig) { throw new dcsnt_OAuthException("Invalid signature"); } } /** * check that the timestamp is new enough */ private function check_timestamp($timestamp) { if( ! $timestamp ) throw new dcsnt_OAuthException( 'Missing timestamp parameter. The parameter is required' ); // verify that timestamp is recentish $now = time(); if (abs($now - $timestamp) > $this->timestamp_threshold) { throw new dcsnt_OAuthException( "Expired timestamp, yours $timestamp, ours $now" ); } } /** * check that the nonce is not repeated */ private function check_nonce($consumer, $token, $nonce, $timestamp) { if( ! $nonce ) throw new dcsnt_OAuthException( 'Missing nonce parameter. The parameter is required' ); // verify that the nonce is uniqueish $found = $this->data_store->lookup_nonce( $consumer, $token, $nonce, $timestamp ); if ($found) { throw new dcsnt_OAuthException("Nonce already used: $nonce"); } } } class dcsnt_OAuthDataStore { function lookup_consumer($consumer_key) { // implement me } function lookup_token($consumer, $token_type, $token) { // implement me } function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me } function new_request_token($consumer, $callback = null) { // return a new token attached to this consumer } function new_access_token($token, $consumer, $verifier = null) { // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token } } class dcsnt_OAuthUtil { public static function urlencode_rfc3986($input) { if (is_array($input)) { return array_map(array('dcsnt_OAuthUtil', 'urlencode_rfc3986'), $input); } else if (is_scalar($input)) { return str_replace( '+', ' ', str_replace('%7E', '~', rawurlencode($input)) ); } else { return ''; } } // This decode function isn't taking into consideration the above // modifications to the encoding process. However, this method doesn't // seem to be used anywhere so leaving it as is. public static function urldecode_rfc3986($string) { return urldecode($string); } // Utility function for turning the Authorization: header into // parameters, has to do some unescaping // Can filter out any non-oauth parameters if needed (default behaviour) public static function split_header($header, $only_allow_oauth_parameters = true) { $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/'; $offset = 0; $params = array(); while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) { $match = $matches[0]; $header_name = $matches[2][0]; $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0]; if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) { $params[$header_name] = dcsnt_OAuthUtil::urldecode_rfc3986($header_content); } $offset = $match[1] + strlen($match[0]); } if (isset($params['realm'])) { unset($params['realm']); } return $params; } // helper to try to sort out headers for people who aren't running apache public static function get_headers() { if (function_exists('apache_request_headers')) { // we need this to get the actual Authorization: header // because apache tends to tell us it doesn't exist $headers = apache_request_headers(); // sanitize the output of apache_request_headers because // we always want the keys to be Cased-Like-This and arh() // returns the headers in the same case as they are in the // request $out = array(); foreach( $headers AS $key => $value ) { $key = str_replace( " ", "-", ucwords(strtolower(str_replace("-", " ", $key))) ); $out[$key] = $value; } } else { // otherwise we don't have apache and are just going to have to hope // that $_SERVER actually contains what we need $out = array(); if( isset($_SERVER['CONTENT_TYPE']) ) $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; if( isset($_ENV['CONTENT_TYPE']) ) $out['Content-Type'] = $_ENV['CONTENT_TYPE']; foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) == "HTTP_") { // this is chaos, basically it is just there to capitalize the first // letter of every word that is not an initial HTTP and strip HTTP // code from przemek $key = str_replace( " ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) ); $out[$key] = $value; } } } return $out; } // This function takes a input like a=b&a=c&d=e and returns the parsed // parameters like this // array('a' => array('b','c'), 'd' => 'e') public static function parse_parameters( $input ) { if (!isset($input) || !$input) return array(); $pairs = explode('&', $input); $parsed_parameters = array(); foreach ($pairs as $pair) { $split = explode('=', $pair, 2); $parameter = dcsnt_OAuthUtil::urldecode_rfc3986($split[0]); $value = isset($split[1]) ? dcsnt_OAuthUtil::urldecode_rfc3986($split[1]) : ''; if (isset($parsed_parameters[$parameter])) { // We have already recieved parameter(s) with this name, so add to the list // of parameters with this name if (is_scalar($parsed_parameters[$parameter])) { // This is the first duplicate, so transform scalar (string) into an array // so we can add the duplicates $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); } $parsed_parameters[$parameter][] = $value; } else { $parsed_parameters[$parameter] = $value; } } return $parsed_parameters; } public static function build_http_query($params) { if (!$params) return ''; // Urlencode both keys and values $keys = dcsnt_OAuthUtil::urlencode_rfc3986(array_keys($params)); $values = dcsnt_OAuthUtil::urlencode_rfc3986(array_values($params)); $params = array_combine($keys, $values); // Parameters are sorted by name, using lexicographical byte value ordering. // Ref: Spec: 9.1.1 (1) uksort($params, 'strcmp'); $pairs = array(); foreach ($params as $parameter => $value) { if (is_array($value)) { // If two or more parameters share the same name, they are sorted by their value // Ref: Spec: 9.1.1 (1) natsort($value); foreach ($value as $duplicate_value) { $pairs[] = $parameter . '=' . $duplicate_value; } } else { $pairs[] = $parameter . '=' . $value; } } // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) // Each name-value pair is separated by an '&' character (ASCII code 38) return implode('&', $pairs); } } ?>
RomainGoncalves/cadell
wp-content/plugins/social-network-tabs/inc/dcwp_twitter.php
PHP
gpl-2.0
36,981
30.019913
169
0.598632
false
#if !defined(__MAC80211_DRIVER_TRACE) || defined(TRACE_HEADER_MULTI_READ) #define __MAC80211_DRIVER_TRACE #include <linux/tracepoint.h> #include <net/mac80211.h> #include "ieee80211_i.h" #undef TRACE_SYSTEM #define TRACE_SYSTEM mac80211 #define MAXNAME 32 #define LOCAL_ENTRY __array(char, wiphy_name, 32) #define LOCAL_ASSIGN strlcpy(__entry->wiphy_name, wiphy_name(local->hw.wiphy), MAXNAME) #define LOCAL_PR_FMT "%s" #define LOCAL_PR_ARG __entry->wiphy_name #define STA_ENTRY __array(char, sta_addr, ETH_ALEN) #define STA_ASSIGN (sta ? memcpy(__entry->sta_addr, sta->addr, ETH_ALEN) : memset(__entry->sta_addr, 0, ETH_ALEN)) #define STA_PR_FMT " sta:%pM" #define STA_PR_ARG __entry->sta_addr #define VIF_ENTRY __field(enum nl80211_iftype, vif_type) __field(void *, sdata) \ __field(bool, p2p) \ __string(vif_name, sdata->dev ? sdata->dev->name : "<nodev>") #define VIF_ASSIGN __entry->vif_type = sdata->vif.type; __entry->sdata = sdata; \ __entry->p2p = sdata->vif.p2p; \ __assign_str(vif_name, sdata->dev ? sdata->dev->name : "<nodev>") #define VIF_PR_FMT " vif:%s(%d%s)" #define VIF_PR_ARG __get_str(vif_name), __entry->vif_type, __entry->p2p ? "/p2p" : "" /* * Tracing for driver callbacks. */ DECLARE_EVENT_CLASS(local_only_evt, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local), TP_STRUCT__entry( LOCAL_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; ), TP_printk(LOCAL_PR_FMT, LOCAL_PR_ARG) ); DECLARE_EVENT_CLASS(local_sdata_addr_evt, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __array(char, addr, 6) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; memcpy(__entry->addr, sdata->vif.addr, 6); ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " addr:%pM", LOCAL_PR_ARG, VIF_PR_ARG, __entry->addr ) ); DECLARE_EVENT_CLASS(local_u32_evt, TP_PROTO(struct ieee80211_local *local, u32 value), TP_ARGS(local, value), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, value) ), TP_fast_assign( LOCAL_ASSIGN; __entry->value = value; ), TP_printk( LOCAL_PR_FMT " value:%d", LOCAL_PR_ARG, __entry->value ) ); DECLARE_EVENT_CLASS(local_sdata_evt, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT, LOCAL_PR_ARG, VIF_PR_ARG ) ); DEFINE_EVENT(local_only_evt, drv_return_void, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_return_int, TP_PROTO(struct ieee80211_local *local, int ret), TP_ARGS(local, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(int, ret) ), TP_fast_assign( LOCAL_ASSIGN; __entry->ret = ret; ), TP_printk(LOCAL_PR_FMT " - %d", LOCAL_PR_ARG, __entry->ret) ); TRACE_EVENT(drv_return_bool, TP_PROTO(struct ieee80211_local *local, bool ret), TP_ARGS(local, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(bool, ret) ), TP_fast_assign( LOCAL_ASSIGN; __entry->ret = ret; ), TP_printk(LOCAL_PR_FMT " - %s", LOCAL_PR_ARG, (__entry->ret) ? "true" : "false") ); TRACE_EVENT(drv_return_u64, TP_PROTO(struct ieee80211_local *local, u64 ret), TP_ARGS(local, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(u64, ret) ), TP_fast_assign( LOCAL_ASSIGN; __entry->ret = ret; ), TP_printk(LOCAL_PR_FMT " - %llu", LOCAL_PR_ARG, __entry->ret) ); DEFINE_EVENT(local_only_evt, drv_start, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_only_evt, drv_suspend, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_only_evt, drv_resume, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_set_wakeup, TP_PROTO(struct ieee80211_local *local, bool enabled), TP_ARGS(local, enabled), TP_STRUCT__entry( LOCAL_ENTRY __field(bool, enabled) ), TP_fast_assign( LOCAL_ASSIGN; __entry->enabled = enabled; ), TP_printk(LOCAL_PR_FMT " enabled:%d", LOCAL_PR_ARG, __entry->enabled) ); DEFINE_EVENT(local_only_evt, drv_stop, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_sdata_addr_evt, drv_add_interface, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); TRACE_EVENT(drv_change_interface, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum nl80211_iftype type, bool p2p), TP_ARGS(local, sdata, type, p2p), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __field(u32, new_type) __field(bool, new_p2p) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; __entry->new_type = type; __entry->new_p2p = p2p; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " new type:%d%s", LOCAL_PR_ARG, VIF_PR_ARG, __entry->new_type, __entry->new_p2p ? "/p2p" : "" ) ); DEFINE_EVENT(local_sdata_addr_evt, drv_remove_interface, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); TRACE_EVENT(drv_config, TP_PROTO(struct ieee80211_local *local, u32 changed), TP_ARGS(local, changed), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, changed) __field(u32, flags) __field(int, power_level) __field(int, dynamic_ps_timeout) __field(int, max_sleep_period) __field(u16, listen_interval) __field(u8, long_frame_max_tx_count) __field(u8, short_frame_max_tx_count) __field(int, center_freq) __field(int, channel_type) __field(int, smps) ), TP_fast_assign( LOCAL_ASSIGN; __entry->changed = changed; __entry->flags = local->hw.conf.flags; __entry->power_level = local->hw.conf.power_level; __entry->dynamic_ps_timeout = local->hw.conf.dynamic_ps_timeout; __entry->max_sleep_period = local->hw.conf.max_sleep_period; __entry->listen_interval = local->hw.conf.listen_interval; __entry->long_frame_max_tx_count = local->hw.conf.long_frame_max_tx_count; __entry->short_frame_max_tx_count = local->hw.conf.short_frame_max_tx_count; __entry->center_freq = local->hw.conf.channel->center_freq; __entry->channel_type = local->hw.conf.channel_type; __entry->smps = local->hw.conf.smps_mode; ), TP_printk( LOCAL_PR_FMT " ch:%#x freq:%d", LOCAL_PR_ARG, __entry->changed, __entry->center_freq ) ); TRACE_EVENT(drv_bss_info_changed, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_bss_conf *info, u32 changed), TP_ARGS(local, sdata, info, changed), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __field(bool, assoc) __field(u16, aid) __field(bool, cts) __field(bool, shortpre) __field(bool, shortslot) __field(u8, dtimper) __field(u16, bcnint) __field(u16, assoc_cap) __field(u64, timestamp) __field(u32, basic_rates) __field(u32, changed) __field(bool, enable_beacon) __field(u16, ht_operation_mode) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; __entry->changed = changed; __entry->aid = info->aid; __entry->assoc = info->assoc; __entry->shortpre = info->use_short_preamble; __entry->cts = info->use_cts_prot; __entry->shortslot = info->use_short_slot; __entry->dtimper = info->dtim_period; __entry->bcnint = info->beacon_int; __entry->assoc_cap = info->assoc_capability; __entry->timestamp = info->last_tsf; __entry->basic_rates = info->basic_rates; __entry->enable_beacon = info->enable_beacon; __entry->ht_operation_mode = info->ht_operation_mode; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " changed:%#x", LOCAL_PR_ARG, VIF_PR_ARG, __entry->changed ) ); TRACE_EVENT(drv_prepare_multicast, TP_PROTO(struct ieee80211_local *local, int mc_count), TP_ARGS(local, mc_count), TP_STRUCT__entry( LOCAL_ENTRY __field(int, mc_count) ), TP_fast_assign( LOCAL_ASSIGN; __entry->mc_count = mc_count; ), TP_printk( LOCAL_PR_FMT " prepare mc (%d)", LOCAL_PR_ARG, __entry->mc_count ) ); TRACE_EVENT(drv_configure_filter, TP_PROTO(struct ieee80211_local *local, unsigned int changed_flags, unsigned int *total_flags, u64 multicast), TP_ARGS(local, changed_flags, total_flags, multicast), TP_STRUCT__entry( LOCAL_ENTRY __field(unsigned int, changed) __field(unsigned int, total) __field(u64, multicast) ), TP_fast_assign( LOCAL_ASSIGN; __entry->changed = changed_flags; __entry->total = *total_flags; __entry->multicast = multicast; ), TP_printk( LOCAL_PR_FMT " changed:%#x total:%#x", LOCAL_PR_ARG, __entry->changed, __entry->total ) ); TRACE_EVENT(drv_set_tim, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta, bool set), TP_ARGS(local, sta, set), TP_STRUCT__entry( LOCAL_ENTRY STA_ENTRY __field(bool, set) ), TP_fast_assign( LOCAL_ASSIGN; STA_ASSIGN; __entry->set = set; ), TP_printk( LOCAL_PR_FMT STA_PR_FMT " set:%d", LOCAL_PR_ARG, STA_PR_FMT, __entry->set ) ); TRACE_EVENT(drv_set_key, TP_PROTO(struct ieee80211_local *local, enum set_key_cmd cmd, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta, struct ieee80211_key_conf *key), TP_ARGS(local, cmd, sdata, sta, key), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY __field(u32, cipher) __field(u8, hw_key_idx) __field(u8, flags) __field(s8, keyidx) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->cipher = key->cipher; __entry->flags = key->flags; __entry->keyidx = key->keyidx; __entry->hw_key_idx = key->hw_key_idx; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT, LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG ) ); TRACE_EVENT(drv_update_tkip_key, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_key_conf *conf, struct ieee80211_sta *sta, u32 iv32), TP_ARGS(local, sdata, conf, sta, iv32), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY __field(u32, iv32) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->iv32 = iv32; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " iv32:%#x", LOCAL_PR_ARG,VIF_PR_ARG,STA_PR_ARG, __entry->iv32 ) ); DEFINE_EVENT(local_sdata_evt, drv_hw_scan, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); DEFINE_EVENT(local_sdata_evt, drv_cancel_hw_scan, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); DEFINE_EVENT(local_sdata_evt, drv_sched_scan_start, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); DEFINE_EVENT(local_sdata_evt, drv_sched_scan_stop, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); DEFINE_EVENT(local_only_evt, drv_sw_scan_start, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_only_evt, drv_sw_scan_complete, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_get_stats, TP_PROTO(struct ieee80211_local *local, struct ieee80211_low_level_stats *stats, int ret), TP_ARGS(local, stats, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(int, ret) __field(unsigned int, ackfail) __field(unsigned int, rtsfail) __field(unsigned int, fcserr) __field(unsigned int, rtssucc) ), TP_fast_assign( LOCAL_ASSIGN; __entry->ret = ret; __entry->ackfail = stats->dot11ACKFailureCount; __entry->rtsfail = stats->dot11RTSFailureCount; __entry->fcserr = stats->dot11FCSErrorCount; __entry->rtssucc = stats->dot11RTSSuccessCount; ), TP_printk( LOCAL_PR_FMT " ret:%d", LOCAL_PR_ARG, __entry->ret ) ); TRACE_EVENT(drv_get_tkip_seq, TP_PROTO(struct ieee80211_local *local, u8 hw_key_idx, u32 *iv32, u16 *iv16), TP_ARGS(local, hw_key_idx, iv32, iv16), TP_STRUCT__entry( LOCAL_ENTRY __field(u8, hw_key_idx) __field(u32, iv32) __field(u16, iv16) ), TP_fast_assign( LOCAL_ASSIGN; __entry->hw_key_idx = hw_key_idx; __entry->iv32 = *iv32; __entry->iv16 = *iv16; ), TP_printk( LOCAL_PR_FMT, LOCAL_PR_ARG ) ); DEFINE_EVENT(local_u32_evt, drv_set_frag_threshold, TP_PROTO(struct ieee80211_local *local, u32 value), TP_ARGS(local, value) ); DEFINE_EVENT(local_u32_evt, drv_set_rts_threshold, TP_PROTO(struct ieee80211_local *local, u32 value), TP_ARGS(local, value) ); TRACE_EVENT(drv_set_coverage_class, TP_PROTO(struct ieee80211_local *local, u8 value), TP_ARGS(local, value), TP_STRUCT__entry( LOCAL_ENTRY __field(u8, value) ), TP_fast_assign( LOCAL_ASSIGN; __entry->value = value; ), TP_printk( LOCAL_PR_FMT " value:%d", LOCAL_PR_ARG, __entry->value ) ); TRACE_EVENT(drv_sta_notify, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum sta_notify_cmd cmd, struct ieee80211_sta *sta), TP_ARGS(local, sdata, cmd, sta), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY __field(u32, cmd) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->cmd = cmd; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " cmd:%d", LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->cmd ) ); TRACE_EVENT(drv_sta_state, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state), TP_ARGS(local, sdata, sta, old_state, new_state), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY __field(u32, old_state) __field(u32, new_state) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->old_state = old_state; __entry->new_state = new_state; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " state: %d->%d", LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->old_state, __entry->new_state ) ); TRACE_EVENT(drv_sta_rc_update, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta, u32 changed), TP_ARGS(local, sdata, sta, changed), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY __field(u32, changed) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->changed = changed; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " changed: 0x%x", LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->changed ) ); TRACE_EVENT(drv_sta_add, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta), TP_ARGS(local, sdata, sta), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT, LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG ) ); TRACE_EVENT(drv_sta_remove, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta), TP_ARGS(local, sdata, sta), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY STA_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT, LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG ) ); TRACE_EVENT(drv_conf_tx, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, u16 ac, const struct ieee80211_tx_queue_params *params), TP_ARGS(local, sdata, ac, params), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __field(u16, ac) __field(u16, txop) __field(u16, cw_min) __field(u16, cw_max) __field(u8, aifs) __field(bool, uapsd) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; __entry->ac = ac; __entry->txop = params->txop; __entry->cw_max = params->cw_max; __entry->cw_min = params->cw_min; __entry->aifs = params->aifs; __entry->uapsd = params->uapsd; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " AC:%d", LOCAL_PR_ARG, VIF_PR_ARG, __entry->ac ) ); DEFINE_EVENT(local_sdata_evt, drv_get_tsf, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); TRACE_EVENT(drv_set_tsf, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, u64 tsf), TP_ARGS(local, sdata, tsf), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __field(u64, tsf) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; __entry->tsf = tsf; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " tsf:%llu", LOCAL_PR_ARG, VIF_PR_ARG, (unsigned long long)__entry->tsf ) ); DEFINE_EVENT(local_sdata_evt, drv_reset_tsf, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata), TP_ARGS(local, sdata) ); DEFINE_EVENT(local_only_evt, drv_tx_last_beacon, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_ampdu_action, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum ieee80211_ampdu_mlme_action action, struct ieee80211_sta *sta, u16 tid, u16 *ssn, u8 buf_size), TP_ARGS(local, sdata, action, sta, tid, ssn, buf_size), TP_STRUCT__entry( LOCAL_ENTRY STA_ENTRY __field(u32, action) __field(u16, tid) __field(u16, ssn) __field(u8, buf_size) VIF_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; STA_ASSIGN; __entry->action = action; __entry->tid = tid; __entry->ssn = ssn ? *ssn : 0; __entry->buf_size = buf_size; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " action:%d tid:%d buf:%d", LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->action, __entry->tid, __entry->buf_size ) ); TRACE_EVENT(drv_get_survey, TP_PROTO(struct ieee80211_local *local, int idx, struct survey_info *survey), TP_ARGS(local, idx, survey), TP_STRUCT__entry( LOCAL_ENTRY __field(int, idx) ), TP_fast_assign( LOCAL_ASSIGN; __entry->idx = idx; ), TP_printk( LOCAL_PR_FMT " idx:%d", LOCAL_PR_ARG, __entry->idx ) ); TRACE_EVENT(drv_flush, TP_PROTO(struct ieee80211_local *local, bool drop), TP_ARGS(local, drop), TP_STRUCT__entry( LOCAL_ENTRY __field(bool, drop) ), TP_fast_assign( LOCAL_ASSIGN; __entry->drop = drop; ), TP_printk( LOCAL_PR_FMT " drop:%d", LOCAL_PR_ARG, __entry->drop ) ); TRACE_EVENT(drv_channel_switch, TP_PROTO(struct ieee80211_local *local, struct ieee80211_channel_switch *ch_switch), TP_ARGS(local, ch_switch), TP_STRUCT__entry( LOCAL_ENTRY __field(u64, timestamp) __field(bool, block_tx) __field(u16, freq) __field(u8, count) ), TP_fast_assign( LOCAL_ASSIGN; __entry->timestamp = ch_switch->timestamp; __entry->block_tx = ch_switch->block_tx; __entry->freq = ch_switch->channel->center_freq; __entry->count = ch_switch->count; ), TP_printk( LOCAL_PR_FMT " new freq:%u count:%d", LOCAL_PR_ARG, __entry->freq, __entry->count ) ); TRACE_EVENT(drv_set_antenna, TP_PROTO(struct ieee80211_local *local, u32 tx_ant, u32 rx_ant, int ret), TP_ARGS(local, tx_ant, rx_ant, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, tx_ant) __field(u32, rx_ant) __field(int, ret) ), TP_fast_assign( LOCAL_ASSIGN; __entry->tx_ant = tx_ant; __entry->rx_ant = rx_ant; __entry->ret = ret; ), TP_printk( LOCAL_PR_FMT " tx_ant:%d rx_ant:%d ret:%d", LOCAL_PR_ARG, __entry->tx_ant, __entry->rx_ant, __entry->ret ) ); TRACE_EVENT(drv_get_antenna, TP_PROTO(struct ieee80211_local *local, u32 tx_ant, u32 rx_ant, int ret), TP_ARGS(local, tx_ant, rx_ant, ret), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, tx_ant) __field(u32, rx_ant) __field(int, ret) ), TP_fast_assign( LOCAL_ASSIGN; __entry->tx_ant = tx_ant; __entry->rx_ant = rx_ant; __entry->ret = ret; ), TP_printk( LOCAL_PR_FMT " tx_ant:%d rx_ant:%d ret:%d", LOCAL_PR_ARG, __entry->tx_ant, __entry->rx_ant, __entry->ret ) ); TRACE_EVENT(drv_remain_on_channel, TP_PROTO(struct ieee80211_local *local, struct ieee80211_channel *chan, enum nl80211_channel_type chantype, unsigned int duration), TP_ARGS(local, chan, chantype, duration), TP_STRUCT__entry( LOCAL_ENTRY __field(int, center_freq) __field(int, channel_type) __field(unsigned int, duration) ), TP_fast_assign( LOCAL_ASSIGN; __entry->center_freq = chan->center_freq; __entry->channel_type = chantype; __entry->duration = duration; ), TP_printk( LOCAL_PR_FMT " freq:%dMHz duration:%dms", LOCAL_PR_ARG, __entry->center_freq, __entry->duration ) ); DEFINE_EVENT(local_only_evt, drv_cancel_remain_on_channel, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_offchannel_tx, TP_PROTO(struct ieee80211_local *local, struct sk_buff *skb, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type, unsigned int wait), TP_ARGS(local, skb, chan, channel_type, wait), TP_STRUCT__entry( LOCAL_ENTRY __field(int, center_freq) __field(int, channel_type) __field(unsigned int, wait) ), TP_fast_assign( LOCAL_ASSIGN; __entry->center_freq = chan->center_freq; __entry->channel_type = channel_type; __entry->wait = wait; ), TP_printk( LOCAL_PR_FMT " freq:%dMHz, wait:%dms", LOCAL_PR_ARG, __entry->center_freq, __entry->wait ) ); TRACE_EVENT(drv_set_ringparam, TP_PROTO(struct ieee80211_local *local, u32 tx, u32 rx), TP_ARGS(local, tx, rx), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, tx) __field(u32, rx) ), TP_fast_assign( LOCAL_ASSIGN; __entry->tx = tx; __entry->rx = rx; ), TP_printk( LOCAL_PR_FMT " tx:%d rx %d", LOCAL_PR_ARG, __entry->tx, __entry->rx ) ); TRACE_EVENT(drv_get_ringparam, TP_PROTO(struct ieee80211_local *local, u32 *tx, u32 *tx_max, u32 *rx, u32 *rx_max), TP_ARGS(local, tx, tx_max, rx, rx_max), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, tx) __field(u32, tx_max) __field(u32, rx) __field(u32, rx_max) ), TP_fast_assign( LOCAL_ASSIGN; __entry->tx = *tx; __entry->tx_max = *tx_max; __entry->rx = *rx; __entry->rx_max = *rx_max; ), TP_printk( LOCAL_PR_FMT " tx:%d tx_max %d rx %d rx_max %d", LOCAL_PR_ARG, __entry->tx, __entry->tx_max, __entry->rx, __entry->rx_max ) ); DEFINE_EVENT(local_only_evt, drv_tx_frames_pending, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_only_evt, drv_offchannel_tx_cancel_wait, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(drv_set_bitrate_mask, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, const struct cfg80211_bitrate_mask *mask), TP_ARGS(local, sdata, mask), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __field(u32, legacy_2g) __field(u32, legacy_5g) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; __entry->legacy_2g = mask->control[IEEE80211_BAND_2GHZ].legacy; __entry->legacy_5g = mask->control[IEEE80211_BAND_5GHZ].legacy; ), TP_printk( LOCAL_PR_FMT VIF_PR_FMT " 2G Mask:0x%x 5G Mask:0x%x", LOCAL_PR_ARG, VIF_PR_ARG, __entry->legacy_2g, __entry->legacy_5g ) ); TRACE_EVENT(drv_set_rekey_data, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct cfg80211_gtk_rekey_data *data), TP_ARGS(local, sdata, data), TP_STRUCT__entry( LOCAL_ENTRY VIF_ENTRY __array(u8, kek, NL80211_KEK_LEN) __array(u8, kck, NL80211_KCK_LEN) __array(u8, replay_ctr, NL80211_REPLAY_CTR_LEN) ), TP_fast_assign( LOCAL_ASSIGN; VIF_ASSIGN; memcpy(__entry->kek, data->kek, NL80211_KEK_LEN); memcpy(__entry->kck, data->kck, NL80211_KCK_LEN); memcpy(__entry->replay_ctr, data->replay_ctr, NL80211_REPLAY_CTR_LEN); ), TP_printk(LOCAL_PR_FMT VIF_PR_FMT, LOCAL_PR_ARG, VIF_PR_ARG) ); TRACE_EVENT(drv_rssi_callback, TP_PROTO(struct ieee80211_local *local, enum ieee80211_rssi_event rssi_event), TP_ARGS(local, rssi_event), TP_STRUCT__entry( LOCAL_ENTRY __field(u32, rssi_event) ), TP_fast_assign( LOCAL_ASSIGN; __entry->rssi_event = rssi_event; ), TP_printk( LOCAL_PR_FMT " rssi_event:%d", LOCAL_PR_ARG, __entry->rssi_event ) ); DECLARE_EVENT_CLASS(release_evt, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data), TP_ARGS(local, sta, tids, num_frames, reason, more_data), TP_STRUCT__entry( LOCAL_ENTRY STA_ENTRY __field(u16, tids) __field(int, num_frames) __field(int, reason) __field(bool, more_data) ), TP_fast_assign( LOCAL_ASSIGN; STA_ASSIGN; __entry->tids = tids; __entry->num_frames = num_frames; __entry->reason = reason; __entry->more_data = more_data; ), TP_printk( LOCAL_PR_FMT STA_PR_FMT " TIDs:0x%.4x frames:%d reason:%d more:%d", LOCAL_PR_ARG, STA_PR_ARG, __entry->tids, __entry->num_frames, __entry->reason, __entry->more_data ) ); DEFINE_EVENT(release_evt, drv_release_buffered_frames, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data), TP_ARGS(local, sta, tids, num_frames, reason, more_data) ); DEFINE_EVENT(release_evt, drv_allow_buffered_frames, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data), TP_ARGS(local, sta, tids, num_frames, reason, more_data) ); /* * Tracing for API calls that drivers call. */ TRACE_EVENT(api_start_tx_ba_session, TP_PROTO(struct ieee80211_sta *sta, u16 tid), TP_ARGS(sta, tid), TP_STRUCT__entry( STA_ENTRY __field(u16, tid) ), TP_fast_assign( STA_ASSIGN; __entry->tid = tid; ), TP_printk( STA_PR_FMT " tid:%d", STA_PR_ARG, __entry->tid ) ); TRACE_EVENT(api_start_tx_ba_cb, TP_PROTO(struct ieee80211_sub_if_data *sdata, const u8 *ra, u16 tid), TP_ARGS(sdata, ra, tid), TP_STRUCT__entry( VIF_ENTRY __array(u8, ra, ETH_ALEN) __field(u16, tid) ), TP_fast_assign( VIF_ASSIGN; memcpy(__entry->ra, ra, ETH_ALEN); __entry->tid = tid; ), TP_printk( VIF_PR_FMT " ra:%pM tid:%d", VIF_PR_ARG, __entry->ra, __entry->tid ) ); TRACE_EVENT(api_stop_tx_ba_session, TP_PROTO(struct ieee80211_sta *sta, u16 tid), TP_ARGS(sta, tid), TP_STRUCT__entry( STA_ENTRY __field(u16, tid) ), TP_fast_assign( STA_ASSIGN; __entry->tid = tid; ), TP_printk( STA_PR_FMT " tid:%d", STA_PR_ARG, __entry->tid ) ); TRACE_EVENT(api_stop_tx_ba_cb, TP_PROTO(struct ieee80211_sub_if_data *sdata, const u8 *ra, u16 tid), TP_ARGS(sdata, ra, tid), TP_STRUCT__entry( VIF_ENTRY __array(u8, ra, ETH_ALEN) __field(u16, tid) ), TP_fast_assign( VIF_ASSIGN; memcpy(__entry->ra, ra, ETH_ALEN); __entry->tid = tid; ), TP_printk( VIF_PR_FMT " ra:%pM tid:%d", VIF_PR_ARG, __entry->ra, __entry->tid ) ); DEFINE_EVENT(local_only_evt, api_restart_hw, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(api_beacon_loss, TP_PROTO(struct ieee80211_sub_if_data *sdata), TP_ARGS(sdata), TP_STRUCT__entry( VIF_ENTRY ), TP_fast_assign( VIF_ASSIGN; ), TP_printk( VIF_PR_FMT, VIF_PR_ARG ) ); TRACE_EVENT(api_connection_loss, TP_PROTO(struct ieee80211_sub_if_data *sdata), TP_ARGS(sdata), TP_STRUCT__entry( VIF_ENTRY ), TP_fast_assign( VIF_ASSIGN; ), TP_printk( VIF_PR_FMT, VIF_PR_ARG ) ); TRACE_EVENT(api_cqm_rssi_notify, TP_PROTO(struct ieee80211_sub_if_data *sdata, enum nl80211_cqm_rssi_threshold_event rssi_event), TP_ARGS(sdata, rssi_event), TP_STRUCT__entry( VIF_ENTRY __field(u32, rssi_event) ), TP_fast_assign( VIF_ASSIGN; __entry->rssi_event = rssi_event; ), TP_printk( VIF_PR_FMT " event:%d", VIF_PR_ARG, __entry->rssi_event ) ); TRACE_EVENT(api_scan_completed, TP_PROTO(struct ieee80211_local *local, bool aborted), TP_ARGS(local, aborted), TP_STRUCT__entry( LOCAL_ENTRY __field(bool, aborted) ), TP_fast_assign( LOCAL_ASSIGN; __entry->aborted = aborted; ), TP_printk( LOCAL_PR_FMT " aborted:%d", LOCAL_PR_ARG, __entry->aborted ) ); TRACE_EVENT(api_sched_scan_results, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local), TP_STRUCT__entry( LOCAL_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; ), TP_printk( LOCAL_PR_FMT, LOCAL_PR_ARG ) ); TRACE_EVENT(api_sched_scan_stopped, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local), TP_STRUCT__entry( LOCAL_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; ), TP_printk( LOCAL_PR_FMT, LOCAL_PR_ARG ) ); TRACE_EVENT(api_sta_block_awake, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta, bool block), TP_ARGS(local, sta, block), TP_STRUCT__entry( LOCAL_ENTRY STA_ENTRY __field(bool, block) ), TP_fast_assign( LOCAL_ASSIGN; STA_ASSIGN; __entry->block = block; ), TP_printk( LOCAL_PR_FMT STA_PR_FMT " block:%d", LOCAL_PR_ARG, STA_PR_FMT, __entry->block ) ); TRACE_EVENT(api_chswitch_done, TP_PROTO(struct ieee80211_sub_if_data *sdata, bool success), TP_ARGS(sdata, success), TP_STRUCT__entry( VIF_ENTRY __field(bool, success) ), TP_fast_assign( VIF_ASSIGN; __entry->success = success; ), TP_printk( VIF_PR_FMT " success=%d", VIF_PR_ARG, __entry->success ) ); DEFINE_EVENT(local_only_evt, api_ready_on_channel, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); DEFINE_EVENT(local_only_evt, api_remain_on_channel_expired, TP_PROTO(struct ieee80211_local *local), TP_ARGS(local) ); TRACE_EVENT(api_gtk_rekey_notify, TP_PROTO(struct ieee80211_sub_if_data *sdata, const u8 *bssid, const u8 *replay_ctr), TP_ARGS(sdata, bssid, replay_ctr), TP_STRUCT__entry( VIF_ENTRY __array(u8, bssid, ETH_ALEN) __array(u8, replay_ctr, NL80211_REPLAY_CTR_LEN) ), TP_fast_assign( VIF_ASSIGN; memcpy(__entry->bssid, bssid, ETH_ALEN); memcpy(__entry->replay_ctr, replay_ctr, NL80211_REPLAY_CTR_LEN); ), TP_printk(VIF_PR_FMT, VIF_PR_ARG) ); TRACE_EVENT(api_enable_rssi_reports, TP_PROTO(struct ieee80211_sub_if_data *sdata, int rssi_min_thold, int rssi_max_thold), TP_ARGS(sdata, rssi_min_thold, rssi_max_thold), TP_STRUCT__entry( VIF_ENTRY __field(int, rssi_min_thold) __field(int, rssi_max_thold) ), TP_fast_assign( VIF_ASSIGN; __entry->rssi_min_thold = rssi_min_thold; __entry->rssi_max_thold = rssi_max_thold; ), TP_printk( VIF_PR_FMT " rssi_min_thold =%d, rssi_max_thold = %d", VIF_PR_ARG, __entry->rssi_min_thold, __entry->rssi_max_thold ) ); TRACE_EVENT(api_eosp, TP_PROTO(struct ieee80211_local *local, struct ieee80211_sta *sta), TP_ARGS(local, sta), TP_STRUCT__entry( LOCAL_ENTRY STA_ENTRY ), TP_fast_assign( LOCAL_ASSIGN; STA_ASSIGN; ), TP_printk( LOCAL_PR_FMT STA_PR_FMT, LOCAL_PR_ARG, STA_PR_FMT ) ); /* * Tracing for internal functions * (which may also be called in response to driver calls) */ TRACE_EVENT(wake_queue, TP_PROTO(struct ieee80211_local *local, u16 queue, enum queue_stop_reason reason), TP_ARGS(local, queue, reason), TP_STRUCT__entry( LOCAL_ENTRY __field(u16, queue) __field(u32, reason) ), TP_fast_assign( LOCAL_ASSIGN; __entry->queue = queue; __entry->reason = reason; ), TP_printk( LOCAL_PR_FMT " queue:%d, reason:%d", LOCAL_PR_ARG, __entry->queue, __entry->reason ) ); TRACE_EVENT(stop_queue, TP_PROTO(struct ieee80211_local *local, u16 queue, enum queue_stop_reason reason), TP_ARGS(local, queue, reason), TP_STRUCT__entry( LOCAL_ENTRY __field(u16, queue) __field(u32, reason) ), TP_fast_assign( LOCAL_ASSIGN; __entry->queue = queue; __entry->reason = reason; ), TP_printk( LOCAL_PR_FMT " queue:%d, reason:%d", LOCAL_PR_ARG, __entry->queue, __entry->reason ) ); #endif /* !__MAC80211_DRIVER_TRACE || TRACE_HEADER_MULTI_READ */ #undef TRACE_INCLUDE_PATH #define TRACE_INCLUDE_PATH . #undef TRACE_INCLUDE_FILE #define TRACE_INCLUDE_FILE driver-trace #include <trace/define_trace.h>
chunyeow/greenmesh
net/mac80211/driver-trace.h
C
gpl-2.0
31,797
18.873125
114
0.65654
false
import win32pipe import win32console import win32process import time import win32con import codecs import ctypes user32 = ctypes.windll.user32 CONQUE_WINDOWS_VK = { '3' : win32con.VK_CANCEL, '8' : win32con.VK_BACK, '9' : win32con.VK_TAB, '12' : win32con.VK_CLEAR, '13' : win32con.VK_RETURN, '17' : win32con.VK_CONTROL, '20' : win32con.VK_CAPITAL, '27' : win32con.VK_ESCAPE, '28' : win32con.VK_CONVERT, '35' : win32con.VK_END, '36' : win32con.VK_HOME, '37' : win32con.VK_LEFT, '38' : win32con.VK_UP, '39' : win32con.VK_RIGHT, '40' : win32con.VK_DOWN, '45' : win32con.VK_INSERT, '46' : win32con.VK_DELETE, '47' : win32con.VK_HELP } def make_input_key(c, control_key_state=None): kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT) kc.KeyDown = True kc.RepeatCount = 1 cnum = ord(c) if cnum == 3: pid_list = win32console.GetConsoleProcessList() win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) return else: kc.Char = unicode(c) if str(cnum) in CONQUE_WINDOWS_VK: kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)] else: kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum) #kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96) #kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED return kc #win32console.AttachConsole() coord = win32console.PyCOORDType con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) flags = win32process.NORMAL_PRIORITY_CLASS si = win32process.STARTUPINFO() si.dwFlags |= win32con.STARTF_USESHOWWINDOW (handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si) time.sleep(1) #size = con_stdout.GetConsoleScreenBufferInfo()['Window'] # with codecs.open("log.txt", "w", "utf8") as f: # for i in xrange(0, size.Bottom): # f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i))) # f.write("\n") import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = "127.0.0.1" PORT = 5554 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) (sc, scname) = s.accept() while True: msg = sc.recv(1) if ord(msg) == 0: break keys = [make_input_key(msg)] if keys: con_stdin.WriteConsoleInput(keys) win32process.TerminateProcess(handle1, 0)
viswimmer1/PythonGenerator
data/python_files/34574373/cmss.py
Python
gpl-2.0
2,623
26.846154
109
0.643157
false
class EventsController < ApplicationController before_filter :authorize_organizer, except: [:index, :show] def index @events_upcoming = Event.paginate(page: params[:page_upcoming], :per_page => 5).upcoming() @events_past = Event.paginate(page: params[:page_past], :per_page => 5).past() @events_past_count = Event.past().count end def show @event = Event.find(params[:id]) end def new @event = Event.new @event.date = Date.today end def edit @event = Event.find(params[:id]) end def create @event = Event.new(params[:event]) if @event.save flash[:success] = "Event was successfully created." redirect_to @event else render 'new' end end def update @event = Event.find(params[:id]) if @event.update_attributes(params[:event]) flash[:success] = "Event was successfully updated." redirect_to @event else render 'edit' end end def destroy @event = Event.find(params[:id]) @event.destroy flash[:success] = "Event was successfully deleted." redirect_to events_url end end
sfreihofer/nama
app/controllers/events_controller.rb
Ruby
gpl-2.0
1,094
20.038462
94
0.651737
false
<?php global $woocommerce; ?> <?php $woocommerce->show_messages(); ?> <?php do_action('woocommerce_before_customer_login_form'); ?> <?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?> <div class="col2-set" id="customer_login"> <div class="col-1"> <?php endif; ?> <h2><?php _e('Login', 'sp'); ?></h2> <form method="post" class="login"> <p class="form-row form-row-first"> <label for="username"><?php _e('Username', 'sp'); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="username" id="username" /> </p> <p class="form-row form-row-last"> <label for="password"><?php _e('Password', 'sp'); ?> <span class="required">*</span></label> <input class="input-text" type="password" name="password" id="password" /> </p> <div class="group"></div> <p class="form-row"> <?php $woocommerce->nonce_field('login', 'login') ?> <input type="submit" class="button" name="login" value="<?php _e('Login', 'sp'); ?>" /> <a class="lost_password" href="<?php echo esc_url( wp_lostpassword_url( home_url() ) ); ?>"><?php _e('Lost Password?', 'sp'); ?></a> </p> </form> <?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?> </div> <div class="col-2"> <h2><?php _e('Register', 'sp'); ?></h2> <form method="post" class="register"> <p class="form-row form-row-first"> <label for="reg_username"><?php _e('Username', 'sp'); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="username" id="reg_username" value="<?php if (isset($_POST['username'])) echo esc_attr($_POST['username']); ?>" /> </p> <p class="form-row form-row-last"> <label for="reg_email"><?php _e('Email', 'sp'); ?> <span class="required">*</span></label> <input type="email" class="input-text" name="email" id="reg_email" value="<?php if (isset($_POST['email'])) echo esc_attr($_POST['email']); ?>" /> </p> <div class="group"></div> <p class="form-row form-row-first"> <label for="reg_password"><?php _e('Password', 'sp'); ?> <span class="required">*</span></label> <input type="password" class="input-text" name="password" id="reg_password" value="<?php if (isset($_POST['password'])) echo esc_attr($_POST['password']); ?>" /> </p> <p class="form-row form-row-last"> <label for="reg_password2"><?php _e('Re-enter password', 'sp'); ?> <span class="required">*</span></label> <input type="password" class="input-text" name="password2" id="reg_password2" value="<?php if (isset($_POST['password2'])) echo esc_attr($_POST['password2']); ?>" /> </p> <div class="group"></div> <!-- Spam Trap --> <div style="left:-999em; position:absolute;"><label for="trap">Anti-spam</label><input type="text" name="email_2" id="trap" /></div> <?php do_action( 'register_form' ); ?> <p class="form-row"> <?php $woocommerce->nonce_field('register', 'register') ?> <input type="submit" class="button" name="register" value="<?php _e('Register', 'sp'); ?>" /> </p> </form> </div> </div> <?php endif; ?> <?php do_action('woocommerce_after_customer_login_form'); ?>
MedvedevKir/gmtest.ru
wp-content/themes/mio/woocommerce/myaccount/form-login.php
PHP
gpl-2.0
3,275
39.481013
169
0.576183
false
#!/bin/bash # ########################################################### # copie_clepub_veyon.sh # Ce script est à lancer sur les clients veyon # Il recupère la clé publique "teacher" du poste "maitre" veyon # 20180327 ########################################################## DATE1=$(date +%F+%0kh%0M) #Couleurs ROUGE="\\033[1;31m" VERT="\\033[1;32m" BLEU="\\033[1;34m" JAUNE="\\033[1;33m" COLTITRE="\033[1;35m" # Rose COLDEFAUT="\033[0;33m" # Brun-jaune COLCMD="\033[1;37m" # Blanc COLERREUR="\033[1;31m" # Rouge COLTXT="\033[0;37m" # Gris COLINFO="\033[0;36m" # Cyan COLPARTIE="\033[1;34m" # Bleu cle=key repcle=/etc/veyon/keys/public/teacher echo -e "$JAUNE" echo "###########################################################################" echo "" echo "Voulez-vous configurer veyon (client) sur ce poste ?" echo "Il faudra indiquer l'adresse ip du poste maitre veyon et son mdp root." echo "" echo "###########################################################################" echo -e "$COLTXT" echo -e "$COLINFO" read -p "Que voulez-vous faire ? 1 (je veux configurer veyon sur ce client) 2 (non, je veux sortir !) : " rep echo -e "$COLTXT" case $rep in 1 ) echo -e "$JAUNE" echo "Entrez l'adresse ip du poste veyon-master : " echo -e "$COLTXT" read IPMAST cd /etc rm -rf veyon cd mkdir -p $repcle #mv $repcle/$cle $repcle/cle_$DATE1 cd $repcle scp root@$IPMAST:$repcle/$cle . || ERREUR="1" if [ "$ERREUR" = "1" ];then echo -e "$COLERREUR" echo "Erreur lors de la copie de la clé..." echo "Vérifier l'adresse ip du poste veyon-master puis relancez le script." echo -e "$COLTXT" else # Ajustement des droits et message cd /etc chmod -R 777 veyon/ echo -e "$VERT" echo "La clé a été copiée depuis le poste veyon-master $IPMAST" echo -e "$COLTXT" # Neutralisation de master et de configurator sur le poste eleve chmod -x /usr/bin/veyon-master chmod -x /usr/bin/veyon-configurator cd /usr/share/applications mv veyon-master.desktop veyon-master.desktop.bak mv veyon-configurator.desktop veyon-configurator.desktop.bak cd echo -e "$COLDEFAUT" echo "Info : veyon-master et veyon-configurator ont été désactivés sur ce poste." echo -e "$COLTXT" fi ;; * ) echo -e "$COLINFO" echo "Pas de copie demandée." echo -e "$VERT" echo "###########################################################################" echo "" echo "Vous pourrez copier la clé publique veyon plus tard en lançant le script" echo "/mnt/netlogon/alancer/copie_clepub_veyon.sh" echo "" echo "###########################################################################" echo -e "$COLINFO" echo "A bientôt !" echo -e "$COLTXT" exit 0 ;; esac echo "Terminé !" exit 0
jcmousse/clinux
se3/alancer/copie_clepub_veyon.sh
Shell
gpl-2.0
3,308
32.232323
121
0.472644
false
$('#section').on('click', '[id$="Empty"]', function(event) { event.preventDefault(); var match = /(.+)Empty/.exec($(event.target).closest('.unwell').attr('id')); var id = match[1]; var emptyId = match[0]; $('#'+id).trigger('addrow'); $('#'+emptyId).addClass('hidden'); return false; }); $('#section').on('submit', 'form[name="formItem"]', function(e) { e.preventDefault(); var form = $(this), btn = form.find('.btn-primary'), valid = isFormValid(form); $('select[name$=".type"]:not(:disabled)').each(function(i,e){ if($(e).val() == "Select an option"){ valid = false; showPermanentError(form, "Please select a valid action."); } }); if (valid) { btn.button('loading'); resetAlert($('#section')); $.ajax({ type: 'POST', url: form.attr('action'), data: form.serialize() }).always(function() { btn.button('reset'); }).done(function(data, textStatus, jqXHR) { showSuccess(form, "Saved"); window.location.hash = "#config/portal_module/"+form.find('input[name="id"]').val()+"/read" }).fail(function(jqXHR) { $("body,html").animate({scrollTop:0}, 'fast'); var status_msg = getStatusMsg(jqXHR); showPermanentError(form, status_msg); }); } }); $('#section').on('click', '.delete-portal-module', function(e){ e.preventDefault(); var button = $(e.target); button.button('loading'); $.ajax({ type: 'GET', url: button.attr('href'), }).always(function() { }).done(function(data, textStatus, jqXHR) { showSuccess(button.closest('.table'), "Deleted"); button.closest('tr').remove(); }).fail(function(jqXHR) { button.button('reset'); $("body,html").animate({scrollTop:0}, 'fast'); var status_msg = getStatusMsg(jqXHR); showPermanentError(button.closest('.table'), status_msg); }); return false; }); $('#section').on('click', '.expand', function(e){ e.preventDefault(); $(e.target).hide(function(){ $($(e.target).attr('data-expand')).slideDown(); }); return false; }); $('#section').on('change', '#actions select[name$=".type"]', function(event) { var type_input = $(event.currentTarget); updateActionMatchInput(type_input,false); }); $('#section').on('click', '#actionsContainer a[href="#add"]', function(event) { setTimeout(initActionMatchInput, 3000); }); function initActionMatchInput() { $('select[name$=".type"]:not(:disabled)').each(function(i,e){ updateActionMatchInput($(e),true); }); } function updateActionMatchInput(type_input, keep) { var match_input = type_input.next(); var type_value = type_input.val(); var match_input_template_id = '#' + type_value + "_action_match"; var match_input_template = $(match_input_template_id); if ( match_input_template.length == 0 ) { match_input_template = $('#default_action_match'); } if ( match_input_template.length ) { changeInputFromTemplate(match_input, match_input_template, keep); if (type_value == "switch") { type_input.next().typeahead({ source: searchSwitchesGenerator($('#section h2')), minLength: 2, items: 11, matcher: function(item) { return true; } }); } } }
jrouzierinverse/packetfence
html/pfappserver/root/static/admin/config/portal_modules.js
JavaScript
gpl-2.0
3,343
29.669725
99
0.580317
false
/* * EffecTV for Android * Copyright (C) 2013 Morihiro Soft * * MatrixTV.h : * * 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. */ /* * EffecTV - Realtime Digital Video Effector * Copyright (C) 2001-2006 FUKUCHI Kentaro * * matrixTV - A Matrix Like effect. * This plugin for EffectTV is under GNU General Public License * See the "COPYING" that should be shiped with this source code * Copyright (C) 2001-2003 Monniez Christophe * d-fence@swing.be * * 2003/12/24 Kentaro Fukuchi * - Completely rewrote but based on Monniez's idea. * - Uses edge detection, not only G value of each pixel. * - Added 4x4 font includes number, alphabet and Japanese Katakana characters. */ #ifndef __MATRIXTV__ #define __MATRIXTV__ #include "BaseEffecTV.h" class MatrixTV : public BaseEffecTV { typedef BaseEffecTV super; protected: struct Blip { int mode; int y; int timer; int speed; }; int show_info; int mode; int pause; int mapW; int mapH; unsigned char* cmap; unsigned char* vmap; unsigned char* img; unsigned char* font; RGB32* palette; Blip* blips; virtual void intialize(bool reset); virtual int readConfig(); virtual int writeConfig(); public: MatrixTV(void); virtual ~MatrixTV(void); virtual const char* name(void); virtual const char* title(void); virtual const char** funcs(void); virtual int start(Utils* utils, int width, int height); virtual int stop(void); virtual int draw(YUV* src_yuv, RGB32* dst_rgb, char* dst_msg); virtual const char* event(int key_code); virtual const char* touch(int action, int x, int y); protected: RGB32 green(unsigned int v); int setPalette(void); int setPattern(void); void drawChar(RGB32* dst, unsigned char c, unsigned char v); void createImg(RGB32* src); void updateCharMap(void); void darkenColumn(int); void blipNone(int x); void blipFall(int x); void blipStop(int x); void blipSlide(int x); }; #endif // __MATRIXTV__
MorihiroSoft/EffecTV_for_Android
jni/effects/MatrixTV.h
C
gpl-2.0
2,596
25.762887
82
0.72188
false
jQuery(function($){ $.supersized({ //Functionality slideshow : 1, //Slideshow on/off autoplay : 1, //Slideshow starts playing automatically start_slide : 1, //Start slide (0 is random) slide_interval : 4000, //Length between transitions slideshow_interval : 4000, //Length between transitions transition : 1, //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left transition_speed : 500, //Speed of transition new_window : 1, //Image links open in new window/tab pause_hover : 0, //Pause slideshow on hover keyboard_nav : 1, //Keyboard navigation on/off performance : 1, //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit) image_protect : 1, //Disables image dragging and right click with Javascript image_path : 'img/', //Default image path //Size & Position min_width : 0, //Min width allowed (in pixels) min_height : 0, //Min height allowed (in pixels) vertical_center : 1, //Vertically center background horizontal_center : 1, //Horizontally center background fit_portrait : 1, //Portrait images will not exceed browser height fit_landscape : 0, //Landscape images will not exceed browser width //Components navigation : 1, //Slideshow controls on/off thumbnail_navigation : 1, //Thumbnail navigation slide_counter : 1, //Display slide numbers slide_captions : 1, //Slide caption (Pull from "title" in slides array) slides : (function(){ var ret = new Array(); for(var i in supersizedImgs){ ret.push({image: supersizedImgs[i]}); } return ret; })() }); });
infosecdev/markroxberry
wp-content/themes/widephoto/supersized/js/supersized.imgs.js
JavaScript
gpl-2.0
2,098
47.813953
160
0.56101
false
/* * This file is part of the coreboot project. * * Copyright (C) 2012 ChromeOS 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; 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <string.h> #include <cbfs.h> #include <cbmem.h> #include <console/console.h> #include <arch/cpu.h> #include <cpu/x86/bist.h> #include <cpu/x86/msr.h> #include <cpu/x86/mtrr.h> #include <halt.h> #include <lib.h> #include <timestamp.h> #include <arch/io.h> #include <arch/stages.h> #include <device/pci_def.h> #include <cpu/x86/lapic.h> #include <cbfs.h> #include <romstage_handoff.h> #include <reset.h> #include <stage_cache.h> #include <vendorcode/google/chromeos/chromeos.h> #if CONFIG_EC_GOOGLE_CHROMEEC #include <ec/google/chromeec/ec.h> #endif #include "haswell.h" #include "northbridge/intel/haswell/haswell.h" #include "northbridge/intel/haswell/raminit.h" #include "southbridge/intel/lynxpoint/pch.h" #include "southbridge/intel/lynxpoint/me.h" static inline void reset_system(void) { hard_reset(); halt(); } /* The cache-as-ram assembly file calls romstage_main() after setting up * cache-as-ram. romstage_main() will then call the mainboards's * mainboard_romstage_entry() function. That function then calls * romstage_common() below. The reason for the back and forth is to provide * common entry point from cache-as-ram while still allowing for code sharing. * Because we can't use global variables the stack is used for allocations -- * thus the need to call back and forth. */ static inline u32 *stack_push(u32 *stack, u32 value) { stack = &stack[-1]; *stack = value; return stack; } /* Romstage needs quite a bit of stack for decompressing images since the lzma * lib keeps its state on the stack during romstage. */ #define ROMSTAGE_RAM_STACK_SIZE 0x5000 static unsigned long choose_top_of_stack(void) { unsigned long stack_top; /* cbmem_add() does a find() before add(). */ stack_top = (unsigned long)cbmem_add(CBMEM_ID_ROMSTAGE_RAM_STACK, ROMSTAGE_RAM_STACK_SIZE); stack_top += ROMSTAGE_RAM_STACK_SIZE; return stack_top; } /* setup_romstage_stack_after_car() determines the stack to use after * cache-as-ram is torn down as well as the MTRR settings to use. */ static void *setup_romstage_stack_after_car(void) { unsigned long top_of_stack; int num_mtrrs; u32 *slot; u32 mtrr_mask_upper; u32 top_of_ram; /* Top of stack needs to be aligned to a 4-byte boundary. */ top_of_stack = choose_top_of_stack() & ~3; slot = (void *)top_of_stack; num_mtrrs = 0; /* The upper bits of the MTRR mask need to set according to the number * of physical address bits. */ mtrr_mask_upper = (1 << ((cpuid_eax(0x80000008) & 0xff) - 32)) - 1; /* The order for each MTRR is value then base with upper 32-bits of * each value coming before the lower 32-bits. The reasoning for * this ordering is to create a stack layout like the following: * +0: Number of MTRRs * +4: MTRR base 0 31:0 * +8: MTRR base 0 63:32 * +12: MTRR mask 0 31:0 * +16: MTRR mask 0 63:32 * +20: MTRR base 1 31:0 * +24: MTRR base 1 63:32 * +28: MTRR mask 1 31:0 * +32: MTRR mask 1 63:32 */ /* Cache the ROM as WP just below 4GiB. */ slot = stack_push(slot, mtrr_mask_upper); /* upper mask */ slot = stack_push(slot, ~(CACHE_ROM_SIZE - 1) | MTRRphysMaskValid); slot = stack_push(slot, 0); /* upper base */ slot = stack_push(slot, ~(CACHE_ROM_SIZE - 1) | MTRR_TYPE_WRPROT); num_mtrrs++; /* Cache RAM as WB from 0 -> CONFIG_RAMTOP. */ slot = stack_push(slot, mtrr_mask_upper); /* upper mask */ slot = stack_push(slot, ~(CONFIG_RAMTOP - 1) | MTRRphysMaskValid); slot = stack_push(slot, 0); /* upper base */ slot = stack_push(slot, 0 | MTRR_TYPE_WRBACK); num_mtrrs++; top_of_ram = (uint32_t)cbmem_top(); /* Cache 8MiB below the top of ram. On haswell systems the top of * ram under 4GiB is the start of the TSEG region. It is required to * be 8MiB aligned. Set this area as cacheable so it can be used later * for ramstage before setting up the entire RAM as cacheable. */ slot = stack_push(slot, mtrr_mask_upper); /* upper mask */ slot = stack_push(slot, ~((8 << 20) - 1) | MTRRphysMaskValid); slot = stack_push(slot, 0); /* upper base */ slot = stack_push(slot, (top_of_ram - (8 << 20)) | MTRR_TYPE_WRBACK); num_mtrrs++; /* Cache 8MiB at the top of ram. Top of ram on haswell systems * is where the TSEG region resides. However, it is not restricted * to SMM mode until SMM has been relocated. By setting the region * to cacheable it provides faster access when relocating the SMM * handler as well as using the TSEG region for other purposes. */ slot = stack_push(slot, mtrr_mask_upper); /* upper mask */ slot = stack_push(slot, ~((8 << 20) - 1) | MTRRphysMaskValid); slot = stack_push(slot, 0); /* upper base */ slot = stack_push(slot, top_of_ram | MTRR_TYPE_WRBACK); num_mtrrs++; /* Save the number of MTRRs to setup. Return the stack location * pointing to the number of MTRRs. */ slot = stack_push(slot, num_mtrrs); return slot; } void * asmlinkage romstage_main(unsigned long bist) { int i; void *romstage_stack_after_car; const int num_guards = 4; const u32 stack_guard = 0xdeadbeef; u32 *stack_base = (void *)(CONFIG_DCACHE_RAM_BASE + CONFIG_DCACHE_RAM_SIZE - CONFIG_DCACHE_RAM_ROMSTAGE_STACK_SIZE); printk(BIOS_DEBUG, "Setting up stack guards.\n"); for (i = 0; i < num_guards; i++) stack_base[i] = stack_guard; mainboard_romstage_entry(bist); /* Check the stack. */ for (i = 0; i < num_guards; i++) { if (stack_base[i] == stack_guard) continue; printk(BIOS_DEBUG, "Smashed stack detected in romstage!\n"); } /* Get the stack to use after cache-as-ram is torn down. */ romstage_stack_after_car = setup_romstage_stack_after_car(); return romstage_stack_after_car; } void romstage_common(const struct romstage_params *params) { int boot_mode; int wake_from_s3; struct romstage_handoff *handoff; timestamp_init(get_initial_timestamp()); timestamp_add_now(TS_START_ROMSTAGE); if (params->bist == 0) enable_lapic(); wake_from_s3 = early_pch_init(params->gpio_map, params->rcba_config); #if CONFIG_EC_GOOGLE_CHROMEEC /* Ensure the EC is in the right mode for recovery */ google_chromeec_early_init(); #endif /* Halt if there was a built in self test failure */ report_bist_failure(params->bist); /* Perform some early chipset initialization required * before RAM initialization can work */ haswell_early_initialization(HASWELL_MOBILE); printk(BIOS_DEBUG, "Back from haswell_early_initialization()\n"); if (wake_from_s3) { #if CONFIG_HAVE_ACPI_RESUME printk(BIOS_DEBUG, "Resume from S3 detected.\n"); #else printk(BIOS_DEBUG, "Resume from S3 detected, but disabled.\n"); wake_from_s3 = 0; #endif } /* There are hard coded assumptions of 2 meaning s3 wake. Normalize * the users of the 2 literal here based off wake_from_s3. */ boot_mode = wake_from_s3 ? 2 : 0; /* Prepare USB controller early in S3 resume */ if (wake_from_s3) enable_usb_bar(); post_code(0x3a); params->pei_data->boot_mode = boot_mode; timestamp_add_now(TS_BEFORE_INITRAM); report_platform_info(); if (params->copy_spd != NULL) params->copy_spd(params->pei_data); sdram_initialize(params->pei_data); timestamp_add_now(TS_AFTER_INITRAM); post_code(0x3b); intel_early_me_status(); quick_ram_check(); post_code(0x3e); if (!wake_from_s3) { cbmem_initialize_empty(); stage_cache_create_empty(); /* Save data returned from MRC on non-S3 resumes. */ save_mrc_data(params->pei_data); } else { stage_cache_recover(); if (cbmem_initialize()) { #if CONFIG_HAVE_ACPI_RESUME /* Failed S3 resume, reset to come up cleanly */ reset_system(); #endif } } handoff = romstage_handoff_find_or_add(); if (handoff != NULL) handoff->s3_resume = wake_from_s3; else printk(BIOS_DEBUG, "Romstage handoff structure not added!\n"); post_code(0x3f); #if CONFIG_CHROMEOS init_chromeos(boot_mode); #endif timestamp_add_now(TS_END_ROMSTAGE); } static inline void prepare_for_resume(struct romstage_handoff *handoff) { /* Only need to save memory when ramstage isn't relocatable. */ #if !CONFIG_RELOCATABLE_RAMSTAGE #if CONFIG_HAVE_ACPI_RESUME /* Back up the OS-controlled memory where ramstage will be loaded. */ if (handoff != NULL && handoff->s3_resume) { void *src = (void *)CONFIG_RAMBASE; void *dest = cbmem_find(CBMEM_ID_RESUME); if (dest != NULL) memcpy(dest, src, HIGH_MEMORY_SAVE); } #endif #endif } void romstage_after_car(void) { struct romstage_handoff *handoff; handoff = romstage_handoff_find_or_add(); prepare_for_resume(handoff); /* Load the ramstage. */ copy_and_run(); } #if IS_ENABLED(CONFIG_CACHE_RELOCATED_RAMSTAGE_OUTSIDE_CBMEM) void stage_cache_external_region(void **base, size_t *size) { /* The ramstage cache lives in the TSEG region at RESERVED_SMM_OFFSET. * The top of ram is defined to be the TSEG base address. */ *size = RESERVED_SMM_SIZE; *base = (void *)((uint32_t)cbmem_top() + RESERVED_SMM_OFFSET); } void ramstage_cache_invalid(void) { #if CONFIG_RESET_ON_INVALID_RAMSTAGE_CACHE reset_system(); #endif } #endif
coreboot-gs45/coreboot
src/cpu/intel/haswell/romstage.c
C
gpl-2.0
9,829
28.694864
78
0.689999
false
package com.mmm.product.domain; import java.io.Serializable; public class ShippingDetails implements Serializable{ private static final long serialVersionUID = 5941389959992371612L; }
Lnjena/mmm.com
mmm-spring-boot/src/main/java/com/mmm/product/domain/ShippingDetails.java
Java
gpl-2.0
189
20
67
0.825397
false
package org.jiserte.bioformats.readers.phylip; import org.jiserte.bioformats.readers.faults.AlignmentReadingFault; public class FirstBlockLinePhylipFault extends AlignmentReadingFault { public FirstBlockLinePhylipFault() { super(); this.setMessage("Sequences in the first block of data must have a description of 10 characters and then the sequence."); } }
javieriserte/XI-bio-formats
XI-Bio-Formats/src/org/jiserte/bioformats/readers/phylip/FirstBlockLinePhylipFault.java
Java
gpl-2.0
378
21.235294
122
0.783069
false
<?php /*======================================================================= // File: BACKEND.INC.PHP // Description: All various output backends for QR barcodes available // Created: 2008-08-01 // Ver: $Id: backend.inc.php 1504 2009-07-06 13:34:57Z ljp $ // // Copyright (c) 2008 Aditus Consulting. All rights reserved. //======================================================================== */ DEFINE('BACKEND_ASCII', 0); DEFINE('BACKEND_IMAGE', 1); DEFINE('BACKEND_PS', 2); DEFINE('BACKEND_EPS', 3); //-------------------------------------------------------------------------------- // Class: QRCodeBackend // Description: Parent class for all common functionality for barcode backends //-------------------------------------------------------------------------------- class QRCodeBackend { protected $iEncoder = NULL; protected $iModWidth = 2; protected $iInv = false; protected $iQuietZone = 0; protected $iError = 0; protected $iQRInfo = array(); // Holds some infromation the QR code just generated function __construct($aBarcodeEncoder) { $this->iEncoder = $aBarcodeEncoder; } function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') { if( $aDebug !== FALSE ) { $this->iEncoder->SetDebugLevel($aDebug); } // If data is an array we assume it is supposed to be manual encodation. // (A more thorough data check is made in the encodation class) $manual = is_array($aData) ; // Return the print specificiation (QRLayout) return $this->iEncoder->Enc($aData, $manual); } function GetQRInfo() { return $this->iQRInfo; } function isCmdLine() { $s=php_sapi_name(); return substr($s, 0, 3) == 'cli'; } function fmtInfo($aS) { if ( !$this->isCmdLine() ) { return '<pre>' . $aS . '<pre>'; } else return $aS; } function SetModuleWidth($aW) { $this->iModWidth = $aW; } function SetQuietZone($aW) { $this->iQuietZone = $aW; } function SetTilde($aFlg = true) { //throw new QRException('Tilde processing is not yet supported for QR Barcodes.',-1); throw new QRExceptionL(1000); //$this->iEncoder->SetTilde($aFlg); } function SetInvert($aFlg = true) { //throw new QRException("Inverting the bit pattern is not supported for QR Barcodes.",-1); throw new QRExceptionL(1001); } function GetError() { return $this->iError; } function StrokeFromFile($aFromFileName,$aFileName='',$aDebug=FALSE) { $data = @file_get_contents($aFromFileName); if( $data === FALSE ) { //throw new QRException("Cannot read data from file $aFromFileName"); throw new QRExceptionL(1002,$aFromFileName); } $this->Stroke($data,$aFileName,$aDebug); } } //-------------------------------------------------------------------------------- // Class: QRCodeBackend_PS // Description: Backend to generate postscript (or EPS) representation of the barcode //-------------------------------------------------------------------------------- class QRCodeBackend_PS extends QRCodeBackend { private $iEPS = false; function __construct($aBarcodeEncoder) { parent::__construct($aBarcodeEncoder); } function SetEPS($aFlg=true) { $this->iEPS = $aFlg; } function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') { $pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile); $w = $this->iModWidth; $n = $pspec->iSize[0]; // width/height of matrix $ystart = 4*$w + $n*$w; $xstart = 4*$w ; $totwidth = $n*$w+8*$w ; $totheight = $n*$w+8*$w ; $psbar = "%Data: $aData\n"; $psbar .= "%Each line represents one row and the x-position for black modules: [xpos]\n"; if( is_array($aData)) { $data = " (manual encodation schemas) \n"; $m = count($aData); for($i=0; $i < $m; $i++) { $data .= "%% (" . $aData[$i][0] . " : " . $aData[$i][1] . ")\n" ; } $aData = $data; } $y = $ystart; $psbar .= "\n"; $psbar .= ($w+0.05)." setlinewidth\n"; for( $r=0; $r < $n ; ++$r, $y -= $w ) { $psbar .= '['; $x = $xstart; for( $i=0; $i < $n; ++$i, $x += $w ) { if( $pspec->iMatrix[$r][$i] == 1) { $psbar .= "[$x]"; } } $psbar .= "] {{} forall $y moveto 0 -".($w+0.05)." rlineto stroke} forall\n"; } $psbar .= "\n"; $y += 4*$w; $psbar .= "%End of QR Barcode \n\n"; if( !$this->iEPS ) $psbar .= "showpage \n\n"; $psbar .= "%%Trailer\n\n"; $errStr = array('L', 'M', 'Q', 'H'); $ps = ($this->iEPS ? "%!PS-Adobe EPSF-3.0\n" : "%!PS-Adobe-3.0\n" ) . "%%Title: QR Barcode ".$pspec->iVersion."-".$errStr[$pspec->iErrLevel].", mask=".$pspec->iMaskIdx."\n". "%%Creator: JpGraph Barcode http://www.aditus.nu/jpgraph/\n". "%%CreationDate: ".date("D j M H:i:s Y",time())."\n"; if( $this->iEPS ) { $ps .= "%%BoundingBox: 0 0 $totwidth $totheight\n"; } else { $ps .= "%%DocumentPaperSizes: A4\n"; } $ps .= "%%EndComments\n". "%%BeginProlog\n". "%%EndProlog\n"; if( !$this->iEPS ) $ps .= "%%Page: 1 1\n"; $ps .= "\n%Module width: $this->iModWidth pt\n\n"; /* if( $this->iScale != 1 ) { $ps .= "%%Scale barcode\n". "$this->iScale $this->iScale scale\n\n"; } */ $ps = $ps.$psbar; $errStr=array ( 'L', 'M', 'Q', 'H' ); $this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx); if( $aFileName !== '' ) { $fp = @fopen($aFileName,'wt'); if( $fp === FALSE ) { // throw new QRException("Cannot open file $aFileName."); throw new QRExceptionL(1003,$aFileName); } if( fwrite($fp,$ps) === FALSE ) { //throw new QRException("Cannot write barcode to file $aFileName."); throw new QRExceptionL(1004,$aFileName); } return fclose($fp); } else { return $ps; } } } require_once('rgb_colors.inc.php'); //-------------------------------------------------------------------------------- // Class: QRCodeBackend_IMAGE // Description: Backend to generate image representation of the barcode //-------------------------------------------------------------------------------- class QRCodeBackend_IMAGE extends QRCodeBackend { private $iColor = array ( array ( 0, 0, 0 ), array ( 255, 255, 255 ), array ( 255, 255, 255 ) ); private $iRGB = null; private $iImgFormat = 'png', $iQualityJPEG = 75; function __construct($aBarcodeEncoder) { parent::__construct($aBarcodeEncoder); $this->iRGB=new BarcodeRGB(); } function SetSize($aShapeIdx) { $this->iEncoder->SetSize($aShapeIdx); } function SetColor($aOne, $aZero, $aBackground = array ( 255, 255, 255 )) { $this->iColor[0]=$aOne; $this->iColor[1]=$aZero; $this->iColor[2]=$aBackground; } // Specify image format. Note depending on your installation // of PHP not all formats may be supported. function SetImgFormat($aFormat, $aQuality = 75) { $this->iQualityJPEG=$aQuality; $this->iImgFormat=$aFormat; } function PrepareImgFormat() { $format=strtolower($this->iImgFormat); if ( $format == 'jpg' ) { $format = 'jpeg'; } $tst=true; $supported=imagetypes(); if ( $format == "auto" ) { if ( $supported & IMG_PNG ) $this->iImgFormat="png"; elseif( $supported & IMG_JPG ) $this->iImgFormat="jpeg"; elseif( $supported & IMG_GIF ) $this->iImgFormat="gif"; elseif( $supported & IMG_WBMP ) $this->iImgFormat="wbmp"; else { //throw new QRException('Unsupported image format selected. Check your GD installation', -1); throw new QRExceptionL(1005); } } else { if ( $format == "jpeg" || $format == "png" || $format == "gif" ) { if ( $format == "jpeg" && !($supported & IMG_JPG) ) $tst=false; elseif( $format == "png" && !($supported & IMG_PNG) ) $tst=false; elseif( $format == "gif" && !($supported & IMG_GIF) ) $tst=false; elseif( $format == "wbmp" && !($supported & IMG_WBMP) ) $tst=false; else { $this->iImgFormat = $format; } } else $tst=false; if ( !$tst ) { //throw new QRException('Unsupported image format selected. Check your GD installation', -1); throw new QRExceptionL(1005); } } return true; } function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') { // Check the chosen graphic format $this->PrepareImgFormat(); $pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile); $mat=$pspec->iMatrix; $m=$this->iModWidth; $this->iQuietZone = $pspec->iQuietZone; $h=$pspec->iSize[0] * $m + 2 * $m * $this->iQuietZone; $w=$pspec->iSize[1] * $m + 2 * $m * $this->iQuietZone; $img=@imagecreatetruecolor($w, $h); if ( !$img ) { $this->iError=-12; return false; } $canvas_color = $this->iRGB->Allocate($img, 'white'); $one_color = $this->iRGB->Allocate($img, $this->iColor[0]); $zero_color = $this->iRGB->Allocate($img, $this->iColor[1]); $bkg_color = $this->iRGB->Allocate($img, $this->iColor[2]); if ( $this->iInv && $pspec->iAllowColorInversion ) { // Swap one/zero colors $tmp=$one_color; $one_color=$zero_color; $zero_color=$tmp; } if ( $canvas_color === false || $one_color === false || $zero_color === false || $bkg_color === false ) { // throw new QRException('Cannot set the selected colors. Check your GD installation and spelling of color name', -1); throw new QRExceptionL(1006); } imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $canvas_color); imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $bkg_color); $borderoffset=0; if ( $pspec->iDrawLeftBottomBorder ) { // Left alignment line imagefilledrectangle($img, $m * $this->iQuietZone, $m * $this->iQuietZone, $m * $this->iQuietZone + $m - 1, $h - $m * $this->iQuietZone - 1, $one_color); // Bottom alignment line imagefilledrectangle($img, $m * $this->iQuietZone, $h - $m * $this->iQuietZone - $m, $w - $m * $this->iQuietZone - 1, $h - $m * $this->iQuietZone - 1, $one_color); $borderoffset=1; } for( $i = 0; $i < $pspec->iSize[0] - $borderoffset; ++$i ) { for( $j = $borderoffset; $j < $pspec->iSize[1]; ++$j ) { $bit = $mat[$i][$j] == 1 ? $one_color : $zero_color; if ( $m == 1 ) { imagesetpixel($img, $j + $m * $this->iQuietZone, $i + $m * $this->iQuietZone, $bit); } else { imagefilledrectangle($img, $j * $m + $m * $this->iQuietZone, $i * $m + $m * $this->iQuietZone, $j * $m + $m - 1 + $m * $this->iQuietZone, $i * $m + $m - 1 + $m * $this->iQuietZone, $bit); } } } if ( $pspec->iDrawLeftBottomBorder ) { // Left alignment line imagefilledrectangle($img, $this->iQuietZone, $this->iQuietZone, $this->iQuietZone + $m - 1, $h - $this->iQuietZone - 1, $one_color); // Bottom alignment line imagefilledrectangle($img, $this->iQuietZone, $h - $this->iQuietZone - $m, $w - $this->iQuietZone - 1, $h - $this->iQuietZone - 1, $one_color); } if ( headers_sent($file, $lineno) ) { // Headers already sent special error throw new QRExceptionL(1007,$file,$lineno); } if ( $aFileName == '' ) { $s=php_sapi_name(); if ( substr($s, 0, 3) != 'cli' ) { header("Content-type: image/$this->iImgFormat"); } switch( $this->iImgFormat ) { case 'png': $res=@imagepng($img); break; case 'jpeg': $res=@imagejpeg($img, NULL, $this->iQualityJPEG); break; case 'gif': $res=@imagegif($img); break; case 'wbmp': $res=@imagewbmp($img); break; } if( $res === FALSE ) { throw new QRExceptionL(1008,$this->iImgFormat); //throw new QRException("Could not create the barcode image. Check your GD/PHP installation."); } } else { switch( $this->iImgFormat ) { case 'png': $res=@imagepng($img, $aFileName); break; case 'jpeg': $res=@imagejpeg($img, $aFileName, $this->iQualityJPEG); break; case 'gif': $res=@imagegif($img, $aFileName); break; case 'wbmp': $res=@imagewbmp($img, $aFileName); break; } if( $res === FALSE ) { throw new QRExceptionL(1011,$this->iImgFormat); // 1011 => 'Could not write the barcode to file. Check the filesystem permission.', } } // If debugging is enabled store encoding info in the specified log file if( $aDebug !== FALSE && $aDebugFile !== '' ) { $s = "QR Barcode Log created: " . date('r')."\n"; $s .= "Debug level = $aDebug \n"; $s .= "SAPI: " . php_sapi_name() ."\n\n"; $s .= $this->iEncoder; $s .= $pspec; $fp = @fopen($aDebugFile,'wt'); if( $fp === FALSE ) { //throw new QRException("Cannot open log file for writing $aDebugFile."); throw new QRExceptionL(1009,$aDebugFile); } if( @fwrite($fp,$s) === FALSE ) { //throw new QRException("Cannot write log info to log file $aDebugFile."); throw new QRExceptionL(1010,$aDebugFile); } fclose($fp); } $errStr=array ( 'L', 'M', 'Q', 'H' ); $this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx); return 'true'; } } //-------------------------------------------------------------------------------- // Class: QRCodeBackend_ASCII // Description: Backend to generate ASCII representation of the barcode //-------------------------------------------------------------------------------- class QRCodeBackend_ASCII extends QRCodeBackend { function __construct(&$aBarcodeEncoder) { parent::__construct($aBarcodeEncoder); } function GetMatrixString($mat, $inv = false, $width = 1, $aOne = 'X', $aZero = '-') { if ( $width > 1 ) { $m=count($mat); $n=count($mat[0]); $newmat=array(); for( $i = 0; $i < $m; ++$i ) for( $j = 0; $j < $n; ++$j ) for( $k = 0; $k < $width; ++$k ) for( $l = 0; $l < $width; ++$l ) $newmat[$i * $width + $k][$j * $width + $l]=$mat[$i][$j]; $mat=$newmat; } $m=count($mat); $n=count($mat[0]); $s = ''; for( $i = 0; $i < $m; ++$i ) { for( $j = 0; $j < $n; ++$j ) { if ( !$inv ) { $s .= $mat[$i][$j] ? $aOne : $aZero; } else { $s .= !$mat[$i][$j] ? $aOne : $aZero; } } $s .= "\n"; } $s .= "\n"; return $this->fmtInfo($s); } function Stroke(&$aData, $aFileName='', $aDebug = FALSE, $aDebugFile = '') { $pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile); // If debugging is enabled store encoding info in the specified log file if( $aDebug !== FALSE ) { $s = str_repeat('=',80)."\n"; $s .= "QR Barcode Log created: " . date('r')."\n"; $s .= str_repeat('=',80)."\n"; $s .= "Debug level = $aDebug \n"; $s .= "SAPI: " . php_sapi_name() ."\n\n"; $s .= $this->iEncoder; $s .= $pspec . "\n"; $s .= str_repeat('=',80)."\nEnd of QR Barcode log file.\n".str_repeat('=',80)."\n\n"; if( $aDebugFile != '' ) { $fp = @fopen($aDebugFile,'wt'); if( $fp === FALSE ) { // throw new QRException("Cannot open log file for writing $aDebugFile."); throw new QRExceptionL(1009,$aDebugFile); } if( @fwrite($fp,$s) === FALSE ) { // throw new QRException("Cannot write log info to log file $aDebugFile."); throw new QRExceptionL(1010,$aDebugFile); } fclose($fp); } else { echo $this->fmtInfo($s); } } $s = $this->GetMatrixString($pspec->iMatrix, $this->iInv, $this->iModWidth, 'X', '-') . "\n"; if( $aFileName !== '' ) { $fp = @fopen($aFileName,'wt'); if( $fp === FALSE ) { // throw new QRException("Cannot open file $aFileName."); throw new QRExceptionL(1003,$aFileName); } if( fwrite($fp,$s) === FALSE ) { // throw new QRException("Cannot write barcode to file $aFileName."); throw new QRExceptionL(1004,$aFileName); } return fclose($fp); } else { return $s; } } } //-------------------------------------------------------------------------------- // Class: QRCodeBackendFactory // Description: Factory to return a suitable backend for generating barcode //-------------------------------------------------------------------------------- class QRCodeBackendFactory { static function Create(&$aBarcodeEncoder, $aBackend = BACKEND_IMAGE) { switch( $aBackend ) { case BACKEND_ASCII: return new QRCodeBackend_ASCII($aBarcodeEncoder); break; case BACKEND_IMAGE: return new QRCodeBackend_Image($aBarcodeEncoder); break; case BACKEND_PS: return new QRCodeBackend_PS($aBarcodeEncoder); break; case BACKEND_EPS: $b = new QRCodeBackend_PS($aBarcodeEncoder); $b->SetEPS(true); return $b; break; default: return false; } } } ?>
noparking/alticcio
core/outils/exterieurs/jpgraph/src/QR/backend.inc.php
PHP
gpl-2.0
19,943
32.689189
130
0.45259
false
namespace Tipshare { partial class Tipshare { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.gbAM = new System.Windows.Forms.GroupBox(); this.tbAMUnallocatedAdj = new System.Windows.Forms.TextBox(); this.lblAMCurrentUnallocated = new System.Windows.Forms.Label(); this.tbAMUnallocatedSugg = new System.Windows.Forms.TextBox(); this.lblAMUnallocated = new System.Windows.Forms.Label(); this.lAMAdj = new System.Windows.Forms.Label(); this.lAMSugg = new System.Windows.Forms.Label(); this.lAMID = new System.Windows.Forms.Label(); this.lAMName = new System.Windows.Forms.Label(); this.gbControls = new System.Windows.Forms.GroupBox(); this.btnDistributeUnallocated = new System.Windows.Forms.Button(); this.btnSettings = new System.Windows.Forms.Button(); this.btnReset = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.lDate = new System.Windows.Forms.Label(); this.lDay = new System.Windows.Forms.Label(); this.bDayBack = new System.Windows.Forms.Button(); this.bDayForward = new System.Windows.Forms.Button(); this.gbPM = new System.Windows.Forms.GroupBox(); this.tbPMUnallocatedAdj = new System.Windows.Forms.TextBox(); this.lblPMCurrentUnallocated = new System.Windows.Forms.Label(); this.tbPMUnallocatedSugg = new System.Windows.Forms.TextBox(); this.lblPMUnallocated = new System.Windows.Forms.Label(); this.lPMAdj = new System.Windows.Forms.Label(); this.lPMSugg = new System.Windows.Forms.Label(); this.lPMID = new System.Windows.Forms.Label(); this.lPMName = new System.Windows.Forms.Label(); this.msMenu = new System.Windows.Forms.MenuStrip(); this.mFile = new System.Windows.Forms.ToolStripMenuItem(); this.miJump = new System.Windows.Forms.ToolStripMenuItem(); this.miPrint = new System.Windows.Forms.ToolStripMenuItem(); this.miExit = new System.Windows.Forms.ToolStripMenuItem(); this.mAbout = new System.Windows.Forms.ToolStripMenuItem(); this.miHelp = new System.Windows.Forms.ToolStripMenuItem(); this.miAbout = new System.Windows.Forms.ToolStripMenuItem(); this.tTimer = new System.Windows.Forms.Timer(this.components); this.gbTotals = new System.Windows.Forms.GroupBox(); this.lTotalSugg = new System.Windows.Forms.Label(); this.lTotalAdj = new System.Windows.Forms.Label(); this.lLabTotSug = new System.Windows.Forms.Label(); this.lTotalAMSugg = new System.Windows.Forms.Label(); this.lTotalAMAdj = new System.Windows.Forms.Label(); this.lLabTotAMSugg = new System.Windows.Forms.Label(); this.lTotalPMSugg = new System.Windows.Forms.Label(); this.lTotalPMAdj = new System.Windows.Forms.Label(); this.lLabTotPMSugg = new System.Windows.Forms.Label(); this.gbAM.SuspendLayout(); this.gbControls.SuspendLayout(); this.gbPM.SuspendLayout(); this.msMenu.SuspendLayout(); this.gbTotals.SuspendLayout(); this.SuspendLayout(); // // gbAM // this.gbAM.Controls.Add(this.tbAMUnallocatedAdj); this.gbAM.Controls.Add(this.lblAMCurrentUnallocated); this.gbAM.Controls.Add(this.tbAMUnallocatedSugg); this.gbAM.Controls.Add(this.lblAMUnallocated); this.gbAM.Controls.Add(this.lAMAdj); this.gbAM.Controls.Add(this.lAMSugg); this.gbAM.Controls.Add(this.lAMID); this.gbAM.Controls.Add(this.lAMName); this.gbAM.Location = new System.Drawing.Point(12, 27); this.gbAM.Name = "gbAM"; this.gbAM.Size = new System.Drawing.Size(318, 430); this.gbAM.TabIndex = 1; this.gbAM.TabStop = false; this.gbAM.Text = "AM Declarations"; // // tbAMUnallocatedAdj // this.tbAMUnallocatedAdj.Location = new System.Drawing.Point(277, 404); this.tbAMUnallocatedAdj.Name = "tbAMUnallocatedAdj"; this.tbAMUnallocatedAdj.ReadOnly = true; this.tbAMUnallocatedAdj.Size = new System.Drawing.Size(35, 20); this.tbAMUnallocatedAdj.TabIndex = 14; // // lblAMCurrentUnallocated // this.lblAMCurrentUnallocated.AutoSize = true; this.lblAMCurrentUnallocated.Location = new System.Drawing.Point(167, 407); this.lblAMCurrentUnallocated.Name = "lblAMCurrentUnallocated"; this.lblAMCurrentUnallocated.Size = new System.Drawing.Size(104, 13); this.lblAMCurrentUnallocated.TabIndex = 13; this.lblAMCurrentUnallocated.Text = "Current Unallocated:"; // // tbAMUnallocatedSugg // this.tbAMUnallocatedSugg.Location = new System.Drawing.Point(118, 404); this.tbAMUnallocatedSugg.Name = "tbAMUnallocatedSugg"; this.tbAMUnallocatedSugg.ReadOnly = true; this.tbAMUnallocatedSugg.Size = new System.Drawing.Size(35, 20); this.tbAMUnallocatedSugg.TabIndex = 12; // // lblAMUnallocated // this.lblAMUnallocated.AutoSize = true; this.lblAMUnallocated.Location = new System.Drawing.Point(6, 407); this.lblAMUnallocated.Name = "lblAMUnallocated"; this.lblAMUnallocated.Size = new System.Drawing.Size(106, 13); this.lblAMUnallocated.TabIndex = 10; this.lblAMUnallocated.Text = "Starting Unallocated:"; // // lAMAdj // this.lAMAdj.AutoSize = true; this.lAMAdj.Location = new System.Drawing.Point(276, 16); this.lAMAdj.Name = "lAMAdj"; this.lAMAdj.Size = new System.Drawing.Size(22, 13); this.lAMAdj.TabIndex = 9; this.lAMAdj.Text = "Adj"; // // lAMSugg // this.lAMSugg.AutoSize = true; this.lAMSugg.Location = new System.Drawing.Point(216, 16); this.lAMSugg.Name = "lAMSugg"; this.lAMSugg.Size = new System.Drawing.Size(32, 13); this.lAMSugg.TabIndex = 8; this.lAMSugg.Text = "Sugg"; // // lAMID // this.lAMID.AutoSize = true; this.lAMID.Location = new System.Drawing.Point(169, 16); this.lAMID.Name = "lAMID"; this.lAMID.Size = new System.Drawing.Size(18, 13); this.lAMID.TabIndex = 7; this.lAMID.Text = "ID"; // // lAMName // this.lAMName.AutoSize = true; this.lAMName.Location = new System.Drawing.Point(69, 16); this.lAMName.Name = "lAMName"; this.lAMName.Size = new System.Drawing.Size(35, 13); this.lAMName.TabIndex = 6; this.lAMName.Text = "Name"; // // gbControls // this.gbControls.Controls.Add(this.btnDistributeUnallocated); this.gbControls.Controls.Add(this.btnSettings); this.gbControls.Controls.Add(this.btnReset); this.gbControls.Controls.Add(this.btnSave); this.gbControls.Controls.Add(this.lDate); this.gbControls.Controls.Add(this.lDay); this.gbControls.Controls.Add(this.bDayBack); this.gbControls.Controls.Add(this.bDayForward); this.gbControls.Location = new System.Drawing.Point(12, 518); this.gbControls.Name = "gbControls"; this.gbControls.Size = new System.Drawing.Size(648, 62); this.gbControls.TabIndex = 2; this.gbControls.TabStop = false; this.gbControls.Text = "Controls"; // // btnDistributeUnallocated // this.btnDistributeUnallocated.Enabled = false; this.btnDistributeUnallocated.Location = new System.Drawing.Point(123, 19); this.btnDistributeUnallocated.Name = "btnDistributeUnallocated"; this.btnDistributeUnallocated.Size = new System.Drawing.Size(111, 35); this.btnDistributeUnallocated.TabIndex = 13; this.btnDistributeUnallocated.Text = "Distribute Unallocated"; this.btnDistributeUnallocated.UseVisualStyleBackColor = true; this.btnDistributeUnallocated.Click += new System.EventHandler(this.btnDistributeUnallocated_Click); // // btnSettings // this.btnSettings.Location = new System.Drawing.Point(6, 19); this.btnSettings.Name = "btnSettings"; this.btnSettings.Size = new System.Drawing.Size(111, 35); this.btnSettings.TabIndex = 12; this.btnSettings.Text = "Advanced Settings"; this.btnSettings.UseVisualStyleBackColor = true; this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click); // // btnReset // this.btnReset.Location = new System.Drawing.Point(414, 19); this.btnReset.Name = "btnReset"; this.btnReset.Size = new System.Drawing.Size(111, 35); this.btnReset.TabIndex = 11; this.btnReset.Text = "Reset Day"; this.btnReset.UseVisualStyleBackColor = true; this.btnReset.Click += new System.EventHandler(this.btnReset_Click); // // btnSave // this.btnSave.Location = new System.Drawing.Point(531, 19); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(111, 35); this.btnSave.TabIndex = 10; this.btnSave.Text = "SAVE"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // lDate // this.lDate.AutoSize = true; this.lDate.Location = new System.Drawing.Point(297, 19); this.lDate.Name = "lDate"; this.lDate.Size = new System.Drawing.Size(64, 13); this.lDate.TabIndex = 9; this.lDate.Text = "##DATE##"; // // lDay // this.lDay.AutoSize = true; this.lDay.Location = new System.Drawing.Point(308, 41); this.lDay.Name = "lDay"; this.lDay.Size = new System.Drawing.Size(26, 13); this.lDay.TabIndex = 8; this.lDay.Text = "Day"; // // bDayBack // this.bDayBack.Location = new System.Drawing.Point(263, 35); this.bDayBack.Name = "bDayBack"; this.bDayBack.Size = new System.Drawing.Size(39, 23); this.bDayBack.TabIndex = 1; this.bDayBack.Text = "<<"; this.bDayBack.UseVisualStyleBackColor = true; this.bDayBack.Click += new System.EventHandler(this.bDayBack_Click); // // bDayForward // this.bDayForward.Location = new System.Drawing.Point(340, 36); this.bDayForward.Name = "bDayForward"; this.bDayForward.Size = new System.Drawing.Size(39, 23); this.bDayForward.TabIndex = 0; this.bDayForward.Text = ">>"; this.bDayForward.UseVisualStyleBackColor = true; this.bDayForward.Click += new System.EventHandler(this.bDayForward_Click); // // gbPM // this.gbPM.Controls.Add(this.tbPMUnallocatedAdj); this.gbPM.Controls.Add(this.lblPMCurrentUnallocated); this.gbPM.Controls.Add(this.tbPMUnallocatedSugg); this.gbPM.Controls.Add(this.lblPMUnallocated); this.gbPM.Controls.Add(this.lPMAdj); this.gbPM.Controls.Add(this.lPMSugg); this.gbPM.Controls.Add(this.lPMID); this.gbPM.Controls.Add(this.lPMName); this.gbPM.Location = new System.Drawing.Point(342, 27); this.gbPM.Name = "gbPM"; this.gbPM.Size = new System.Drawing.Size(318, 430); this.gbPM.TabIndex = 4; this.gbPM.TabStop = false; this.gbPM.Text = "PM Declarations"; // // tbPMUnallocatedAdj // this.tbPMUnallocatedAdj.Location = new System.Drawing.Point(277, 404); this.tbPMUnallocatedAdj.Name = "tbPMUnallocatedAdj"; this.tbPMUnallocatedAdj.ReadOnly = true; this.tbPMUnallocatedAdj.Size = new System.Drawing.Size(35, 20); this.tbPMUnallocatedAdj.TabIndex = 18; // // lblPMCurrentUnallocated // this.lblPMCurrentUnallocated.AutoSize = true; this.lblPMCurrentUnallocated.Location = new System.Drawing.Point(167, 407); this.lblPMCurrentUnallocated.Name = "lblPMCurrentUnallocated"; this.lblPMCurrentUnallocated.Size = new System.Drawing.Size(104, 13); this.lblPMCurrentUnallocated.TabIndex = 17; this.lblPMCurrentUnallocated.Text = "Current Unallocated:"; // // tbPMUnallocatedSugg // this.tbPMUnallocatedSugg.Location = new System.Drawing.Point(115, 404); this.tbPMUnallocatedSugg.Name = "tbPMUnallocatedSugg"; this.tbPMUnallocatedSugg.ReadOnly = true; this.tbPMUnallocatedSugg.Size = new System.Drawing.Size(35, 20); this.tbPMUnallocatedSugg.TabIndex = 15; // // lblPMUnallocated // this.lblPMUnallocated.AutoSize = true; this.lblPMUnallocated.Location = new System.Drawing.Point(6, 407); this.lblPMUnallocated.Name = "lblPMUnallocated"; this.lblPMUnallocated.Size = new System.Drawing.Size(106, 13); this.lblPMUnallocated.TabIndex = 14; this.lblPMUnallocated.Text = "Starting Unallocated:"; // // lPMAdj // this.lPMAdj.AutoSize = true; this.lPMAdj.Location = new System.Drawing.Point(276, 16); this.lPMAdj.Name = "lPMAdj"; this.lPMAdj.Size = new System.Drawing.Size(22, 13); this.lPMAdj.TabIndex = 13; this.lPMAdj.Text = "Adj"; // // lPMSugg // this.lPMSugg.AutoSize = true; this.lPMSugg.Location = new System.Drawing.Point(216, 16); this.lPMSugg.Name = "lPMSugg"; this.lPMSugg.Size = new System.Drawing.Size(32, 13); this.lPMSugg.TabIndex = 12; this.lPMSugg.Text = "Sugg"; // // lPMID // this.lPMID.AutoSize = true; this.lPMID.Location = new System.Drawing.Point(169, 16); this.lPMID.Name = "lPMID"; this.lPMID.Size = new System.Drawing.Size(18, 13); this.lPMID.TabIndex = 11; this.lPMID.Text = "ID"; // // lPMName // this.lPMName.AutoSize = true; this.lPMName.Location = new System.Drawing.Point(69, 16); this.lPMName.Name = "lPMName"; this.lPMName.Size = new System.Drawing.Size(35, 13); this.lPMName.TabIndex = 10; this.lPMName.Text = "Name"; // // msMenu // this.msMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mFile, this.mAbout}); this.msMenu.Location = new System.Drawing.Point(0, 0); this.msMenu.Name = "msMenu"; this.msMenu.Size = new System.Drawing.Size(672, 24); this.msMenu.TabIndex = 5; this.msMenu.Text = "MenuStrip"; // // mFile // this.mFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miJump, this.miPrint, this.miExit}); this.mFile.Name = "mFile"; this.mFile.Size = new System.Drawing.Size(37, 20); this.mFile.Text = "File"; // // miJump // this.miJump.Name = "miJump"; this.miJump.Size = new System.Drawing.Size(148, 22); this.miJump.Text = "Jump to day..."; // // miPrint // this.miPrint.Name = "miPrint"; this.miPrint.Size = new System.Drawing.Size(148, 22); this.miPrint.Text = "Print Today"; this.miPrint.Click += new System.EventHandler(this.miPrint_Click); // // miExit // this.miExit.Name = "miExit"; this.miExit.Size = new System.Drawing.Size(148, 22); this.miExit.Text = "Exit"; this.miExit.Click += new System.EventHandler(this.miExit_Click); // // mAbout // this.mAbout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miHelp, this.miAbout}); this.mAbout.Name = "mAbout"; this.mAbout.Size = new System.Drawing.Size(52, 20); this.mAbout.Text = "About"; // // miHelp // this.miHelp.Name = "miHelp"; this.miHelp.Size = new System.Drawing.Size(107, 22); this.miHelp.Text = "Help"; this.miHelp.Click += new System.EventHandler(this.miHelp_Click); // // miAbout // this.miAbout.Name = "miAbout"; this.miAbout.Size = new System.Drawing.Size(107, 22); this.miAbout.Text = "About"; this.miAbout.Click += new System.EventHandler(this.miAbout_Click); // // tTimer // this.tTimer.Tick += new System.EventHandler(this.tTimer_Tick); // // gbTotals // this.gbTotals.Controls.Add(this.lTotalSugg); this.gbTotals.Controls.Add(this.lTotalAdj); this.gbTotals.Controls.Add(this.lLabTotSug); this.gbTotals.Controls.Add(this.lTotalAMSugg); this.gbTotals.Controls.Add(this.lTotalAMAdj); this.gbTotals.Controls.Add(this.lLabTotAMSugg); this.gbTotals.Controls.Add(this.lTotalPMSugg); this.gbTotals.Controls.Add(this.lTotalPMAdj); this.gbTotals.Controls.Add(this.lLabTotPMSugg); this.gbTotals.Location = new System.Drawing.Point(12, 463); this.gbTotals.Name = "gbTotals"; this.gbTotals.Size = new System.Drawing.Size(648, 49); this.gbTotals.TabIndex = 6; this.gbTotals.TabStop = false; this.gbTotals.Text = "Totals"; // // lTotalSugg // this.lTotalSugg.AutoSize = true; this.lTotalSugg.Location = new System.Drawing.Point(285, 29); this.lTotalSugg.Name = "lTotalSugg"; this.lTotalSugg.Size = new System.Drawing.Size(21, 13); this.lTotalSugg.TabIndex = 8; this.lTotalSugg.Text = "##"; // // lTotalAdj // this.lTotalAdj.AutoSize = true; this.lTotalAdj.Location = new System.Drawing.Point(348, 29); this.lTotalAdj.Name = "lTotalAdj"; this.lTotalAdj.Size = new System.Drawing.Size(21, 13); this.lTotalAdj.TabIndex = 7; this.lTotalAdj.Text = "##"; // // lLabTotSug // this.lLabTotSug.AutoSize = true; this.lLabTotSug.Location = new System.Drawing.Point(285, 16); this.lLabTotSug.Name = "lLabTotSug"; this.lLabTotSug.Size = new System.Drawing.Size(79, 13); this.lLabTotSug.TabIndex = 6; this.lLabTotSug.Text = "Total Sugg/Adj"; // // lTotalAMSugg // this.lTotalAMSugg.AutoSize = true; this.lTotalAMSugg.Location = new System.Drawing.Point(32, 29); this.lTotalAMSugg.Name = "lTotalAMSugg"; this.lTotalAMSugg.Size = new System.Drawing.Size(21, 13); this.lTotalAMSugg.TabIndex = 5; this.lTotalAMSugg.Text = "##"; // // lTotalAMAdj // this.lTotalAMAdj.AutoSize = true; this.lTotalAMAdj.Location = new System.Drawing.Point(83, 29); this.lTotalAMAdj.Name = "lTotalAMAdj"; this.lTotalAMAdj.Size = new System.Drawing.Size(21, 13); this.lTotalAMAdj.TabIndex = 4; this.lTotalAMAdj.Text = "##"; // // lLabTotAMSugg // this.lLabTotAMSugg.AutoSize = true; this.lLabTotAMSugg.Location = new System.Drawing.Point(19, 16); this.lLabTotAMSugg.Name = "lLabTotAMSugg"; this.lLabTotAMSugg.Size = new System.Drawing.Size(98, 13); this.lLabTotAMSugg.TabIndex = 3; this.lLabTotAMSugg.Text = "Total AM Sugg/Adj"; // // lTotalPMSugg // this.lTotalPMSugg.AutoSize = true; this.lTotalPMSugg.Location = new System.Drawing.Point(545, 29); this.lTotalPMSugg.Name = "lTotalPMSugg"; this.lTotalPMSugg.Size = new System.Drawing.Size(21, 13); this.lTotalPMSugg.TabIndex = 2; this.lTotalPMSugg.Text = "##"; // // lTotalPMAdj // this.lTotalPMAdj.AutoSize = true; this.lTotalPMAdj.Location = new System.Drawing.Point(596, 29); this.lTotalPMAdj.Name = "lTotalPMAdj"; this.lTotalPMAdj.Size = new System.Drawing.Size(21, 13); this.lTotalPMAdj.TabIndex = 1; this.lTotalPMAdj.Text = "##"; // // lLabTotPMSugg // this.lLabTotPMSugg.AutoSize = true; this.lLabTotPMSugg.Location = new System.Drawing.Point(530, 16); this.lLabTotPMSugg.Name = "lLabTotPMSugg"; this.lLabTotPMSugg.Size = new System.Drawing.Size(98, 13); this.lLabTotPMSugg.TabIndex = 0; this.lLabTotPMSugg.Text = "Total PM Sugg/Adj"; // // Tipshare // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(672, 592); this.Controls.Add(this.gbTotals); this.Controls.Add(this.gbPM); this.Controls.Add(this.gbControls); this.Controls.Add(this.gbAM); this.Controls.Add(this.msMenu); this.MainMenuStrip = this.msMenu; this.Name = "Tipshare"; this.Text = "Tipshare##VERSION## - ##STORENAME##"; this.Load += new System.EventHandler(this.Tipshare_Load); this.gbAM.ResumeLayout(false); this.gbAM.PerformLayout(); this.gbControls.ResumeLayout(false); this.gbControls.PerformLayout(); this.gbPM.ResumeLayout(false); this.gbPM.PerformLayout(); this.msMenu.ResumeLayout(false); this.msMenu.PerformLayout(); this.gbTotals.ResumeLayout(false); this.gbTotals.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox gbAM; private System.Windows.Forms.GroupBox gbControls; private System.Windows.Forms.GroupBox gbPM; private System.Windows.Forms.Button bDayBack; private System.Windows.Forms.Button bDayForward; private System.Windows.Forms.Label lAMName; private System.Windows.Forms.Label lAMAdj; private System.Windows.Forms.Label lAMSugg; private System.Windows.Forms.Label lAMID; private System.Windows.Forms.Label lDate; private System.Windows.Forms.Label lDay; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnDistributeUnallocated; private System.Windows.Forms.Button btnSettings; private System.Windows.Forms.Button btnReset; private System.Windows.Forms.Label lPMAdj; private System.Windows.Forms.Label lPMSugg; private System.Windows.Forms.Label lPMID; private System.Windows.Forms.Label lPMName; private System.Windows.Forms.MenuStrip msMenu; private System.Windows.Forms.ToolStripMenuItem mFile; private System.Windows.Forms.ToolStripMenuItem miJump; private System.Windows.Forms.ToolStripMenuItem miPrint; private System.Windows.Forms.ToolStripMenuItem miExit; private System.Windows.Forms.ToolStripMenuItem mAbout; private System.Windows.Forms.ToolStripMenuItem miHelp; private System.Windows.Forms.ToolStripMenuItem miAbout; private System.Windows.Forms.Timer tTimer; private System.Windows.Forms.GroupBox gbTotals; private System.Windows.Forms.Label lTotalPMAdj; private System.Windows.Forms.Label lLabTotPMSugg; private System.Windows.Forms.Label lTotalAMSugg; private System.Windows.Forms.Label lTotalAMAdj; private System.Windows.Forms.Label lLabTotAMSugg; private System.Windows.Forms.Label lTotalPMSugg; private System.Windows.Forms.Label lTotalSugg; private System.Windows.Forms.Label lTotalAdj; private System.Windows.Forms.Label lLabTotSug; private System.Windows.Forms.TextBox tbAMUnallocatedSugg; private System.Windows.Forms.Label lblAMUnallocated; private System.Windows.Forms.TextBox tbPMUnallocatedSugg; private System.Windows.Forms.Label lblPMUnallocated; private System.Windows.Forms.TextBox tbAMUnallocatedAdj; private System.Windows.Forms.Label lblAMCurrentUnallocated; private System.Windows.Forms.TextBox tbPMUnallocatedAdj; private System.Windows.Forms.Label lblPMCurrentUnallocated; } }
nsherrill/Consulting
Concord/Tipshare/Tipshare.Designer.cs
C#
gpl-2.0
27,660
45.019967
112
0.577554
false
using SFML.Graphics; using SFML.Window; namespace LudumDare.ParticleSystem { public class Emitter { public Vector2f Position; public int ParticlesSpawnRate; public float Spread; public Color Color; } }
WebFreak001/LD-30
ParticleSystem/Emitter.cs
C#
gpl-2.0
249
18.076923
38
0.663968
false
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" #include "SDL_mouse.h" #include "../../events/SDL_events_c.h" #include "SDL_vglvideo.h" #include "SDL_vglmouse_c.h" struct WMcursor { int unused; }; void VGL_FreeWMCursor(_THIS, WMcursor *cursor) { return; } WMcursor *VGL_CreateWMCursor(_THIS, Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y) { return(NULL); } int VGL_ShowWMCursor(_THIS, WMcursor *cursor) { return(0); } void VGL_WarpWMCursor(_THIS, Uint16 x, Uint16 y) { SDL_PrivateMouseMotion(0, 0, x, y); }
qtekfun/htcDesire820Kernel
external/qemu/distrib/sdl-1.2.15/src/video/vgl/SDL_vglmouse.c
C
gpl-2.0
1,382
24.127273
78
0.712735
false
/* Copyright (c) 2006 Paolo Capriotti <p.capriotti@gmail.com> (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. */ #include <cmath> #include <QDebug> #include <QString> #include "common.h" #include "point.h" Point::Point(int x, int y) : x(x), y(y) { } Point::Point(const QPoint& p) : x(p.x()), y(p.y()) { } Point::Point() { } Point::Point(const QString& str, int ysize) { x = y = -1; int length = str.length(); if(length == 0) return; if(str[0].isLetter()) { char c = str[0].toAscii(); if(c >= 'a' && c <= 'z') x = c-'a'; else if(c >= 'A' && c <= 'Z') x = c-'A'; if(length>1) y = ysize - str.mid(1).toInt(); } else y = ysize - str.toInt(); } QString Point::row(int ysize) const { if (y != -1) return QString::number(ysize - y); else return QString(); } QString Point::numcol(int xsize) const { if (x != -1) return QString::number(xsize - x); else return QString(); } QString Point::col() const { if (x != -1) { if(x >= 26) return QChar(static_cast<char>(x - 26 + 'A')); else return QChar(static_cast<char>(x + 'a')); } else return QString(); } QString Point::alpharow() const { if (y != -1) { if(y >= 26) return QChar(static_cast<char>(y - 26 + 'A')); else return QChar(static_cast<char>(y + 'a')); } else return QString(); } QString Point::toString(int ysize) const { return col() + row(ysize); } Point Point::operator+(const Point& other) const { return Point(x + other.x, y + other.y); } Point Point::operator+=(const Point& other) { return *this = *this + other; } Point Point::operator-() const { return Point(-x, -y); } Point Point::operator-(const Point& other) const { return Point(x - other.x, y - other.y); } Point Point::operator*(int n) const { return Point(x * n, y * n); } Point Point::operator/(int n) const { return Point(x / n, y / n); } Point Point::div(int n) const { return Point(x >= 0 ? x / n : x / n - 1, y >= 0 ? y / n : y / n - 1); } bool Point::operator==(const Point& other) const { return x == other.x && y == other.y; } bool Point::operator!=(const Point& other) const { return !(*this == other); } bool Point::operator<(const Point& other) const { return y < other.y || (y == other.y && x < other.x); } bool Point::operator<=(const Point& other) const { return y <= other.y || (y == other.y && x <= other.x); } bool Point::resembles(const Point& other) const { return (other.x == -1 || x == other.x) && (other.y == -1 || y == other.y); } Point::operator QPoint() const { return QPoint(x,y); } Point Point::normalizeInfinity() const { return Point( normalizeInfinityHelper(x), normalizeInfinityHelper(y) ); } double Point::norm() const { return sqrt((double)(x*x + y*y)); } int Point::normalizeInfinityHelper(int n) const { if (n == 0) return 0; else return n > 0 ? 1 : -1; } QDebug operator<<(QDebug dbg, const Point& p) { dbg << "(" << (p.x == -1 ? QString("?") : QString::number(p.x)) << ", " << (p.y == -1 ? QString("?") : QString::number(p.y)) << ")"; return dbg; }
ruphy/tagua
src/point.cpp
C++
gpl-2.0
3,545
20.748466
74
0.556559
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_04) on Thu May 15 10:36:11 IDT 2014 --> <title>Painter (Codename One API)</title> <meta name="date" content="2014-05-15"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Painter (Codename One API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li> <li><a href="Painter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.codename1.ui</div> <h2 title="Interface Painter" class="title">Interface Painter</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../com/codename1/ui/painter/BackgroundPainter.html" title="class in com.codename1.ui.painter">BackgroundPainter</a>, <a href="../../../com/codename1/ui/util/GlassTutorial.html" title="class in com.codename1.ui.util">GlassTutorial</a>, <a href="../../../com/codename1/ui/painter/PainterChain.html" title="class in com.codename1.ui.painter">PainterChain</a>, <a href="../../../com/codename1/ui/animations/Timeline.html" title="class in com.codename1.ui.animations">Timeline</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">Painter</span></pre> <div class="block">Painter can be used to draw on components backgrounds. The use of such painter allows reuse of a background painters for various components. Note in order to view the painter drawing, component need to have some level of transparency.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/codename1/ui/Painter.html#paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)">paint</a></strong>(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a>&nbsp;g, <a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a>&nbsp;rect)</code> <div class="block">Draws inside the given rectangle clipping area.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>paint</h4> <pre>void&nbsp;paint(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a>&nbsp;g, <a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a>&nbsp;rect)</pre> <div class="block">Draws inside the given rectangle clipping area.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>g</code> - the <a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui"><code>Graphics</code></a> object</dd><dd><code>rect</code> - the given rectangle cliping area</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li> <li><a href="Painter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
shannah/cn1
CodenameOne/javadoc/com/codename1/ui/Painter.html
HTML
gpl-2.0
8,079
35.890411
499
0.636465
false
# class.upload by verot.net ## contributor github.com/paulds #### v0.31 Download from verot.net/php_class_upload_download.htm This version is not PHP 5.3 compatible
paulds/class.upload
README.md
Markdown
gpl-2.0
167
23
64
0.760479
false
/* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is modified by Felix Natter in 2013. * * 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/>. */ package org.freeplane.core.resources.components; import javax.swing.JButton; import com.jgoodies.forms.builder.DefaultFormBuilder; public class ButtonProperty extends PropertyBean implements IPropertyControl { final JButton mButton; /** */ public ButtonProperty(final String name, JButton button) { super(name); mButton = button; } @Override public String getValue() { return ""; } public void appendToForm(final DefaultFormBuilder builder) { appendToForm(builder, mButton); } public void setEnabled(final boolean pEnabled) { mButton.setEnabled(pEnabled); super.setEnabled(pEnabled); } @Override public void setValue(final String value) { } public void setToolTipText(String text) { mButton.setToolTipText(text); } }
freeplane/freeplane
freeplane/src/main/java/org/freeplane/core/resources/components/ButtonProperty.java
Java
gpl-2.0
1,600
27.070175
89
0.741875
false
/* * @author Philip Stutz * @author Francisco de Freitas * * Copyright 2011 University of Zurich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.signalcollect.configuration import com.signalcollect.interfaces._ import java.util.HashMap import com.signalcollect._ import com.signalcollect.logging.DefaultLogger import akka.actor.ActorRef import com.signalcollect.nodeprovisioning.NodeProvisioner import com.signalcollect.nodeprovisioning.local.LocalNodeProvisioner /** * All the graph configuration parameters with their defaults. */ case class GraphConfiguration( maxInboxSize: Option[Long] = Some(Runtime.getRuntime.availableProcessors * 5000), //None loggingLevel: Int = LoggingLevel.Warning, logger: LogMessage => Unit = DefaultLogger.log, workerFactory: WorkerFactory = factory.worker.Akka, messageBusFactory: MessageBusFactory = factory.messagebus.SharedMemory, storageFactory: StorageFactory = factory.storage.InMemory, statusUpdateIntervalInMillis: Option[Long] = Some(500l), akkaDispatcher: AkkaDispatcher = Pinned, nodeProvisioner: NodeProvisioner = new LocalNodeProvisioner) object LoggingLevel { val Debug = 0 val Config = 100 val Info = 200 val Warning = 300 val Severe = 400 } sealed trait AkkaDispatcher case object EventBased extends AkkaDispatcher case object Pinned extends AkkaDispatcher
Tjoene/thesis
Case_Programs/signal-collect/src/main/scala/com/signalcollect/configuration/GraphConfiguration.scala
Scala
gpl-2.0
1,931
34.109091
92
0.758156
false
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. systemd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "sd-id128.h" #include "sd-messages.h" #include "alloc-util.h" #include "bus-common-errors.h" #include "bus-util.h" #include "cgroup-util.h" #include "dbus-unit.h" #include "dbus.h" #include "dropin.h" #include "escape.h" #include "execute.h" #include "fileio-label.h" #include "formats-util.h" #include "load-dropin.h" #include "load-fragment.h" #include "log.h" #include "macro.h" #include "missing.h" #include "mkdir.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "set.h" #include "special.h" #include "stat-util.h" #include "string-util.h" #include "strv.h" #include "unit-name.h" #include "unit.h" #include "user-util.h" #include "virt.h" const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = { [UNIT_SERVICE] = &service_vtable, [UNIT_SOCKET] = &socket_vtable, [UNIT_BUSNAME] = &busname_vtable, [UNIT_TARGET] = &target_vtable, [UNIT_DEVICE] = &device_vtable, [UNIT_MOUNT] = &mount_vtable, [UNIT_AUTOMOUNT] = &automount_vtable, [UNIT_SWAP] = &swap_vtable, [UNIT_TIMER] = &timer_vtable, [UNIT_PATH] = &path_vtable, [UNIT_SLICE] = &slice_vtable, [UNIT_SCOPE] = &scope_vtable }; static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency); Unit *unit_new(Manager *m, size_t size) { Unit *u; assert(m); assert(size >= sizeof(Unit)); u = malloc0(size); if (!u) return NULL; u->names = set_new(&string_hash_ops); if (!u->names) { free(u); return NULL; } u->manager = m; u->type = _UNIT_TYPE_INVALID; u->default_dependencies = true; u->unit_file_state = _UNIT_FILE_STATE_INVALID; u->unit_file_preset = -1; u->on_failure_job_mode = JOB_REPLACE; u->cgroup_inotify_wd = -1; RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16); return u; } bool unit_has_name(Unit *u, const char *name) { assert(u); assert(name); return !!set_get(u->names, (char*) name); } static void unit_init(Unit *u) { CGroupContext *cc; ExecContext *ec; KillContext *kc; assert(u); assert(u->manager); assert(u->type >= 0); cc = unit_get_cgroup_context(u); if (cc) { cgroup_context_init(cc); /* Copy in the manager defaults into the cgroup * context, _before_ the rest of the settings have * been initialized */ cc->cpu_accounting = u->manager->default_cpu_accounting; cc->blockio_accounting = u->manager->default_blockio_accounting; cc->memory_accounting = u->manager->default_memory_accounting; cc->tasks_accounting = u->manager->default_tasks_accounting; } ec = unit_get_exec_context(u); if (ec) exec_context_init(ec); kc = unit_get_kill_context(u); if (kc) kill_context_init(kc); if (UNIT_VTABLE(u)->init) UNIT_VTABLE(u)->init(u); } int unit_add_name(Unit *u, const char *text) { _cleanup_free_ char *s = NULL, *i = NULL; UnitType t; int r; assert(u); assert(text); if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) { if (!u->instance) return -EINVAL; r = unit_name_replace_instance(text, u->instance, &s); if (r < 0) return r; } else { s = strdup(text); if (!s) return -ENOMEM; } if (set_contains(u->names, s)) return 0; if (hashmap_contains(u->manager->units, s)) return -EEXIST; if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) return -EINVAL; t = unit_name_to_type(s); if (t < 0) return -EINVAL; if (u->type != _UNIT_TYPE_INVALID && t != u->type) return -EINVAL; r = unit_name_to_instance(s, &i); if (r < 0) return r; if (i && unit_vtable[t]->no_instances) return -EINVAL; /* Ensure that this unit is either instanced or not instanced, * but not both. Note that we do allow names with different * instance names however! */ if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i) return -EINVAL; if (unit_vtable[t]->no_alias && !set_isempty(u->names)) return -EEXIST; if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES) return -E2BIG; r = set_put(u->names, s); if (r < 0) return r; assert(r > 0); r = hashmap_put(u->manager->units, s, u); if (r < 0) { (void) set_remove(u->names, s); return r; } if (u->type == _UNIT_TYPE_INVALID) { u->type = t; u->id = s; u->instance = i; LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u); unit_init(u); i = NULL; } s = NULL; unit_add_to_dbus_queue(u); return 0; } int unit_choose_id(Unit *u, const char *name) { _cleanup_free_ char *t = NULL; char *s, *i; int r; assert(u); assert(name); if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) { if (!u->instance) return -EINVAL; r = unit_name_replace_instance(name, u->instance, &t); if (r < 0) return r; name = t; } /* Selects one of the names of this unit as the id */ s = set_get(u->names, (char*) name); if (!s) return -ENOENT; /* Determine the new instance from the new id */ r = unit_name_to_instance(s, &i); if (r < 0) return r; u->id = s; free(u->instance); u->instance = i; unit_add_to_dbus_queue(u); return 0; } int unit_set_description(Unit *u, const char *description) { char *s; assert(u); if (isempty(description)) s = NULL; else { s = strdup(description); if (!s) return -ENOMEM; } free(u->description); u->description = s; unit_add_to_dbus_queue(u); return 0; } bool unit_check_gc(Unit *u) { UnitActiveState state; assert(u); if (u->job) return true; if (u->nop_job) return true; state = unit_active_state(u); /* If the unit is inactive and failed and no job is queued for * it, then release its runtime resources */ if (UNIT_IS_INACTIVE_OR_FAILED(state) && UNIT_VTABLE(u)->release_resources) UNIT_VTABLE(u)->release_resources(u); /* But we keep the unit object around for longer when it is * referenced or configured to not be gc'ed */ if (state != UNIT_INACTIVE) return true; if (UNIT_VTABLE(u)->no_gc) return true; if (u->no_gc) return true; if (u->refs) return true; if (UNIT_VTABLE(u)->check_gc) if (UNIT_VTABLE(u)->check_gc(u)) return true; return false; } void unit_add_to_load_queue(Unit *u) { assert(u); assert(u->type != _UNIT_TYPE_INVALID); if (u->load_state != UNIT_STUB || u->in_load_queue) return; LIST_PREPEND(load_queue, u->manager->load_queue, u); u->in_load_queue = true; } void unit_add_to_cleanup_queue(Unit *u) { assert(u); if (u->in_cleanup_queue) return; LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u); u->in_cleanup_queue = true; } void unit_add_to_gc_queue(Unit *u) { assert(u); if (u->in_gc_queue || u->in_cleanup_queue) return; if (unit_check_gc(u)) return; LIST_PREPEND(gc_queue, u->manager->gc_queue, u); u->in_gc_queue = true; u->manager->n_in_gc_queue ++; } void unit_add_to_dbus_queue(Unit *u) { assert(u); assert(u->type != _UNIT_TYPE_INVALID); if (u->load_state == UNIT_STUB || u->in_dbus_queue) return; /* Shortcut things if nobody cares */ if (sd_bus_track_count(u->manager->subscribed) <= 0 && set_isempty(u->manager->private_buses)) { u->sent_dbus_new_signal = true; return; } LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u); u->in_dbus_queue = true; } static void bidi_set_free(Unit *u, Set *s) { Iterator i; Unit *other; assert(u); /* Frees the set and makes sure we are dropped from the * inverse pointers */ SET_FOREACH(other, s, i) { UnitDependency d; for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) set_remove(other->dependencies[d], u); unit_add_to_gc_queue(other); } set_free(s); } static void unit_remove_transient(Unit *u) { char **i; assert(u); if (!u->transient) return; if (u->fragment_path) (void) unlink(u->fragment_path); STRV_FOREACH(i, u->dropin_paths) { _cleanup_free_ char *p = NULL; (void) unlink(*i); p = dirname_malloc(*i); if (p) (void) rmdir(p); } } static void unit_free_requires_mounts_for(Unit *u) { char **j; STRV_FOREACH(j, u->requires_mounts_for) { char s[strlen(*j) + 1]; PATH_FOREACH_PREFIX_MORE(s, *j) { char *y; Set *x; x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y); if (!x) continue; set_remove(x, u); if (set_isempty(x)) { hashmap_remove(u->manager->units_requiring_mounts_for, y); free(y); set_free(x); } } } u->requires_mounts_for = strv_free(u->requires_mounts_for); } static void unit_done(Unit *u) { ExecContext *ec; CGroupContext *cc; int r; assert(u); if (u->type < 0) return; if (UNIT_VTABLE(u)->done) UNIT_VTABLE(u)->done(u); ec = unit_get_exec_context(u); if (ec) exec_context_done(ec); cc = unit_get_cgroup_context(u); if (cc) cgroup_context_done(cc); r = unit_remove_from_netclass_cgroup(u); if (r < 0) log_warning_errno(r, "Unable to remove unit from netclass group: %m"); } void unit_free(Unit *u) { UnitDependency d; Iterator i; char *t; assert(u); if (u->manager->n_reloading <= 0) unit_remove_transient(u); bus_unit_send_removed_signal(u); unit_done(u); sd_bus_slot_unref(u->match_bus_slot); unit_free_requires_mounts_for(u); SET_FOREACH(t, u->names, i) hashmap_remove_value(u->manager->units, t, u); if (u->job) { Job *j = u->job; job_uninstall(j); job_free(j); } if (u->nop_job) { Job *j = u->nop_job; job_uninstall(j); job_free(j); } for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) bidi_set_free(u, u->dependencies[d]); if (u->type != _UNIT_TYPE_INVALID) LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u); if (u->in_load_queue) LIST_REMOVE(load_queue, u->manager->load_queue, u); if (u->in_dbus_queue) LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u); if (u->in_cleanup_queue) LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u); if (u->in_gc_queue) { LIST_REMOVE(gc_queue, u->manager->gc_queue, u); u->manager->n_in_gc_queue--; } if (u->in_cgroup_queue) LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u); unit_release_cgroup(u); (void) manager_update_failed_units(u->manager, u, false); set_remove(u->manager->startup_units, u); free(u->description); strv_free(u->documentation); free(u->fragment_path); free(u->source_path); strv_free(u->dropin_paths); free(u->instance); free(u->job_timeout_reboot_arg); set_free_free(u->names); unit_unwatch_all_pids(u); condition_free_list(u->conditions); condition_free_list(u->asserts); unit_ref_unset(&u->slice); while (u->refs) unit_ref_unset(u->refs); free(u); } UnitActiveState unit_active_state(Unit *u) { assert(u); if (u->load_state == UNIT_MERGED) return unit_active_state(unit_follow_merge(u)); /* After a reload it might happen that a unit is not correctly * loaded but still has a process around. That's why we won't * shortcut failed loading to UNIT_INACTIVE_FAILED. */ return UNIT_VTABLE(u)->active_state(u); } const char* unit_sub_state_to_string(Unit *u) { assert(u); return UNIT_VTABLE(u)->sub_state_to_string(u); } static int complete_move(Set **s, Set **other) { int r; assert(s); assert(other); if (!*other) return 0; if (*s) { r = set_move(*s, *other); if (r < 0) return r; } else { *s = *other; *other = NULL; } return 0; } static int merge_names(Unit *u, Unit *other) { char *t; Iterator i; int r; assert(u); assert(other); r = complete_move(&u->names, &other->names); if (r < 0) return r; set_free_free(other->names); other->names = NULL; other->id = NULL; SET_FOREACH(t, u->names, i) assert_se(hashmap_replace(u->manager->units, t, u) == 0); return 0; } static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) { unsigned n_reserve; assert(u); assert(other); assert(d < _UNIT_DEPENDENCY_MAX); /* * If u does not have this dependency set allocated, there is no need * to reserve anything. In that case other's set will be transferred * as a whole to u by complete_move(). */ if (!u->dependencies[d]) return 0; /* merge_dependencies() will skip a u-on-u dependency */ n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u); return set_reserve(u->dependencies[d], n_reserve); } static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) { Iterator i; Unit *back; int r; assert(u); assert(other); assert(d < _UNIT_DEPENDENCY_MAX); /* Fix backwards pointers */ SET_FOREACH(back, other->dependencies[d], i) { UnitDependency k; for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) { /* Do not add dependencies between u and itself */ if (back == u) { if (set_remove(back->dependencies[k], other)) maybe_warn_about_dependency(u, other_id, k); } else { r = set_remove_and_put(back->dependencies[k], other, u); if (r == -EEXIST) set_remove(back->dependencies[k], other); else assert(r >= 0 || r == -ENOENT); } } } /* Also do not move dependencies on u to itself */ back = set_remove(other->dependencies[d], u); if (back) maybe_warn_about_dependency(u, other_id, d); /* The move cannot fail. The caller must have performed a reservation. */ assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0); other->dependencies[d] = set_free(other->dependencies[d]); } int unit_merge(Unit *u, Unit *other) { UnitDependency d; const char *other_id = NULL; int r; assert(u); assert(other); assert(u->manager == other->manager); assert(u->type != _UNIT_TYPE_INVALID); other = unit_follow_merge(other); if (other == u) return 0; if (u->type != other->type) return -EINVAL; if (!u->instance != !other->instance) return -EINVAL; if (other->load_state != UNIT_STUB && other->load_state != UNIT_NOT_FOUND) return -EEXIST; if (other->job) return -EEXIST; if (other->nop_job) return -EEXIST; if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) return -EEXIST; if (other->id) other_id = strdupa(other->id); /* Make reservations to ensure merge_dependencies() won't fail */ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) { r = reserve_dependencies(u, other, d); /* * We don't rollback reservations if we fail. We don't have * a way to undo reservations. A reservation is not a leak. */ if (r < 0) return r; } /* Merge names */ r = merge_names(u, other); if (r < 0) return r; /* Redirect all references */ while (other->refs) unit_ref_set(other->refs, u); /* Merge dependencies */ for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) merge_dependencies(u, other, other_id, d); other->load_state = UNIT_MERGED; other->merged_into = u; /* If there is still some data attached to the other node, we * don't need it anymore, and can free it. */ if (other->load_state != UNIT_STUB) if (UNIT_VTABLE(other)->done) UNIT_VTABLE(other)->done(other); unit_add_to_dbus_queue(u); unit_add_to_cleanup_queue(other); return 0; } int unit_merge_by_name(Unit *u, const char *name) { Unit *other; int r; _cleanup_free_ char *s = NULL; assert(u); assert(name); if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) { if (!u->instance) return -EINVAL; r = unit_name_replace_instance(name, u->instance, &s); if (r < 0) return r; name = s; } other = manager_get_unit(u->manager, name); if (other) return unit_merge(u, other); return unit_add_name(u, name); } Unit* unit_follow_merge(Unit *u) { assert(u); while (u->load_state == UNIT_MERGED) assert_se(u = u->merged_into); return u; } int unit_add_exec_dependencies(Unit *u, ExecContext *c) { int r; assert(u); assert(c); if (c->working_directory) { r = unit_require_mounts_for(u, c->working_directory); if (r < 0) return r; } if (c->root_directory) { r = unit_require_mounts_for(u, c->root_directory); if (r < 0) return r; } if (u->manager->running_as != MANAGER_SYSTEM) return 0; if (c->private_tmp) { r = unit_require_mounts_for(u, "/tmp"); if (r < 0) return r; r = unit_require_mounts_for(u, "/var/tmp"); if (r < 0) return r; } if (c->std_output != EXEC_OUTPUT_KMSG && c->std_output != EXEC_OUTPUT_SYSLOG && c->std_output != EXEC_OUTPUT_JOURNAL && c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE && c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE && c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE && c->std_error != EXEC_OUTPUT_KMSG && c->std_error != EXEC_OUTPUT_SYSLOG && c->std_error != EXEC_OUTPUT_JOURNAL && c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE && c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE && c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE) return 0; /* If syslog or kernel logging is requested, make sure our own * logging daemon is run first. */ r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true); if (r < 0) return r; return 0; } const char *unit_description(Unit *u) { assert(u); if (u->description) return u->description; return strna(u->id); } void unit_dump(Unit *u, FILE *f, const char *prefix) { char *t, **j; UnitDependency d; Iterator i; const char *prefix2; char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX], timestamp3[FORMAT_TIMESTAMP_MAX], timestamp4[FORMAT_TIMESTAMP_MAX], timespan[FORMAT_TIMESPAN_MAX]; Unit *following; _cleanup_set_free_ Set *following_set = NULL; int r; assert(u); assert(u->type >= 0); prefix = strempty(prefix); prefix2 = strjoina(prefix, "\t"); fprintf(f, "%s-> Unit %s:\n" "%s\tDescription: %s\n" "%s\tInstance: %s\n" "%s\tUnit Load State: %s\n" "%s\tUnit Active State: %s\n" "%s\tInactive Exit Timestamp: %s\n" "%s\tActive Enter Timestamp: %s\n" "%s\tActive Exit Timestamp: %s\n" "%s\tInactive Enter Timestamp: %s\n" "%s\tGC Check Good: %s\n" "%s\tNeed Daemon Reload: %s\n" "%s\tTransient: %s\n" "%s\tSlice: %s\n" "%s\tCGroup: %s\n" "%s\tCGroup realized: %s\n" "%s\tCGroup mask: 0x%x\n" "%s\tCGroup members mask: 0x%x\n", prefix, u->id, prefix, unit_description(u), prefix, strna(u->instance), prefix, unit_load_state_to_string(u->load_state), prefix, unit_active_state_to_string(unit_active_state(u)), prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)), prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)), prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)), prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)), prefix, yes_no(unit_check_gc(u)), prefix, yes_no(unit_need_daemon_reload(u)), prefix, yes_no(u->transient), prefix, strna(unit_slice_name(u)), prefix, strna(u->cgroup_path), prefix, yes_no(u->cgroup_realized), prefix, u->cgroup_realized_mask, prefix, u->cgroup_members_mask); SET_FOREACH(t, u->names, i) fprintf(f, "%s\tName: %s\n", prefix, t); STRV_FOREACH(j, u->documentation) fprintf(f, "%s\tDocumentation: %s\n", prefix, *j); following = unit_following(u); if (following) fprintf(f, "%s\tFollowing: %s\n", prefix, following->id); r = unit_following_set(u, &following_set); if (r >= 0) { Unit *other; SET_FOREACH(other, following_set, i) fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id); } if (u->fragment_path) fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path); if (u->source_path) fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path); STRV_FOREACH(j, u->dropin_paths) fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j); if (u->job_timeout > 0) fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0)); if (u->job_timeout_action != FAILURE_ACTION_NONE) fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action)); if (u->job_timeout_reboot_arg) fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg); condition_dump_list(u->conditions, f, prefix, condition_type_to_string); condition_dump_list(u->asserts, f, prefix, assert_type_to_string); if (dual_timestamp_is_set(&u->condition_timestamp)) fprintf(f, "%s\tCondition Timestamp: %s\n" "%s\tCondition Result: %s\n", prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)), prefix, yes_no(u->condition_result)); if (dual_timestamp_is_set(&u->assert_timestamp)) fprintf(f, "%s\tAssert Timestamp: %s\n" "%s\tAssert Result: %s\n", prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)), prefix, yes_no(u->assert_result)); for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) { Unit *other; SET_FOREACH(other, u->dependencies[d], i) fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id); } if (!strv_isempty(u->requires_mounts_for)) { fprintf(f, "%s\tRequiresMountsFor:", prefix); STRV_FOREACH(j, u->requires_mounts_for) fprintf(f, " %s", *j); fputs("\n", f); } if (u->load_state == UNIT_LOADED) { fprintf(f, "%s\tStopWhenUnneeded: %s\n" "%s\tRefuseManualStart: %s\n" "%s\tRefuseManualStop: %s\n" "%s\tDefaultDependencies: %s\n" "%s\tOnFailureJobMode: %s\n" "%s\tIgnoreOnIsolate: %s\n", prefix, yes_no(u->stop_when_unneeded), prefix, yes_no(u->refuse_manual_start), prefix, yes_no(u->refuse_manual_stop), prefix, yes_no(u->default_dependencies), prefix, job_mode_to_string(u->on_failure_job_mode), prefix, yes_no(u->ignore_on_isolate)); if (UNIT_VTABLE(u)->dump) UNIT_VTABLE(u)->dump(u, f, prefix2); } else if (u->load_state == UNIT_MERGED) fprintf(f, "%s\tMerged into: %s\n", prefix, u->merged_into->id); else if (u->load_state == UNIT_ERROR) fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error)); if (u->job) job_dump(u->job, f, prefix2); if (u->nop_job) job_dump(u->nop_job, f, prefix2); } /* Common implementation for multiple backends */ int unit_load_fragment_and_dropin(Unit *u) { int r; assert(u); /* Load a .{service,socket,...} file */ r = unit_load_fragment(u); if (r < 0) return r; if (u->load_state == UNIT_STUB) return -ENOENT; /* Load drop-in directory data */ r = unit_load_dropin(unit_follow_merge(u)); if (r < 0) return r; return 0; } /* Common implementation for multiple backends */ int unit_load_fragment_and_dropin_optional(Unit *u) { int r; assert(u); /* Same as unit_load_fragment_and_dropin(), but whether * something can be loaded or not doesn't matter. */ /* Load a .service file */ r = unit_load_fragment(u); if (r < 0) return r; if (u->load_state == UNIT_STUB) u->load_state = UNIT_LOADED; /* Load drop-in directory data */ r = unit_load_dropin(unit_follow_merge(u)); if (r < 0) return r; return 0; } int unit_add_default_target_dependency(Unit *u, Unit *target) { assert(u); assert(target); if (target->type != UNIT_TARGET) return 0; /* Only add the dependency if both units are loaded, so that * that loop check below is reliable */ if (u->load_state != UNIT_LOADED || target->load_state != UNIT_LOADED) return 0; /* If either side wants no automatic dependencies, then let's * skip this */ if (!u->default_dependencies || !target->default_dependencies) return 0; /* Don't create loops */ if (set_get(target->dependencies[UNIT_BEFORE], u)) return 0; return unit_add_dependency(target, UNIT_AFTER, u, true); } static int unit_add_target_dependencies(Unit *u) { static const UnitDependency deps[] = { UNIT_REQUIRED_BY, UNIT_REQUISITE_OF, UNIT_WANTED_BY, UNIT_BOUND_BY }; Unit *target; Iterator i; unsigned k; int r = 0; assert(u); for (k = 0; k < ELEMENTSOF(deps); k++) SET_FOREACH(target, u->dependencies[deps[k]], i) { r = unit_add_default_target_dependency(u, target); if (r < 0) return r; } return r; } static int unit_add_slice_dependencies(Unit *u) { assert(u); if (!UNIT_HAS_CGROUP_CONTEXT(u)) return 0; if (UNIT_ISSET(u->slice)) return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true); if (unit_has_name(u, SPECIAL_ROOT_SLICE)) return 0; return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true); } static int unit_add_mount_dependencies(Unit *u) { char **i; int r; assert(u); STRV_FOREACH(i, u->requires_mounts_for) { char prefix[strlen(*i) + 1]; PATH_FOREACH_PREFIX_MORE(prefix, *i) { _cleanup_free_ char *p = NULL; Unit *m; r = unit_name_from_path(prefix, ".mount", &p); if (r < 0) return r; m = manager_get_unit(u->manager, p); if (!m) { /* Make sure to load the mount unit if * it exists. If so the dependencies * on this unit will be added later * during the loading of the mount * unit. */ (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m); continue; } if (m == u) continue; if (m->load_state != UNIT_LOADED) continue; r = unit_add_dependency(u, UNIT_AFTER, m, true); if (r < 0) return r; if (m->fragment_path) { r = unit_add_dependency(u, UNIT_REQUIRES, m, true); if (r < 0) return r; } } } return 0; } static int unit_add_startup_units(Unit *u) { CGroupContext *c; int r; c = unit_get_cgroup_context(u); if (!c) return 0; if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID && c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID) return 0; r = set_ensure_allocated(&u->manager->startup_units, NULL); if (r < 0) return r; return set_put(u->manager->startup_units, u); } int unit_load(Unit *u) { int r; assert(u); if (u->in_load_queue) { LIST_REMOVE(load_queue, u->manager->load_queue, u); u->in_load_queue = false; } if (u->type == _UNIT_TYPE_INVALID) return -EINVAL; if (u->load_state != UNIT_STUB) return 0; if (UNIT_VTABLE(u)->load) { r = UNIT_VTABLE(u)->load(u); if (r < 0) goto fail; } if (u->load_state == UNIT_STUB) { r = -ENOENT; goto fail; } if (u->load_state == UNIT_LOADED) { r = unit_add_target_dependencies(u); if (r < 0) goto fail; r = unit_add_slice_dependencies(u); if (r < 0) goto fail; r = unit_add_mount_dependencies(u); if (r < 0) goto fail; r = unit_add_startup_units(u); if (r < 0) goto fail; if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) { log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing."); r = -EINVAL; goto fail; } unit_update_cgroup_members_masks(u); /* If we are reloading, we need to wait for the deserializer * to restore the net_cls ids that have been set previously */ if (u->manager->n_reloading <= 0) { r = unit_add_to_netclass_cgroup(u); if (r < 0) return r; } } assert((u->load_state != UNIT_MERGED) == !u->merged_into); unit_add_to_dbus_queue(unit_follow_merge(u)); unit_add_to_gc_queue(u); return 0; fail: u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR; u->load_error = r; unit_add_to_dbus_queue(u); unit_add_to_gc_queue(u); log_unit_debug_errno(u, r, "Failed to load configuration: %m"); return r; } static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) { Condition *c; int triggered = -1; assert(u); assert(to_string); /* If the condition list is empty, then it is true */ if (!first) return true; /* Otherwise, if all of the non-trigger conditions apply and * if any of the trigger conditions apply (unless there are * none) we return true */ LIST_FOREACH(conditions, c, first) { int r; r = condition_test(c); if (r < 0) log_unit_warning(u, "Couldn't determine result for %s=%s%s%s, assuming failed: %m", to_string(c->type), c->trigger ? "|" : "", c->negate ? "!" : "", c->parameter); else log_unit_debug(u, "%s=%s%s%s %s.", to_string(c->type), c->trigger ? "|" : "", c->negate ? "!" : "", c->parameter, condition_result_to_string(c->result)); if (!c->trigger && r <= 0) return false; if (c->trigger && triggered <= 0) triggered = r > 0; } return triggered != 0; } static bool unit_condition_test(Unit *u) { assert(u); dual_timestamp_get(&u->condition_timestamp); u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string); return u->condition_result; } static bool unit_assert_test(Unit *u) { assert(u); dual_timestamp_get(&u->assert_timestamp); u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string); return u->assert_result; } _pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) { const char *format; const UnitStatusMessageFormats *format_table; assert(u); assert(t == JOB_START || t == JOB_STOP || t == JOB_RELOAD); if (t != JOB_RELOAD) { format_table = &UNIT_VTABLE(u)->status_message_formats; if (format_table) { format = format_table->starting_stopping[t == JOB_STOP]; if (format) return format; } } /* Return generic strings */ if (t == JOB_START) return "Starting %s."; else if (t == JOB_STOP) return "Stopping %s."; else return "Reloading %s."; } static void unit_status_print_starting_stopping(Unit *u, JobType t) { const char *format; assert(u); format = unit_get_status_message_format(u, t); DISABLE_WARNING_FORMAT_NONLITERAL; unit_status_printf(u, "", format); REENABLE_WARNING; } static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) { const char *format; char buf[LINE_MAX]; sd_id128_t mid; assert(u); if (t != JOB_START && t != JOB_STOP && t != JOB_RELOAD) return; if (log_on_console()) return; /* We log status messages for all units and all operations. */ format = unit_get_status_message_format(u, t); DISABLE_WARNING_FORMAT_NONLITERAL; snprintf(buf, sizeof(buf), format, unit_description(u)); REENABLE_WARNING; mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING : t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING : SD_MESSAGE_UNIT_RELOADING; /* Note that we deliberately use LOG_MESSAGE() instead of * LOG_UNIT_MESSAGE() here, since this is supposed to mimic * closely what is written to screen using the status output, * which is supposed the highest level, friendliest output * possible, which means we should avoid the low-level unit * name. */ log_struct(LOG_INFO, LOG_MESSAGE_ID(mid), LOG_UNIT_ID(u), LOG_MESSAGE("%s", buf), NULL); } void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) { unit_status_log_starting_stopping_reloading(u, t); /* Reload status messages have traditionally not been printed to console. */ if (t != JOB_RELOAD) unit_status_print_starting_stopping(u, t); } /* Errors: * -EBADR: This unit type does not support starting. * -EALREADY: Unit is already started. * -EAGAIN: An operation is already in progress. Retry later. * -ECANCELED: Too many requests for now. * -EPROTO: Assert failed */ int unit_start(Unit *u) { UnitActiveState state; Unit *following; assert(u); /* Units that aren't loaded cannot be started */ if (u->load_state != UNIT_LOADED) return -EINVAL; /* If this is already started, then this will succeed. Note * that this will even succeed if this unit is not startable * by the user. This is relied on to detect when we need to * wait for units and when waiting is finished. */ state = unit_active_state(u); if (UNIT_IS_ACTIVE_OR_RELOADING(state)) return -EALREADY; /* If the conditions failed, don't do anything at all. If we * already are activating this call might still be useful to * speed up activation in case there is some hold-off time, * but we don't want to recheck the condition in that case. */ if (state != UNIT_ACTIVATING && !unit_condition_test(u)) { log_unit_debug(u, "Starting requested but condition failed. Not starting unit."); return -EALREADY; } /* If the asserts failed, fail the entire job */ if (state != UNIT_ACTIVATING && !unit_assert_test(u)) { log_unit_notice(u, "Starting requested but asserts failed."); return -EPROTO; } /* Units of types that aren't supported cannot be * started. Note that we do this test only after the condition * checks, so that we rather return condition check errors * (which are usually not considered a true failure) than "not * supported" errors (which are considered a failure). */ if (!unit_supported(u)) return -EOPNOTSUPP; /* Forward to the main object, if we aren't it. */ following = unit_following(u); if (following) { log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id); return unit_start(following); } /* If it is stopped, but we cannot start it, then fail */ if (!UNIT_VTABLE(u)->start) return -EBADR; /* We don't suppress calls to ->start() here when we are * already starting, to allow this request to be used as a * "hurry up" call, for example when the unit is in some "auto * restart" state where it waits for a holdoff timer to elapse * before it will start again. */ unit_add_to_dbus_queue(u); return UNIT_VTABLE(u)->start(u); } bool unit_can_start(Unit *u) { assert(u); if (u->load_state != UNIT_LOADED) return false; if (!unit_supported(u)) return false; return !!UNIT_VTABLE(u)->start; } bool unit_can_isolate(Unit *u) { assert(u); return unit_can_start(u) && u->allow_isolate; } /* Errors: * -EBADR: This unit type does not support stopping. * -EALREADY: Unit is already stopped. * -EAGAIN: An operation is already in progress. Retry later. */ int unit_stop(Unit *u) { UnitActiveState state; Unit *following; assert(u); state = unit_active_state(u); if (UNIT_IS_INACTIVE_OR_FAILED(state)) return -EALREADY; following = unit_following(u); if (following) { log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id); return unit_stop(following); } if (!UNIT_VTABLE(u)->stop) return -EBADR; unit_add_to_dbus_queue(u); return UNIT_VTABLE(u)->stop(u); } /* Errors: * -EBADR: This unit type does not support reloading. * -ENOEXEC: Unit is not started. * -EAGAIN: An operation is already in progress. Retry later. */ int unit_reload(Unit *u) { UnitActiveState state; Unit *following; assert(u); if (u->load_state != UNIT_LOADED) return -EINVAL; if (!unit_can_reload(u)) return -EBADR; state = unit_active_state(u); if (state == UNIT_RELOADING) return -EALREADY; if (state != UNIT_ACTIVE) { log_unit_warning(u, "Unit cannot be reloaded because it is inactive."); return -ENOEXEC; } following = unit_following(u); if (following) { log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id); return unit_reload(following); } unit_add_to_dbus_queue(u); return UNIT_VTABLE(u)->reload(u); } bool unit_can_reload(Unit *u) { assert(u); if (!UNIT_VTABLE(u)->reload) return false; if (!UNIT_VTABLE(u)->can_reload) return true; return UNIT_VTABLE(u)->can_reload(u); } static void unit_check_unneeded(Unit *u) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; static const UnitDependency needed_dependencies[] = { UNIT_REQUIRED_BY, UNIT_REQUISITE_OF, UNIT_WANTED_BY, UNIT_BOUND_BY, }; Unit *other; Iterator i; unsigned j; int r; assert(u); /* If this service shall be shut down when unneeded then do * so. */ if (!u->stop_when_unneeded) return; if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) return; for (j = 0; j < ELEMENTSOF(needed_dependencies); j++) SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i) if (unit_active_or_pending(other)) return; /* If stopping a unit fails continously we might enter a stop * loop here, hence stop acting on the service being * unnecessary after a while. */ if (!ratelimit_test(&u->auto_stop_ratelimit)) { log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently."); return; } log_unit_info(u, "Unit not needed anymore. Stopping."); /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */ r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL); if (r < 0) log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r)); } static void unit_check_binds_to(Unit *u) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; bool stop = false; Unit *other; Iterator i; int r; assert(u); if (u->job) return; if (unit_active_state(u) != UNIT_ACTIVE) return; SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) { if (other->job) continue; if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) continue; stop = true; break; } if (!stop) return; /* If stopping a unit fails continously we might enter a stop * loop here, hence stop acting on the service being * unnecessary after a while. */ if (!ratelimit_test(&u->auto_stop_ratelimit)) { log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id); return; } assert(other); log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id); /* A unit we need to run is gone. Sniff. Let's stop this. */ r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL); if (r < 0) log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r)); } static void retroactively_start_dependencies(Unit *u) { Iterator i; Unit *other; assert(u); assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))); SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i) if (!set_get(u->dependencies[UNIT_AFTER], other) && !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL); SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) if (!set_get(u->dependencies[UNIT_AFTER], other) && !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL); SET_FOREACH(other, u->dependencies[UNIT_WANTS], i) if (!set_get(u->dependencies[UNIT_AFTER], other) && !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL); SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL); SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL); } static void retroactively_stop_dependencies(Unit *u) { Iterator i; Unit *other; assert(u); assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u))); /* Pull down units which are bound to us recursively if enabled */ SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL); } static void check_unneeded_dependencies(Unit *u) { Iterator i; Unit *other; assert(u); assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u))); /* Garbage collect services that might not be needed anymore, if enabled */ SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) unit_check_unneeded(other); SET_FOREACH(other, u->dependencies[UNIT_WANTS], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) unit_check_unneeded(other); SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) unit_check_unneeded(other); SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other))) unit_check_unneeded(other); } void unit_start_on_failure(Unit *u) { Unit *other; Iterator i; assert(u); if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0) return; log_unit_info(u, "Triggering OnFailure= dependencies."); SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) { int r; r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL); if (r < 0) log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m"); } } void unit_trigger_notify(Unit *u) { Unit *other; Iterator i; assert(u); SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i) if (UNIT_VTABLE(other)->trigger_notify) UNIT_VTABLE(other)->trigger_notify(other, u); } void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) { Manager *m; bool unexpected; assert(u); assert(os < _UNIT_ACTIVE_STATE_MAX); assert(ns < _UNIT_ACTIVE_STATE_MAX); /* Note that this is called for all low-level state changes, * even if they might map to the same high-level * UnitActiveState! That means that ns == os is an expected * behavior here. For example: if a mount point is remounted * this function will be called too! */ m = u->manager; /* Update timestamps for state changes */ if (m->n_reloading <= 0) { dual_timestamp ts; dual_timestamp_get(&ts); if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns)) u->inactive_exit_timestamp = ts; else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns)) u->inactive_enter_timestamp = ts; if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns)) u->active_enter_timestamp = ts; else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns)) u->active_exit_timestamp = ts; } /* Keep track of failed units */ (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED); /* Make sure the cgroup is always removed when we become inactive */ if (UNIT_IS_INACTIVE_OR_FAILED(ns)) unit_prune_cgroup(u); /* Note that this doesn't apply to RemainAfterExit services exiting * successfully, since there's no change of state in that case. Which is * why it is handled in service_set_state() */ if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) { ExecContext *ec; ec = unit_get_exec_context(u); if (ec && exec_context_may_touch_console(ec)) { if (UNIT_IS_INACTIVE_OR_FAILED(ns)) { m->n_on_console --; if (m->n_on_console == 0) /* unset no_console_output flag, since the console is free */ m->no_console_output = false; } else m->n_on_console ++; } } if (u->job) { unexpected = false; if (u->job->state == JOB_WAITING) /* So we reached a different state for this * job. Let's see if we can run it now if it * failed previously due to EAGAIN. */ job_add_to_run_queue(u->job); /* Let's check whether this state change constitutes a * finished job, or maybe contradicts a running job and * hence needs to invalidate jobs. */ switch (u->job->type) { case JOB_START: case JOB_VERIFY_ACTIVE: if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) job_finish_and_invalidate(u->job, JOB_DONE, true); else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) { unexpected = true; if (UNIT_IS_INACTIVE_OR_FAILED(ns)) job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true); } break; case JOB_RELOAD: case JOB_RELOAD_OR_START: if (u->job->state == JOB_RUNNING) { if (ns == UNIT_ACTIVE) job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true); else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) { unexpected = true; if (UNIT_IS_INACTIVE_OR_FAILED(ns)) job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true); } } break; case JOB_STOP: case JOB_RESTART: case JOB_TRY_RESTART: if (UNIT_IS_INACTIVE_OR_FAILED(ns)) job_finish_and_invalidate(u->job, JOB_DONE, true); else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) { unexpected = true; job_finish_and_invalidate(u->job, JOB_FAILED, true); } break; default: assert_not_reached("Job type unknown"); } } else unexpected = true; if (m->n_reloading <= 0) { /* If this state change happened without being * requested by a job, then let's retroactively start * or stop dependencies. We skip that step when * deserializing, since we don't want to create any * additional jobs just because something is already * activated. */ if (unexpected) { if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns)) retroactively_start_dependencies(u); else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns)) retroactively_stop_dependencies(u); } /* stop unneeded units regardless if going down was expected or not */ if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns)) check_unneeded_dependencies(u); if (ns != os && ns == UNIT_FAILED) { log_unit_notice(u, "Unit entered failed state."); unit_start_on_failure(u); } } /* Some names are special */ if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) { if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) /* The bus might have just become available, * hence try to connect to it, if we aren't * yet connected. */ bus_init(m, true); if (u->type == UNIT_SERVICE && !UNIT_IS_ACTIVE_OR_RELOADING(os) && m->n_reloading <= 0) { /* Write audit record if we have just finished starting up */ manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true); u->in_audit = true; } if (!UNIT_IS_ACTIVE_OR_RELOADING(os)) manager_send_unit_plymouth(m, u); } else { /* We don't care about D-Bus here, since we'll get an * asynchronous notification for it anyway. */ if (u->type == UNIT_SERVICE && UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os) && m->n_reloading <= 0) { /* Hmm, if there was no start record written * write it now, so that we always have a nice * pair */ if (!u->in_audit) { manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE); if (ns == UNIT_INACTIVE) manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true); } else /* Write audit record if we have just finished shutting down */ manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE); u->in_audit = false; } } manager_recheck_journal(m); unit_trigger_notify(u); if (u->manager->n_reloading <= 0) { /* Maybe we finished startup and are now ready for * being stopped because unneeded? */ unit_check_unneeded(u); /* Maybe we finished startup, but something we needed * has vanished? Let's die then. (This happens when * something BindsTo= to a Type=oneshot unit, as these * units go directly from starting to inactive, * without ever entering started.) */ unit_check_binds_to(u); } unit_add_to_dbus_queue(u); unit_add_to_gc_queue(u); } int unit_watch_pid(Unit *u, pid_t pid) { int q, r; assert(u); assert(pid >= 1); /* Watch a specific PID. We only support one or two units * watching each PID for now, not more. */ r = set_ensure_allocated(&u->pids, NULL); if (r < 0) return r; r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL); if (r < 0) return r; r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u); if (r == -EEXIST) { r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL); if (r < 0) return r; r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u); } q = set_put(u->pids, PID_TO_PTR(pid)); if (q < 0) return q; return r; } void unit_unwatch_pid(Unit *u, pid_t pid) { assert(u); assert(pid >= 1); (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u); (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u); (void) set_remove(u->pids, PID_TO_PTR(pid)); } void unit_unwatch_all_pids(Unit *u) { assert(u); while (!set_isempty(u->pids)) unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids))); u->pids = set_free(u->pids); } void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) { Iterator i; void *e; assert(u); /* Cleans dead PIDs from our list */ SET_FOREACH(e, u->pids, i) { pid_t pid = PTR_TO_PID(e); if (pid == except1 || pid == except2) continue; if (!pid_is_unwaited(pid)) unit_unwatch_pid(u, pid); } } bool unit_job_is_applicable(Unit *u, JobType j) { assert(u); assert(j >= 0 && j < _JOB_TYPE_MAX); switch (j) { case JOB_VERIFY_ACTIVE: case JOB_START: case JOB_STOP: case JOB_NOP: return true; case JOB_RESTART: case JOB_TRY_RESTART: return unit_can_start(u); case JOB_RELOAD: return unit_can_reload(u); case JOB_RELOAD_OR_START: return unit_can_reload(u) && unit_can_start(u); default: assert_not_reached("Invalid job type"); } } static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) { assert(u); /* Only warn about some unit types */ if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY)) return; if (streq_ptr(u->id, other)) log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id); else log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id); } int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) { static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = { [UNIT_REQUIRES] = UNIT_REQUIRED_BY, [UNIT_WANTS] = UNIT_WANTED_BY, [UNIT_REQUISITE] = UNIT_REQUISITE_OF, [UNIT_BINDS_TO] = UNIT_BOUND_BY, [UNIT_PART_OF] = UNIT_CONSISTS_OF, [UNIT_REQUIRED_BY] = UNIT_REQUIRES, [UNIT_REQUISITE_OF] = UNIT_REQUISITE, [UNIT_WANTED_BY] = UNIT_WANTS, [UNIT_BOUND_BY] = UNIT_BINDS_TO, [UNIT_CONSISTS_OF] = UNIT_PART_OF, [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY, [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS, [UNIT_BEFORE] = UNIT_AFTER, [UNIT_AFTER] = UNIT_BEFORE, [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID, [UNIT_REFERENCES] = UNIT_REFERENCED_BY, [UNIT_REFERENCED_BY] = UNIT_REFERENCES, [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY, [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS, [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM, [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO, [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF, }; int r, q = 0, v = 0, w = 0; Unit *orig_u = u, *orig_other = other; assert(u); assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX); assert(other); u = unit_follow_merge(u); other = unit_follow_merge(other); /* We won't allow dependencies on ourselves. We will not * consider them an error however. */ if (u == other) { maybe_warn_about_dependency(orig_u, orig_other->id, d); return 0; } r = set_ensure_allocated(&u->dependencies[d], NULL); if (r < 0) return r; if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) { r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL); if (r < 0) return r; } if (add_reference) { r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL); if (r < 0) return r; r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL); if (r < 0) return r; } q = set_put(u->dependencies[d], other); if (q < 0) return q; if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) { v = set_put(other->dependencies[inverse_table[d]], u); if (v < 0) { r = v; goto fail; } } if (add_reference) { w = set_put(u->dependencies[UNIT_REFERENCES], other); if (w < 0) { r = w; goto fail; } r = set_put(other->dependencies[UNIT_REFERENCED_BY], u); if (r < 0) goto fail; } unit_add_to_dbus_queue(u); return 0; fail: if (q > 0) set_remove(u->dependencies[d], other); if (v > 0) set_remove(other->dependencies[inverse_table[d]], u); if (w > 0) set_remove(u->dependencies[UNIT_REFERENCES], other); return r; } int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) { int r; assert(u); r = unit_add_dependency(u, d, other, add_reference); if (r < 0) return r; return unit_add_dependency(u, e, other, add_reference); } static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) { int r; assert(u); assert(name || path); assert(buf); assert(ret); if (!name) name = basename(path); if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) { *buf = NULL; *ret = name; return 0; } if (u->instance) r = unit_name_replace_instance(name, u->instance, buf); else { _cleanup_free_ char *i = NULL; r = unit_name_to_prefix(u->id, &i); if (r < 0) return r; r = unit_name_replace_instance(name, i, buf); } if (r < 0) return r; *ret = *buf; return 0; } int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) { _cleanup_free_ char *buf = NULL; Unit *other; int r; assert(u); assert(name || path); r = resolve_template(u, name, path, &buf, &name); if (r < 0) return r; r = manager_load_unit(u->manager, name, path, NULL, &other); if (r < 0) return r; return unit_add_dependency(u, d, other, add_reference); } int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) { _cleanup_free_ char *buf = NULL; Unit *other; int r; assert(u); assert(name || path); r = resolve_template(u, name, path, &buf, &name); if (r < 0) return r; r = manager_load_unit(u->manager, name, path, NULL, &other); if (r < 0) return r; return unit_add_two_dependencies(u, d, e, other, add_reference); } int set_unit_path(const char *p) { /* This is mostly for debug purposes */ if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0) return -errno; return 0; } char *unit_dbus_path(Unit *u) { assert(u); if (!u->id) return NULL; return unit_dbus_path_from_name(u->id); } int unit_set_slice(Unit *u, Unit *slice) { assert(u); assert(slice); /* Sets the unit slice if it has not been set before. Is extra * careful, to only allow this for units that actually have a * cgroup context. Also, we don't allow to set this for slices * (since the parent slice is derived from the name). Make * sure the unit we set is actually a slice. */ if (!UNIT_HAS_CGROUP_CONTEXT(u)) return -EOPNOTSUPP; if (u->type == UNIT_SLICE) return -EINVAL; if (unit_active_state(u) != UNIT_INACTIVE) return -EBUSY; if (slice->type != UNIT_SLICE) return -EINVAL; if (unit_has_name(u, SPECIAL_INIT_SCOPE) && !unit_has_name(slice, SPECIAL_ROOT_SLICE)) return -EPERM; if (UNIT_DEREF(u->slice) == slice) return 0; if (UNIT_ISSET(u->slice)) return -EBUSY; unit_ref_set(&u->slice, slice); return 1; } int unit_set_default_slice(Unit *u) { _cleanup_free_ char *b = NULL; const char *slice_name; Unit *slice; int r; assert(u); if (UNIT_ISSET(u->slice)) return 0; if (u->instance) { _cleanup_free_ char *prefix = NULL, *escaped = NULL; /* Implicitly place all instantiated units in their * own per-template slice */ r = unit_name_to_prefix(u->id, &prefix); if (r < 0) return r; /* The prefix is already escaped, but it might include * "-" which has a special meaning for slice units, * hence escape it here extra. */ escaped = unit_name_escape(prefix); if (!escaped) return -ENOMEM; if (u->manager->running_as == MANAGER_SYSTEM) b = strjoin("system-", escaped, ".slice", NULL); else b = strappend(escaped, ".slice"); if (!b) return -ENOMEM; slice_name = b; } else slice_name = u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE) ? SPECIAL_SYSTEM_SLICE : SPECIAL_ROOT_SLICE; r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice); if (r < 0) return r; return unit_set_slice(u, slice); } const char *unit_slice_name(Unit *u) { assert(u); if (!UNIT_ISSET(u->slice)) return NULL; return UNIT_DEREF(u->slice)->id; } int unit_load_related_unit(Unit *u, const char *type, Unit **_found) { _cleanup_free_ char *t = NULL; int r; assert(u); assert(type); assert(_found); r = unit_name_change_suffix(u->id, type, &t); if (r < 0) return r; if (unit_has_name(u, t)) return -EINVAL; r = manager_load_unit(u->manager, t, NULL, NULL, _found); assert(r < 0 || *_found != u); return r; } static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) { const char *name, *old_owner, *new_owner; Unit *u = userdata; int r; assert(message); assert(u); r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner); if (r < 0) { bus_log_parse_error(r); return 0; } if (UNIT_VTABLE(u)->bus_name_owner_change) UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner); return 0; } int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) { const char *match; assert(u); assert(bus); assert(name); if (u->match_bus_slot) return -EBUSY; match = strjoina("type='signal'," "sender='org.freedesktop.DBus'," "path='/org/freedesktop/DBus'," "interface='org.freedesktop.DBus'," "member='NameOwnerChanged'," "arg0='", name, "'", NULL); return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u); } int unit_watch_bus_name(Unit *u, const char *name) { int r; assert(u); assert(name); /* Watch a specific name on the bus. We only support one unit * watching each name for now. */ if (u->manager->api_bus) { /* If the bus is already available, install the match directly. * Otherwise, just put the name in the list. bus_setup_api() will take care later. */ r = unit_install_bus_match(u, u->manager->api_bus, name); if (r < 0) return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name); } r = hashmap_put(u->manager->watch_bus, name, u); if (r < 0) { u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot); return log_warning_errno(r, "Failed to put bus name to hashmap: %m"); } return 0; } void unit_unwatch_bus_name(Unit *u, const char *name) { assert(u); assert(name); hashmap_remove_value(u->manager->watch_bus, name, u); u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot); } bool unit_can_serialize(Unit *u) { assert(u); return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item; } int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) { int r; assert(u); assert(f); assert(fds); if (unit_can_serialize(u)) { ExecRuntime *rt; r = UNIT_VTABLE(u)->serialize(u, f, fds); if (r < 0) return r; rt = unit_get_exec_runtime(u); if (rt) { r = exec_runtime_serialize(u, rt, f, fds); if (r < 0) return r; } } dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp); dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp); dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp); dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp); dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp); dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp); if (dual_timestamp_is_set(&u->condition_timestamp)) unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result)); if (dual_timestamp_is_set(&u->assert_timestamp)) unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result)); unit_serialize_item(u, f, "transient", yes_no(u->transient)); unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base); if (u->cgroup_path) unit_serialize_item(u, f, "cgroup", u->cgroup_path); unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized)); if (u->cgroup_netclass_id) unit_serialize_item_format(u, f, "netclass-id", "%" PRIu32, u->cgroup_netclass_id); if (serialize_jobs) { if (u->job) { fprintf(f, "job\n"); job_serialize(u->job, f, fds); } if (u->nop_job) { fprintf(f, "job\n"); job_serialize(u->nop_job, f, fds); } } /* End marker */ fputc('\n', f); return 0; } int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) { assert(u); assert(f); assert(key); if (!value) return 0; fputs(key, f); fputc('=', f); fputs(value, f); fputc('\n', f); return 1; } int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) { _cleanup_free_ char *c = NULL; assert(u); assert(f); assert(key); if (!value) return 0; c = cescape(value); if (!c) return -ENOMEM; fputs(key, f); fputc('=', f); fputs(c, f); fputc('\n', f); return 1; } int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) { int copy; assert(u); assert(f); assert(key); if (fd < 0) return 0; copy = fdset_put_dup(fds, fd); if (copy < 0) return copy; fprintf(f, "%s=%i\n", key, copy); return 1; } void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) { va_list ap; assert(u); assert(f); assert(key); assert(format); fputs(key, f); fputc('=', f); va_start(ap, format); vfprintf(f, format, ap); va_end(ap); fputc('\n', f); } int unit_deserialize(Unit *u, FILE *f, FDSet *fds) { ExecRuntime **rt = NULL; size_t offset; int r; assert(u); assert(f); assert(fds); offset = UNIT_VTABLE(u)->exec_runtime_offset; if (offset > 0) rt = (ExecRuntime**) ((uint8_t*) u + offset); for (;;) { char line[LINE_MAX], *l, *v; size_t k; if (!fgets(line, sizeof(line), f)) { if (feof(f)) return 0; return -errno; } char_array_0(line); l = strstrip(line); /* End marker */ if (isempty(l)) return 0; k = strcspn(l, "="); if (l[k] == '=') { l[k] = 0; v = l+k+1; } else v = l+k; if (streq(l, "job")) { if (v[0] == '\0') { /* new-style serialized job */ Job *j; j = job_new_raw(u); if (!j) return log_oom(); r = job_deserialize(j, f, fds); if (r < 0) { job_free(j); return r; } r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j); if (r < 0) { job_free(j); return r; } r = job_install_deserialized(j); if (r < 0) { hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id)); job_free(j); return r; } } else /* legacy for pre-44 */ log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v); continue; } else if (streq(l, "inactive-exit-timestamp")) { dual_timestamp_deserialize(v, &u->inactive_exit_timestamp); continue; } else if (streq(l, "active-enter-timestamp")) { dual_timestamp_deserialize(v, &u->active_enter_timestamp); continue; } else if (streq(l, "active-exit-timestamp")) { dual_timestamp_deserialize(v, &u->active_exit_timestamp); continue; } else if (streq(l, "inactive-enter-timestamp")) { dual_timestamp_deserialize(v, &u->inactive_enter_timestamp); continue; } else if (streq(l, "condition-timestamp")) { dual_timestamp_deserialize(v, &u->condition_timestamp); continue; } else if (streq(l, "assert-timestamp")) { dual_timestamp_deserialize(v, &u->assert_timestamp); continue; } else if (streq(l, "condition-result")) { r = parse_boolean(v); if (r < 0) log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v); else u->condition_result = r; continue; } else if (streq(l, "assert-result")) { r = parse_boolean(v); if (r < 0) log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v); else u->assert_result = r; continue; } else if (streq(l, "transient")) { r = parse_boolean(v); if (r < 0) log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v); else u->transient = r; continue; } else if (streq(l, "cpuacct-usage-base")) { r = safe_atou64(v, &u->cpuacct_usage_base); if (r < 0) log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v); continue; } else if (streq(l, "cgroup")) { r = unit_set_cgroup_path(u, v); if (r < 0) log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v); (void) unit_watch_cgroup(u); continue; } else if (streq(l, "cgroup-realized")) { int b; b = parse_boolean(v); if (b < 0) log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v); else u->cgroup_realized = b; continue; } else if (streq(l, "netclass-id")) { r = safe_atou32(v, &u->cgroup_netclass_id); if (r < 0) log_unit_debug(u, "Failed to parse netclass ID %s, ignoring.", v); else { r = unit_add_to_netclass_cgroup(u); if (r < 0) log_unit_debug_errno(u, r, "Failed to add unit to netclass cgroup, ignoring: %m"); } continue; } if (unit_can_serialize(u)) { if (rt) { r = exec_runtime_deserialize_item(u, rt, l, v, fds); if (r < 0) { log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l); continue; } /* Returns positive if key was handled by the call */ if (r > 0) continue; } r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds); if (r < 0) log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l); } } } int unit_add_node_link(Unit *u, const char *what, bool wants) { Unit *device; _cleanup_free_ char *e = NULL; int r; assert(u); /* Adds in links to the device node that this unit is based on */ if (isempty(what)) return 0; if (!is_device_path(what)) return 0; /* When device units aren't supported (such as in a * container), don't create dependencies on them. */ if (!unit_type_supported(UNIT_DEVICE)) return 0; r = unit_name_from_path(what, ".device", &e); if (r < 0) return r; r = manager_load_unit(u->manager, e, NULL, NULL, &device); if (r < 0) return r; r = unit_add_two_dependencies(u, UNIT_AFTER, u->manager->running_as == MANAGER_SYSTEM ? UNIT_BINDS_TO : UNIT_WANTS, device, true); if (r < 0) return r; if (wants) { r = unit_add_dependency(device, UNIT_WANTS, u, false); if (r < 0) return r; } return 0; } int unit_coldplug(Unit *u) { int r = 0, q = 0; assert(u); /* Make sure we don't enter a loop, when coldplugging * recursively. */ if (u->coldplugged) return 0; u->coldplugged = true; if (UNIT_VTABLE(u)->coldplug) r = UNIT_VTABLE(u)->coldplug(u); if (u->job) q = job_coldplug(u->job); if (r < 0) return r; if (q < 0) return q; return 0; } void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) { DISABLE_WARNING_FORMAT_NONLITERAL; manager_status_printf(u->manager, STATUS_TYPE_NORMAL, status, unit_status_msg_format, unit_description(u)); REENABLE_WARNING; } bool unit_need_daemon_reload(Unit *u) { _cleanup_strv_free_ char **t = NULL; char **path; struct stat st; unsigned loaded_cnt, current_cnt; assert(u); if (u->fragment_path) { zero(st); if (stat(u->fragment_path, &st) < 0) /* What, cannot access this anymore? */ return true; if (u->fragment_mtime > 0 && timespec_load(&st.st_mtim) != u->fragment_mtime) return true; } if (u->source_path) { zero(st); if (stat(u->source_path, &st) < 0) return true; if (u->source_mtime > 0 && timespec_load(&st.st_mtim) != u->source_mtime) return true; } (void) unit_find_dropin_paths(u, &t); loaded_cnt = strv_length(t); current_cnt = strv_length(u->dropin_paths); if (loaded_cnt == current_cnt) { if (loaded_cnt == 0) return false; if (strv_overlap(u->dropin_paths, t)) { STRV_FOREACH(path, u->dropin_paths) { zero(st); if (stat(*path, &st) < 0) return true; if (u->dropin_mtime > 0 && timespec_load(&st.st_mtim) > u->dropin_mtime) return true; } return false; } else return true; } else return true; } void unit_reset_failed(Unit *u) { assert(u); if (UNIT_VTABLE(u)->reset_failed) UNIT_VTABLE(u)->reset_failed(u); } Unit *unit_following(Unit *u) { assert(u); if (UNIT_VTABLE(u)->following) return UNIT_VTABLE(u)->following(u); return NULL; } bool unit_stop_pending(Unit *u) { assert(u); /* This call does check the current state of the unit. It's * hence useful to be called from state change calls of the * unit itself, where the state isn't updated yet. This is * different from unit_inactive_or_pending() which checks both * the current state and for a queued job. */ return u->job && u->job->type == JOB_STOP; } bool unit_inactive_or_pending(Unit *u) { assert(u); /* Returns true if the unit is inactive or going down */ if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u))) return true; if (unit_stop_pending(u)) return true; return false; } bool unit_active_or_pending(Unit *u) { assert(u); /* Returns true if the unit is active or going up */ if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) return true; if (u->job && (u->job->type == JOB_START || u->job->type == JOB_RELOAD_OR_START || u->job->type == JOB_RESTART)) return true; return false; } int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) { assert(u); assert(w >= 0 && w < _KILL_WHO_MAX); assert(signo > 0); assert(signo < _NSIG); if (!UNIT_VTABLE(u)->kill) return -EOPNOTSUPP; return UNIT_VTABLE(u)->kill(u, w, signo, error); } static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) { Set *pid_set; int r; pid_set = set_new(NULL); if (!pid_set) return NULL; /* Exclude the main/control pids from being killed via the cgroup */ if (main_pid > 0) { r = set_put(pid_set, PID_TO_PTR(main_pid)); if (r < 0) goto fail; } if (control_pid > 0) { r = set_put(pid_set, PID_TO_PTR(control_pid)); if (r < 0) goto fail; } return pid_set; fail: set_free(pid_set); return NULL; } int unit_kill_common( Unit *u, KillWho who, int signo, pid_t main_pid, pid_t control_pid, sd_bus_error *error) { int r = 0; bool killed = false; if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) { if (main_pid < 0) return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type)); else if (main_pid == 0) return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill"); } if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) { if (control_pid < 0) return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type)); else if (control_pid == 0) return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill"); } if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL)) if (control_pid > 0) { if (kill(control_pid, signo) < 0) r = -errno; else killed = true; } if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL)) if (main_pid > 0) { if (kill(main_pid, signo) < 0) r = -errno; else killed = true; } if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) { _cleanup_set_free_ Set *pid_set = NULL; int q; /* Exclude the main/control pids from being killed via the cgroup */ pid_set = unit_pid_set(main_pid, control_pid); if (!pid_set) return -ENOMEM; q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set); if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT) r = q; else killed = true; } if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_ALL_FAIL)) return -ESRCH; return r; } int unit_following_set(Unit *u, Set **s) { assert(u); assert(s); if (UNIT_VTABLE(u)->following_set) return UNIT_VTABLE(u)->following_set(u, s); *s = NULL; return 0; } UnitFileState unit_get_unit_file_state(Unit *u) { int r; assert(u); if (u->unit_file_state < 0 && u->fragment_path) { r = unit_file_get_state( u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER, NULL, basename(u->fragment_path), &u->unit_file_state); if (r < 0) u->unit_file_state = UNIT_FILE_BAD; } return u->unit_file_state; } int unit_get_unit_file_preset(Unit *u) { assert(u); if (u->unit_file_preset < 0 && u->fragment_path) u->unit_file_preset = unit_file_query_preset( u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER, NULL, basename(u->fragment_path)); return u->unit_file_preset; } Unit* unit_ref_set(UnitRef *ref, Unit *u) { assert(ref); assert(u); if (ref->unit) unit_ref_unset(ref); ref->unit = u; LIST_PREPEND(refs, u->refs, ref); return u; } void unit_ref_unset(UnitRef *ref) { assert(ref); if (!ref->unit) return; LIST_REMOVE(refs, ref->unit->refs, ref); ref->unit = NULL; } int unit_patch_contexts(Unit *u) { CGroupContext *cc; ExecContext *ec; unsigned i; int r; assert(u); /* Patch in the manager defaults into the exec and cgroup * contexts, _after_ the rest of the settings have been * initialized */ ec = unit_get_exec_context(u); if (ec) { /* This only copies in the ones that need memory */ for (i = 0; i < _RLIMIT_MAX; i++) if (u->manager->rlimit[i] && !ec->rlimit[i]) { ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1); if (!ec->rlimit[i]) return -ENOMEM; } if (u->manager->running_as == MANAGER_USER && !ec->working_directory) { r = get_home_dir(&ec->working_directory); if (r < 0) return r; /* Allow user services to run, even if the * home directory is missing */ ec->working_directory_missing_ok = true; } if (u->manager->running_as == MANAGER_USER && (ec->syscall_whitelist || !set_isempty(ec->syscall_filter) || !set_isempty(ec->syscall_archs) || ec->address_families_whitelist || !set_isempty(ec->address_families))) ec->no_new_privileges = true; if (ec->private_devices) ec->capability_bounding_set_drop |= (uint64_t) 1ULL << (uint64_t) CAP_MKNOD; } cc = unit_get_cgroup_context(u); if (cc) { if (ec && ec->private_devices && cc->device_policy == CGROUP_AUTO) cc->device_policy = CGROUP_CLOSED; } return 0; } ExecContext *unit_get_exec_context(Unit *u) { size_t offset; assert(u); if (u->type < 0) return NULL; offset = UNIT_VTABLE(u)->exec_context_offset; if (offset <= 0) return NULL; return (ExecContext*) ((uint8_t*) u + offset); } KillContext *unit_get_kill_context(Unit *u) { size_t offset; assert(u); if (u->type < 0) return NULL; offset = UNIT_VTABLE(u)->kill_context_offset; if (offset <= 0) return NULL; return (KillContext*) ((uint8_t*) u + offset); } CGroupContext *unit_get_cgroup_context(Unit *u) { size_t offset; if (u->type < 0) return NULL; offset = UNIT_VTABLE(u)->cgroup_context_offset; if (offset <= 0) return NULL; return (CGroupContext*) ((uint8_t*) u + offset); } ExecRuntime *unit_get_exec_runtime(Unit *u) { size_t offset; if (u->type < 0) return NULL; offset = UNIT_VTABLE(u)->exec_runtime_offset; if (offset <= 0) return NULL; return *(ExecRuntime**) ((uint8_t*) u + offset); } static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) { assert(u); if (u->manager->running_as == MANAGER_USER) { int r; if (mode == UNIT_PERSISTENT && !transient) r = user_config_home(dir); else r = user_runtime_dir(dir); if (r == 0) return -ENOENT; return r; } if (mode == UNIT_PERSISTENT && !transient) *dir = strdup("/etc/systemd/system"); else *dir = strdup("/run/systemd/system"); if (!*dir) return -ENOMEM; return 0; } int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) { _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL; int r; assert(u); if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME)) return 0; r = unit_drop_in_dir(u, mode, u->transient, &dir); if (r < 0) return r; r = write_drop_in(dir, u->id, 50, name, data); if (r < 0) return r; r = drop_in_file(dir, u->id, 50, name, &p, &q); if (r < 0) return r; r = strv_extend(&u->dropin_paths, q); if (r < 0) return r; strv_sort(u->dropin_paths); strv_uniq(u->dropin_paths); u->dropin_mtime = now(CLOCK_REALTIME); return 0; } int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) { _cleanup_free_ char *p = NULL; va_list ap; int r; assert(u); assert(name); assert(format); if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME)) return 0; va_start(ap, format); r = vasprintf(&p, format, ap); va_end(ap); if (r < 0) return -ENOMEM; return unit_write_drop_in(u, mode, name, p); } int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) { _cleanup_free_ char *ndata = NULL; assert(u); assert(name); assert(data); if (!UNIT_VTABLE(u)->private_section) return -EINVAL; if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME)) return 0; ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL); if (!ndata) return -ENOMEM; return unit_write_drop_in(u, mode, name, ndata); } int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) { _cleanup_free_ char *p = NULL; va_list ap; int r; assert(u); assert(name); assert(format); if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME)) return 0; va_start(ap, format); r = vasprintf(&p, format, ap); va_end(ap); if (r < 0) return -ENOMEM; return unit_write_drop_in_private(u, mode, name, p); } int unit_make_transient(Unit *u) { assert(u); if (!UNIT_VTABLE(u)->can_transient) return -EOPNOTSUPP; u->load_state = UNIT_STUB; u->load_error = 0; u->transient = true; u->fragment_path = mfree(u->fragment_path); return 0; } int unit_kill_context( Unit *u, KillContext *c, KillOperation k, pid_t main_pid, pid_t control_pid, bool main_pid_alien) { bool wait_for_exit = false; int sig, r; assert(u); assert(c); if (c->kill_mode == KILL_NONE) return 0; switch (k) { case KILL_KILL: sig = SIGKILL; break; case KILL_ABORT: sig = SIGABRT; break; case KILL_TERMINATE: sig = c->kill_signal; break; default: assert_not_reached("KillOperation unknown"); } if (main_pid > 0) { r = kill_and_sigcont(main_pid, sig); if (r < 0 && r != -ESRCH) { _cleanup_free_ char *comm = NULL; get_process_comm(main_pid, &comm); log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm)); } else { if (!main_pid_alien) wait_for_exit = true; if (c->send_sighup && k == KILL_TERMINATE) (void) kill(main_pid, SIGHUP); } } if (control_pid > 0) { r = kill_and_sigcont(control_pid, sig); if (r < 0 && r != -ESRCH) { _cleanup_free_ char *comm = NULL; get_process_comm(control_pid, &comm); log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm)); } else { wait_for_exit = true; if (c->send_sighup && k == KILL_TERMINATE) (void) kill(control_pid, SIGHUP); } } if (u->cgroup_path && (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) { _cleanup_set_free_ Set *pid_set = NULL; /* Exclude the main/control pids from being killed via the cgroup */ pid_set = unit_pid_set(main_pid, control_pid); if (!pid_set) return -ENOMEM; r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set); if (r < 0) { if (r != -EAGAIN && r != -ESRCH && r != -ENOENT) log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path); } else if (r > 0) { /* FIXME: For now, on the legacy hierarchy, we * will not wait for the cgroup members to die * if we are running in a container or if this * is a delegation unit, simply because cgroup * notification is unreliable in these * cases. It doesn't work at all in * containers, and outside of containers it * can be confused easily by left-over * directories in the cgroup -- which however * should not exist in non-delegated units. On * the unified hierarchy that's different, * there we get proper events. Hence rely on * them.*/ if (cg_unified() > 0 || (detect_container() == 0 && !unit_cgroup_delegate(u))) wait_for_exit = true; if (c->send_sighup && k != KILL_KILL) { set_free(pid_set); pid_set = unit_pid_set(main_pid, control_pid); if (!pid_set) return -ENOMEM; cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set); } } } return wait_for_exit; } int unit_require_mounts_for(Unit *u, const char *path) { char prefix[strlen(path) + 1], *p; int r; assert(u); assert(path); /* Registers a unit for requiring a certain path and all its * prefixes. We keep a simple array of these paths in the * unit, since its usually short. However, we build a prefix * table for all possible prefixes so that new appearing mount * units can easily determine which units to make themselves a * dependency of. */ if (!path_is_absolute(path)) return -EINVAL; p = strdup(path); if (!p) return -ENOMEM; path_kill_slashes(p); if (!path_is_safe(p)) { free(p); return -EPERM; } if (strv_contains(u->requires_mounts_for, p)) { free(p); return 0; } r = strv_consume(&u->requires_mounts_for, p); if (r < 0) return r; PATH_FOREACH_PREFIX_MORE(prefix, p) { Set *x; x = hashmap_get(u->manager->units_requiring_mounts_for, prefix); if (!x) { char *q; r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops); if (r < 0) return r; q = strdup(prefix); if (!q) return -ENOMEM; x = set_new(NULL); if (!x) { free(q); return -ENOMEM; } r = hashmap_put(u->manager->units_requiring_mounts_for, q, x); if (r < 0) { free(q); set_free(x); return r; } } r = set_put(x, u); if (r < 0) return r; } return 0; } int unit_setup_exec_runtime(Unit *u) { ExecRuntime **rt; size_t offset; Iterator i; Unit *other; offset = UNIT_VTABLE(u)->exec_runtime_offset; assert(offset > 0); /* Check if there already is an ExecRuntime for this unit? */ rt = (ExecRuntime**) ((uint8_t*) u + offset); if (*rt) return 0; /* Try to get it from somebody else */ SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) { *rt = unit_get_exec_runtime(other); if (*rt) { exec_runtime_ref(*rt); return 0; } } return exec_runtime_make(rt, unit_get_exec_context(u), u->id); } bool unit_type_supported(UnitType t) { if (_unlikely_(t < 0)) return false; if (_unlikely_(t >= _UNIT_TYPE_MAX)) return false; if (!unit_vtable[t]->supported) return true; return unit_vtable[t]->supported(); } void unit_warn_if_dir_nonempty(Unit *u, const char* where) { int r; assert(u); assert(where); r = dir_is_empty(where); if (r > 0) return; if (r < 0) { log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where); return; } log_struct(LOG_NOTICE, LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING), LOG_UNIT_ID(u), LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where), "WHERE=%s", where, NULL); } int unit_fail_if_symlink(Unit *u, const char* where) { int r; assert(u); assert(where); r = is_symlink(where); if (r < 0) { log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where); return 0; } if (r == 0) return 0; log_struct(LOG_ERR, LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING), LOG_UNIT_ID(u), LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where), "WHERE=%s", where, NULL); return -ELOOP; }
lnykryn/systemd
src/core/unit.c
C
gpl-2.0
116,041
30.311657
151
0.471997
false
// logs.cpp // // Rivendell web service portal -- Log services // // (C) Copyright 2013,2016 Fred Gleason <fredg@paravelsystems.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. // // 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 <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <rdcreate_log.h> #include <rddb.h> #include <rdformpost.h> #include <rdweb.h> #include <rdsvc.h> #include <rduser.h> #include <rdlog.h> #include <rdlog_event.h> #include <rdlog_line.h> #include <rdconf.h> #include <rdescape_string.h> #include <rdxport.h> void Xport::AddLog() { QString log_name; QString service_name; // // Get Arguments // if(!xport_post->getValue("LOG_NAME",&log_name)) { XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("SERVICE_NAME",&service_name)) { XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER); } RDSvc *svc=new RDSvc(service_name); if(!svc->exists()) { XmlExit("No such service",404,"logs.cpp",LINE_NUMBER); } // // Verify User Perms // if(!xport_user->createLog()) { XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER); } RDLog *log=new RDLog(log_name); if(!log->exists()) { delete log; log=new RDLog(log_name,true); if(!log->exists()) { delete log; XmlExit("Unable to create log",500,"logs.cpp",LINE_NUMBER); } log->setOriginUser(xport_user->name()); log->setDescription("[new log]"); log->setService(service_name); } delete log; RDCreateLogTable(RDLog::tableName(log_name)); XmlExit("OK",200,"logs.cpp",LINE_NUMBER); } void Xport::DeleteLog() { QString log_name; // // Get Arguments // if(!xport_post->getValue("LOG_NAME",&log_name)) { XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER); } // // Verify User Perms // if(!xport_user->deleteLog()) { XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER); } RDLog *log=new RDLog(log_name); if(log->exists()) { if(!log->remove(xport_station,xport_user,xport_config)) { delete log; XmlExit("Unable to delete log",500,"logs.cpp",LINE_NUMBER); } } delete log; XmlExit("OK",200,"logs.cpp",LINE_NUMBER); } void Xport::ListLogs() { QString sql; RDSqlQuery *q; RDLog *log; QString service_name=""; QString log_name=""; QString trackable; // // Get Options // xport_post->getValue("SERVICE_NAME",&service_name); xport_post->getValue("LOG_NAME",&log_name); xport_post->getValue("TRACKABLE",&trackable); // // Generate Log List // sql="select NAME from LOGS"; if((!service_name.isEmpty())||(!log_name.isEmpty())||(trackable=="1")) { sql+=" where"; if(!log_name.isEmpty()) { sql+=" (NAME=\""+RDEscapeString(log_name)+"\")&&"; } if(!service_name.isEmpty()) { sql+=" (SERVICE=\""+RDEscapeString(service_name)+"\")&&"; } if(trackable=="1") { sql+=" (SCHEDULED_TRACKS>0)&&"; } sql=sql.left(sql.length()-2); } sql+=" order by NAME"; q=new RDSqlQuery(sql); // // Process Request // printf("Content-type: application/xml\n"); printf("Status: 200\n\n"); printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); printf("<logList>\n"); while(q->next()) { log=new RDLog(q->value(0).toString()); printf("%s",(const char *)log->xml()); delete log; } printf("</logList>\n"); delete q; Exit(0); } void Xport::ListLog() { RDLog *log; QString name=""; // // Get Options // xport_post->getValue("NAME",&name); // // Verify that log exists // log=new RDLog(name); if(!log->exists()) { delete log; XmlExit("No such log",404,"logs.cpp",LINE_NUMBER); } // // Generate Log Listing // RDLogEvent *log_event=log->createLogEvent(); log_event->load(true); // // Process Request // printf("Content-type: application/xml\n"); printf("Status: 200\n\n"); printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); printf("%s\n",(const char *)log_event->xml()); Exit(0); } void Xport::SaveLog() { // // Verify User Perms // if((!xport_user->addtoLog())||(!xport_user->removefromLog())||(!xport_user->arrangeLog())) { XmlExit("No user privilege",404,"logs.cpp",LINE_NUMBER); } QString log_name; QString service_name; QString description; QDate purge_date; bool auto_refresh; QDate start_date; QDate end_date; int line_quantity; // // Header Data // if(!xport_post->getValue("LOG_NAME",&log_name)) { XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("SERVICE_NAME",&service_name)) { XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("DESCRIPTION",&description)) { XmlExit("Missing DESCRIPTION",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("PURGE_DATE",&purge_date)) { XmlExit("Missing PURGE_DATE",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("AUTO_REFRESH",&auto_refresh)) { XmlExit("Missing AUTO_REFRESH",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("START_DATE",&start_date)) { XmlExit("Missing START_DATE",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("END_DATE",&end_date)) { XmlExit("Missing END_DATE",400,"logs.cpp",LINE_NUMBER); } if(!xport_post->getValue("LINE_QUANTITY",&line_quantity)) { XmlExit("Missing LINE_QUANTITY",400,"logs.cpp",LINE_NUMBER); } // // Logline Data // RDLogEvent *logevt=new RDLogEvent(RDLog::tableName(log_name)); for(int i=0;i<line_quantity;i++) { logevt->insert(i,1); RDLogLine *ll=logevt->logLine(i); QString line=QString().sprintf("LINE%d",i); QString str; int integer1; int integer2; QDateTime datetime; QTime time; bool state; bool ok=false; if(!xport_post->getValue(line+"_ID",&integer1,&ok)) { XmlExit("Missing "+line+"_ID",400,"logs.cpp",LINE_NUMBER); } if(!ok) { XmlExit("Invalid "+line+"_ID",400,"logs.cpp",LINE_NUMBER); } ll->setId(integer1); if(!xport_post->getValue(line+"_TYPE",&integer1)) { XmlExit("Missing "+line+"_TYPE",400,"logs.cpp",LINE_NUMBER); } ll->setType((RDLogLine::Type)integer1); if(!xport_post->getValue(line+"_CART_NUMBER",&integer1)) { XmlExit("Missing "+line+"_CART_NUMBER",400,"logs.cpp",LINE_NUMBER); } ll->setCartNumber(integer1); if(!xport_post->getValue(line+"_TIME_TYPE",&integer2)) { XmlExit("Missing "+line+"_TIME_TYPE",400,"logs.cpp",LINE_NUMBER); } ll->setTimeType((RDLogLine::TimeType)integer2); if(!xport_post->getValue(line+"_START_TIME",&integer1)) { XmlExit("Missing "+line+"_START_TIME",400,"logs.cpp",LINE_NUMBER); } if(ll->timeType()==RDLogLine::Hard) { ll->setStartTime(RDLogLine::Logged,QTime().addMSecs(integer1)); } else { ll->setStartTime(RDLogLine::Predicted,QTime().addMSecs(integer1)); } if(!xport_post->getValue(line+"_GRACE_TIME",&integer1)) { XmlExit("Missing "+line+"_GRACE_TIME",400,"logs.cpp",LINE_NUMBER); } ll->setGraceTime(integer1); if(!xport_post->getValue(line+"_TRANS_TYPE",&str)) { XmlExit("Missing "+line+"_TRANS_TYPE",400,"logs.cpp",LINE_NUMBER); } integer1=-1; if(str.lower()=="play") { integer1=RDLogLine::Play; } if(str.lower()=="segue") { integer1=RDLogLine::Segue; } if(str.lower()=="stop") { integer1=RDLogLine::Stop; } if(integer1<0) { XmlExit("Invalid transition type in "+line+"_TRANS_TYPE",400, "logs.cpp",LINE_NUMBER); } ll->setTransType((RDLogLine::TransType)integer1); if(!xport_post->getValue(line+"_START_POINT",&integer1)) { XmlExit("Missing "+line+"_START_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setStartPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_END_POINT",&integer1)) { XmlExit("Missing "+line+"_END_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setEndPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_SEGUE_START_POINT",&integer1)) { XmlExit("Missing "+line+"_SEGUE_START_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setSegueStartPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_SEGUE_END_POINT",&integer1)) { XmlExit("Missing "+line+"_SEGUE_END_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setSegueEndPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_FADEUP_POINT",&integer1)) { XmlExit("Missing "+line+"_FADEUP_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setFadeupPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_FADEUP_GAIN",&integer1)) { XmlExit("Missing "+line+"_FADEUP_GAIN",400,"logs.cpp",LINE_NUMBER); } ll->setFadeupGain(integer1); if(!xport_post->getValue(line+"_FADEDOWN_POINT",&integer1)) { XmlExit("Missing "+line+"_FADEDOWN_POINT",400,"logs.cpp",LINE_NUMBER); } ll->setFadedownPoint(integer1,RDLogLine::LogPointer); if(!xport_post->getValue(line+"_FADEDOWN_GAIN",&integer1)) { XmlExit("Missing "+line+"_FADEDOWN_GAIN",400,"logs.cpp",LINE_NUMBER); } ll->setFadedownGain(integer1); if(!xport_post->getValue(line+"_DUCK_UP_GAIN",&integer1)) { XmlExit("Missing "+line+"_DUCK_UP_GAIN",400,"logs.cpp",LINE_NUMBER); } ll->setDuckUpGain(integer1); if(!xport_post->getValue(line+"_DUCK_DOWN_GAIN",&integer1)) { XmlExit("Missing "+line+"_DUCK_DOWN_GAIN",400,"logs.cpp",LINE_NUMBER); } ll->setDuckDownGain(integer1); if(!xport_post->getValue(line+"_COMMENT",&str)) { XmlExit("Missing "+line+"_COMMENT",400,"logs.cpp",LINE_NUMBER); } ll->setMarkerComment(str); if(!xport_post->getValue(line+"_LABEL",&str)) { XmlExit("Missing "+line+"_LABEL",400,"logs.cpp",LINE_NUMBER); } ll->setMarkerLabel(str); if(!xport_post->getValue(line+"_ORIGIN_USER",&str)) { XmlExit("Missing "+line+"_ORIGIN_USER",400,"logs.cpp",LINE_NUMBER); } ll->setOriginUser(str); if(!xport_post->getValue(line+"_ORIGIN_DATETIME",&datetime)) { XmlExit("Missing "+line+"_ORIGIN_DATETIME",400,"logs.cpp",LINE_NUMBER); } ll->setOriginDateTime(datetime); if(!xport_post->getValue(line+"_EVENT_LENGTH",&integer1)) { XmlExit("Missing "+line+"_EVENT_LENGTH",400,"logs.cpp",LINE_NUMBER); } ll->setEventLength(integer1); if(!xport_post->getValue(line+"_LINK_EVENT_NAME",&str)) { XmlExit("Missing "+line+"_LINK_EVENT_NAME",400,"logs.cpp",LINE_NUMBER); } ll->setLinkEventName(str); if(!xport_post->getValue(line+"_LINK_START_TIME",&integer1)) { XmlExit("Missing "+line+"_LINK_START_TIME",400,"logs.cpp",LINE_NUMBER); } ll->setLinkStartTime(QTime().addMSecs(integer1)); if(!xport_post->getValue(line+"_LINK_LENGTH",&integer1)) { XmlExit("Missing "+line+"_LINK_LENGTH",400,"logs.cpp",LINE_NUMBER); } ll->setLinkLength(integer1); if(!xport_post->getValue(line+"_LINK_START_SLOP",&integer1)) { XmlExit("Missing "+line+"_LINK_START_SLOP",400,"logs.cpp",LINE_NUMBER); } ll->setLinkStartSlop(integer1); if(!xport_post->getValue(line+"_LINK_END_SLOP",&integer1)) { XmlExit("Missing "+line+"_LINK_END_SLOP",400,"logs.cpp",LINE_NUMBER); } ll->setLinkEndSlop(integer1); if(!xport_post->getValue(line+"_LINK_ID",&integer1)) { XmlExit("Missing "+line+"_LINK_ID",400,"logs.cpp",LINE_NUMBER); } ll->setLinkId(integer1); if(!xport_post->getValue(line+"_LINK_EMBEDDED",&state)) { XmlExit("Missing "+line+"_LINK_EMBEDDED",400,"logs.cpp",LINE_NUMBER); } ll->setLinkEmbedded(state); if(!xport_post->getValue(line+"_EXT_START_TIME",&time)) { XmlExit("Missing "+line+"_EXT_START_TIME",400,"logs.cpp",LINE_NUMBER); } ll->setExtStartTime(time); if(!xport_post->getValue(line+"_EXT_CART_NAME",&str)) { XmlExit("Missing "+line+"_EXT_CART_NAME",400,"logs.cpp",LINE_NUMBER); } ll->setExtCartName(str); if(!xport_post->getValue(line+"_EXT_DATA",&str)) { XmlExit("Missing "+line+"_EXT_DATA",400,"logs.cpp",LINE_NUMBER); } ll->setExtData(str); if(!xport_post->getValue(line+"_EXT_EVENT_ID",&str)) { XmlExit("Missing "+line+"_EXT_EVENT_ID",400,"logs.cpp",LINE_NUMBER); } ll->setExtEventId(str); if(!xport_post->getValue(line+"_EXT_ANNC_TYPE",&str)) { XmlExit("Missing "+line+"_EXT_ANNC_TYPE",400,"logs.cpp",LINE_NUMBER); } ll->setExtAnncType(str); } RDLog *log=new RDLog(log_name); if(!log->exists()) { XmlExit("No such log",404,"logs.cpp",LINE_NUMBER); } log->setService(service_name); log->setDescription(description); log->setPurgeDate(purge_date); log->setAutoRefresh(auto_refresh); log->setStartDate(start_date); log->setEndDate(end_date); log->setModifiedDatetime(QDateTime::currentDateTime()); logevt->save(); XmlExit(QString().sprintf("OK Saved %d events",logevt->size()), 200,"logs.cpp",LINE_NUMBER); }
NBassan/rivendell
web/rdxport/logs.cpp
C++
gpl-2.0
13,675
27.489583
94
0.629616
false
/*************************************************************************** Copyright (C) 2003-2009 Robby Stephenson <robby@periapsis.org> ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License as * * published by the Free Software Foundation; either version 2 of * * the License or (at your option) version 3 or any later version * * accepted by the membership of KDE e.V. (or its successor approved * * by the membership of KDE e.V.), which shall act as a proxy * * defined in Section 14 of version 3 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, see <http://www.gnu.org/licenses/>. * * * ***************************************************************************/ // The layout borrows heavily from kmsearchpatternedit.cpp in kmail // which is authored by Marc Mutz <Marc@Mutz.com> under the GPL #include "filterdialog.h" #include "tellico_kernel.h" #include "document.h" #include "collection.h" #include "fieldcompletion.h" #include "gui/filterrulewidgetlister.h" #include "gui/filterrulewidget.h" #include "tellico_debug.h" #include <KLocalizedString> #include <KHelpClient> #include <QGroupBox> #include <QRadioButton> #include <QButtonGroup> #include <QLabel> #include <QApplication> #include <QFrame> #include <QVBoxLayout> #include <QPushButton> #include <QLineEdit> #include <QDialogButtonBox> using Tellico::FilterDialog; namespace { static const int FILTER_MIN_WIDTH = 600; } // modal dialog so I don't have to worry about updating stuff // don't show apply button if not saving, i.e. just modifying existing filter FilterDialog::FilterDialog(Mode mode_, QWidget* parent_) : QDialog(parent_), m_filter(nullptr), m_mode(mode_), m_saveFilter(nullptr) { setModal(true); setWindowTitle(mode_ == CreateFilter ? i18n("Advanced Filter") : i18n("Modify Filter")); QVBoxLayout* topLayout = new QVBoxLayout(); setLayout(topLayout); QDialogButtonBox* buttonBox; if(mode_ == CreateFilter) { buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply); } else { buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel); } m_okButton = buttonBox->button(QDialogButtonBox::Ok); m_applyButton = buttonBox->button(QDialogButtonBox::Apply); connect(m_okButton, &QAbstractButton::clicked, this, &FilterDialog::slotOk); if(m_applyButton) { connect(m_applyButton, &QAbstractButton::clicked, this, &FilterDialog::slotApply); } connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); connect(buttonBox, &QDialogButtonBox::helpRequested, this, &FilterDialog::slotHelp); QGroupBox* m_matchGroup = new QGroupBox(i18n("Filter Criteria"), this); QVBoxLayout* vlay = new QVBoxLayout(m_matchGroup); topLayout->addWidget(m_matchGroup); m_matchGroup->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); m_matchAll = new QRadioButton(i18n("Match a&ll of the following"), m_matchGroup); m_matchAny = new QRadioButton(i18n("Match an&y of the following"), m_matchGroup); m_matchAll->setChecked(true); vlay->addWidget(m_matchAll); vlay->addWidget(m_matchAny); QButtonGroup* bg = new QButtonGroup(m_matchGroup); bg->addButton(m_matchAll); bg->addButton(m_matchAny); #if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0)) void (QButtonGroup::* buttonClicked)(int) = &QButtonGroup::buttonClicked; connect(bg, buttonClicked, this, &FilterDialog::slotFilterChanged); #else connect(bg, &QButtonGroup::idClicked, this, &FilterDialog::slotFilterChanged); #endif m_ruleLister = new FilterRuleWidgetLister(m_matchGroup); connect(m_ruleLister, &KWidgetLister::widgetRemoved, this, &FilterDialog::slotShrink); connect(m_ruleLister, &FilterRuleWidgetLister::signalModified, this, &FilterDialog::slotFilterChanged); m_ruleLister->setFocus(); vlay->addWidget(m_ruleLister); QHBoxLayout* blay = new QHBoxLayout(); topLayout->addLayout(blay); QLabel* lab = new QLabel(i18n("Filter name:"), this); blay->addWidget(lab); m_filterName = new QLineEdit(this); blay->addWidget(m_filterName); connect(m_filterName, &QLineEdit::textChanged, this, &FilterDialog::slotFilterChanged); // only when creating a new filter can it be saved if(m_mode == CreateFilter) { m_saveFilter = new QPushButton(QIcon::fromTheme(QStringLiteral("view-filter")), i18n("&Save Filter"), this); blay->addWidget(m_saveFilter); m_saveFilter->setEnabled(false); connect(m_saveFilter, &QAbstractButton::clicked, this, &FilterDialog::slotSaveFilter); m_applyButton->setEnabled(false); } m_okButton->setEnabled(false); // disable at start buttonBox->button(QDialogButtonBox::Cancel)->setDefault(true); setMinimumWidth(qMax(minimumWidth(), FILTER_MIN_WIDTH)); topLayout->addWidget(buttonBox); } Tellico::FilterPtr FilterDialog::currentFilter(bool alwaysCreateNew_) { FilterPtr newFilter(new Filter(Filter::MatchAny)); if(m_matchAll->isChecked()) { newFilter->setMatch(Filter::MatchAll); } else { newFilter->setMatch(Filter::MatchAny); } foreach(QWidget* widget, m_ruleLister->widgetList()) { FilterRuleWidget* rw = static_cast<FilterRuleWidget*>(widget); FilterRule* rule = rw->rule(); if(rule && !rule->isEmpty()) { newFilter->append(rule); } else { delete rule; } } newFilter->setName(m_filterName->text()); if(!m_filter || !alwaysCreateNew_) { m_filter = newFilter; } return newFilter; } void FilterDialog::setFilter(Tellico::FilterPtr filter_) { if(!filter_) { slotClear(); return; } if(filter_->op() == Filter::MatchAll) { m_matchAll->setChecked(true); } else { m_matchAny->setChecked(true); } m_ruleLister->setFilter(filter_); m_filterName->setText(filter_->name()); m_filter = filter_; } void FilterDialog::slotOk() { slotApply(); accept(); } void FilterDialog::slotApply() { emit signalUpdateFilter(currentFilter()); } void FilterDialog::slotHelp() { KHelpClient::invokeHelp(QStringLiteral("filter-dialog")); } void FilterDialog::slotClear() { // myDebug(); m_matchAll->setChecked(true); m_ruleLister->reset(); m_filterName->clear(); } void FilterDialog::slotShrink() { updateGeometry(); QApplication::sendPostedEvents(); resize(width(), sizeHint().height()); } void FilterDialog::slotFilterChanged() { const bool hadFilter = m_filter && !m_filter->isEmpty(); const bool emptyFilter = currentFilter(true)->isEmpty(); // an empty filter can be ok if the filter was originally not empty const bool enableOk = !currentFilter()->isEmpty() || hadFilter; if(m_saveFilter) { m_saveFilter->setEnabled(!m_filterName->text().isEmpty() && !emptyFilter); if(m_applyButton) { m_applyButton->setEnabled(!emptyFilter); } } if(m_applyButton) { m_applyButton->setEnabled(enableOk); } m_okButton->setEnabled(enableOk); m_okButton->setDefault(enableOk); } void FilterDialog::slotSaveFilter() { // non-op if editing an existing filter if(m_mode != CreateFilter) { return; } // in this case, currentFilter() either creates a new filter or // updates the current one. If creating a new one, then I want to copy it const bool wasEmpty = !m_filter; FilterPtr filter(new Filter(*currentFilter())); if(wasEmpty) { m_filter = filter; } // this keeps the saving completely decoupled from the filter setting in the detailed view if(filter->isEmpty()) { m_filter = FilterPtr(); return; } Kernel::self()->addFilter(filter); }
KDE/tellico
src/filterdialog.cpp
C++
gpl-2.0
8,620
35.066946
131
0.655104
false
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2014 VINADES.,JSC. All rights reserved * @Language Tiếng Việt * @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/) * @Createdate Mar 04, 2010, 03:22:00 PM */ if (!defined('NV_ADMIN') or !defined('NV_MAINFILE')) { die('Stop!!!'); } $lang_translator['author'] = 'VINADES.,JSC (contact@vinades.vn)'; $lang_translator['createdate'] = '04/03/2010, 15:22'; $lang_translator['copyright'] = '@Copyright (C) 2012 VINADES.,JSC. All rights reserved'; $lang_translator['info'] = ''; $lang_translator['langtype'] = 'lang_module'; $lang_module['is_suspend0'] = 'Hoạt động'; $lang_module['is_suspend1'] = 'Bị đình chỉ vào &ldquo;%1$s&rdquo; bởi &ldquo;%2$s&rdquo; với lý do &ldquo;%3$s&rdquo;'; $lang_module['is_suspend2'] = 'Bị đình chỉ'; $lang_module['last_login0'] = 'Chưa bao giờ'; $lang_module['login'] = 'Tên tài khoản'; $lang_module['email'] = 'Email'; $lang_module['full_name'] = 'Tên gọi trên site'; $lang_module['name'] = 'Tên gọi trên site'; $lang_module['sig'] = 'Chữ ký'; $lang_module['editor'] = 'Trình soạn thảo'; $lang_module['lev'] = 'Quyền hạn'; $lang_module['position'] = 'Chức danh'; $lang_module['regtime'] = 'Ngày tham gia'; $lang_module['is_suspend'] = 'Tình trạng hiện tại'; $lang_module['last_login'] = 'Lần đăng nhập gần đây'; $lang_module['last_ip'] = 'Bằng IP'; $lang_module['browser'] = 'Bằng trình duyệt'; $lang_module['os'] = 'Bằng hệ điều hành'; $lang_module['admin_info_title1'] = 'Thông tin tài khoản: %s'; $lang_module['admin_info_title2'] = 'Thông tin tài khoản: %s (là bạn)'; $lang_module['menulist'] = 'Danh sách Quản trị'; $lang_module['menuadd'] = 'Thêm Quản trị'; $lang_module['main'] = 'Danh sách Quản trị website'; $lang_module['nv_admin_edit'] = 'Sửa thông tin Quản trị website'; $lang_module['nv_admin_add'] = 'Thêm Quản trị website'; $lang_module['nv_admin_del'] = 'Xóa Quản trị website'; $lang_module['username_noactive'] = 'Lỗi: tài khoản: %s chưa được kích hoạt, bạn cần kích hoạt tài khoản này trước khi thêm vào quản trị site'; $lang_module['full_name_incorrect'] = 'Bạn chưa khai báo tên gọi của người quản trị này'; $lang_module['position_incorrect'] = 'Bạn chưa khai báo chức danh của người quản trị này'; $lang_module['nv_admin_add_info'] = 'Để tạo một tài khoản Quản trị website mới, bạn cần khai báo đầy đủ vào các ô trống dưới đây. Bạn chỉ có quyền tạo tài khoản Quản trị dưới cấp của mình'; $lang_module['if_level3_selected'] = 'Hãy đánh dấu tích vào những module mà bạn cho phép quản lý'; $lang_module['login_info'] = 'Bạn cần nhập tên thành viên, nếu chưa có thành viên bạn cần tạo thành viên trước.'; $lang_module['nv_admin_add_result'] = 'Thông tin về Quản trị website mới'; $lang_module['nv_admin_add_title'] = 'Hệ thống đã tạo thành công tài khoản Quản trị website mới với những thông tin dưới đây'; $lang_module['nv_admin_modules'] = 'Quản lý các module'; $lang_module['admin_account_info'] = 'Thông tin tài khoản Quản trị website %s'; $lang_module['nv_admin_add_download'] = 'Tải về'; $lang_module['nv_admin_add_sendmail'] = 'Gửi thông báo'; $lang_module['nv_admin_login_address'] = 'URL trang quản lý website'; $lang_module['nv_admin_edit_info'] = 'Thay đổi thông tin tài khoản &ldquo;<strong>%s</strong>&rdquo;'; $lang_module['show_mail'] = 'Hiển thị email'; $lang_module['sig_info'] = 'Chữ ký được chèn vào cuối mỗi bài trả lời, thư... được gửi đi từ tài khoản Quản trị &ldquo;<strong>%s</strong>&rdquo;. Chỉ chấp nhận dạng text đơn thuần'; $lang_module['not_use'] = 'Không sử dụng'; $lang_module['nv_admin_edit_result'] = 'Thay đổi thông tin tài khoản Quản trị: %s'; $lang_module['nv_admin_edit_result_title'] = 'Những thay đổi vừa được thực hiện đối với tài khoản Quản trị %s'; $lang_module['show_mail0'] = 'Không hiển thị'; $lang_module['show_mail1'] = 'Hiển thị'; $lang_module['field'] = 'tiêu chí'; $lang_module['old_value'] = 'Cũ'; $lang_module['new_value'] = 'Mới'; $lang_module['chg_is_suspend0'] = 'Tình trạng hiện tại: Đang bị đình chỉ. Để Khôi phục hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây'; $lang_module['chg_is_suspend1'] = 'Tình trạng hiện tại: Đang hoạt động. Để Đình chỉ hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây'; $lang_module['chg_is_suspend2'] = 'Khôi phục/Đình chỉ hoạt động'; $lang_module['nv_admin_chg_suspend'] = 'Thay đổi trạng thái hoạt động của tài khoản Quản trị &ldquo;<strong>%s</strong>&rdquo;'; $lang_module['position_info'] = 'Chức danh dùng trong các hoạt động đối ngoại như trao đổi thư từ, viết lời bình...'; $lang_module['susp_reason_empty'] = 'Bạn chưa khai báo lý do đình chỉ hoạt động của tài khoản Quản trị &ldquo;<strong>%s</strong>&rdquo;'; $lang_module['suspend_info_empty'] = 'Tài khoản quản trị &ldquo;<strong>%s</strong>&rdquo; chưa bị đình chỉ hoạt động lần nào'; $lang_module['suspend_info_yes'] = 'Danh sách các lần đình chỉ hoạt động của tài khoản quản trị &ldquo;<strong>%s</strong>&rdquo;'; $lang_module['suspend_start'] = 'Bắt đầu'; $lang_module['suspend_end'] = 'Kết thúc'; $lang_module['suspend_reason'] = 'Lý do đình chỉ'; $lang_module['suspend_info'] = 'Vào: %1$s<br />Bởi: %2$s'; $lang_module['suspend0'] = 'Khôi phục hoạt động'; $lang_module['suspend1'] = 'Đình chỉ hoạt động'; $lang_module['clean_history'] = 'Xóa lịch sử'; $lang_module['suspend_sendmail'] = 'Gửi thông báo'; $lang_module['suspend_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị đình chỉ hoạt động vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s'; $lang_module['suspend_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã hoạt động trở lại vào %2$s.<br />Trước đó tài khoản này đã bị đình chỉ hoạt động vì lý do: %3$s'; $lang_module['suspend_sendmail_title'] = 'Thông báo từ website %s'; $lang_module['delete_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %3$s'; $lang_module['delete_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s'; $lang_module['delete_sendmail_title'] = 'Thông báo từ website %s'; $lang_module['delete_sendmail_info'] = 'Bạn thực sự muốn xóa tài khoản quản trị &ldquo;<strong>%s</strong>&rdquo;? Hãy điền các thông tin vào các ô trống dưới đây để khẳng định thao tác này'; $lang_module['admin_del_sendmail'] = 'Gửi thông báo'; $lang_module['admin_del_reason'] = 'Lý do xóa'; $lang_module['allow_files_type'] = 'Các kiểu file được phép tải lên'; $lang_module['allow_modify_files'] = 'Được phép sửa, xóa files'; $lang_module['allow_create_subdirectories'] = 'Được phép tạo thư mục'; $lang_module['allow_modify_subdirectories'] = 'Được phép đổi tên, xóa thư mục'; $lang_module['admin_login_incorrect'] = 'Tài khoản &ldquo;<strong>%s</strong>&rdquo; đã có trong danh sách quản trị. Hãy sử dụng một tài khoản khác'; $lang_module['config'] = 'Cấu hình'; $lang_module['funcs'] = 'Chức năng'; $lang_module['checkall'] = 'Chọn tất cả'; $lang_module['uncheckall'] = 'Bỏ chọn tất cả'; $lang_module['ip_version'] = 'Loại IP'; $lang_module['adminip'] = 'Quản lý IP truy cập khu vực quản trị'; $lang_module['adminip_ip'] = 'Ip'; $lang_module['adminip_timeban'] = 'Thời gian bắt đầu'; $lang_module['adminip_timeendban'] = 'Thời gian kết thúc'; $lang_module['adminip_add'] = 'Thêm địa chỉ IP'; $lang_module['adminip_address'] = 'Địa chỉ'; $lang_module['adminip_begintime'] = 'Thời gian bắt đầu'; $lang_module['adminip_endtime'] = 'Thời gian kết thúc'; $lang_module['adminip_notice'] = 'Ghi chú'; $lang_module['save'] = 'Lưu thay đổi'; $lang_module['adminip_mask_select'] = 'Hãy chọn'; $lang_module['adminip_nolimit'] = 'Vô thời hạn'; $lang_module['adminip_del_success'] = 'Đã xóa thành công !'; $lang_module['adminip_delete_confirm'] = 'Bạn có chắc muốn xóa ip này ra khỏi danh sách?'; $lang_module['adminip_mask'] = 'Mask IP'; $lang_module['adminip_edit'] = 'Sửa địa chỉ IP'; $lang_module['adminip_delete'] = 'Xóa'; $lang_module['adminip_error_ip'] = 'Hãy nhập Ip được truy cập khu vực quản trị '; $lang_module['adminip_error_validip'] = 'Lỗi: Bạn cần nhập IP đúng chuẩn'; $lang_module['title_username'] = 'Quản lý tài khoản tường lửa khu vực admin'; $lang_module['admfirewall'] = 'Kiểm tra tường lửa cho khu vực admin'; $lang_module['block_admin_ip'] = 'Kiểm tra IP khi truy cập khu vực admin'; $lang_module['username_add'] = 'Thêm tài khoản'; $lang_module['username_edit'] = 'Sửa tài khoản'; $lang_module['nicknam_delete_confirm'] = 'Bạn có chắc muốn xóa tài khoản này ra khỏi danh sách?'; $lang_module['passwordsincorrect'] = 'Mật khẩu bạn nhập hai lần không giống nhau.'; $lang_module['nochangepass'] = 'Nếu không thay đổi mật khẩu bạn không nhập hai trường mật khẩu'; $lang_module['rule_user'] = 'Tài khoản chỉ dùng các ký tự a-zA-Z0-9_-'; $lang_module['rule_pass'] = 'Mật khẩu chỉ dùng các ký tự a-zA-Z0-9_-'; $lang_module['spadmin_add_admin'] = 'Cho phép người điều hành chung tạo và thay đổi quyền hạn người điều hành modules'; $lang_module['authors_detail_main'] = 'Hiển thị chi tiết các thông tin tài khoản của người quản trị'; $lang_module['admin_check_pass_time'] = 'Thời gian kiểm tra lại mật khẩu, nếu admin không sử dụng trình duyệt'; $lang_module['add_user'] = 'Chỉ định thành viên'; $lang_module['add_select'] = 'Chọn'; $lang_module['add_error_choose'] = 'Lỗi: Bạn chưa chọn thành viên được chỉ định làm quản trị'; $lang_module['add_error_exist'] = 'Lỗi: Thành viên này đã là quản trị'; $lang_module['add_error_notexist'] = 'Lỗi: Thành viên này không tồn tại'; $lang_module['add_error_diff'] = 'Xảy ra lỗi không xác định'; $lang_module['action_account'] = 'Tài khoản thành viên'; $lang_module['action_account_nochange'] = 'Giữ nguyên tài khoản thành viên'; $lang_module['action_account_suspend'] = 'Khóa tài khoản thành viên'; $lang_module['action_account_del'] = 'Xóa tài khoản thành viên'; $lang_module['module_admin'] = 'Phân quyền hệ thống'; $lang_module['users'] = 'Tài khoản'; $lang_module['number'] = 'STT'; $lang_module['module'] = 'Tên module'; $lang_module['custom_title'] = 'Tiêu đề'; $lang_module['main_module'] = 'Module trang chính'; $lang_module['themeadmin'] = 'Giao diện người quản trị'; $lang_module['theme_default'] = 'Mặc định theo cấu hình site'; $lang_module['2step_manager'] = 'Quản lý xác thực hai bước'; $lang_module['2step_code_off'] = 'Xác thực hai bước bằng ứng dụng đang tắt'; $lang_module['2step_code_on'] = 'Xác thực hai bước bằng ứng dụng đang bật'; $lang_module['2step_oauth'] = 'Xác thực hai bước bằng Oauth'; $lang_module['2step_oauth_gate'] = 'Cổng Oauth'; $lang_module['2step_oauth_email'] = 'Email sử dụng'; $lang_module['2step_oauth_empty'] = 'Chưa có tài khoản xác thực nào'; $lang_module['2step_add_google'] = 'Thêm tài khoản Google'; $lang_module['2step_add_facebook'] = 'Thêm tài khoản Facebook'; $lang_module['2step_delete_all'] = 'Gỡ tất cả'; $lang_module['2step_error_oauth_exists'] = 'Tài khoản này đã có trong danh sách xác thực'; $lang_module['2step_addtime'] = 'Thêm lúc';
NukeVietCMS/nukeviet
includes/language/vi/admin_authors.php
PHP
gpl-2.0
12,863
64.581395
238
0.687943
false
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #ifndef LMP_KSPACE_H #define LMP_KSPACE_H #include "pointers.h" // IWYU pragma: export #ifdef FFT_SINGLE typedef float FFT_SCALAR; #define MPI_FFT_SCALAR MPI_FLOAT #else typedef double FFT_SCALAR; #define MPI_FFT_SCALAR MPI_DOUBLE #endif namespace LAMMPS_NS { class KSpace : protected Pointers { friend class ThrOMP; friend class FixOMP; public: double energy; // accumulated energies double energy_1,energy_6; double virial[6]; // accumulated virial double *eatom,**vatom; // accumulated per-atom energy/virial double e2group; // accumulated group-group energy double f2group[3]; // accumulated group-group force int triclinic_support; // 1 if supports triclinic geometries int ewaldflag; // 1 if a Ewald solver int pppmflag; // 1 if a PPPM solver int msmflag; // 1 if a MSM solver int dispersionflag; // 1 if a LJ/dispersion solver int tip4pflag; // 1 if a TIP4P solver int dipoleflag; // 1 if a dipole solver int spinflag; // 1 if a spin solver int differentiation_flag; int neighrequest_flag; // used to avoid obsolete construction // of neighbor lists int mixflag; // 1 if geometric mixing rules are enforced // for LJ coefficients int slabflag; int scalar_pressure_flag; // 1 if using MSM fast scalar pressure double slab_volfactor; int warn_nonneutral; // 0 = error if non-neutral system // 1 = warn once if non-neutral system // 2 = warn, but already warned int warn_nocharge; // 0 = already warned // 1 = warn if zero charge int order,order_6,order_allocated; double accuracy; // accuracy of KSpace solver (force units) double accuracy_absolute; // user-specified accuracy in force units double accuracy_relative; // user-specified dimensionless accuracy // accurary = acc_rel * two_charge_force double accuracy_real_6; // real space accuracy for // dispersion solver (force units) double accuracy_kspace_6; // reciprocal space accuracy for // dispersion solver (force units) int auto_disp_flag; // use automatic parameter generation for pppm/disp double two_charge_force; // force in user units of two point // charges separated by 1 Angstrom double g_ewald,g_ewald_6; int nx_pppm,ny_pppm,nz_pppm; // global FFT grid for Coulombics int nx_pppm_6,ny_pppm_6,nz_pppm_6; // global FFT grid for dispersion int nx_msm_max,ny_msm_max,nz_msm_max; int group_group_enable; // 1 if style supports group/group calculation // KOKKOS host/device flag and data masks ExecutionSpace execution_space; unsigned int datamask_read,datamask_modify; int copymode; int compute_flag; // 0 if skip compute() int fftbench; // 0 if skip FFT timing int collective_flag; // 1 if use MPI collectives for FFT/remap int stagger_flag; // 1 if using staggered PPPM grids double splittol; // tolerance for when to truncate splitting KSpace(class LAMMPS *); virtual ~KSpace(); void two_charge(); void triclinic_check(); void modify_params(int, char **); void *extract(const char *); void compute_dummy(int, int); // triclinic void x2lamdaT(double *, double *); void lamda2xT(double *, double *); void lamda2xvector(double *, double *); void kspacebbox(double, double *); // public so can be called by commands that change charge void qsum_qsq(int warning_flag = 1); // general child-class methods virtual void settings(int, char **) {}; virtual void init() = 0; virtual void setup() = 0; virtual void setup_grid() {}; virtual void compute(int, int) = 0; virtual void compute_group_group(int, int, int) {}; virtual void pack_forward(int, FFT_SCALAR *, int, int *) {}; virtual void unpack_forward(int, FFT_SCALAR *, int, int *) {}; virtual void pack_reverse(int, FFT_SCALAR *, int, int *) {}; virtual void unpack_reverse(int, FFT_SCALAR *, int, int *) {}; virtual int timing(int, double &, double &) {return 0;} virtual int timing_1d(int, double &) {return 0;} virtual int timing_3d(int, double &) {return 0;} virtual int modify_param(int, char **) {return 0;} virtual double memory_usage() {return 0.0;} /* ---------------------------------------------------------------------- compute gamma for MSM and pair styles see Eq 4 from Parallel Computing 35 (2009) 164-177 ------------------------------------------------------------------------- */ double gamma(const double &rho) const { if (rho <= 1.0) { const int split_order = order/2; const double rho2 = rho*rho; double g = gcons[split_order][0]; double rho_n = rho2; for (int n = 1; n <= split_order; n++) { g += gcons[split_order][n]*rho_n; rho_n *= rho2; } return g; } else return (1.0/rho); } /* ---------------------------------------------------------------------- compute the derivative of gamma for MSM and pair styles see Eq 4 from Parallel Computing 35 (2009) 164-177 ------------------------------------------------------------------------- */ double dgamma(const double &rho) const { if (rho <= 1.0) { const int split_order = order/2; const double rho2 = rho*rho; double dg = dgcons[split_order][0]*rho; double rho_n = rho*rho2; for (int n = 1; n < split_order; n++) { dg += dgcons[split_order][n]*rho_n; rho_n *= rho2; } return dg; } else return (-1.0/rho/rho); } double **get_gcons() { return gcons; } double **get_dgcons() { return dgcons; } protected: int gridflag,gridflag_6; int gewaldflag,gewaldflag_6; int minorder,overlap_allowed; int adjust_cutoff_flag; int suffix_flag; // suffix compatibility flag bigint natoms_original; double scale,qqrd2e; double qsum,qsqsum,q2; double **gcons,**dgcons; // accumulated per-atom energy/virial int evflag,evflag_atom; int eflag_either,eflag_global,eflag_atom; int vflag_either,vflag_global,vflag_atom; int maxeatom,maxvatom; int kewaldflag; // 1 if kspace range set for Ewald sum int kx_ewald,ky_ewald,kz_ewald; // kspace settings for Ewald sum void pair_check(); void ev_init(int eflag, int vflag, int alloc = 1) { if (eflag||vflag) ev_setup(eflag, vflag, alloc); else evflag = eflag_either = eflag_global = eflag_atom = vflag_either = vflag_global = vflag_atom = 0; } void ev_setup(int, int, int alloc = 1); double estimate_table_accuracy(double, double); }; } #endif /* ERROR/WARNING messages: E: KSpace style does not yet support triclinic geometries The specified kspace style does not allow for non-orthogonal simulation boxes. E: KSpace solver requires a pair style No pair style is defined. E: KSpace style is incompatible with Pair style Setting a kspace style requires that a pair style with matching long-range Coulombic or dispersion components be used. W: Using kspace solver on system with no charge Self-explanatory. E: System is not charge neutral, net charge = %g The total charge on all atoms on the system is not 0.0. For some KSpace solvers this is an error. W: System is not charge neutral, net charge = %g The total charge on all atoms on the system is not 0.0. For some KSpace solvers this is only a warning. W: For better accuracy use 'pair_modify table 0' The user-specified force accuracy cannot be achieved unless the table feature is disabled by using 'pair_modify table 0'. E: Illegal ... command Self-explanatory. Check the input script syntax and compare to the documentation for the command. You can use -echo screen as a command-line option when running LAMMPS to see the offending line. E: Bad kspace_modify slab parameter Kspace_modify value for the slab/volume keyword must be >= 2.0. E: Kspace_modify mesh parameter must be all zero or all positive Valid kspace mesh parameters are >0. The code will try to auto-detect suitable values when all three mesh sizes are set to zero (the default). E: Kspace_modify mesh/disp parameter must be all zero or all positive Valid kspace mesh/disp parameters are >0. The code will try to auto-detect suitable values when all three mesh sizes are set to zero [and] the required accuracy via {force/disp/real} as well as {force/disp/kspace} is set. W: Kspace_modify slab param < 2.0 may cause unphysical behavior The kspace_modify slab parameter should be larger to insure periodic grids padded with empty space do not overlap. E: Bad kspace_modify kmax/ewald parameter Kspace_modify values for the kmax/ewald keyword must be integers > 0 E: Kspace_modify eigtol must be smaller than one Self-explanatory. */
pdebuyl/lammps
src/kspace.h
C
gpl-2.0
9,875
34.142349
106
0.624608
false
// Copyright 2013 Dolphin Emulator Project // Licensed under GPLv2 // Refer to the license.txt file included. #include <cstddef> #include <string> #include <vector> #include <wx/chartype.h> #include <wx/defs.h> #include <wx/dynarray.h> #include <wx/event.h> #include <wx/frame.h> #include <wx/gdicmn.h> #include <wx/list.h> #include <wx/menu.h> #include <wx/menuitem.h> #include <wx/msgdlg.h> #include <wx/object.h> #include <wx/panel.h> #include <wx/rtti.h> #include <wx/sizer.h> #include <wx/statusbr.h> #include <wx/string.h> #include <wx/textdlg.h> #include <wx/toplevel.h> #include <wx/translation.h> #include <wx/window.h> #include <wx/windowid.h> #include <wx/aui/auibar.h> #include <wx/aui/auibook.h> #include <wx/aui/framemanager.h> #include "Common/CommonTypes.h" #include "Common/FileUtil.h" #include "Common/IniFile.h" #include "Common/MathUtil.h" #include "Common/StringUtil.h" #include "Common/Logging/ConsoleListener.h" #include "Core/ConfigManager.h" #include "DolphinWX/Frame.h" #include "DolphinWX/Globals.h" #include "DolphinWX/LogConfigWindow.h" #include "DolphinWX/LogWindow.h" #include "DolphinWX/WxUtils.h" #include "DolphinWX/Debugger/CodeWindow.h" // ------------ // Aui events void CFrame::OnManagerResize(wxAuiManagerEvent& event) { if (!g_pCodeWindow && m_LogWindow && m_Mgr->GetPane("Pane 1").IsShown() && !m_Mgr->GetPane("Pane 1").IsFloating()) { m_LogWindow->x = m_Mgr->GetPane("Pane 1").rect.GetWidth(); m_LogWindow->y = m_Mgr->GetPane("Pane 1").rect.GetHeight(); m_LogWindow->winpos = m_Mgr->GetPane("Pane 1").dock_direction; } event.Skip(); } void CFrame::OnPaneClose(wxAuiManagerEvent& event) { event.Veto(); wxAuiNotebook * nb = (wxAuiNotebook*)event.pane->window; if (!nb) return; if (!g_pCodeWindow) { if (nb->GetPage(0)->GetId() == IDM_LOGWINDOW || nb->GetPage(0)->GetId() == IDM_LOGCONFIGWINDOW) { SConfig::GetInstance().m_InterfaceLogWindow = false; SConfig::GetInstance().m_InterfaceLogConfigWindow = false; ToggleLogWindow(false); ToggleLogConfigWindow(false); } } else { if (GetNotebookCount() == 1) { wxMessageBox(_("At least one pane must remain open."), _("Notice"), wxOK, this); } else if (nb->GetPageCount() != 0 && !nb->GetPageText(0).IsSameAs("<>")) { wxMessageBox(_("You can't close panes that have pages in them."), _("Notice"), wxOK, this); } else { // Detach and delete the empty notebook event.pane->DestroyOnClose(true); m_Mgr->ClosePane(*event.pane); } } m_Mgr->Update(); } void CFrame::ToggleLogWindow(bool bShow) { if (!m_LogWindow) return; GetMenuBar()->FindItem(IDM_LOGWINDOW)->Check(bShow); if (bShow) { // Create a new log window if it doesn't exist. if (!m_LogWindow) { m_LogWindow = new CLogWindow(this, IDM_LOGWINDOW); } m_LogWindow->Enable(); DoAddPage(m_LogWindow, g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[0] : 0, g_pCodeWindow ? bFloatWindow[0] : false); } else { // Hiding the log window, so disable it and remove it. m_LogWindow->Disable(); DoRemovePage(m_LogWindow, true); } // Hide or Show the pane if (!g_pCodeWindow) TogglePane(); } void CFrame::ToggleLogConfigWindow(bool bShow) { GetMenuBar()->FindItem(IDM_LOGCONFIGWINDOW)->Check(bShow); if (bShow) { if (!m_LogConfigWindow) m_LogConfigWindow = new LogConfigWindow(this, m_LogWindow, IDM_LOGCONFIGWINDOW); const int nbIndex = IDM_LOGCONFIGWINDOW - IDM_LOGWINDOW; DoAddPage(m_LogConfigWindow, g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[nbIndex] : 0, g_pCodeWindow ? bFloatWindow[nbIndex] : false); } else { DoRemovePage(m_LogConfigWindow, false); m_LogConfigWindow = nullptr; } // Hide or Show the pane if (!g_pCodeWindow) TogglePane(); } void CFrame::OnToggleWindow(wxCommandEvent& event) { bool bShow = GetMenuBar()->IsChecked(event.GetId()); switch (event.GetId()) { case IDM_LOGWINDOW: if (!g_pCodeWindow) SConfig::GetInstance().m_InterfaceLogWindow = bShow; ToggleLogWindow(bShow); break; case IDM_LOGCONFIGWINDOW: if (!g_pCodeWindow) SConfig::GetInstance().m_InterfaceLogConfigWindow = bShow; ToggleLogConfigWindow(bShow); break; case IDM_REGISTERWINDOW: g_pCodeWindow->ToggleRegisterWindow(bShow); break; case IDM_WATCHWINDOW: g_pCodeWindow->ToggleWatchWindow(bShow); break; case IDM_BREAKPOINTWINDOW: g_pCodeWindow->ToggleBreakPointWindow(bShow); break; case IDM_MEMORYWINDOW: g_pCodeWindow->ToggleMemoryWindow(bShow); break; case IDM_JITWINDOW: g_pCodeWindow->ToggleJitWindow(bShow); break; case IDM_SOUNDWINDOW: g_pCodeWindow->ToggleSoundWindow(bShow); break; case IDM_VIDEOWINDOW: g_pCodeWindow->ToggleVideoWindow(bShow); break; } } // Notebooks // --------------------- void CFrame::ClosePages() { ToggleLogWindow(false); ToggleLogConfigWindow(false); if (g_pCodeWindow) { g_pCodeWindow->ToggleCodeWindow(false); g_pCodeWindow->ToggleRegisterWindow(false); g_pCodeWindow->ToggleWatchWindow(false); g_pCodeWindow->ToggleBreakPointWindow(false); g_pCodeWindow->ToggleMemoryWindow(false); g_pCodeWindow->ToggleJitWindow(false); g_pCodeWindow->ToggleSoundWindow(false); g_pCodeWindow->ToggleVideoWindow(false); } } void CFrame::OnNotebookPageChanged(wxAuiNotebookEvent& event) { event.Skip(); if (!g_pCodeWindow) return; // Remove the blank page if any AddRemoveBlankPage(); // Update the notebook affiliation for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++) { if (GetNotebookAffiliation(i) >= 0) g_pCodeWindow->iNbAffiliation[i - IDM_LOGWINDOW] = GetNotebookAffiliation(i); } } void CFrame::OnNotebookPageClose(wxAuiNotebookEvent& event) { // Override event event.Veto(); wxAuiNotebook* Ctrl = (wxAuiNotebook*)event.GetEventObject(); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGWINDOW) ToggleLogWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGCONFIGWINDOW) ToggleLogConfigWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_REGISTERWINDOW) g_pCodeWindow->ToggleRegisterWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_WATCHWINDOW) g_pCodeWindow->ToggleWatchWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_BREAKPOINTWINDOW) g_pCodeWindow->ToggleBreakPointWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_JITWINDOW) g_pCodeWindow->ToggleJitWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_MEMORYWINDOW) g_pCodeWindow->ToggleMemoryWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_SOUNDWINDOW) g_pCodeWindow->ToggleSoundWindow(false); if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_VIDEOWINDOW) g_pCodeWindow->ToggleVideoWindow(false); } void CFrame::OnFloatingPageClosed(wxCloseEvent& event) { ToggleFloatWindow(event.GetId() - IDM_LOGWINDOW_PARENT + IDM_FLOAT_LOGWINDOW); } void CFrame::OnFloatingPageSize(wxSizeEvent& event) { event.Skip(); } void CFrame::OnFloatWindow(wxCommandEvent& event) { ToggleFloatWindow(event.GetId()); } void CFrame::ToggleFloatWindow(int Id) { wxWindowID WinId = Id - IDM_FLOAT_LOGWINDOW + IDM_LOGWINDOW; if (GetNotebookPageFromId(WinId)) { DoFloatNotebookPage(WinId); bFloatWindow[WinId - IDM_LOGWINDOW] = true; } else { if (FindWindowById(WinId)) DoUnfloatPage(WinId - IDM_LOGWINDOW + IDM_LOGWINDOW_PARENT); bFloatWindow[WinId - IDM_LOGWINDOW] = false; } } void CFrame::DoFloatNotebookPage(wxWindowID Id) { wxPanel *Win = (wxPanel*)FindWindowById(Id); if (!Win) return; for (int i = 0; i < GetNotebookCount(); i++) { wxAuiNotebook *nb = GetNotebookFromId(i); if (nb->GetPageIndex(Win) != wxNOT_FOUND) { nb->RemovePage(nb->GetPageIndex(Win)); // Create the parent frame and reparent the window CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW, Win->GetName(), Win); if (nb->GetPageCount() == 0) AddRemoveBlankPage(); } } } void CFrame::DoUnfloatPage(int Id) { wxFrame * Win = (wxFrame*)FindWindowById(Id); if (!Win) return; wxWindow * Child = Win->GetChildren().Item(0)->GetData(); Child->Reparent(this); DoAddPage(Child, g_pCodeWindow->iNbAffiliation[Child->GetId() - IDM_LOGWINDOW], false); Win->Destroy(); } void CFrame::OnTab(wxAuiNotebookEvent& event) { event.Skip(); if (!g_pCodeWindow) return; // Create the popup menu wxMenu* MenuPopup = new wxMenu; wxMenuItem* Item = new wxMenuItem(MenuPopup, wxID_ANY, _("Select floating windows")); MenuPopup->Append(Item); Item->Enable(false); MenuPopup->Append(new wxMenuItem(MenuPopup)); for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++) { wxWindow *Win = FindWindowById(i); if (Win && Win->IsEnabled()) { Item = new wxMenuItem(MenuPopup, i + IDM_FLOAT_LOGWINDOW - IDM_LOGWINDOW, Win->GetName(), "", wxITEM_CHECK); MenuPopup->Append(Item); Item->Check(!!FindWindowById(i + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW)); } } // Line up our menu with the cursor wxPoint Pt = ::wxGetMousePosition(); Pt = ScreenToClient(Pt); // Show PopupMenu(MenuPopup, Pt); } void CFrame::OnAllowNotebookDnD(wxAuiNotebookEvent& event) { event.Skip(); event.Allow(); } void CFrame::ShowResizePane() { if (!m_LogWindow) return; // Make sure the size is sane if (m_LogWindow->x > GetClientRect().GetWidth()) m_LogWindow->x = GetClientRect().GetWidth() / 2; if (m_LogWindow->y > GetClientRect().GetHeight()) m_LogWindow->y = GetClientRect().GetHeight() / 2; wxAuiPaneInfo &pane = m_Mgr->GetPane("Pane 1"); // Hide first otherwise a resize doesn't work pane.Hide(); m_Mgr->Update(); pane.BestSize(m_LogWindow->x, m_LogWindow->y) .MinSize(m_LogWindow->x, m_LogWindow->y) .Direction(m_LogWindow->winpos).Show(); m_Mgr->Update(); // Reset the minimum size of the pane pane.MinSize(-1, -1); m_Mgr->Update(); } void CFrame::TogglePane() { // Get the first notebook wxAuiNotebook * NB = nullptr; for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window; } if (NB) { if (NB->GetPageCount() == 0) { m_Mgr->GetPane("Pane 1").Hide(); m_Mgr->Update(); } else { ShowResizePane(); } } } void CFrame::DoRemovePage(wxWindow *Win, bool bHide) { if (!Win) return; wxWindow *Parent = FindWindowById(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW); if (Parent) { if (bHide) { Win->Hide(); Win->Reparent(this); } else { Win->Destroy(); } Parent->Destroy(); } else { for (int i = 0; i < GetNotebookCount(); i++) { int PageIndex = GetNotebookFromId(i)->GetPageIndex(Win); if (PageIndex != wxNOT_FOUND) { GetNotebookFromId(i)->RemovePage(PageIndex); if (bHide) { Win->Hide(); Win->Reparent(this); } else { Win->Destroy(); } } } } if (g_pCodeWindow) AddRemoveBlankPage(); } void CFrame::DoAddPage(wxWindow *Win, int i, bool Float) { if (!Win) return; // Ensure accessor remains within valid bounds. if (i < 0 || i > GetNotebookCount()-1) i = 0; // The page was already previously added, no need to add it again. if (Win && GetNotebookFromId(i)->GetPageIndex(Win) != wxNOT_FOUND) return; if (!Float) GetNotebookFromId(i)->AddPage(Win, Win->GetName(), true); else CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW, Win->GetName(), Win); } void CFrame::PopulateSavedPerspectives() { // If the perspective submenu hasn't been created yet, return if (!m_SavedPerspectives) return; // Delete all saved perspective menu items while (m_SavedPerspectives->GetMenuItemCount() != 0) { // Delete the first menu item in the list (while there are menu items) m_SavedPerspectives->Delete(m_SavedPerspectives->FindItemByPosition(0)); } if (Perspectives.size() > 0) { for (u32 i = 0; i < Perspectives.size(); i++) { wxMenuItem* mItem = new wxMenuItem(m_SavedPerspectives, IDM_PERSPECTIVES_0 + i, StrToWxStr(Perspectives[i].Name), "", wxITEM_CHECK); m_SavedPerspectives->Append(mItem); if (i == ActivePerspective) { mItem->Check(true); } } } } void CFrame::OnPerspectiveMenu(wxCommandEvent& event) { ClearStatusBar(); switch (event.GetId()) { case IDM_SAVE_PERSPECTIVE: if (Perspectives.size() == 0) { wxMessageBox(_("Please create a perspective before saving"), _("Notice"), wxOK, this); return; } SaveIniPerspectives(); GetStatusBar()->SetStatusText(StrToWxStr(std::string ("Saved " + Perspectives[ActivePerspective].Name)), 0); break; case IDM_PERSPECTIVES_ADD_PANE: AddPane(); break; case IDM_EDIT_PERSPECTIVES: m_bEdit = event.IsChecked(); TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES); break; case IDM_ADD_PERSPECTIVE: { wxTextEntryDialog dlg(this, _("Enter a name for the new perspective:"), _("Create new perspective")); wxString DefaultValue = wxString::Format(_("Perspective %d"), (int)(Perspectives.size() + 1)); dlg.SetValue(DefaultValue); int Return = 0; bool DlgOk = false; while (!DlgOk) { Return = dlg.ShowModal(); if (Return == wxID_CANCEL) { return; } else if (dlg.GetValue().Find(",") != -1) { wxMessageBox(_("The name cannot contain the character ','"), _("Notice"), wxOK, this); wxString Str = dlg.GetValue(); Str.Replace(",", "", true); dlg.SetValue(Str); } else if (dlg.GetValue().IsSameAs("")) { wxMessageBox(_("The name cannot be empty"), _("Notice"), wxOK, this); dlg.SetValue(DefaultValue); } else { DlgOk = true; } } SPerspectives Tmp; Tmp.Name = WxStrToStr(dlg.GetValue()); Tmp.Perspective = m_Mgr->SavePerspective(); ActivePerspective = (u32)Perspectives.size(); Perspectives.push_back(Tmp); UpdateCurrentPerspective(); PopulateSavedPerspectives(); } break; case IDM_TAB_SPLIT: m_bTabSplit = event.IsChecked(); ToggleNotebookStyle(m_bTabSplit, wxAUI_NB_TAB_SPLIT); break; case IDM_NO_DOCKING: m_bNoDocking = event.IsChecked(); TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING); break; } } void CFrame::TogglePaneStyle(bool On, int EventId) { wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes(); for (u32 i = 0; i < AllPanes.GetCount(); ++i) { wxAuiPaneInfo& Pane = AllPanes[i]; if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook))) { // Default Pane.CloseButton(true); Pane.MaximizeButton(true); Pane.MinimizeButton(true); Pane.PinButton(true); Pane.Show(); switch (EventId) { case IDM_EDIT_PERSPECTIVES: Pane.CaptionVisible(On); Pane.Movable(On); Pane.Floatable(On); Pane.Dockable(On); break; } Pane.Dockable(!m_bNoDocking); } } m_Mgr->Update(); } void CFrame::ToggleNotebookStyle(bool On, long Style) { wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes(); for (int i = 0, Count = (int)AllPanes.GetCount(); i < Count; ++i) { wxAuiPaneInfo& Pane = AllPanes[i]; if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook))) { wxAuiNotebook* NB = (wxAuiNotebook*)Pane.window; if (On) NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() | Style); else NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() &~ Style); NB->Refresh(); } } } void CFrame::OnSelectPerspective(wxCommandEvent& event) { u32 _Selection = event.GetId() - IDM_PERSPECTIVES_0; if (Perspectives.size() <= _Selection) _Selection = 0; ActivePerspective = _Selection; DoLoadPerspective(); } void CFrame::SetPaneSize() { if (Perspectives.size() <= ActivePerspective) return; int iClientX = GetSize().GetX(); int iClientY = GetSize().GetY(); for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar))) { if (!m_Mgr->GetAllPanes()[i].IsOk()) return; if (Perspectives[ActivePerspective].Width.size() <= j || Perspectives[ActivePerspective].Height.size() <= j) continue; // Width and height of the active perspective u32 W = Perspectives[ActivePerspective].Width[j], H = Perspectives[ActivePerspective].Height[j]; // Check limits MathUtil::Clamp<u32>(&W, 5, 95); MathUtil::Clamp<u32>(&H, 5, 95); // Convert percentages to pixel lengths W = (W * iClientX) / 100; H = (H * iClientY) / 100; m_Mgr->GetAllPanes()[i].BestSize(W,H).MinSize(W,H); j++; } } m_Mgr->Update(); for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar))) { m_Mgr->GetAllPanes()[i].MinSize(-1,-1); } } } void CFrame::ReloadPanes() { // Close all pages ClosePages(); CloseAllNotebooks(); // Create new panes with notebooks for (u32 i = 0; i < Perspectives[ActivePerspective].Width.size() - 1; i++) { wxString PaneName = wxString::Format("Pane %i", i + 1); m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo().Hide() .CaptionVisible(m_bEdit).Dockable(!m_bNoDocking).Position(i) .Name(PaneName).Caption(PaneName)); } // Perspectives m_Mgr->LoadPerspective(Perspectives[ActivePerspective].Perspective, false); // Restore settings TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING); TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES); // Load GUI settings g_pCodeWindow->Load(); // Open notebook pages AddRemoveBlankPage(); g_pCodeWindow->OpenPages(); // Repopulate perspectives PopulateSavedPerspectives(); } void CFrame::DoLoadPerspective() { ReloadPanes(); // Restore the exact window sizes, which LoadPerspective doesn't always do SetPaneSize(); m_Mgr->Update(); } // Update the local perspectives array void CFrame::LoadIniPerspectives() { Perspectives.clear(); std::vector<std::string> VPerspectives; std::string _Perspectives; IniFile ini; ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX)); IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives"); perspectives->Get("Perspectives", &_Perspectives, "Perspective 1"); perspectives->Get("Active", &ActivePerspective, 0); SplitString(_Perspectives, ',', VPerspectives); for (auto& VPerspective : VPerspectives) { SPerspectives Tmp; std::string _Section, _Perspective, _Widths, _Heights; std::vector<std::string> _SWidth, _SHeight; Tmp.Name = VPerspective; // Don't save a blank perspective if (Tmp.Name.empty()) { continue; } _Section = StringFromFormat("P - %s", Tmp.Name.c_str()); IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section); perspec_section->Get("Perspective", &_Perspective, "layout2|" "name=Pane 0;caption=Pane 0;state=768;dir=5;prop=100000;|" "name=Pane 1;caption=Pane 1;state=31458108;dir=4;prop=100000;|" "dock_size(5,0,0)=22|dock_size(4,0,0)=333|"); perspec_section->Get("Width", &_Widths, "70,25"); perspec_section->Get("Height", &_Heights, "80,80"); Tmp.Perspective = StrToWxStr(_Perspective); SplitString(_Widths, ',', _SWidth); SplitString(_Heights, ',', _SHeight); for (auto& Width : _SWidth) { int _Tmp; if (TryParse(Width, &_Tmp)) Tmp.Width.push_back(_Tmp); } for (auto& Height : _SHeight) { int _Tmp; if (TryParse(Height, &_Tmp)) Tmp.Height.push_back(_Tmp); } Perspectives.push_back(Tmp); } } void CFrame::UpdateCurrentPerspective() { SPerspectives *current = &Perspectives[ActivePerspective]; current->Perspective = m_Mgr->SavePerspective(); // Get client size int iClientX = GetSize().GetX(), iClientY = GetSize().GetY(); current->Width.clear(); current->Height.clear(); for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window-> IsKindOf(CLASSINFO(wxAuiToolBar))) { // Save width and height as a percentage of the client width and height current->Width.push_back( (m_Mgr->GetAllPanes()[i].window->GetClientSize().GetX() * 100) / iClientX); current->Height.push_back( (m_Mgr->GetAllPanes()[i].window->GetClientSize().GetY() * 100) / iClientY); } } } void CFrame::SaveIniPerspectives() { if (Perspectives.size() == 0) return; if (ActivePerspective >= Perspectives.size()) ActivePerspective = 0; // Turn off edit before saving TogglePaneStyle(false, IDM_EDIT_PERSPECTIVES); UpdateCurrentPerspective(); IniFile ini; ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX)); // Save perspective names std::string STmp = ""; for (auto& Perspective : Perspectives) { STmp += Perspective.Name + ","; } STmp = STmp.substr(0, STmp.length()-1); IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives"); perspectives->Set("Perspectives", STmp); perspectives->Set("Active", ActivePerspective); // Save the perspectives for (auto& Perspective : Perspectives) { std::string _Section = "P - " + Perspective.Name; IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section); perspec_section->Set("Perspective", WxStrToStr(Perspective.Perspective)); std::string SWidth = "", SHeight = ""; for (u32 j = 0; j < Perspective.Width.size(); j++) { SWidth += StringFromFormat("%i,", Perspective.Width[j]); SHeight += StringFromFormat("%i,", Perspective.Height[j]); } // Remove the ending "," SWidth = SWidth.substr(0, SWidth.length()-1); SHeight = SHeight.substr(0, SHeight.length()-1); perspec_section->Set("Width", SWidth); perspec_section->Set("Height", SHeight); } ini.Save(File::GetUserPath(F_DEBUGGERCONFIG_IDX)); // Save notebook affiliations g_pCodeWindow->Save(); TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES); } void CFrame::AddPane() { int PaneNum = GetNotebookCount() + 1; wxString PaneName = wxString::Format("Pane %i", PaneNum); m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo() .CaptionVisible(m_bEdit).Dockable(!m_bNoDocking) .Name(PaneName).Caption(PaneName) .Position(GetNotebookCount())); AddRemoveBlankPage(); m_Mgr->Update(); } wxWindow * CFrame::GetNotebookPageFromId(wxWindowID Id) { for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) continue; wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window; for (u32 j = 0; j < NB->GetPageCount(); j++) { if (NB->GetPage(j)->GetId() == Id) return NB->GetPage(j); } } return nullptr; } wxFrame* CFrame::CreateParentFrame(wxWindowID Id, const wxString& Title, wxWindow* Child) { wxFrame* Frame = new wxFrame(this, Id, Title); Child->Reparent(Frame); wxBoxSizer* m_MainSizer = new wxBoxSizer(wxHORIZONTAL); m_MainSizer->Add(Child, 1, wxEXPAND); Frame->Bind(wxEVT_CLOSE_WINDOW, &CFrame::OnFloatingPageClosed, this); // Main sizer Frame->SetSizer(m_MainSizer); // Minimum frame size Frame->SetMinSize(wxSize(200, 200)); Frame->Show(); return Frame; } wxAuiNotebook* CFrame::CreateEmptyNotebook() { const long NOTEBOOK_STYLE = wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT | wxAUI_NB_TAB_EXTERNAL_MOVE | wxAUI_NB_SCROLL_BUTTONS | wxAUI_NB_WINDOWLIST_BUTTON | wxNO_BORDER; wxAuiNotebook* NB = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, NOTEBOOK_STYLE); return NB; } void CFrame::AddRemoveBlankPage() { for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) continue; wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window; for (u32 j = 0; j < NB->GetPageCount(); j++) { if (NB->GetPageText(j).IsSameAs("<>") && NB->GetPageCount() > 1) NB->DeletePage(j); } if (NB->GetPageCount() == 0) NB->AddPage(new wxPanel(this, wxID_ANY), "<>", true); } } int CFrame::GetNotebookAffiliation(wxWindowID Id) { for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) continue; wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window; for (u32 k = 0; k < NB->GetPageCount(); k++) { if (NB->GetPage(k)->GetId() == Id) return j; } j++; } return -1; } // Close all panes with notebooks void CFrame::CloseAllNotebooks() { wxAuiPaneInfoArray AllPanes = m_Mgr->GetAllPanes(); for (u32 i = 0; i < AllPanes.GetCount(); i++) { if (AllPanes[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) { AllPanes[i].DestroyOnClose(true); m_Mgr->ClosePane(AllPanes[i]); } } } int CFrame::GetNotebookCount() { int Ret = 0; for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) Ret++; } return Ret; } wxAuiNotebook * CFrame::GetNotebookFromId(u32 NBId) { for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++) { if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook))) continue; if (j == NBId) return (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window; j++; } return nullptr; }
Asmodean-/dolphin
Source/Core/DolphinWX/FrameAui.cpp
C++
gpl-2.0
25,156
23.833169
98
0.671053
false
/***************************************************************************** * Free42 -- an HP-42S calculator simulator * Copyright (C) 2004-2016 Thomas Okken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see http://www.gnu.org/licenses/. *****************************************************************************/ #include <stdlib.h> #include "core_commands2.h" #include "core_commands3.h" #include "core_commands4.h" #include "core_display.h" #include "core_helpers.h" #include "core_linalg1.h" #include "core_sto_rcl.h" #include "core_variables.h" /********************************************************/ /* Implementations of HP-42S built-in functions, part 4 */ /********************************************************/ int docmd_insr(arg_struct *arg) { vartype *m, *newx; vartype_realmatrix *rm; vartype_complexmatrix *cm; int4 rows, columns, i; int err, refcount; int interactive; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX) return ERR_INVALID_TYPE; interactive = matedit_mode == 2 || matedit_mode == 3; if (interactive) { err = docmd_stoel(NULL); if (err != ERR_NONE) return err; } if (m->type == TYPE_REALMATRIX) { rm = (vartype_realmatrix *) m; rows = rm->rows; columns = rm->columns; refcount = rm->array->refcount; if (interactive) { newx = new_real(0); if (newx == NULL) return ERR_INSUFFICIENT_MEMORY; } } else { cm = (vartype_complexmatrix *) m; rows = cm->rows; columns = cm->columns; refcount = cm->array->refcount; if (interactive) { newx = new_complex(0, 0); if (newx == NULL) return ERR_INSUFFICIENT_MEMORY; } } if (matedit_i >= rows) matedit_i = rows - 1; if (matedit_j >= columns) matedit_j = columns - 1; if (refcount == 1) { /* We have this array to ourselves so we can modify it in place */ err = dimension_array_ref(m, rows + 1, columns); if (err != ERR_NONE) { if (interactive) free_vartype(newx); return err; } rows++; if (m->type == TYPE_REALMATRIX) { for (i = rows * columns - 1; i >= (matedit_i + 1) * columns; i--) { rm->array->is_string[i] = rm->array->is_string[i - columns]; rm->array->data[i] = rm->array->data[i - columns]; } for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) { rm->array->is_string[i] = 0; rm->array->data[i] = 0; } } else { for (i = 2 * rows * columns - 1; i >= 2 * (matedit_i + 1) * columns; i--) cm->array->data[i] = cm->array->data[i - 2 * columns]; for (i = 2 * matedit_i * columns; i < 2 * (matedit_i + 1) * columns; i++) cm->array->data[i] = 0; } } else { /* We're sharing this array. I don't use disentangle() because it * does not deal with resizing. */ int4 newsize = (rows + 1) * columns; if (m->type == TYPE_REALMATRIX) { realmatrix_data *array = (realmatrix_data *) malloc(sizeof(realmatrix_data)); if (array == NULL) { if (interactive) free_vartype(newx); return ERR_INSUFFICIENT_MEMORY; } array->data = (phloat *) malloc(newsize * sizeof(phloat)); if (array->data == NULL) { if (interactive) free_vartype(newx); free(array); return ERR_INSUFFICIENT_MEMORY; } array->is_string = (char *) malloc(newsize); if (array->is_string == NULL) { if (interactive) free_vartype(newx); free(array->data); free(array); return ERR_INSUFFICIENT_MEMORY; } for (i = 0; i < matedit_i * columns; i++) { array->is_string[i] = rm->array->is_string[i]; array->data[i] = rm->array->data[i]; } for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) { array->is_string[i] = 0; array->data[i] = 0; } for (i = (matedit_i + 1) * columns; i < newsize; i++) { array->is_string[i] = rm->array->is_string[i - columns]; array->data[i] = rm->array->data[i - columns]; } array->refcount = 1; rm->array->refcount--; rm->array = array; rm->rows++; } else { complexmatrix_data *array = (complexmatrix_data *) malloc(sizeof(complexmatrix_data)); if (array == NULL) { if (interactive) free_vartype(newx); return ERR_INSUFFICIENT_MEMORY; } array->data = (phloat *) malloc(2 * newsize * sizeof(phloat)); if (array->data == NULL) { if (interactive) free_vartype(newx); free(array); return ERR_INSUFFICIENT_MEMORY; } for (i = 0; i < 2 * matedit_i * columns; i++) array->data[i] = cm->array->data[i]; for (i = 2 * matedit_i * columns; i < 2 * (matedit_i + 1) * columns; i++) array->data[i] = 0; for (i = 2 * (matedit_i + 1) * columns; i < 2 * newsize; i++) array->data[i] = cm->array->data[i - 2 * columns]; array->refcount = 1; cm->array->refcount--; cm->array = array; cm->rows++; } } if (interactive) { free_vartype(reg_x); reg_x = newx; } mode_disable_stack_lift = true; return ERR_NONE; } static void invrt_completion(int error, vartype *res) { if (error == ERR_NONE) unary_result(res); } int docmd_invrt(arg_struct *arg) { if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX) return ERR_INVALID_TYPE; else if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else return linalg_inv(reg_x, invrt_completion); } int docmd_j_add(arg_struct *arg) { int4 rows, columns; int4 oldi = matedit_i; int4 oldj = matedit_j; int err = matedit_get_dim(&rows, &columns); if (err != ERR_NONE) return err; if (++matedit_j >= columns) { flags.f.matrix_edge_wrap = 1; matedit_j = 0; if (++matedit_i >= rows) { flags.f.matrix_end_wrap = 1; if (flags.f.grow) { if (matedit_mode == 2) err = dimension_array_ref(matedit_x, rows + 1, columns); else err = dimension_array(matedit_name, matedit_length, rows + 1, columns); if (err != ERR_NONE) { matedit_i = oldi; matedit_j = oldj; return err; } matedit_i = rows; } else matedit_i = 0; } else flags.f.matrix_end_wrap = 0; } else { flags.f.matrix_edge_wrap = 0; flags.f.matrix_end_wrap = 0; } return ERR_NONE; } int docmd_j_sub(arg_struct *arg) { int4 rows, columns; int err = matedit_get_dim(&rows, &columns); if (err != ERR_NONE) return err; if (--matedit_j < 0) { flags.f.matrix_edge_wrap = 1; matedit_j = columns - 1; if (--matedit_i < 0) { flags.f.matrix_end_wrap = 1; matedit_i = rows - 1; } else flags.f.matrix_end_wrap = 0; } else { flags.f.matrix_edge_wrap = 0; flags.f.matrix_end_wrap = 0; } return ERR_NONE; } static int mappable_ln_1_x(phloat x, phloat *y) { if (x <= -1) return ERR_INVALID_DATA; *y = log1p(x); return ERR_NONE; } int docmd_ln_1_x(arg_struct *arg) { if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_REALMATRIX) { vartype *v; int err = map_unary(reg_x, &v, mappable_ln_1_x, NULL); if (err == ERR_NONE) unary_result(v); return err; } else if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else return ERR_INVALID_TYPE; } int docmd_old(arg_struct *arg) { return docmd_rclel(NULL); } int docmd_posa(arg_struct *arg) { int pos = -1; vartype *v; if (reg_x->type == TYPE_REAL) { phloat x = ((vartype_real *) reg_x)->x; char c; int i; if (x < 0) x = -x; if (x >= 256) return ERR_INVALID_DATA; c = to_char(x); for (i = 0; i < reg_alpha_length; i++) if (reg_alpha[i] == c) { pos = i; break; } } else if (reg_x->type == TYPE_STRING) { vartype_string *s = (vartype_string *) reg_x; if (s->length != 0) { int i, j; for (i = 0; i < reg_alpha_length - s->length; i++) { for (j = 0; j < s->length; j++) if (reg_alpha[i + j] != s->text[j]) goto notfound; pos = i; break; notfound:; } } } else return ERR_INVALID_TYPE; v = new_real(pos); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; unary_result(v); return ERR_NONE; } int docmd_putm(arg_struct *arg) { vartype *m; int4 i, j; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX) /* Shouldn't happen, but could, as long as I don't * implement matrix locking */ return ERR_INVALID_TYPE; if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX) return ERR_INVALID_TYPE; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *src, *dst; if (reg_x->type == TYPE_COMPLEXMATRIX) return ERR_INVALID_TYPE; src = (vartype_realmatrix *) reg_x; dst = (vartype_realmatrix *) m; if (src->rows + matedit_i > dst->rows || src->columns + matedit_j > dst->columns) return ERR_DIMENSION_ERROR; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < src->rows; i++) for (j = 0; j < src->columns; j++) { int4 n1 = i * src->columns + j; int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j; dst->array->is_string[n2] = src->array->is_string[n1]; dst->array->data[n2] = src->array->data[n1]; } return ERR_NONE; } else if (reg_x->type == TYPE_REALMATRIX) { vartype_realmatrix *src = (vartype_realmatrix *) reg_x; vartype_complexmatrix *dst = (vartype_complexmatrix *) m; if (src->rows + matedit_i > dst->rows || src->columns + matedit_j > dst->columns) return ERR_DIMENSION_ERROR; for (i = 0; i < src->rows * src->columns; i++) if (src->array->is_string[i]) return ERR_ALPHA_DATA_IS_INVALID; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < src->rows; i++) for (j = 0; j < src->columns; j++) { int4 n1 = i * src->columns + j; int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j; dst->array->data[n2 * 2] = src->array->data[n1]; dst->array->data[n2 * 2 + 1] = 0; } return ERR_NONE; } else { vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x; vartype_complexmatrix *dst = (vartype_complexmatrix *) m; if (src->rows + matedit_i > dst->rows || src->columns + matedit_j > dst->columns) return ERR_DIMENSION_ERROR; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < src->rows; i++) for (j = 0; j < src->columns; j++) { int4 n1 = i * src->columns + j; int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j; dst->array->data[n2 * 2] = src->array->data[n1 * 2]; dst->array->data[n2 * 2 + 1] = src->array->data[n1 * 2 + 1]; } return ERR_NONE; } } int docmd_rclel(arg_struct *arg) { vartype *m, *v; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) m; int4 n = matedit_i * rm->columns + matedit_j; if (rm->array->is_string[n]) v = new_string(phloat_text(rm->array->data[n]), phloat_length(rm->array->data[n])); else v = new_real(rm->array->data[n]); } else if (m->type == TYPE_COMPLEXMATRIX) { vartype_complexmatrix *cm = (vartype_complexmatrix *) m; int4 n = matedit_i * cm->columns + matedit_j; v = new_complex(cm->array->data[2 * n], cm->array->data[2 * n + 1]); } else return ERR_INVALID_TYPE; if (v == NULL) return ERR_INSUFFICIENT_MEMORY; recall_result(v); return ERR_NONE; } int docmd_rclij(arg_struct *arg) { vartype *i, *j; if (matedit_mode == 0) return ERR_NONEXISTENT; i = new_real(matedit_i + 1); j = new_real(matedit_j + 1); if (i == NULL || j == NULL) { free_vartype(i); free_vartype(j); return ERR_INSUFFICIENT_MEMORY; } recall_two_results(j, i); return ERR_NONE; } int docmd_rnrm(arg_struct *arg) { if (reg_x->type == TYPE_REALMATRIX) { vartype *v; vartype_realmatrix *rm = (vartype_realmatrix *) reg_x; int4 size = rm->rows * rm->columns; int4 i, j; phloat max = 0; for (i = 0; i < size; i++) if (rm->array->is_string[i]) return ERR_ALPHA_DATA_IS_INVALID; for (i = 0; i < rm->rows; i++) { phloat nrm = 0; for (j = 0; j < rm->columns; j++) { phloat x = rm->array->data[i * rm->columns + j]; if (x >= 0) nrm += x; else nrm -= x; } if (p_isinf(nrm)) { if (flags.f.range_error_ignore) max = POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; break; } if (nrm > max) max = nrm; } v = new_real(max); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; unary_result(v); return ERR_NONE; } else if (reg_x->type == TYPE_COMPLEXMATRIX) { vartype *v; vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x; int4 i, j; phloat max = 0; for (i = 0; i < cm->rows; i++) { phloat nrm = 0; for (j = 0; j < cm->columns; j++) { phloat re = cm->array->data[2 * (i * cm->columns + j)]; phloat im = cm->array->data[2 * (i * cm->columns + j) + 1]; nrm += hypot(re, im); } if (p_isinf(nrm)) { if (flags.f.range_error_ignore) max = POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; break; } if (nrm > max) max = nrm; } v = new_real(max); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; unary_result(v); return ERR_NONE; } else if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else return ERR_INVALID_TYPE; } int docmd_rsum(arg_struct *arg) { if (reg_x->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) reg_x; vartype_realmatrix *res; int4 size = rm->rows * rm->columns; int4 i, j; for (i = 0; i < size; i++) if (rm->array->is_string[i]) return ERR_ALPHA_DATA_IS_INVALID; res = (vartype_realmatrix *) new_realmatrix(rm->rows, 1); if (res == NULL) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < rm->rows; i++) { phloat sum = 0; int inf; for (j = 0; j < rm->columns; j++) sum += rm->array->data[i * rm->columns + j]; if ((inf = p_isinf(sum)) != 0) { if (flags.f.range_error_ignore) sum = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else { free_vartype((vartype *) res); return ERR_OUT_OF_RANGE; } } res->array->data[i] = sum; } unary_result((vartype *) res); return ERR_NONE; } else if (reg_x->type == TYPE_COMPLEXMATRIX) { vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x; vartype_complexmatrix *res; int4 i, j; res = (vartype_complexmatrix *) new_complexmatrix(cm->rows, 1); if (res == NULL) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < cm->rows; i++) { phloat sum_re = 0, sum_im = 0; int inf; for (j = 0; j < cm->columns; j++) { sum_re += cm->array->data[2 * (i * cm->columns + j)]; sum_im += cm->array->data[2 * (i * cm->columns + j) + 1]; } if ((inf = p_isinf(sum_re)) != 0) { if (flags.f.range_error_ignore) sum_re = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else { free_vartype((vartype *) res); return ERR_OUT_OF_RANGE; } } if ((inf = p_isinf(sum_im)) != 0) { if (flags.f.range_error_ignore) sum_im = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else { free_vartype((vartype *) res); return ERR_OUT_OF_RANGE; } } res->array->data[2 * i] = sum_re; res->array->data[2 * i + 1] = sum_im; } unary_result((vartype *) res); return ERR_NONE; } else if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else return ERR_INVALID_TYPE; } int docmd_swap_r(arg_struct *arg) { vartype *m; phloat xx, yy; int4 x, y, i; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX) /* Should not happen, but could, as long as I don't implement * matrix locking. */ return ERR_INVALID_TYPE; if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_x->type != TYPE_REAL) return ERR_INVALID_TYPE; if (reg_y->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_y->type != TYPE_REAL) return ERR_INVALID_TYPE; xx = ((vartype_real *) reg_x)->x; if (xx <= -2147483648.0 || xx >= 2147483648.0) return ERR_DIMENSION_ERROR; x = to_int4(xx); if (x == 0) return ERR_DIMENSION_ERROR; if (x < 0) x = -x; x--; yy = ((vartype_real *) reg_y)->x; if (yy <= -2147483648.0 || yy >= 2147483648.0) return ERR_DIMENSION_ERROR; y = to_int4(yy); if (y == 0) return ERR_DIMENSION_ERROR; if (y < 0) y = -y; y--; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) m; if (x > rm->rows || y > rm->rows) return ERR_DIMENSION_ERROR; else if (x == y) return ERR_NONE; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < rm->columns; i++) { int4 n1 = x * rm->columns + i; int4 n2 = y * rm->columns + i; char tempc = rm->array->is_string[n1]; phloat tempds = rm->array->data[n1]; rm->array->is_string[n1] = rm->array->is_string[n2]; rm->array->data[n1] = rm->array->data[n2]; rm->array->is_string[n2] = tempc; rm->array->data[n2] = tempds; } return ERR_NONE; } else /* m->type == TYPE_COMPLEXMATRIX */ { vartype_complexmatrix *cm = (vartype_complexmatrix *) m; if (x > cm->rows || y > cm->rows) return ERR_DIMENSION_ERROR; else if (x == y) return ERR_NONE; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < 2 * cm->columns; i++) { int4 n1 = x * 2 * cm->columns + i; int4 n2 = y * 2 * cm->columns + i; phloat tempd = cm->array->data[n1]; cm->array->data[n1] = cm->array->data[n2]; cm->array->data[n2] = tempd; } return ERR_NONE; } } static int mappable_sinh_r(phloat x, phloat *y) { int inf; *y = sinh(x); if ((inf = p_isinf(*y)) != 0) { if (flags.f.range_error_ignore) *y = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } return ERR_NONE; } static int mappable_sinh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) { phloat sinhxre, coshxre; phloat sinxim, cosxim; int inf; sinhxre = sinh(xre); coshxre = cosh(xre); sincos(xim, &sinxim, &cosxim); *yre = sinhxre * cosxim; if ((inf = p_isinf(*yre)) != 0) { if (flags.f.range_error_ignore) *yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } *yim = coshxre * sinxim; if ((inf = p_isinf(*yim)) != 0) { if (flags.f.range_error_ignore) *yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } return ERR_NONE; } int docmd_sinh(arg_struct *arg) { if (reg_x->type != TYPE_STRING) { vartype *v; int err = map_unary(reg_x, &v, mappable_sinh_r, mappable_sinh_c); if (err == ERR_NONE) unary_result(v); return err; } else return ERR_ALPHA_DATA_IS_INVALID; } int docmd_stoel(arg_struct *arg) { vartype *m; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX) /* Should not happen, but could, as long as I don't implement * matrix locking. */ return ERR_INVALID_TYPE; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) m; int4 n = matedit_i * rm->columns + matedit_j; if (reg_x->type == TYPE_REAL) { rm->array->is_string[n] = 0; rm->array->data[n] = ((vartype_real *) reg_x)->x; return ERR_NONE; } else if (reg_x->type == TYPE_STRING) { vartype_string *s = (vartype_string *) reg_x; int i; rm->array->is_string[n] = 1; phloat_length(rm->array->data[n]) = s->length; for (i = 0; i < s->length; i++) phloat_text(rm->array->data[n])[i] = s->text[i]; return ERR_NONE; } else return ERR_INVALID_TYPE; } else /* m->type == TYPE_COMPLEXMATRIX */ { vartype_complexmatrix *cm = (vartype_complexmatrix *) m; int4 n = matedit_i * cm->columns + matedit_j; if (reg_x->type == TYPE_REAL) { cm->array->data[2 * n] = ((vartype_real *) reg_x)->x; cm->array->data[2 * n + 1] = 0; return ERR_NONE; } else if (reg_x->type == TYPE_COMPLEX) { vartype_complex *c = (vartype_complex *) reg_x; cm->array->data[2 * n] = c->re; cm->array->data[2 * n + 1] = c->im; return ERR_NONE; } else return ERR_INVALID_TYPE; } } int docmd_stoij(arg_struct *arg) { vartype *m; phloat x, y; int4 i, j; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_x->type != TYPE_REAL) return ERR_INVALID_TYPE; if (reg_y->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_y->type != TYPE_REAL) return ERR_INVALID_TYPE; x = ((vartype_real *) reg_x)->x; if (x <= -2147483648.0 || x >= 2147483648.0) return ERR_DIMENSION_ERROR; j = to_int4(x); if (j < 0) j = -j; y = ((vartype_real *) reg_y)->x; if (y <= -2147483648.0 || y >= 2147483648.0) return ERR_DIMENSION_ERROR; i = to_int4(y); if (i < 0) i = -i; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) m; if (i == 0 || i > rm->rows || j == 0 || j > rm->columns) return ERR_DIMENSION_ERROR; } else if (m->type == TYPE_COMPLEXMATRIX) { vartype_complexmatrix *cm = (vartype_complexmatrix *) m; if (i == 0 || i > cm->rows || j == 0 || j > cm->columns) return ERR_DIMENSION_ERROR; } else /* Should not happen, but could, as long as I don't implement * matrix locking. */ return ERR_INVALID_TYPE; matedit_i = i - 1; matedit_j = j - 1; return ERR_NONE; } static int mappable_tanh_r(phloat x, phloat *y) { *y = tanh(x); return ERR_NONE; } static int mappable_tanh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) { phloat sinhxre, coshxre; phloat sinxim, cosxim; phloat re_sinh, re_cosh, im_sinh, im_cosh, abs_cosh; int inf; sinhxre = sinh(xre); coshxre = cosh(xre); sincos(xim, &sinxim, &cosxim); re_sinh = sinhxre * cosxim; im_sinh = coshxre * sinxim; re_cosh = coshxre * cosxim; im_cosh = sinhxre * sinxim; abs_cosh = hypot(re_cosh, im_cosh); if (abs_cosh == 0) { if (flags.f.range_error_ignore) { *yre = re_sinh * im_sinh + re_cosh * im_cosh > 0 ? POS_HUGE_PHLOAT : NEG_HUGE_PHLOAT; *yim = im_sinh * re_cosh - re_sinh * im_cosh > 0 ? POS_HUGE_PHLOAT : NEG_HUGE_PHLOAT; } else return ERR_OUT_OF_RANGE; } *yre = (re_sinh * re_cosh + im_sinh * im_cosh) / abs_cosh / abs_cosh; if ((inf = p_isinf(*yre)) != 0) { if (flags.f.range_error_ignore) *yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } *yim = (im_sinh * re_cosh - re_sinh * im_cosh) / abs_cosh / abs_cosh; if ((inf = p_isinf(*yim)) != 0) { if (flags.f.range_error_ignore) *yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } return ERR_NONE; } int docmd_tanh(arg_struct *arg) { if (reg_x->type != TYPE_STRING) { vartype *v; int err = map_unary(reg_x, &v, mappable_tanh_r, mappable_tanh_c); if (err == ERR_NONE) unary_result(v); return err; } else return ERR_ALPHA_DATA_IS_INVALID; } int docmd_trans(arg_struct *arg) { if (reg_x->type == TYPE_REALMATRIX) { vartype_realmatrix *src = (vartype_realmatrix *) reg_x; vartype_realmatrix *dst; int4 rows = src->rows; int4 columns = src->columns; int4 i, j; dst = (vartype_realmatrix *) new_realmatrix(columns, rows); if (dst == NULL) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) { int4 n1 = i * columns + j; int4 n2 = j * rows + i; dst->array->is_string[n2] = src->array->is_string[n1]; dst->array->data[n2] = src->array->data[n1]; } unary_result((vartype *) dst); return ERR_NONE; } else if (reg_x->type == TYPE_COMPLEXMATRIX) { vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x; vartype_complexmatrix *dst; int4 rows = src->rows; int4 columns = src->columns; int4 i, j; dst = (vartype_complexmatrix *) new_complexmatrix(columns, rows); if (dst == NULL) return ERR_INSUFFICIENT_MEMORY; for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) { int4 n1 = 2 * (i * columns + j); int4 n2 = 2 * (j * rows + i); dst->array->data[n2] = src->array->data[n1]; dst->array->data[n2 + 1] = src->array->data[n1 + 1]; } unary_result((vartype *) dst); return ERR_NONE; } else if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; else return ERR_INVALID_TYPE; } int docmd_wrap(arg_struct *arg) { flags.f.grow = 0; return ERR_NONE; } int docmd_x_swap(arg_struct *arg) { vartype *v; int err = generic_rcl(arg, &v); if (err != ERR_NONE) return err; err = generic_sto(arg, 0); if (err != ERR_NONE) free_vartype(v); else { free_vartype(reg_x); reg_x = v; if (flags.f.trace_print && flags.f.printer_exists) docmd_prx(NULL); } return err; } #define DIR_LEFT 0 #define DIR_RIGHT 1 #define DIR_UP 2 #define DIR_DOWN 3 static int matedit_move(int direction) { vartype *m, *v; vartype_realmatrix *rm; vartype_complexmatrix *cm; int4 rows, columns, new_i, new_j, old_n, new_n; int edge_flag = 0; int end_flag = 0; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type == TYPE_REALMATRIX) { rm = (vartype_realmatrix *) m; rows = rm->rows; columns = rm->columns; } else if (m->type == TYPE_COMPLEXMATRIX) { cm = (vartype_complexmatrix *) m; rows = cm->rows; columns = cm->columns; } else return ERR_INVALID_TYPE; if (!disentangle(m)) return ERR_INSUFFICIENT_MEMORY; new_i = matedit_i; new_j = matedit_j; switch (direction) { case DIR_LEFT: if (--new_j < 0) { edge_flag = 1; new_j = columns - 1; if (--new_i < 0) { end_flag = 1; new_i = rows - 1; } } break; case DIR_RIGHT: if (++new_j >= columns) { edge_flag = 1; new_j = 0; if (++new_i >= rows) { end_flag = 1; if (flags.f.grow) { int err; if (matedit_mode == 2) err = dimension_array_ref(matedit_x, rows + 1, columns); else err = dimension_array(matedit_name, matedit_length, rows + 1, columns); if (err != ERR_NONE) return err; new_i = rows++; } else new_i = 0; } } break; case DIR_UP: if (--new_i < 0) { edge_flag = 1; new_i = rows - 1; if (--new_j < 0) { end_flag = 1; new_j = columns - 1; } } break; case DIR_DOWN: if (++new_i >= rows) { edge_flag = 1; new_i = 0; if (++new_j >= columns) { end_flag = 1; new_j = 0; } } break; } old_n = matedit_i * columns + matedit_j; new_n = new_i * columns + new_j; if (m->type == TYPE_REALMATRIX) { if (old_n != new_n) { if (rm->array->is_string[new_n]) v = new_string(phloat_text(rm->array->data[new_n]), phloat_length(rm->array->data[new_n])); else v = new_real(rm->array->data[new_n]); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; } if (reg_x->type == TYPE_REAL) { rm->array->is_string[old_n] = 0; rm->array->data[old_n] = ((vartype_real *) reg_x)->x; } else if (reg_x->type == TYPE_STRING) { vartype_string *s = (vartype_string *) reg_x; int i; rm->array->is_string[old_n] = 1; phloat_length(rm->array->data[old_n]) = s->length; for (i = 0; i < s->length; i++) phloat_text(rm->array->data[old_n])[i] = s->text[i]; } else { free_vartype(v); return ERR_INVALID_TYPE; } } else /* m->type == TYPE_COMPLEXMATRIX */ { if (old_n != new_n) { v = new_complex(cm->array->data[2 * new_n], cm->array->data[2 * new_n + 1]); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; } if (reg_x->type == TYPE_REAL) { cm->array->data[2 * old_n] = ((vartype_real *) reg_x)->x; cm->array->data[2 * old_n + 1] = 0; } else if (reg_x->type == TYPE_COMPLEX) { vartype_complex *c = (vartype_complex *) reg_x; cm->array->data[2 * old_n] = c->re; cm->array->data[2 * old_n + 1] = c->im; } else { free_vartype(v); return ERR_INVALID_TYPE; } } matedit_i = new_i; matedit_j = new_j; flags.f.matrix_edge_wrap = edge_flag; flags.f.matrix_end_wrap = end_flag; if (old_n != new_n) { free_vartype(reg_x); reg_x = v; } mode_disable_stack_lift = true; if (flags.f.trace_print && flags.f.printer_enable) docmd_prx(NULL); return ERR_NONE; } int docmd_left(arg_struct *arg) { return matedit_move(DIR_LEFT); } int docmd_up(arg_struct *arg) { return matedit_move(DIR_UP); } int docmd_down(arg_struct *arg) { return matedit_move(DIR_DOWN); } int docmd_right(arg_struct *arg) { return matedit_move(DIR_RIGHT); } int docmd_percent_ch(arg_struct *arg) { phloat x, y, r; int inf; vartype *v; if (reg_x->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_x->type != TYPE_REAL) return ERR_INVALID_TYPE; if (reg_y->type == TYPE_STRING) return ERR_ALPHA_DATA_IS_INVALID; if (reg_y->type != TYPE_REAL) return ERR_INVALID_TYPE; x = ((vartype_real *) reg_x)->x; y = ((vartype_real *) reg_y)->x; if (y == 0) return ERR_DIVIDE_BY_0; r = (x - y) / y * 100; if ((inf = p_isinf(r)) != 0) { if (flags.f.range_error_ignore) r = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; else return ERR_OUT_OF_RANGE; } v = new_real(r); if (v == NULL) return ERR_INSUFFICIENT_MEMORY; /* Binary function, but unary result, like % */ unary_result(v); return ERR_NONE; } static vartype *matx_v; static void matx_completion(int error, vartype *res) { if (error != ERR_NONE) { free_vartype(matx_v); return; } store_var("MATX", 4, res); matedit_prev_appmenu = MENU_MATRIX_SIMQ; set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1); /* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX] * commands can only be invoked from the SIMQ menu; the SIMQ menu * has no exit callback, so leaving it never fails. */ set_appmenu_exitcallback(1); if (res->type == TYPE_REALMATRIX) { vartype_realmatrix *m = (vartype_realmatrix *) res; vartype_real *v = (vartype_real *) matx_v; v->x = m->array->data[0]; } else { vartype_complexmatrix *m = (vartype_complexmatrix *) res; vartype_complex *v = (vartype_complex *) matx_v; v->re = m->array->data[0]; v->im = m->array->data[1]; } free_vartype(reg_x); reg_x = matx_v; matedit_mode = 3; matedit_length = 4; matedit_name[0] = 'M'; matedit_name[1] = 'A'; matedit_name[2] = 'T'; matedit_name[3] = 'X'; matedit_i = 0; matedit_j = 0; } static int matabx(int which) { vartype *mat, *v; switch (which) { case 0: mat = recall_var("MATA", 4); break; case 1: mat = recall_var("MATB", 4); break; case 2: { vartype *mata, *matb; mata = recall_var("MATA", 4); if (mata == NULL) return ERR_NONEXISTENT; if (mata->type != TYPE_REALMATRIX && mata->type != TYPE_COMPLEXMATRIX) return ERR_INVALID_TYPE; matb = recall_var("MATB", 4); if (matb == NULL) return ERR_NONEXISTENT; if (matb->type != TYPE_REALMATRIX && matb->type != TYPE_COMPLEXMATRIX) return ERR_INVALID_TYPE; if (mata->type == TYPE_REALMATRIX && matb->type == TYPE_REALMATRIX) matx_v = new_real(0); else matx_v = new_complex(0, 0); if (matx_v == NULL) return ERR_INSUFFICIENT_MEMORY; return linalg_div(matb, mata, matx_completion); } } if (mat->type == TYPE_REALMATRIX) { vartype_realmatrix *rm = (vartype_realmatrix *) mat; if (rm->array->is_string[0]) v = new_string(phloat_text(rm->array->data[0]), phloat_length(rm->array->data[0])); else v = new_real(rm->array->data[0]); } else { vartype_complexmatrix *cm = (vartype_complexmatrix *) mat; v = new_complex(cm->array->data[0], cm->array->data[1]); } if (v == NULL) return ERR_INSUFFICIENT_MEMORY; matedit_prev_appmenu = MENU_MATRIX_SIMQ; set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1); /* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX] * commands can only be invoked from the SIMQ menu; the SIMQ menu * has no exit callback, so leaving it never fails. */ set_appmenu_exitcallback(1); free_vartype(reg_x); reg_x = v; matedit_mode = 3; matedit_length = 4; matedit_name[0] = 'M'; matedit_name[1] = 'A'; matedit_name[2] = 'T'; matedit_name[3] = which == 0 ? 'A' : 'B'; matedit_i = 0; matedit_j = 0; return ERR_NONE; } int docmd_mata(arg_struct *arg) { return matabx(0); } int docmd_matb(arg_struct *arg) { return matabx(1); } int docmd_matx(arg_struct *arg) { return matabx(2); } int docmd_simq(arg_struct *arg) { vartype *m, *mata, *matb, *matx; int4 dim; int err; if (arg->type != ARGTYPE_NUM) return ERR_INVALID_TYPE; dim = arg->val.num; if (dim <= 0) return ERR_DIMENSION_ERROR; m = recall_var("MATA", 4); if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) { mata = dup_vartype(m); if (mata == NULL) return ERR_INSUFFICIENT_MEMORY; err = dimension_array_ref(mata, dim, dim); if (err != ERR_NONE) goto abort_and_free_a; } else { mata = new_realmatrix(dim, dim); if (mata == NULL) return ERR_INSUFFICIENT_MEMORY; } m = recall_var("MATB", 4); if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) { matb = dup_vartype(m); if (matb == NULL) { err = ERR_INSUFFICIENT_MEMORY; goto abort_and_free_a; } err = dimension_array_ref(matb, dim, 1); if (err != ERR_NONE) goto abort_and_free_a_b; } else { matb = new_realmatrix(dim, 1); if (matb == NULL) { err = ERR_INSUFFICIENT_MEMORY; goto abort_and_free_a; } } m = recall_var("MATX", 4); if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) { matx = dup_vartype(m); if (matx == NULL) { err = ERR_INSUFFICIENT_MEMORY; goto abort_and_free_a_b; } err = dimension_array_ref(matx, dim, 1); if (err != ERR_NONE) goto abort_and_free_a_b_x; } else { matx = new_realmatrix(dim, 1); if (matx == NULL) { err = ERR_INSUFFICIENT_MEMORY; goto abort_and_free_a_b; } } err = set_menu_return_err(MENULEVEL_APP, MENU_MATRIX_SIMQ); if (err != ERR_NONE) { /* Didn't work; we're stuck in the matrix editor * waiting for the user to put something valid into X. * (Then again, how can anyone issue the SIMQ command if * they're in the matrix editor? SIMQ has the 'hidden' * command property. Oh, well, better safe than sorry...) */ abort_and_free_a_b_x: free_vartype(matx); abort_and_free_a_b: free_vartype(matb); abort_and_free_a: free_vartype(mata); return err; } store_var("MATX", 4, matx); store_var("MATB", 4, matb); store_var("MATA", 4, mata); return ERR_NONE; } static int max_min_helper(int do_max) { vartype *m; vartype_realmatrix *rm; phloat max_or_min_value = do_max ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT; int4 i, max_or_min_index = 0; vartype *new_x, *new_y; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type != TYPE_REALMATRIX) return ERR_INVALID_TYPE; rm = (vartype_realmatrix *) m; for (i = matedit_i; i < rm->rows; i++) { int4 index = i * rm->columns + matedit_j; phloat e; if (rm->array->is_string[index]) return ERR_ALPHA_DATA_IS_INVALID; e = rm->array->data[index]; if (do_max ? e >= max_or_min_value : e <= max_or_min_value) { max_or_min_value = e; max_or_min_index = i; } } new_x = new_real(max_or_min_value); if (new_x == NULL) return ERR_INSUFFICIENT_MEMORY; new_y = new_real(max_or_min_index + 1); if (new_y == NULL) { free_vartype(new_x); return ERR_INSUFFICIENT_MEMORY; } recall_two_results(new_x, new_y); return ERR_NONE; } int docmd_max(arg_struct *arg) { return max_min_helper(1); } int docmd_min(arg_struct *arg) { return max_min_helper(0); } int docmd_find(arg_struct *arg) { vartype *m; if (reg_x->type == TYPE_REALMATRIX || reg_x->type == TYPE_COMPLEXMATRIX) return ERR_INVALID_TYPE; switch (matedit_mode) { case 0: return ERR_NONEXISTENT; case 1: case 3: m = recall_var(matedit_name, matedit_length); break; case 2: m = matedit_x; break; default: return ERR_INTERNAL_ERROR; } if (m == NULL) return ERR_NONEXISTENT; if (m->type == TYPE_REALMATRIX) { vartype_realmatrix *rm; int4 i, j, p = 0; if (reg_x->type == TYPE_COMPLEX) return ERR_NO; rm = (vartype_realmatrix *) m; if (reg_x->type == TYPE_REAL) { phloat d = ((vartype_real *) reg_x)->x; for (i = 0; i < rm->rows; i++) for (j = 0; j < rm->columns; j++) if (!rm->array->is_string[p] && rm->array->data[p] == d) { matedit_i = i; matedit_j = j; return ERR_YES; } else p++; } else /* reg_x->type == TYPE_STRING */ { vartype_string *s = (vartype_string *) reg_x; for (i = 0; i < rm->rows; i++) for (j = 0; j < rm->columns; j++) if (rm->array->is_string[p] && string_equals(s->text, s->length, phloat_text(rm->array->data[p]), phloat_length(rm->array->data[p]))) { matedit_i = i; matedit_j = j; return ERR_YES; } else p++; } } else /* m->type == TYPE_COMPLEXMATRIX */ { vartype_complexmatrix *cm; int4 i, j, p = 0; phloat re, im; if (reg_x->type != TYPE_COMPLEX) return ERR_NO; cm = (vartype_complexmatrix *) m; re = ((vartype_complex *) reg_x)->re; im = ((vartype_complex *) reg_x)->im; for (i = 0; i < cm->rows; i++) for (j = 0; j < cm->columns; j++) if (cm->array->data[p] == re && cm->array->data[p + 1] == im) { matedit_i = i; matedit_j = j; return ERR_YES; } else p += 2; } return ERR_NO; } int docmd_xrom(arg_struct *arg) { return ERR_NONEXISTENT; }
axd1967/free42s
common/core_commands4.cc
C++
gpl-2.0
48,956
30.686731
85
0.477184
false
/* * mpc8610-pcm.h - ALSA PCM interface for the Freescale MPC8610 SoC * * 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. */ #ifndef _MPC8610_PCM_H #define _MPC8610_PCM_H struct ccsr_dma { u8 res0[0x100]; struct ccsr_dma_channel { __be32 mr; /* Mode register */ __be32 sr; /* Status register */ __be32 eclndar; /* Current link descriptor extended addr reg */ __be32 clndar; /* Current link descriptor address register */ __be32 satr; /* Source attributes register */ __be32 sar; /* Source address register */ __be32 datr; /* Destination attributes register */ __be32 dar; /* Destination address register */ __be32 bcr; /* Byte count register */ __be32 enlndar; /* Next link descriptor extended address reg */ __be32 nlndar; /* Next link descriptor address register */ u8 res1[4]; __be32 eclsdar; /* Current list descriptor extended addr reg */ __be32 clsdar; /* Current list descriptor address register */ __be32 enlsdar; /* Next list descriptor extended address reg */ __be32 nlsdar; /* Next list descriptor address register */ __be32 ssr; /* Source stride register */ __be32 dsr; /* Destination stride register */ u8 res2[0x38]; } channel[4]; __be32 dgsr; }; #define CCSR_DMA_MR_BWC_DISABLED 0x0F000000 #define CCSR_DMA_MR_BWC_SHIFT 24 #define CCSR_DMA_MR_BWC_MASK 0x0F000000 #define CCSR_DMA_MR_BWC(x) \ ((ilog2(x) << CCSR_DMA_MR_BWC_SHIFT) & CCSR_DMA_MR_BWC_MASK) #define CCSR_DMA_MR_EMP_EN 0x00200000 #define CCSR_DMA_MR_EMS_EN 0x00040000 #define CCSR_DMA_MR_DAHTS_MASK 0x00030000 #define CCSR_DMA_MR_DAHTS_1 0x00000000 #define CCSR_DMA_MR_DAHTS_2 0x00010000 #define CCSR_DMA_MR_DAHTS_4 0x00020000 #define CCSR_DMA_MR_DAHTS_8 0x00030000 #define CCSR_DMA_MR_SAHTS_MASK 0x0000C000 #define CCSR_DMA_MR_SAHTS_1 0x00000000 #define CCSR_DMA_MR_SAHTS_2 0x00004000 #define CCSR_DMA_MR_SAHTS_4 0x00008000 #define CCSR_DMA_MR_SAHTS_8 0x0000C000 #define CCSR_DMA_MR_DAHE 0x00002000 #define CCSR_DMA_MR_SAHE 0x00001000 #define CCSR_DMA_MR_SRW 0x00000400 #define CCSR_DMA_MR_EOSIE 0x00000200 #define CCSR_DMA_MR_EOLNIE 0x00000100 #define CCSR_DMA_MR_EOLSIE 0x00000080 #define CCSR_DMA_MR_EIE 0x00000040 #define CCSR_DMA_MR_XFE 0x00000020 #define CCSR_DMA_MR_CDSM_SWSM 0x00000010 #define CCSR_DMA_MR_CA 0x00000008 #define CCSR_DMA_MR_CTM 0x00000004 #define CCSR_DMA_MR_CC 0x00000002 #define CCSR_DMA_MR_CS 0x00000001 #define CCSR_DMA_SR_TE 0x00000080 #define CCSR_DMA_SR_CH 0x00000020 #define CCSR_DMA_SR_PE 0x00000010 #define CCSR_DMA_SR_EOLNI 0x00000008 #define CCSR_DMA_SR_CB 0x00000004 #define CCSR_DMA_SR_EOSI 0x00000002 #define CCSR_DMA_SR_EOLSI 0x00000001 /* ECLNDAR takes bits 32-36 of the CLNDAR register */ static inline u32 CCSR_DMA_ECLNDAR_ADDR(u64 x) { return (x >> 32) & 0xf; } #define CCSR_DMA_CLNDAR_ADDR(x) ((x) & 0xFFFFFFFE) #define CCSR_DMA_CLNDAR_EOSIE 0x00000008 /* SATR and DATR, combined */ #define CCSR_DMA_ATR_PBATMU 0x20000000 #define CCSR_DMA_ATR_TFLOWLVL_0 0x00000000 #define CCSR_DMA_ATR_TFLOWLVL_1 0x06000000 #define CCSR_DMA_ATR_TFLOWLVL_2 0x08000000 #define CCSR_DMA_ATR_TFLOWLVL_3 0x0C000000 #define CCSR_DMA_ATR_PCIORDER 0x02000000 #define CCSR_DMA_ATR_SME 0x01000000 #define CCSR_DMA_ATR_NOSNOOP 0x00040000 #define CCSR_DMA_ATR_SNOOP 0x00050000 #define CCSR_DMA_ATR_ESAD_MASK 0x0000000F /** * List Descriptor for extended chaining mode DMA operations. * * The CLSDAR register points to the first (in a linked-list) List * Descriptor. Each object must be aligned on a 32-byte boundary. Each * list descriptor points to a linked-list of link Descriptors. */ struct fsl_dma_list_descriptor { __be64 next; /* Address of next list descriptor */ __be64 first_link; /* Address of first link descriptor */ __be32 source; /* Source stride */ __be32 dest; /* Destination stride */ u8 res[8]; /* Reserved */ } __attribute__ ((aligned(32), packed)); /** * Link Descriptor for basic and extended chaining mode DMA operations. * * A Link Descriptor points to a single DMA buffer. Each link descriptor * must be aligned on a 32-byte boundary. */ struct fsl_dma_link_descriptor { __be32 source_attr; /* Programmed into SATR register */ __be32 source_addr; /* Programmed into SAR register */ __be32 dest_attr; /* Programmed into DATR register */ __be32 dest_addr; /* Programmed into DAR register */ __be64 next; /* Address of next link descriptor */ __be32 count; /* Byte count */ u8 res[4]; /* Reserved */ } __attribute__ ((aligned(32), packed)); <<<<<<< HEAD ======= /* DMA information needed to create a snd_soc_dai object * * ssi_stx_phys: bus address of SSI STX register to use * ssi_srx_phys: bus address of SSI SRX register to use * dma[0]: points to the DMA channel to use for playback * dma[1]: points to the DMA channel to use for capture * dma_irq[0]: IRQ of the DMA channel to use for playback * dma_irq[1]: IRQ of the DMA channel to use for capture */ struct fsl_dma_info { dma_addr_t ssi_stx_phys; dma_addr_t ssi_srx_phys; struct ccsr_dma_channel __iomem *dma_channel[2]; unsigned int dma_irq[2]; }; extern struct snd_soc_platform fsl_soc_platform; int fsl_dma_configure(struct fsl_dma_info *dma_info); >>>>>>> 296c66da8a02d52243f45b80521febece5ed498a #endif
Core2idiot/Kernel-Samsung-3.0...-
sound/soc/fsl/fsl_dma.h
C
gpl-2.0
5,573
35.664474
74
0.693522
false
ALTER TABLE db_version CHANGE COLUMN required_z0652_134_01_mangos_creature_model_info required_z0662_135_01_mangos_mangos_string bit; DELETE FROM mangos_string WHERE entry BETWEEN 1149 AND 1151; INSERT INTO mangos_string VALUES (1149,' (Pool %u)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), (1150,' (Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), (1151,' (Pool %u Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); DELETE FROM mangos_string WHERE entry in (515, 517, 1110, 1111, 1137); INSERT INTO mangos_string VALUES (515,'%d%s - |cffffffff|Hcreature:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CHAT (.list creature) (517,'%d%s, Entry %d - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_MIXED_LIST_CHAT (.gobject near) (1110,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CONSOLE (1111,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_LIST_CONSOLE (1137,'%d%s - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); -- LANG_GO_LIST_CHAT (.list object)
natedahl32/portalclassic
sql/archive/0.12.2/z0662_135_01_mangos_mangos_string.sql
SQL
gpl-2.0
1,248
71.529412
168
0.684295
false
/* * HT Editor * syssdl.h * * Copyright (C) 2004 Stefan Weyergraf * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __SYSSDL_H__ #define __SYSSDL_H__ #ifdef __MACH__ #include <SDL/SDL.h> #else #include <SDL.h> #endif #include "system/display.h" #include "system/systhread.h" extern SDL_Surface * gSDLScreen; class SDLSystemDisplay: public SystemDisplay { protected: DisplayCharacteristics mSDLChar; byte * mSDLFrameBuffer; bool mChangingScreen; SDL_Surface * mSDLClientScreen; sys_mutex mRedrawMutex; SDL_Cursor * mVisibleCursor; SDL_Cursor * mInvisibleCursor; uint bitsPerPixelToXBitmapPad(uint bitsPerPixel); void dumpDisplayChar(const DisplayCharacteristics &chr); public: char * mTitle; DisplayCharacteristics mSDLChartemp; SDL_cond *mWaitcondition; bool mChangeResRet; uint32 mEventThreadID; SDLSystemDisplay(const char *title, const DisplayCharacteristics &chr, int redraw_ms); void finishMenu(); virtual void updateTitle(); virtual int toString(char *buf, int buflen) const; void toggleFullScreen(); virtual void displayShow(); virtual void convertCharacteristicsToHost(DisplayCharacteristics &aHostChar, const DisplayCharacteristics &aClientChar); virtual bool changeResolution(const DisplayCharacteristics &aCharacteristics); virtual bool changeResolutionREAL(const DisplayCharacteristics &aCharacteristics); virtual void getHostCharacteristics(Container &modes); virtual void setMouseGrab(bool enable); virtual void initCursor(); }; #endif
tycho/pearpc
src/system/ui/sdl/syssdl.h
C
gpl-2.0
2,112
28.746479
121
0.767045
false
/***************************************************/ /*! \class BiQuad \brief STK biquad (two-pole, two-zero) filter class. This class implements a two-pole, two-zero digital filter. Methods are provided for creating a resonance or notch in the frequency response while maintaining a constant filter gain. by Perry R. Cook and Gary P. Scavone, 1995-2012. */ /***************************************************/ #include "BiQuad.h" #include <cmath> namespace stk { BiQuad :: BiQuad() : Filter() { b_.resize( 3, 0.0 ); a_.resize( 3, 0.0 ); b_[0] = 1.0; a_[0] = 1.0; inputs_.resize( 3, 1, 0.0 ); outputs_.resize( 3, 1, 0.0 ); Stk::addSampleRateAlert( this ); } BiQuad :: ~BiQuad() { Stk::removeSampleRateAlert( this ); } void BiQuad :: setCoefficients( StkFloat b0, StkFloat b1, StkFloat b2, StkFloat a1, StkFloat a2, bool clearState ) { b_[0] = b0; b_[1] = b1; b_[2] = b2; a_[1] = a1; a_[2] = a2; if ( clearState ) this->clear(); } void BiQuad :: sampleRateChanged( StkFloat newRate, StkFloat oldRate ) { if ( !ignoreSampleRateChange_ ) { std::cerr << "BiQuad::sampleRateChanged: you may need to recompute filter coefficients!"; handleError( StkError::WARNING ); } } void BiQuad :: setResonance( StkFloat frequency, StkFloat radius, bool normalize ) { #if defined(_STK_DEBUG_) if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) { std::cerr << "BiQuad::setResonance: frequency argument (" << frequency << ") is out of range!"; handleError( StkError::WARNING ); return; } if ( radius < 0.0 || radius >= 1.0 ) { std::cerr << "BiQuad::setResonance: radius argument (" << radius << ") is out of range!"; handleError( StkError::WARNING ); return; } #endif a_[2] = radius * radius; a_[1] = -2.0 * radius * cos( TWO_PI * frequency / Stk::sampleRate() ); if ( normalize ) { // Use zeros at +- 1 and normalize the filter peak gain. b_[0] = 0.5 - 0.5 * a_[2]; b_[1] = 0.0; b_[2] = -b_[0]; } } void BiQuad :: setNotch( StkFloat frequency, StkFloat radius ) { #if defined(_STK_DEBUG_) if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) { std::cerr << "BiQuad::setNotch: frequency argument (" << frequency << ") is out of range!"; handleError( StkError::WARNING ); return; } if ( radius < 0.0 ) { std::cerr << "BiQuad::setNotch: radius argument (" << radius << ") is negative!"; handleError( StkError::WARNING ); return; } #endif // This method does not attempt to normalize the filter gain. b_[2] = radius * radius; b_[1] = (StkFloat) -2.0 * radius * cos( TWO_PI * (double) frequency / Stk::sampleRate() ); } void BiQuad :: setEqualGainZeroes( void ) { b_[0] = 1.0; b_[1] = 0.0; b_[2] = -1.0; } } // stk namespace
TheAlphaNerd/theremax
include/stk/BiQuad.cpp
C++
gpl-2.0
2,784
26.029126
114
0.587284
false
/* * Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 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/>. */ #include "mpqfile.h" #include <deque> #include <cstdio> #include "StormLib.h" MPQFile::MPQFile(HANDLE mpq, const char* filename, bool warnNoExist /*= true*/) : eof(false), buffer(0), pointer(0), size(0) { HANDLE file; if (!SFileOpenFileEx(mpq, filename, SFILE_OPEN_PATCHED_FILE, &file)) { if (warnNoExist || GetLastError() != ERROR_FILE_NOT_FOUND) fprintf(stderr, "Can't open %s, err=%u!\n", filename, GetLastError()); eof = true; return; } DWORD hi = 0; size = SFileGetFileSize(file, &hi); if (hi) { fprintf(stderr, "Can't open %s, size[hi] = %u!\n", filename, uint32(hi)); SFileCloseFile(file); eof = true; return; } if (size <= 1) { fprintf(stderr, "Can't open %s, size = %u!\n", filename, uint32(size)); SFileCloseFile(file); eof = true; return; } DWORD read = 0; buffer = new char[size]; if (!SFileReadFile(file, buffer, size, &read) || size != read) { fprintf(stderr, "Can't read %s, size=%u read=%u!\n", filename, uint32(size), uint32(read)); SFileCloseFile(file); eof = true; return; } SFileCloseFile(file); } size_t MPQFile::read(void* dest, size_t bytes) { if (eof) return 0; size_t rpos = pointer + bytes; if (rpos > size) { bytes = size - pointer; eof = true; } memcpy(dest, &(buffer[pointer]), bytes); pointer = rpos; return bytes; } void MPQFile::seek(int offset) { pointer = offset; eof = (pointer >= size); } void MPQFile::seekRelative(int offset) { pointer += offset; eof = (pointer >= size); } void MPQFile::close() { if (buffer) delete[] buffer; buffer = 0; eof = true; }
MistyWorld/MistyWorld_6xx
src/outils/vmap4_extracteur/mpqfile.cpp
C++
gpl-2.0
2,513
22.707547
99
0.604855
false
<div><p><br/></p></div><div class="container"> <div class="row"> <div id="index" class="col-md-3"> <div > <div class="panel panel-default"> <div class="panel-heading">Classes</div> <div class="panel-body"><a href="/docs/api/BB_Frame"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Frame</span></span></a></div> <div class="panel-body"><a href="/docs/api/BB_RecPlayer"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">RecPlayer</span></span></a></div> <div class="panel-body"><a href="/docs/api/BB_Recording"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Recording</span></span></a></div> <div class="panel-body"><a href="/docs/api/BB_Session"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Session</span></span></a></div> <div class="panel-body"><a href="/docs/api/_global_"><span class="indent" style="padding-left:0px;"><i class="icon-jsdoc icon-jsdoc-namespace"></i><span class="jsdoc-class-index">_global_</span></span></a></div> </div> </div> </div> <div id="content" class="col-md-9"> <pre class="prettyprint linenums">goog.provide('BB.Session'); goog.require('BB.Frame'); goog.require('BB.Recording'); /** * * @param {string} backendUrl * @param {number=} fps * @param {string=} title * @param {string=} url * * @constructor */ BB.Session = function(backendUrl, fps, title, url) { /** @type {string} */ this.backendUrl = backendUrl; /** @type {number} */ this.fps = fps || 3; /** @type {number} */ this.TICK_MILLI = 1000 / this.fps; /** @type {string} */ this.title = title || BB.Session.getPageTitle(); /** @type {string} */ this.url = url || BB.Session.getPageUrl(); /** @type {Array.&lt;BB.Frame&gt;} */ this.frames = []; /** @type {boolean} */ this.active = false; /** @type {number} Pointer to setTimeout */ this.timer; /** @type {boolean} */ this.clicked = false; this.init(); }; /** * @private */ BB.Session.prototype.init = function(){ var self = this; document.addEventListener('mousemove', function(e) { BB.Session.mouse.x = e.clientX || e.pageX; BB.Session.mouse.y = e.clientY || e.pageY; }, false); document.addEventListener('click', function(e) { self.clicked = true; }, false); }; /** * Start recording a session */ BB.Session.prototype.start = function(){ if (!this.active) { this.active = true; this.tick(); } }; /** * Stop recording a session */ BB.Session.prototype.stop = function(){ clearTimeout(this.timer); this.active = false; }; /** * Captures the current frame * * @private */ BB.Session.prototype.tick = function(){ if (this.active) { var frame = new BB.Frame( BB.Frame.getCurrentWin(), BB.Frame.getCurrentScroll(), BB.Frame.getCurrentMouse(), this.clicked ); this.frames.push(frame); this.timer = setTimeout(this.tick.bind(this), this.TICK_MILLI); this.clicked = false; } }; /** * Send recording to backend server */ BB.Session.prototype.upload = function(){ var xhr = new XMLHttpRequest(); xhr.open('POST', '/save.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send('recording=' + this.toString()); }; /** * * @returns {string} */ BB.Session.getPageTitle = function() { var el = document.getElementsByTagName('title'); var title = 'Untitled document'; if (el.length &gt; 0) { title = el[0].textContent; } return title; }; /** * * @returns {string} */ BB.Session.getPageUrl = function(){ return window.location.href; }; /** * * @returns {string} */ BB.Session.prototype.toString = function(){ return JSON.stringify( new BB.Recording(this.title, this.url, BB.Frame.getClientRes(), this.fps, this.frames) ); }; /** * * @type {BB.mouse} */ BB.Session.mouse = { x: 0, y: 0 }; </div> </div> </div> <script type="text/javascript"> prettyPrint(); var i = 1; $('#source-code li').each(function() { $(this).attr({ id: 'line' + (i++) }); }); </script> </div></div>
formigone/big-brother-js
promo-site/application/views/scripts/docs/src/BB_Session_js.php
PHP
gpl-2.0
4,500
21.61809
216
0.596222
false
import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait()
deggis/drinkcounter
clients/s60-python/client.py
Python
gpl-2.0
1,757
22.426667
98
0.63745
false
package com.mikesantiago.mariofighter; import static com.mikesantiago.mariofighter.GlobalVariables.PPM; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.mikesantiago.mariofighter.assets.Animation; public class PlayerOne { public enum Direction { LEFT, RIGHT, STOP } private BodyDef playerBodyDef; private Body playerBody; private PolygonShape playerShape; private FixtureDef playerFixtureDef; private Fixture playerFixture; private boolean isMoving = false; private Direction currentDirection = Direction.RIGHT; private Animation animationRight; private Animation animationLeft; public boolean getMoving(){return isMoving;} public Direction getCurrentDirection(){return currentDirection;} public PlayerOne(World worldToCreateIn) { playerBodyDef = new BodyDef(); playerBodyDef.type = BodyType.DynamicBody; playerBodyDef.position.set(new Vector2(32f / PPM, 256f / PPM)); playerBody = worldToCreateIn.createBody(playerBodyDef); playerShape = new PolygonShape(); playerShape.setAsBox((32f / 2) / PPM, (36f / 2) / PPM); playerFixtureDef = new FixtureDef(); playerFixtureDef.shape = playerShape; playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT; playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT; playerFixture = playerBody.createFixture(playerFixtureDef); playerFixture.setUserData("body"); //create foot sensor { playerShape.setAsBox(2 / PPM, 2 / PPM, new Vector2(0, -32 / PPM), 0); playerFixtureDef.shape = playerShape; playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT; playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT; playerFixtureDef.isSensor = true; playerBody.createFixture(playerFixtureDef).setUserData("FOOT"); } CreateAnimation(); System.out.println("Player 1 created!"); } private void CreateAnimation() { float updateInterval = 1 / 20f; Texture tex = GlobalVariables.manager.GetTexture("mario"); TextureRegion[] sprites = TextureRegion.split(tex, 16, 28)[0]; if(animationRight == null) animationRight = new Animation(); animationRight.setFrames(sprites, updateInterval); if(animationLeft == null) animationLeft = new Animation(); TextureRegion[] leftSprites = TextureRegion.split(tex, 16, 28)[0]; for(TextureRegion tr : leftSprites) tr.flip(true, false); animationLeft.setFrames(leftSprites, updateInterval); sprWidth = sprites[0].getRegionWidth(); sprHeight = sprites[0].getRegionHeight(); } private int sprWidth, sprHeight; public void update(float dt) { if(this.isMoving) { animationRight.update(dt); animationLeft.update(dt); } } public void render(SpriteBatch sb) { if(!sb.isDrawing()) sb.begin(); sb.setProjectionMatrix(GlobalVariables.maincamera.combined); if(this.isMoving) { if(this.currentDirection == Direction.RIGHT) { sb.draw(animationRight.getFrame(), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } else if(this.currentDirection == Direction.LEFT) { sb.draw(animationLeft.getFrame(), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } } else { if(this.currentDirection == Direction.RIGHT) { sb.draw(animationRight.getFrame(0), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } else if(this.currentDirection == Direction.LEFT) { sb.draw(animationLeft.getFrame(0), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } } if(sb.isDrawing()) sb.end(); } public void setMoving(boolean a){this.isMoving = a;} public void setCurrentDirection(Direction a){currentDirection = a;} public BodyDef getPlayerBodyDef() { return playerBodyDef; } public void setPlayerBodyDef(BodyDef playerBodyDef) { this.playerBodyDef = playerBodyDef; } public Body getPlayerBody() { return playerBody; } public void setPlayerBody(Body playerBody) { this.playerBody = playerBody; } public PolygonShape getPlayerShape() { return playerShape; } public void setPlayerShape(PolygonShape playerShape) { this.playerShape = playerShape; } public FixtureDef getPlayerFixtureDef() { return playerFixtureDef; } public void setPlayerFixtureDef(FixtureDef playerFixtureDef) { this.playerFixtureDef = playerFixtureDef; } public Fixture getPlayerFixture() { return playerFixture; } public void setPlayerFixture(Fixture playerFixture) { this.playerFixture = playerFixture; } }
Luigifan/MarioFighter
core/src/com/mikesantiago/mariofighter/PlayerOne.java
Java
gpl-2.0
5,195
27.081081
87
0.734167
false
#include "exec/def-helper.h" #ifdef CONFIG_TCG_PLUGIN DEF_HELPER_FLAGS_4(tcg_plugin_pre_tb, 0, void, i64, i64, i64, i64) #endif DEF_HELPER_2(exception, noreturn, env, i32) DEF_HELPER_3(exception_cause, noreturn, env, i32, i32) DEF_HELPER_4(exception_cause_vaddr, noreturn, env, i32, i32, i32) DEF_HELPER_3(debug_exception, noreturn, env, i32, i32) DEF_HELPER_FLAGS_1(nsa, TCG_CALL_NO_RWG_SE, i32, i32) DEF_HELPER_FLAGS_1(nsau, TCG_CALL_NO_RWG_SE, i32, i32) DEF_HELPER_2(wsr_windowbase, void, env, i32) DEF_HELPER_4(entry, void, env, i32, i32, i32) DEF_HELPER_2(retw, i32, env, i32) DEF_HELPER_2(rotw, void, env, i32) DEF_HELPER_3(window_check, void, env, i32, i32) DEF_HELPER_1(restore_owb, void, env) DEF_HELPER_2(movsp, void, env, i32) DEF_HELPER_2(wsr_lbeg, void, env, i32) DEF_HELPER_2(wsr_lend, void, env, i32) DEF_HELPER_1(simcall, void, env) DEF_HELPER_1(dump_state, void, env) DEF_HELPER_3(waiti, void, env, i32, i32) DEF_HELPER_3(timer_irq, void, env, i32, i32) DEF_HELPER_2(advance_ccount, void, env, i32) DEF_HELPER_1(check_interrupts, void, env) DEF_HELPER_3(check_atomctl, void, env, i32, i32) DEF_HELPER_2(wsr_rasid, void, env, i32) DEF_HELPER_FLAGS_3(rtlb0, TCG_CALL_NO_RWG_SE, i32, env, i32, i32) DEF_HELPER_FLAGS_3(rtlb1, TCG_CALL_NO_RWG_SE, i32, env, i32, i32) DEF_HELPER_3(itlb, void, env, i32, i32) DEF_HELPER_3(ptlb, i32, env, i32, i32) DEF_HELPER_4(wtlb, void, env, i32, i32, i32) DEF_HELPER_2(wsr_ibreakenable, void, env, i32) DEF_HELPER_3(wsr_ibreaka, void, env, i32, i32) DEF_HELPER_3(wsr_dbreaka, void, env, i32, i32) DEF_HELPER_3(wsr_dbreakc, void, env, i32, i32) DEF_HELPER_2(wur_fcr, void, env, i32) DEF_HELPER_FLAGS_1(abs_s, TCG_CALL_NO_RWG_SE, f32, f32) DEF_HELPER_FLAGS_1(neg_s, TCG_CALL_NO_RWG_SE, f32, f32) DEF_HELPER_3(add_s, f32, env, f32, f32) DEF_HELPER_3(sub_s, f32, env, f32, f32) DEF_HELPER_3(mul_s, f32, env, f32, f32) DEF_HELPER_4(madd_s, f32, env, f32, f32, f32) DEF_HELPER_4(msub_s, f32, env, f32, f32, f32) DEF_HELPER_FLAGS_3(ftoi, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32) DEF_HELPER_FLAGS_3(ftoui, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32) DEF_HELPER_3(itof, f32, env, i32, i32) DEF_HELPER_3(uitof, f32, env, i32, i32) DEF_HELPER_4(un_s, void, env, i32, f32, f32) DEF_HELPER_4(oeq_s, void, env, i32, f32, f32) DEF_HELPER_4(ueq_s, void, env, i32, f32, f32) DEF_HELPER_4(olt_s, void, env, i32, f32, f32) DEF_HELPER_4(ult_s, void, env, i32, f32, f32) DEF_HELPER_4(ole_s, void, env, i32, f32, f32) DEF_HELPER_4(ule_s, void, env, i32, f32, f32) #include "exec/def-helper.h"
cedric-vincent/qemu
target-xtensa/helper.h
C
gpl-2.0
2,522
37.8
66
0.692308
false
<?php class Request { public static function redirect($to) { header('Location: ' . Config::get('url') . $to); } public static function path() { return $_SERVER['REQUEST_URI']; } public static function method() { $method = $_SERVER['REQUEST_METHOD']; if($method === 'PUT') return 'put'; if($method === 'GET') return 'post'; if($method === 'GET') return 'get'; if($method === 'HEAD') return 'head'; if($method === 'DELETE') return 'delete'; if($method === 'OPTIONS') return 'options'; return false; } public static function isMethod($method) { if(self::method() === $method) { return true; } return false; } }
thatasko/elsa
system/modules/Request.php
PHP
gpl-2.0
708
14.090909
50
0.55226
false
# show_off_web_app/services
mikeckennedy/cookiecutter-course
src/ch8_sharing_your_template/show_off_web_app/show_off_web_app/services/readme.md
Markdown
gpl-2.0
33
4.5
27
0.636364
false
/* Copyright (c) 2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/slab.h> #include <linux/of_gpio.h> #include <linux/platform_device.h> #include <linux/irq.h> #include <media/rc-core.h> #include <media/gpio-ir-recv.h> #define GPIO_IR_DRIVER_NAME "gpio-rc-recv" #define GPIO_IR_DEVICE_NAME "gpio_ir_recv" struct gpio_rc_dev { struct rc_dev *rcdev; unsigned int gpio_nr; bool active_low; int can_sleep; }; #ifdef CONFIG_OF /* * Translate OpenFirmware node properties into platform_data */ static int gpio_ir_recv_get_devtree_pdata(struct device *dev, struct gpio_ir_recv_platform_data *pdata) { struct device_node *np = dev->of_node; enum of_gpio_flags flags; int gpio; gpio = of_get_gpio_flags(np, 0, &flags); if (gpio < 0) { if (gpio != -EPROBE_DEFER) dev_err(dev, "Failed to get gpio flags (%d)\n", gpio); return gpio; } pdata->gpio_nr = gpio; pdata->active_low = (flags & OF_GPIO_ACTIVE_LOW); /* probe() takes care of map_name == NULL or allowed_protos == 0 */ pdata->map_name = of_get_property(np, "linux,rc-map-name", NULL); pdata->allowed_protos = 0; return 0; } static struct of_device_id gpio_ir_recv_of_match[] = { { .compatible = "gpio-ir-receiver", }, { }, }; MODULE_DEVICE_TABLE(of, gpio_ir_recv_of_match); #else /* !CONFIG_OF */ #define gpio_ir_recv_get_devtree_pdata(dev, pdata) (-ENOSYS) #endif static irqreturn_t gpio_ir_recv_irq(int irq, void *dev_id) { struct gpio_rc_dev *gpio_dev = dev_id; unsigned int gval; int rc = 0; enum raw_event_type type = IR_SPACE; if (gpio_dev->can_sleep) gval = gpio_get_value_cansleep(gpio_dev->gpio_nr); else gval = gpio_get_value(gpio_dev->gpio_nr); if (gval < 0) goto err_get_value; if (gpio_dev->active_low) gval = !gval; if (gval == 1) type = IR_PULSE; rc = ir_raw_event_store_edge(gpio_dev->rcdev, type); if (rc < 0) goto err_get_value; ir_raw_event_handle(gpio_dev->rcdev); err_get_value: return IRQ_HANDLED; } static int gpio_ir_recv_probe(struct platform_device *pdev) { struct gpio_rc_dev *gpio_dev; struct rc_dev *rcdev; const struct gpio_ir_recv_platform_data *pdata = pdev->dev.platform_data; int rc; if (pdev->dev.of_node) { struct gpio_ir_recv_platform_data *dtpdata = devm_kzalloc(&pdev->dev, sizeof(*dtpdata), GFP_KERNEL); if (!dtpdata) return -ENOMEM; rc = gpio_ir_recv_get_devtree_pdata(&pdev->dev, dtpdata); if (rc) return rc; pdata = dtpdata; } if (!pdata) return -EINVAL; if (pdata->gpio_nr < 0) return -EINVAL; gpio_dev = kzalloc(sizeof(struct gpio_rc_dev), GFP_KERNEL); if (!gpio_dev) return -ENOMEM; rcdev = rc_allocate_device(); if (!rcdev) { rc = -ENOMEM; goto err_allocate_device; } rcdev->priv = gpio_dev; rcdev->driver_type = RC_DRIVER_IR_RAW; rcdev->input_name = GPIO_IR_DEVICE_NAME; rcdev->input_phys = GPIO_IR_DEVICE_NAME "/input0"; rcdev->input_id.bustype = BUS_HOST; rcdev->input_id.vendor = 0x0001; rcdev->input_id.product = 0x0001; rcdev->input_id.version = 0x0100; rcdev->dev.parent = &pdev->dev; rcdev->driver_name = GPIO_IR_DRIVER_NAME; <<<<<<< HEAD rcdev->map_name = RC_MAP_SAMSUNG_NECX; ======= if (pdata->allowed_protos) rcdev->allowed_protos = pdata->allowed_protos; else rcdev->allowed_protos = RC_BIT_ALL; rcdev->map_name = pdata->map_name ?: RC_MAP_EMPTY; >>>>>>> common/android-3.10.y gpio_dev->rcdev = rcdev; gpio_dev->gpio_nr = pdata->gpio_nr; gpio_dev->active_low = pdata->active_low; rc = gpio_request(pdata->gpio_nr, "gpio-ir-recv"); if (rc < 0) goto err_gpio_request; gpio_dev->can_sleep = gpio_cansleep(pdata->gpio_nr); rc = gpio_direction_input(pdata->gpio_nr); if (rc < 0) goto err_gpio_direction_input; rc = rc_register_device(rcdev); if (rc < 0) { dev_err(&pdev->dev, "failed to register rc device\n"); goto err_register_rc_device; } platform_set_drvdata(pdev, gpio_dev); rc = request_any_context_irq(gpio_to_irq(pdata->gpio_nr), gpio_ir_recv_irq, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "gpio-ir-recv-irq", gpio_dev); if (rc < 0) goto err_request_irq; device_init_wakeup(&pdev->dev, pdata->can_wakeup); return 0; err_request_irq: platform_set_drvdata(pdev, NULL); rc_unregister_device(rcdev); rcdev = NULL; err_register_rc_device: err_gpio_direction_input: gpio_free(pdata->gpio_nr); err_gpio_request: rc_free_device(rcdev); err_allocate_device: kfree(gpio_dev); return rc; } static int gpio_ir_recv_remove(struct platform_device *pdev) { struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev); free_irq(gpio_to_irq(gpio_dev->gpio_nr), gpio_dev); platform_set_drvdata(pdev, NULL); rc_unregister_device(gpio_dev->rcdev); gpio_free(gpio_dev->gpio_nr); kfree(gpio_dev); return 0; } #ifdef CONFIG_PM static int gpio_ir_recv_suspend(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev); if (device_may_wakeup(dev)) enable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr)); else disable_irq(gpio_to_irq(gpio_dev->gpio_nr)); return 0; } static int gpio_ir_recv_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev); if (device_may_wakeup(dev)) disable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr)); else enable_irq(gpio_to_irq(gpio_dev->gpio_nr)); return 0; } static const struct dev_pm_ops gpio_ir_recv_pm_ops = { .suspend = gpio_ir_recv_suspend, .resume = gpio_ir_recv_resume, }; #endif static struct platform_driver gpio_ir_recv_driver = { .probe = gpio_ir_recv_probe, .remove = gpio_ir_recv_remove, .driver = { .name = GPIO_IR_DRIVER_NAME, .owner = THIS_MODULE, .of_match_table = of_match_ptr(gpio_ir_recv_of_match), #ifdef CONFIG_PM .pm = &gpio_ir_recv_pm_ops, #endif }, }; module_platform_driver(gpio_ir_recv_driver); MODULE_DESCRIPTION("GPIO IR Receiver driver"); MODULE_LICENSE("GPL v2");
javelinanddart/android_kernel_3.10_ville
drivers/media/rc/gpio-ir-recv.c
C
gpl-2.0
6,544
23.509363
71
0.682304
false
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.quercus.lib.spl; import com.caucho.quercus.env.Value; public interface OuterIterator extends Iterator { public Value getInnerIterator(); }
dlitz/resin
modules/quercus/src/com/caucho/quercus/lib/spl/OuterIterator.java
Java
gpl-2.0
1,187
30.236842
76
0.737152
false