code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/* Copyright (c) 2012 Google Inc.
*
* 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 org.cocos2dx.plugin.util;
/**
* Exception thrown when something went wrong with in-app billing.
* An IabException has an associated IabResult (an error).
* To get the IAB result that caused this exception to be thrown,
* call {@link #getResult()}.
*/
public class IabException extends Exception {
IabResult mResult;
public IabException(IabResult r) {
this(r, null);
}
public IabException(int response, String message) {
this(new IabResult(response, message));
}
public IabException(IabResult r, Exception cause) {
super(r.getMessage(), cause);
mResult = r;
}
public IabException(int response, String message, Exception cause) {
this(new IabResult(response, message), cause);
}
/** Returns the IAB result (error) that this exception signals. */
public IabResult getResult() { return mResult; }
}
|
cmdwin32/tileMapHomework
|
tillmap/cocos2d/plugin/plugins/googleplay/proj.android/src/org/cocos2dx/plugin/util/IabException.java
|
Java
|
unlicense
| 1,492
|
#ifndef _ASM_POWERPC_PROCESSOR_H
#define _ASM_POWERPC_PROCESSOR_H
/*
* Copyright (C) 2001 PPC 64 Team, IBM Corp
*
* 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 <asm/reg.h>
#ifdef CONFIG_VSX
#define TS_FPRWIDTH 2
#ifdef __BIG_ENDIAN__
#define TS_FPROFFSET 0
#define TS_VSRLOWOFFSET 1
#else
#define TS_FPROFFSET 1
#define TS_VSRLOWOFFSET 0
#endif
#else
#define TS_FPRWIDTH 1
#define TS_FPROFFSET 0
#endif
#ifdef CONFIG_PPC64
/* Default SMT priority is set to 3. Use 11- 13bits to save priority. */
#define PPR_PRIORITY 3
#ifdef __ASSEMBLY__
#define INIT_PPR (PPR_PRIORITY << 50)
#else
#define INIT_PPR ((u64)PPR_PRIORITY << 50)
#endif /* __ASSEMBLY__ */
#endif /* CONFIG_PPC64 */
#ifndef __ASSEMBLY__
#include <linux/compiler.h>
#include <linux/cache.h>
#include <asm/ptrace.h>
#include <asm/types.h>
#include <asm/hw_breakpoint.h>
/* We do _not_ want to define new machine types at all, those must die
* in favor of using the device-tree
* -- BenH.
*/
/* PREP sub-platform types. Unused */
#define _PREP_Motorola 0x01 /* motorola prep */
#define _PREP_Firm 0x02 /* firmworks prep */
#define _PREP_IBM 0x00 /* ibm prep */
#define _PREP_Bull 0x03 /* bull prep */
/* CHRP sub-platform types. These are arbitrary */
#define _CHRP_Motorola 0x04 /* motorola chrp, the cobra */
#define _CHRP_IBM 0x05 /* IBM chrp, the longtrail and longtrail 2 */
#define _CHRP_Pegasos 0x06 /* Genesi/bplan's Pegasos and Pegasos2 */
#define _CHRP_briq 0x07 /* TotalImpact's briQ */
#if defined(__KERNEL__) && defined(CONFIG_PPC32)
extern int _chrp_type;
#endif /* defined(__KERNEL__) && defined(CONFIG_PPC32) */
/*
* Default implementation of macro that returns current
* instruction pointer ("program counter").
*/
#define current_text_addr() ({ __label__ _l; _l: &&_l;})
/* Macros for adjusting thread priority (hardware multi-threading) */
#define HMT_very_low() asm volatile("or 31,31,31 # very low priority")
#define HMT_low() asm volatile("or 1,1,1 # low priority")
#define HMT_medium_low() asm volatile("or 6,6,6 # medium low priority")
#define HMT_medium() asm volatile("or 2,2,2 # medium priority")
#define HMT_medium_high() asm volatile("or 5,5,5 # medium high priority")
#define HMT_high() asm volatile("or 3,3,3 # high priority")
#ifdef __KERNEL__
struct task_struct;
void start_thread(struct pt_regs *regs, unsigned long fdptr, unsigned long sp);
void release_thread(struct task_struct *);
/* Lazy FPU handling on uni-processor */
extern struct task_struct *last_task_used_math;
extern struct task_struct *last_task_used_altivec;
extern struct task_struct *last_task_used_vsx;
extern struct task_struct *last_task_used_spe;
#ifdef CONFIG_PPC32
#if CONFIG_TASK_SIZE > CONFIG_KERNEL_START
#error User TASK_SIZE overlaps with KERNEL_START address
#endif
#define TASK_SIZE (CONFIG_TASK_SIZE)
/* This decides where the kernel will search for a free chunk of vm
* space during mmap's.
*/
#define TASK_UNMAPPED_BASE (TASK_SIZE / 8 * 3)
#endif
#ifdef CONFIG_PPC64
/* 64-bit user address space is 46-bits (64TB user VM) */
#define TASK_SIZE_USER64 (0x0000400000000000UL)
/*
* 32-bit user address space is 4GB - 1 page
* (this 1 page is needed so referencing of 0xFFFFFFFF generates EFAULT
*/
#define TASK_SIZE_USER32 (0x0000000100000000UL - (1*PAGE_SIZE))
#define TASK_SIZE_OF(tsk) (test_tsk_thread_flag(tsk, TIF_32BIT) ? \
TASK_SIZE_USER32 : TASK_SIZE_USER64)
#define TASK_SIZE TASK_SIZE_OF(current)
/* This decides where the kernel will search for a free chunk of vm
* space during mmap's.
*/
#define TASK_UNMAPPED_BASE_USER32 (PAGE_ALIGN(TASK_SIZE_USER32 / 4))
#define TASK_UNMAPPED_BASE_USER64 (PAGE_ALIGN(TASK_SIZE_USER64 / 4))
#define TASK_UNMAPPED_BASE ((is_32bit_task()) ? \
TASK_UNMAPPED_BASE_USER32 : TASK_UNMAPPED_BASE_USER64 )
#endif
#ifdef __powerpc64__
#define STACK_TOP_USER64 TASK_SIZE_USER64
#define STACK_TOP_USER32 TASK_SIZE_USER32
#define STACK_TOP (is_32bit_task() ? \
STACK_TOP_USER32 : STACK_TOP_USER64)
#define STACK_TOP_MAX STACK_TOP_USER64
#else /* __powerpc64__ */
#define STACK_TOP TASK_SIZE
#define STACK_TOP_MAX STACK_TOP
#endif /* __powerpc64__ */
typedef struct {
unsigned long seg;
} mm_segment_t;
#define TS_FPR(i) fp_state.fpr[i][TS_FPROFFSET]
#define TS_TRANS_FPR(i) transact_fp.fpr[i][TS_FPROFFSET]
/* FP and VSX 0-31 register set */
struct thread_fp_state {
u64 fpr[32][TS_FPRWIDTH] __attribute__((aligned(16)));
u64 fpscr; /* Floating point status */
};
/* Complete AltiVec register set including VSCR */
struct thread_vr_state {
vector128 vr[32] __attribute__((aligned(16)));
vector128 vscr __attribute__((aligned(16)));
};
struct debug_reg {
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
/*
* The following help to manage the use of Debug Control Registers
* om the BookE platforms.
*/
uint32_t dbcr0;
uint32_t dbcr1;
#ifdef CONFIG_BOOKE
uint32_t dbcr2;
#endif
/*
* The stored value of the DBSR register will be the value at the
* last debug interrupt. This register can only be read from the
* user (will never be written to) and has value while helping to
* describe the reason for the last debug trap. Torez
*/
uint32_t dbsr;
/*
* The following will contain addresses used by debug applications
* to help trace and trap on particular address locations.
* The bits in the Debug Control Registers above help define which
* of the following registers will contain valid data and/or addresses.
*/
unsigned long iac1;
unsigned long iac2;
#if CONFIG_PPC_ADV_DEBUG_IACS > 2
unsigned long iac3;
unsigned long iac4;
#endif
unsigned long dac1;
unsigned long dac2;
#if CONFIG_PPC_ADV_DEBUG_DVCS > 0
unsigned long dvc1;
unsigned long dvc2;
#endif
#endif
};
struct thread_struct {
unsigned long ksp; /* Kernel stack pointer */
#ifdef CONFIG_PPC64
unsigned long ksp_vsid;
#endif
struct pt_regs *regs; /* Pointer to saved register state */
mm_segment_t fs; /* for get_fs() validation */
#ifdef CONFIG_BOOKE
/* BookE base exception scratch space; align on cacheline */
unsigned long normsave[8] ____cacheline_aligned;
#endif
#ifdef CONFIG_PPC32
void *pgdir; /* root of page-table tree */
unsigned long ksp_limit; /* if ksp <= ksp_limit stack overflow */
#endif
/* Debug Registers */
struct debug_reg debug;
struct thread_fp_state fp_state;
struct thread_fp_state *fp_save_area;
int fpexc_mode; /* floating-point exception mode */
unsigned int align_ctl; /* alignment handling control */
#ifdef CONFIG_PPC64
unsigned long start_tb; /* Start purr when proc switched in */
unsigned long accum_tb; /* Total accumilated purr for process */
#ifdef CONFIG_HAVE_HW_BREAKPOINT
struct perf_event *ptrace_bps[HBP_NUM];
/*
* Helps identify source of single-step exception and subsequent
* hw-breakpoint enablement
*/
struct perf_event *last_hit_ubp;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
#endif
struct arch_hw_breakpoint hw_brk; /* info on the hardware breakpoint */
unsigned long trap_nr; /* last trap # on this thread */
#ifdef CONFIG_ALTIVEC
struct thread_vr_state vr_state;
struct thread_vr_state *vr_save_area;
unsigned long vrsave;
int used_vr; /* set if process has used altivec */
#endif /* CONFIG_ALTIVEC */
#ifdef CONFIG_VSX
/* VSR status */
int used_vsr; /* set if process has used altivec */
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
unsigned long evr[32]; /* upper 32-bits of SPE regs */
u64 acc; /* Accumulator */
unsigned long spefscr; /* SPE & eFP status */
unsigned long spefscr_last; /* SPEFSCR value on last prctl
call or trap return */
int used_spe; /* set if process has used spe */
#endif /* CONFIG_SPE */
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
u64 tm_tfhar; /* Transaction fail handler addr */
u64 tm_texasr; /* Transaction exception & summary */
u64 tm_tfiar; /* Transaction fail instr address reg */
unsigned long tm_orig_msr; /* Thread's MSR on ctx switch */
struct pt_regs ckpt_regs; /* Checkpointed registers */
unsigned long tm_tar;
unsigned long tm_ppr;
unsigned long tm_dscr;
/*
* Transactional FP and VSX 0-31 register set.
* NOTE: the sense of these is the opposite of the integer ckpt_regs!
*
* When a transaction is active/signalled/scheduled etc., *regs is the
* most recent set of/speculated GPRs with ckpt_regs being the older
* checkpointed regs to which we roll back if transaction aborts.
*
* However, fpr[] is the checkpointed 'base state' of FP regs, and
* transact_fpr[] is the new set of transactional values.
* VRs work the same way.
*/
struct thread_fp_state transact_fp;
struct thread_vr_state transact_vr;
unsigned long transact_vrsave;
#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
#ifdef CONFIG_KVM_BOOK3S_32_HANDLER
void* kvm_shadow_vcpu; /* KVM internal data */
#endif /* CONFIG_KVM_BOOK3S_32_HANDLER */
#if defined(CONFIG_KVM) && defined(CONFIG_BOOKE)
struct kvm_vcpu *kvm_vcpu;
#endif
#ifdef CONFIG_PPC64
unsigned long dscr;
int dscr_inherit;
unsigned long ppr; /* used to save/restore SMT priority */
#endif
#ifdef CONFIG_PPC_BOOK3S_64
unsigned long tar;
unsigned long ebbrr;
unsigned long ebbhr;
unsigned long bescr;
unsigned long siar;
unsigned long sdar;
unsigned long sier;
unsigned long mmcr2;
unsigned mmcr0;
unsigned used_ebb;
#endif
};
#define ARCH_MIN_TASKALIGN 16
#define INIT_SP (sizeof(init_stack) + (unsigned long) &init_stack)
#define INIT_SP_LIMIT \
(_ALIGN_UP(sizeof(init_thread_info), 16) + (unsigned long) &init_stack)
#ifdef CONFIG_SPE
#define SPEFSCR_INIT \
.spefscr = SPEFSCR_FINVE | SPEFSCR_FDBZE | SPEFSCR_FUNFE | SPEFSCR_FOVFE, \
.spefscr_last = SPEFSCR_FINVE | SPEFSCR_FDBZE | SPEFSCR_FUNFE | SPEFSCR_FOVFE,
#else
#define SPEFSCR_INIT
#endif
#ifdef CONFIG_PPC32
#define INIT_THREAD { \
.ksp = INIT_SP, \
.ksp_limit = INIT_SP_LIMIT, \
.fs = KERNEL_DS, \
.pgdir = swapper_pg_dir, \
.fpexc_mode = MSR_FE0 | MSR_FE1, \
SPEFSCR_INIT \
}
#else
#define INIT_THREAD { \
.ksp = INIT_SP, \
.regs = (struct pt_regs *)INIT_SP - 1, /* XXX bogus, I think */ \
.fs = KERNEL_DS, \
.fpexc_mode = 0, \
.ppr = INIT_PPR, \
}
#endif
/*
* Return saved PC of a blocked thread. For now, this is the "user" PC
*/
#define thread_saved_pc(tsk) \
((tsk)->thread.regs? (tsk)->thread.regs->nip: 0)
#define task_pt_regs(tsk) ((struct pt_regs *)(tsk)->thread.regs)
unsigned long get_wchan(struct task_struct *p);
#define KSTK_EIP(tsk) ((tsk)->thread.regs? (tsk)->thread.regs->nip: 0)
#define KSTK_ESP(tsk) ((tsk)->thread.regs? (tsk)->thread.regs->gpr[1]: 0)
/* Get/set floating-point exception mode */
#define GET_FPEXC_CTL(tsk, adr) get_fpexc_mode((tsk), (adr))
#define SET_FPEXC_CTL(tsk, val) set_fpexc_mode((tsk), (val))
extern int get_fpexc_mode(struct task_struct *tsk, unsigned long adr);
extern int set_fpexc_mode(struct task_struct *tsk, unsigned int val);
#define GET_ENDIAN(tsk, adr) get_endian((tsk), (adr))
#define SET_ENDIAN(tsk, val) set_endian((tsk), (val))
extern int get_endian(struct task_struct *tsk, unsigned long adr);
extern int set_endian(struct task_struct *tsk, unsigned int val);
#define GET_UNALIGN_CTL(tsk, adr) get_unalign_ctl((tsk), (adr))
#define SET_UNALIGN_CTL(tsk, val) set_unalign_ctl((tsk), (val))
extern int get_unalign_ctl(struct task_struct *tsk, unsigned long adr);
extern int set_unalign_ctl(struct task_struct *tsk, unsigned int val);
extern void fp_enable(void);
extern void vec_enable(void);
extern void load_fp_state(struct thread_fp_state *fp);
extern void store_fp_state(struct thread_fp_state *fp);
extern void load_vr_state(struct thread_vr_state *vr);
extern void store_vr_state(struct thread_vr_state *vr);
static inline unsigned int __unpack_fe01(unsigned long msr_bits)
{
return ((msr_bits & MSR_FE0) >> 10) | ((msr_bits & MSR_FE1) >> 8);
}
static inline unsigned long __pack_fe01(unsigned int fpmode)
{
return ((fpmode << 10) & MSR_FE0) | ((fpmode << 8) & MSR_FE1);
}
#ifdef CONFIG_PPC64
#define cpu_relax() do { HMT_low(); HMT_medium(); barrier(); } while (0)
#else
#define cpu_relax() barrier()
#endif
/* Check that a certain kernel stack pointer is valid in task_struct p */
int validate_sp(unsigned long sp, struct task_struct *p,
unsigned long nbytes);
/*
* Prefetch macros.
*/
#define ARCH_HAS_PREFETCH
#define ARCH_HAS_PREFETCHW
#define ARCH_HAS_SPINLOCK_PREFETCH
static inline void prefetch(const void *x)
{
if (unlikely(!x))
return;
__asm__ __volatile__ ("dcbt 0,%0" : : "r" (x));
}
static inline void prefetchw(const void *x)
{
if (unlikely(!x))
return;
__asm__ __volatile__ ("dcbtst 0,%0" : : "r" (x));
}
#define spin_lock_prefetch(x) prefetchw(x)
#define HAVE_ARCH_PICK_MMAP_LAYOUT
#ifdef CONFIG_PPC64
static inline unsigned long get_clean_sp(unsigned long sp, int is_32)
{
if (is_32)
return sp & 0x0ffffffffUL;
return sp;
}
#else
static inline unsigned long get_clean_sp(unsigned long sp, int is_32)
{
return sp;
}
#endif
extern unsigned long cpuidle_disable;
enum idle_boot_override {IDLE_NO_OVERRIDE = 0, IDLE_POWERSAVE_OFF};
extern int powersave_nap; /* set if nap mode can be used in idle loop */
extern void power7_nap(void);
extern void flush_instruction_cache(void);
extern void hard_reset_now(void);
extern void poweroff_now(void);
extern int fix_alignment(struct pt_regs *);
extern void cvt_fd(float *from, double *to);
extern void cvt_df(double *from, float *to);
extern void _nmask_and_or_msr(unsigned long nmask, unsigned long or_val);
#ifdef CONFIG_PPC64
/*
* We handle most unaligned accesses in hardware. On the other hand
* unaligned DMA can be very expensive on some ppc64 IO chips (it does
* powers of 2 writes until it reaches sufficient alignment).
*
* Based on this we disable the IP header alignment in network drivers.
*/
#define NET_IP_ALIGN 0
#endif
#endif /* __KERNEL__ */
#endif /* __ASSEMBLY__ */
#endif /* _ASM_POWERPC_PROCESSOR_H */
|
maoze/linux-3-14-for-arm
|
linux-3.14/arch/powerpc/include/asm/processor.h
|
C
|
gpl-3.0
| 14,046
|
#ifndef __OPENCV_OLD_CXMISC_H__
#define __OPENCV_OLD_CXMISC_H__
#include "opencv2/core/internal.hpp"
#endif
|
niftylettuce/depthjs
|
webkit-plugin-mac/include/opencv/cxmisc.h
|
C
|
agpl-3.0
| 110
|
<?php
namespace Drupal\Core\Routing;
use Symfony\Component\Routing\CompiledRoute as SymfonyCompiledRoute;
/**
* A compiled route contains derived information from a route object.
*/
class CompiledRoute extends SymfonyCompiledRoute {
/**
* The fitness of this route.
*
* @var int
*/
protected $fit;
/**
* The pattern outline of this route.
*
* @var string
*/
protected $patternOutline;
/**
* The number of parts in the path of this route.
*
* @var int
*/
protected $numParts;
/**
* Constructs a new compiled route object.
*
* This is a ridiculously long set of constructor parameters, but as this
* object is little more than a collection of values it's not a serious
* problem. The parent Symfony class does the same, as well, making it
* difficult to override differently.
*
* @param int $fit
* The fitness of the route.
* @param string $pattern_outline
* The pattern outline for this route.
* @param int $num_parts
* The number of parts in the path.
* @param string $staticPrefix
* The static prefix of the compiled route
* @param string $regex
* The regular expression to use to match this route
* @param array $tokens
* An array of tokens to use to generate URL for this route
* @param array $pathVariables
* An array of path variables
* @param string|null $hostRegex
* Host regex
* @param array $hostTokens
* Host tokens
* @param array $hostVariables
* An array of host variables
* @param array $variables
* An array of variables (variables defined in the path and in the host patterns)
*/
public function __construct($fit, $pattern_outline, $num_parts, $staticPrefix, $regex, array $tokens, array $pathVariables, $hostRegex = NULL, array $hostTokens = array(), array $hostVariables = array(), array $variables = array()) {
parent::__construct($staticPrefix, $regex, $tokens, $pathVariables, $hostRegex, $hostTokens, $hostVariables, $variables);
$this->fit = $fit;
$this->patternOutline = $pattern_outline;
$this->numParts = $num_parts;
}
/**
* Returns the fit of this route.
*
* See RouteCompiler for a definition of how the fit is calculated.
*
* @return int
* The fit of the route.
*/
public function getFit() {
return $this->fit;
}
/**
* Returns the number of parts in this route's path.
*
* The string "foo/bar/baz" has 3 parts, regardless of how many of them are
* placeholders.
*
* @return int
* The number of parts in the path.
*/
public function getNumParts() {
return $this->numParts;
}
/**
* Returns the pattern outline of this route.
*
* The pattern outline of a route is the path pattern of the route, but
* normalized such that all placeholders are replaced with %.
*
* @return string
* The normalized path pattern.
*/
public function getPatternOutline() {
return $this->patternOutline;
}
/**
* Returns the options.
*
* @return array
* The options.
*/
public function getOptions() {
return $this->route->getOptions();
}
/**
* Returns the defaults.
*
* @return array
* The defaults.
*/
public function getDefaults() {
return $this->route->getDefaults();
}
/**
* Returns the requirements.
*
* @return array
* The requirements.
*/
public function getRequirements() {
return $this->route->getRequirements();
}
/**
* {@inheritdoc}
*/
public function serialize() {
// Calling the parent method is safer than trying to optimize out the extra
// function calls.
$data = unserialize(parent::serialize());
$data['fit'] = $this->fit;
$data['patternOutline'] = $this->patternOutline;
$data['numParts'] = $this->numParts;
return serialize($data);
}
/**
* {@inheritdoc}
*/
public function unserialize($serialized) {
parent::unserialize($serialized);
$data = unserialize($serialized);
$this->fit = $data['fit'];
$this->patternOutline = $data['patternOutline'];
$this->numParts = $data['numParts'];
}
}
|
ModulesUnraveled/test-built
|
web/core/lib/Drupal/Core/Routing/CompiledRoute.php
|
PHP
|
gpl-2.0
| 4,167
|
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by tools/gentest.py. -->
<title>Canvas test: 2d.path.fill.winding.add</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/canvas-tests.js"></script>
<link rel="stylesheet" href="/common/canvas-tests.css">
<body class="show_output">
<h1>2d.path.fill.winding.add</h1>
<p class="desc"></p>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="/images/green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
var t = async_test("");
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.fillStyle = '#0f0';
ctx.moveTo(-10, -10);
ctx.lineTo(110, -10);
ctx.lineTo(110, 60);
ctx.lineTo(-10, 60);
ctx.lineTo(-10, -10);
ctx.lineTo(0, 0);
ctx.lineTo(100, 0);
ctx.lineTo(100, 50);
ctx.lineTo(0, 50);
ctx.fill();
_assertPixel(canvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
});
</script>
|
cr/fxos-certsuite
|
web-platform-tests/tests/2dcontext/path-objects/2d.path.fill.winding.add.html
|
HTML
|
mpl-2.0
| 1,160
|
<head>
<meta charset="utf-8">
<title>Meteor • TodoMVC</title>
</head>
<body>
<section id="todoapp" data-framework="meteor">
{{> todoapp}}
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by Matthias Stumpp - <a href="http://github.com/MStumpp">GitHub</a> <a href="http://twitter.com/MatStumpp">Twitter</a></p>
<p><a href="http://todomvcapp.meteor.com">Meteor TodoMVC</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
</body>
<template name="todoapp">
<header id="header">
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
</header>
{{#if todos}}
{{> main}}
{{> footer}}
{{/if}}
</template>
<template name="main">
<section id="main">
<input id="toggle-all" type="checkbox" checked="{{#unless todos_not_completed}}checked{{/unless}}">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list">
{{#each todos}}
{{> todo}}
{{/each}}
</ul>
</section>
</template>
<template name="todo">
<li class="{{#if todo_completed}}completed{{/if}}{{#if todo_editing}}editing{{/if}}">
<div class="view">
<input class="toggle" type="checkbox" checked="{{#if todo_completed}}checked{{/if}}">
<label>{{title}}</label>
<button class="destroy"></button>
</div>
<input class="edit" value="{{title}}">
</li>
</template>
<template name="footer">
<footer id="footer">
<span id="todo-count"><strong>{{todos_not_completed}}</strong>
{{#if todos_one_not_completed}}item{{else}}items{{/if}} left</span>
<ul id="filters">
{{#each filters}}
<li>
<a class="{{#if filter_selected this}} selected {{/if}}" href="#/{{this}}">{{this}}</a>
</li>
{{/each}}
</ul>
{{#if todos_completed}}
<button id="clear-completed">Clear completed</button>
{{/if}}
</footer>
</template>
|
gabrielmancini/interactor
|
src/demo/meteor/app.html
|
HTML
|
bsd-2-clause
| 1,859
|
var baseForRight = require('./_baseForRight'),
keys = require('./keys');
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
module.exports = baseForOwnRight;
|
ChrisChenSZ/code
|
表单注册验证/node_modules/lodash/_baseForOwnRight.js
|
JavaScript
|
apache-2.0
| 486
|
<?php
namespace Drupal\condition_test;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Condition\ConditionManager;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
/**
* Routing controller class for condition_test testing of condition forms.
*/
class FormController implements FormInterface {
/**
* The condition plugin we will be working with.
*
* @var \Drupal\Core\Condition\ConditionInterface
*/
protected $condition;
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'condition_node_type_test_form';
}
/**
* Constructs a \Drupal\condition_test\FormController object.
*/
public function __construct() {
$manager = new ConditionManager(\Drupal::service('container.namespaces'), \Drupal::cache('discovery'), \Drupal::moduleHandler());
$this->condition = $manager->createInstance('node_type');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = $this->condition->buildConfigurationForm($form, $form_state);
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
/**
* Implements \Drupal\Core\Form\FormInterface::validateForm().
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$this->condition->validateConfigurationForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->condition->submitConfigurationForm($form, $form_state);
$config = $this->condition->getConfig();
foreach ($config['bundles'] as $bundle) {
drupal_set_message('Bundle: ' . $bundle);
}
$article = Node::load(1);
$this->condition->setContextValue('node', $article);
if ($this->condition->execute()) {
drupal_set_message(t('Executed successfully.'));
}
}
}
|
sunlight25/d8
|
web/core/modules/system/tests/modules/condition_test/src/FormController.php
|
PHP
|
gpl-2.0
| 1,940
|
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright IBM Corp. 2001,2008
*
* This file contains the IRQ specific code for hvc_console
*
*/
#include <linux/interrupt.h>
#include "hvc_console.h"
static irqreturn_t hvc_handle_interrupt(int irq, void *dev_instance)
{
/* if hvc_poll request a repoll, then kick the hvcd thread */
if (hvc_poll(dev_instance))
hvc_kick();
/*
* We're safe to always return IRQ_HANDLED as the hvcd thread will
* iterate through each hvc_struct.
*/
return IRQ_HANDLED;
}
/*
* For IRQ based systems these callbacks can be used
*/
int notifier_add_irq(struct hvc_struct *hp, int irq)
{
int rc;
if (!irq) {
hp->irq_requested = 0;
return 0;
}
rc = request_irq(irq, hvc_handle_interrupt, hp->flags,
"hvc_console", hp);
if (!rc)
hp->irq_requested = 1;
return rc;
}
void notifier_del_irq(struct hvc_struct *hp, int irq)
{
if (!hp->irq_requested)
return;
free_irq(irq, hp);
hp->irq_requested = 0;
}
void notifier_hangup_irq(struct hvc_struct *hp, int irq)
{
notifier_del_irq(hp, irq);
}
|
CSE3320/kernel-code
|
linux-5.8/drivers/tty/hvc/hvc_irq.c
|
C
|
gpl-2.0
| 1,049
|
/*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include "cx88.h"
static unsigned int vbibufs = 4;
module_param(vbibufs,int,0644);
MODULE_PARM_DESC(vbibufs,"number of vbi buffers, range 2-32");
static unsigned int vbi_debug;
module_param(vbi_debug,int,0644);
MODULE_PARM_DESC(vbi_debug,"enable debug messages [vbi]");
#define dprintk(level,fmt, arg...) if (vbi_debug >= level) \
printk(KERN_DEBUG "%s: " fmt, dev->core->name , ## arg)
/* ------------------------------------------------------------------ */
int cx8800_vbi_fmt (struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx8800_fh *fh = priv;
struct cx8800_dev *dev = fh->dev;
f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
f->fmt.vbi.offset = 244;
f->fmt.vbi.count[0] = VBI_LINE_COUNT;
f->fmt.vbi.count[1] = VBI_LINE_COUNT;
if (dev->core->tvnorm & V4L2_STD_525_60) {
/* ntsc */
f->fmt.vbi.sampling_rate = 28636363;
f->fmt.vbi.start[0] = 10;
f->fmt.vbi.start[1] = 273;
} else if (dev->core->tvnorm & V4L2_STD_625_50) {
/* pal */
f->fmt.vbi.sampling_rate = 35468950;
f->fmt.vbi.start[0] = 7 -1;
f->fmt.vbi.start[1] = 319 -1;
}
return 0;
}
static int cx8800_start_vbi_dma(struct cx8800_dev *dev,
struct cx88_dmaqueue *q,
struct cx88_buffer *buf)
{
struct cx88_core *core = dev->core;
/* setup fifo + format */
cx88_sram_channel_setup(dev->core, &cx88_sram_channels[SRAM_CH24],
buf->vb.width, buf->risc.dma);
cx_write(MO_VBOS_CONTROL, ( (1 << 18) | // comb filter delay fixup
(1 << 15) | // enable vbi capture
(1 << 11) ));
/* reset counter */
cx_write(MO_VBI_GPCNTRL, GP_COUNT_CONTROL_RESET);
q->count = 1;
/* enable irqs */
cx_set(MO_PCI_INTMSK, core->pci_irqmask | PCI_INT_VIDINT);
cx_set(MO_VID_INTMSK, 0x0f0088);
/* enable capture */
cx_set(VID_CAPTURE_CONTROL,0x18);
/* start dma */
cx_set(MO_DEV_CNTRL2, (1<<5));
cx_set(MO_VID_DMACNTRL, 0x88);
return 0;
}
int cx8800_stop_vbi_dma(struct cx8800_dev *dev)
{
struct cx88_core *core = dev->core;
/* stop dma */
cx_clear(MO_VID_DMACNTRL, 0x88);
/* disable capture */
cx_clear(VID_CAPTURE_CONTROL,0x18);
/* disable irqs */
cx_clear(MO_PCI_INTMSK, PCI_INT_VIDINT);
cx_clear(MO_VID_INTMSK, 0x0f0088);
return 0;
}
int cx8800_restart_vbi_queue(struct cx8800_dev *dev,
struct cx88_dmaqueue *q)
{
struct cx88_buffer *buf;
if (list_empty(&q->active))
return 0;
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
dprintk(2,"restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx8800_start_vbi_dma(dev, q, buf);
list_for_each_entry(buf, &q->active, vb.queue)
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
void cx8800_vbi_timeout(unsigned long data)
{
struct cx8800_dev *dev = (struct cx8800_dev*)data;
struct cx88_core *core = dev->core;
struct cx88_dmaqueue *q = &dev->vbiq;
struct cx88_buffer *buf;
unsigned long flags;
cx88_sram_channel_dump(dev->core, &cx88_sram_channels[SRAM_CH24]);
cx_clear(MO_VID_DMACNTRL, 0x88);
cx_clear(VID_CAPTURE_CONTROL, 0x18);
spin_lock_irqsave(&dev->slock,flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
printk("%s/0: [%p/%d] timeout - dma=0x%08lx\n", dev->core->name,
buf, buf->vb.i, (unsigned long)buf->risc.dma);
}
cx8800_restart_vbi_queue(dev,q);
spin_unlock_irqrestore(&dev->slock,flags);
}
/* ------------------------------------------------------------------ */
static int
vbi_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
{
*size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 == *count)
*count = vbibufs;
if (*count < 2)
*count = 2;
if (*count > 32)
*count = 32;
return 0;
}
static int
vbi_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct cx8800_fh *fh = q->priv_data;
struct cx8800_dev *dev = fh->dev;
struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb);
unsigned int size;
int rc;
size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
struct videobuf_dmabuf *dma=videobuf_to_dma(&buf->vb);
buf->vb.width = VBI_LINE_LENGTH;
buf->vb.height = VBI_LINE_COUNT;
buf->vb.size = size;
buf->vb.field = V4L2_FIELD_SEQ_TB;
if (0 != (rc = videobuf_iolock(q,&buf->vb,NULL)))
goto fail;
cx88_risc_buffer(dev->pci, &buf->risc,
dma->sglist,
0, buf->vb.width * buf->vb.height,
buf->vb.width, 0,
buf->vb.height);
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx88_free_buffer(q,buf);
return rc;
}
static void
vbi_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb);
struct cx88_buffer *prev;
struct cx8800_fh *fh = vq->priv_data;
struct cx8800_dev *dev = fh->dev;
struct cx88_dmaqueue *q = &dev->vbiq;
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma);
if (list_empty(&q->active)) {
list_add_tail(&buf->vb.queue,&q->active);
cx8800_start_vbi_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2,"[%p/%d] vbi_queue - first active\n",
buf, buf->vb.i);
} else {
prev = list_entry(q->active.prev, struct cx88_buffer, vb.queue);
list_add_tail(&buf->vb.queue,&q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
dprintk(2,"[%p/%d] buffer_queue - append to active\n",
buf, buf->vb.i);
}
}
static void vbi_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb);
cx88_free_buffer(q,buf);
}
struct videobuf_queue_ops cx8800_vbi_qops = {
.buf_setup = vbi_setup,
.buf_prepare = vbi_prepare,
.buf_queue = vbi_queue,
.buf_release = vbi_release,
};
/* ------------------------------------------------------------------ */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
|
felixhaedicke/nst-kernel
|
src/drivers/media/video/cx88/cx88-vbi.c
|
C
|
gpl-2.0
| 6,438
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Bootstrap Admin Theme</title>
<!-- Bootstrap Core CSS -->
<link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<!-- Social Buttons CSS -->
<link href="../bower_components/bootstrap-social/bootstrap-social.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">SB Admin v2.0</a>
</div>
<!-- /.navbar-header -->
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>Read All Messages</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-messages -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-tasks">
<li>
<a href="#">
<div>
<p>
<strong>Task 1</strong>
<span class="pull-right text-muted">40% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 2</strong>
<span class="pull-right text-muted">20% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
<span class="sr-only">20% Complete</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 3</strong>
<span class="pull-right text-muted">60% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<p>
<strong>Task 4</strong>
<span class="pull-right text-muted">80% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%">
<span class="sr-only">80% Complete (danger)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Tasks</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-tasks -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="#">
<div>
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-twitter fa-fw"></i> 3 New Followers
<span class="pull-right text-muted small">12 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-envelope fa-fw"></i> Message Sent
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-tasks fa-fw"></i> New Task
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<div>
<i class="fa fa-upload fa-fw"></i> Server Rebooted
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Alerts</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-alerts -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a>
</li>
<li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a>
</li>
<li class="divider"></li>
<li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<!-- /input-group -->
</li>
<li>
<a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Charts<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="flot.html">Flot Charts</a>
</li>
<li>
<a href="morris.html">Morris.js Charts</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="tables.html"><i class="fa fa-table fa-fw"></i> Tables</a>
</li>
<li>
<a href="forms.html"><i class="fa fa-edit fa-fw"></i> Forms</a>
</li>
<li>
<a href="#"><i class="fa fa-wrench fa-fw"></i> UI Elements<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="panels-wells.html">Panels and Wells</a>
</li>
<li>
<a href="buttons.html">Buttons</a>
</li>
<li>
<a href="notifications.html">Notifications</a>
</li>
<li>
<a href="typography.html">Typography</a>
</li>
<li>
<a href="icons.html"> Icons</a>
</li>
<li>
<a href="grid.html">Grid</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-sitemap fa-fw"></i> Multi-Level Dropdown<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Second Level Item</a>
</li>
<li>
<a href="#">Third Level <span class="fa arrow"></span></a>
<ul class="nav nav-third-level">
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
<li>
<a href="#">Third Level Item</a>
</li>
</ul>
<!-- /.nav-third-level -->
</li>
</ul>
<!-- /.nav-second-level -->
</li>
<li>
<a href="#"><i class="fa fa-files-o fa-fw"></i> Sample Pages<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="blank.html">Blank Page</a>
</li>
<li>
<a href="login.html">Login Page</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side -->
</nav>
<!-- Page Content -->
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Buttons</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Default Buttons
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<h4>Normal Buttons</h4>
<p>
<button type="button" class="btn btn-default">Default</button>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-link">Link</button>
</p>
<br>
<h4>Disabled Buttons</h4>
<p>
<button type="button" class="btn btn-default disabled">Default</button>
<button type="button" class="btn btn-primary disabled">Primary</button>
<button type="button" class="btn btn-success disabled">Success</button>
<button type="button" class="btn btn-info disabled">Info</button>
<button type="button" class="btn btn-warning disabled">Warning</button>
<button type="button" class="btn btn-danger disabled">Danger</button>
<button type="button" class="btn btn-link disabled">Link</button>
</p>
<br>
<h4>Button Sizes</h4>
<p>
<button type="button" class="btn btn-primary btn-lg">Large button</button>
<button type="button" class="btn btn-primary">Default button</button>
<button type="button" class="btn btn-primary btn-sm">Small button</button>
<button type="button" class="btn btn-primary btn-xs">Mini button</button>
<br>
<br>
<button type="button" class="btn btn-primary btn-lg btn-block">Block level button</button>
</p>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="panel panel-default">
<div class="panel-heading">
Circle Icon Buttons with Font Awesome Icons
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<h4>Normal Circle Buttons</h4>
<button type="button" class="btn btn-default btn-circle"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-primary btn-circle"><i class="fa fa-list"></i>
</button>
<button type="button" class="btn btn-success btn-circle"><i class="fa fa-link"></i>
</button>
<button type="button" class="btn btn-info btn-circle"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-warning btn-circle"><i class="fa fa-times"></i>
</button>
<button type="button" class="btn btn-danger btn-circle"><i class="fa fa-heart"></i>
</button>
<br>
<br>
<h4>Large Circle Buttons</h4>
<button type="button" class="btn btn-default btn-circle btn-lg"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-primary btn-circle btn-lg"><i class="fa fa-list"></i>
</button>
<button type="button" class="btn btn-success btn-circle btn-lg"><i class="fa fa-link"></i>
</button>
<button type="button" class="btn btn-info btn-circle btn-lg"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-warning btn-circle btn-lg"><i class="fa fa-times"></i>
</button>
<button type="button" class="btn btn-danger btn-circle btn-lg"><i class="fa fa-heart"></i>
</button>
<br>
<br>
<h4>Extra Large Circle Buttons</h4>
<button type="button" class="btn btn-default btn-circle btn-xl"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-primary btn-circle btn-xl"><i class="fa fa-list"></i>
</button>
<button type="button" class="btn btn-success btn-circle btn-xl"><i class="fa fa-link"></i>
</button>
<button type="button" class="btn btn-info btn-circle btn-xl"><i class="fa fa-check"></i>
</button>
<button type="button" class="btn btn-warning btn-circle btn-xl"><i class="fa fa-times"></i>
</button>
<button type="button" class="btn btn-danger btn-circle btn-xl"><i class="fa fa-heart"></i>
</button>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Outline Buttons with Smooth Transition
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<h4>Outline Buttons</h4>
<p>
<button type="button" class="btn btn-outline btn-default">Default</button>
<button type="button" class="btn btn-outline btn-primary">Primary</button>
<button type="button" class="btn btn-outline btn-success">Success</button>
<button type="button" class="btn btn-outline btn-info">Info</button>
<button type="button" class="btn btn-outline btn-warning">Warning</button>
<button type="button" class="btn btn-outline btn-danger">Danger</button>
<button type="button" class="btn btn-outline btn-link">Link</button>
</p>
<br>
<h4>Outline Button Sizes</h4>
<p>
<button type="button" class="btn btn-outline btn-primary btn-lg">Large button</button>
<button type="button" class="btn btn-outline btn-primary">Default button</button>
<button type="button" class="btn btn-outline btn-primary btn-sm">Small button</button>
<button type="button" class="btn btn-outline btn-primary btn-xs">Mini button</button>
<br>
<br>
<button type="button" class="btn btn-outline btn-primary btn-lg btn-block">Block level button</button>
</p>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="panel panel-default">
<div class="panel-heading">
Social Buttons with Font Awesome Icons
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<h4>Social Buttons</h4>
<a class="btn btn-block btn-social btn-bitbucket">
<i class="fa fa-bitbucket"></i> Sign in with Bitbucket
</a>
<a class="btn btn-block btn-social btn-dropbox">
<i class="fa fa-dropbox"></i> Sign in with Dropbox
</a>
<a class="btn btn-block btn-social btn-facebook">
<i class="fa fa-facebook"></i> Sign in with Facebook
</a>
<a class="btn btn-block btn-social btn-flickr">
<i class="fa fa-flickr"></i> Sign in with Flickr
</a>
<a class="btn btn-block btn-social btn-github">
<i class="fa fa-github"></i> Sign in with GitHub
</a>
<a class="btn btn-block btn-social btn-google-plus">
<i class="fa fa-google-plus"></i> Sign in with Google
</a>
<a class="btn btn-block btn-social btn-instagram">
<i class="fa fa-instagram"></i> Sign in with Instagram
</a>
<a class="btn btn-block btn-social btn-linkedin">
<i class="fa fa-linkedin"></i> Sign in with LinkedIn
</a>
<a class="btn btn-block btn-social btn-pinterest">
<i class="fa fa-pinterest"></i> Sign in with Pinterest
</a>
<a class="btn btn-block btn-social btn-tumblr">
<i class="fa fa-tumblr"></i> Sign in with Tumblr
</a>
<a class="btn btn-block btn-social btn-twitter">
<i class="fa fa-twitter"></i> Sign in with Twitter
</a>
<a class="btn btn-block btn-social btn-vk">
<i class="fa fa-vk"></i> Sign in with VK
</a>
<hr>
<div class="text-center">
<a class="btn btn-social-icon btn-bitbucket"><i class="fa fa-bitbucket"></i></a>
<a class="btn btn-social-icon btn-dropbox"><i class="fa fa-dropbox"></i></a>
<a class="btn btn-social-icon btn-facebook"><i class="fa fa-facebook"></i></a>
<a class="btn btn-social-icon btn-flickr"><i class="fa fa-flickr"></i></a>
<a class="btn btn-social-icon btn-github"><i class="fa fa-github"></i></a>
<a class="btn btn-social-icon btn-google-plus"><i class="fa fa-google-plus"></i></a>
<a class="btn btn-social-icon btn-instagram"><i class="fa fa-instagram"></i></a>
<a class="btn btn-social-icon btn-linkedin"><i class="fa fa-linkedin"></i></a>
<a class="btn btn-social-icon btn-pinterest"><i class="fa fa-pinterest"></i></a>
<a class="btn btn-social-icon btn-tumblr"><i class="fa fa-tumblr"></i></a>
<a class="btn btn-social-icon btn-twitter"><i class="fa fa-twitter"></i></a>
<a class="btn btn-social-icon btn-vk"><i class="fa fa-vk"></i></a>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
</body>
</html>
|
keepeye/fragments
|
前端/模板/后台模板/sb-admin-2-1.0.7/pages/buttons.html
|
HTML
|
mit
| 32,435
|
$(function () {
'use strict';
module('affix plugin')
test('should be defined on jquery object', function () {
ok($(document.body).affix, 'affix method is defined')
})
module('affix', {
setup: function () {
// Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode
$.fn.bootstrapAffix = $.fn.affix.noConflict()
},
teardown: function () {
$.fn.affix = $.fn.bootstrapAffix
delete $.fn.bootstrapAffix
}
})
test('should provide no conflict', function () {
strictEqual($.fn.affix, undefined, 'affix was set back to undefined (org value)')
})
test('should return jquery collection containing the element', function () {
var $el = $('<div/>')
var $affix = $el.bootstrapAffix()
ok($affix instanceof $, 'returns jquery collection')
strictEqual($affix[0], $el[0], 'collection contains element')
})
test('should exit early if element is not visible', function () {
var $affix = $('<div style="display: none"/>').bootstrapAffix()
$affix.data('bs.affix').checkPosition()
ok(!$affix.hasClass('affix'), 'affix class was not added')
})
test('should trigger affixed event after affix', function () {
stop()
var templateHTML = '<div id="affixTarget">'
+ '<ul>'
+ '<li>Please affix</li>'
+ '<li>And unaffix</li>'
+ '</ul>'
+ '</div>'
+ '<div id="affixAfter" style="height: 20000px; display: block;"/>'
$(templateHTML).appendTo(document.body)
$('#affixTarget').bootstrapAffix({
offset: $('#affixTarget ul').position()
})
$('#affixTarget')
.on('affix.bs.affix', function () {
ok(true, 'affix event fired')
}).on('affixed.bs.affix', function () {
ok(true, 'affixed event fired')
$('#affixTarget, #affixAfter').remove()
start()
})
setTimeout(function () {
window.scrollTo(0, document.body.scrollHeight)
setTimeout(function () {
window.scroll(0, 0)
}, 16) // for testing in a browser
}, 0)
})
})
|
jackTheRipper/chat_nodejs
|
www/node_modules/bootstrap/js/tests/unit/affix.js
|
JavaScript
|
apache-2.0
| 2,099
|
/*
* rsrc_mgr.c -- Resource management routines and/or wrappers
*
* 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.
*
* The initial developer of the original code is David A. Hinds
* <dahinds@users.sourceforge.net>. Portions created by David A. Hinds
* are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
*
* (C) 1999 David A. Hinds
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <pcmcia/cs_types.h>
#include <pcmcia/ss.h>
#include <pcmcia/cs.h>
#include <pcmcia/cistpl.h>
#include "cs_internal.h"
int static_init(struct pcmcia_socket *s)
{
/* the good thing about SS_CAP_STATIC_MAP sockets is
* that they don't need a resource database */
s->resource_setup_done = 1;
return 0;
}
struct resource *pcmcia_make_resource(unsigned long start, unsigned long end,
int flags, const char *name)
{
struct resource *res = kzalloc(sizeof(*res), GFP_KERNEL);
if (res) {
res->name = name;
res->start = start;
res->end = start + end - 1;
res->flags = flags;
}
return res;
}
static int static_find_io(struct pcmcia_socket *s, unsigned int attr,
unsigned int *base, unsigned int num,
unsigned int align)
{
if (!s->io_offset)
return -EINVAL;
*base = s->io_offset | (*base & 0x0fff);
return 0;
}
struct pccard_resource_ops pccard_static_ops = {
.validate_mem = NULL,
.find_io = static_find_io,
.find_mem = NULL,
.add_io = NULL,
.add_mem = NULL,
.init = static_init,
.exit = NULL,
};
EXPORT_SYMBOL(pccard_static_ops);
MODULE_AUTHOR("David A. Hinds, Dominik Brodowski");
MODULE_LICENSE("GPL");
MODULE_ALIAS("rsrc_nonstatic");
|
KOala888/GB_kernel
|
linux_kernel_galaxyplayer-master/drivers/pcmcia/rsrc_mgr.c
|
C
|
gpl-2.0
| 1,756
|
require('../modules/es6.object.to-string');
require('../modules/web.dom.iterable');
require('../modules/es6.weak-map');
module.exports = require('../modules/$.core').WeakMap;
|
yuyang545262477/Resume
|
项目三jQueryMobile/node_modules/core-js/library/fn/weak-map.js
|
JavaScript
|
mit
| 174
|
/*
* fs/cifs/cifsglob.h
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French (sfrench@us.ibm.com)
* Jeremy Allison (jra@samba.org)
*
* 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.
*
*/
#ifndef _CIFS_GLOB_H
#define _CIFS_GLOB_H
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/slab.h>
#include <linux/mempool.h>
#include <linux/workqueue.h>
#include "cifs_fs_sb.h"
#include "cifsacl.h"
#include <crypto/internal/hash.h>
#include <linux/scatterlist.h>
#ifdef CONFIG_CIFS_SMB2
#include "smb2pdu.h"
#endif
#define CIFS_MAGIC_NUMBER 0xFF534D42 /* the first four bytes of SMB PDUs */
/*
* The sizes of various internal tables and strings
*/
#define MAX_UID_INFO 16
#define MAX_SES_INFO 2
#define MAX_TCON_INFO 4
#define MAX_TREE_SIZE (2 + MAX_SERVER_SIZE + 1 + MAX_SHARE_SIZE + 1)
#define MAX_SERVER_SIZE 15
#define MAX_SHARE_SIZE 80
#define CIFS_MAX_DOMAINNAME_LEN 256 /* max domain name length */
#define MAX_USERNAME_SIZE 256 /* reasonable maximum for current servers */
#define MAX_PASSWORD_SIZE 512 /* max for windows seems to be 256 wide chars */
#define CIFS_MIN_RCV_POOL 4
#define MAX_REOPEN_ATT 5 /* these many maximum attempts to reopen a file */
/*
* default attribute cache timeout (jiffies)
*/
#define CIFS_DEF_ACTIMEO (1 * HZ)
/*
* max attribute cache timeout (jiffies) - 2^30
*/
#define CIFS_MAX_ACTIMEO (1 << 30)
/*
* MAX_REQ is the maximum number of requests that WE will send
* on one socket concurrently.
*/
#define CIFS_MAX_REQ 32767
#define RFC1001_NAME_LEN 15
#define RFC1001_NAME_LEN_WITH_NULL (RFC1001_NAME_LEN + 1)
/* currently length of NIP6_FMT */
#define SERVER_NAME_LENGTH 40
#define SERVER_NAME_LEN_WITH_NULL (SERVER_NAME_LENGTH + 1)
/* SMB echo "timeout" -- FIXME: tunable? */
#define SMB_ECHO_INTERVAL (60 * HZ)
#include "cifspdu.h"
#ifndef XATTR_DOS_ATTRIB
#define XATTR_DOS_ATTRIB "user.DOSATTRIB"
#endif
/*
* CIFS vfs client Status information (based on what we know.)
*/
/* associated with each tcp and smb session */
enum statusEnum {
CifsNew = 0,
CifsGood,
CifsExiting,
CifsNeedReconnect,
CifsNeedNegotiate
};
enum securityEnum {
LANMAN = 0, /* Legacy LANMAN auth */
NTLM, /* Legacy NTLM012 auth with NTLM hash */
NTLMv2, /* Legacy NTLM auth with NTLMv2 hash */
RawNTLMSSP, /* NTLMSSP without SPNEGO, NTLMv2 hash */
/* NTLMSSP, */ /* can use rawNTLMSSP instead of NTLMSSP via SPNEGO */
Kerberos, /* Kerberos via SPNEGO */
};
enum protocolEnum {
TCP = 0,
SCTP
/* Netbios frames protocol not supported at this time */
};
struct session_key {
unsigned int len;
char *response;
};
/* crypto security descriptor definition */
struct sdesc {
struct shash_desc shash;
char ctx[];
};
/* crypto hashing related structure/fields, not specific to a sec mech */
struct cifs_secmech {
struct crypto_shash *hmacmd5; /* hmac-md5 hash function */
struct crypto_shash *md5; /* md5 hash function */
struct crypto_shash *hmacsha256; /* hmac-sha256 hash function */
struct sdesc *sdeschmacmd5; /* ctxt to generate ntlmv2 hash, CR1 */
struct sdesc *sdescmd5; /* ctxt to generate cifs/smb signature */
struct sdesc *sdeschmacsha256; /* ctxt to generate smb2 signature */
};
/* per smb session structure/fields */
struct ntlmssp_auth {
__u32 client_flags; /* sent by client in type 1 ntlmsssp exchange */
__u32 server_flags; /* sent by server in type 2 ntlmssp exchange */
unsigned char ciphertext[CIFS_CPHTXT_SIZE]; /* sent to server */
char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlmssp */
};
struct cifs_cred {
int uid;
int gid;
int mode;
int cecount;
struct cifs_sid osid;
struct cifs_sid gsid;
struct cifs_ntace *ntaces;
struct cifs_ace *aces;
};
/*
*****************************************************************
* Except the CIFS PDUs themselves all the
* globally interesting structs should go here
*****************************************************************
*/
/*
* A smb_rqst represents a complete request to be issued to a server. It's
* formed by a kvec array, followed by an array of pages. Page data is assumed
* to start at the beginning of the first page.
*/
struct smb_rqst {
struct kvec *rq_iov; /* array of kvecs */
unsigned int rq_nvec; /* number of kvecs in array */
struct page **rq_pages; /* pointer to array of page ptrs */
unsigned int rq_npages; /* number pages in array */
unsigned int rq_pagesz; /* page size to use */
unsigned int rq_tailsz; /* length of last page */
};
enum smb_version {
Smb_1 = 1,
Smb_20,
Smb_21,
Smb_30,
};
struct mid_q_entry;
struct TCP_Server_Info;
struct cifsFileInfo;
struct cifs_ses;
struct cifs_tcon;
struct dfs_info3_param;
struct cifs_fattr;
struct smb_vol;
struct cifs_fid;
struct cifs_readdata;
struct cifs_writedata;
struct cifs_io_parms;
struct cifs_search_info;
struct cifsInodeInfo;
struct smb_version_operations {
int (*send_cancel)(struct TCP_Server_Info *, void *,
struct mid_q_entry *);
bool (*compare_fids)(struct cifsFileInfo *, struct cifsFileInfo *);
/* setup request: allocate mid, sign message */
struct mid_q_entry *(*setup_request)(struct cifs_ses *,
struct smb_rqst *);
/* setup async request: allocate mid, sign message */
struct mid_q_entry *(*setup_async_request)(struct TCP_Server_Info *,
struct smb_rqst *);
/* check response: verify signature, map error */
int (*check_receive)(struct mid_q_entry *, struct TCP_Server_Info *,
bool);
void (*add_credits)(struct TCP_Server_Info *, const unsigned int,
const int);
void (*set_credits)(struct TCP_Server_Info *, const int);
int * (*get_credits_field)(struct TCP_Server_Info *, const int);
unsigned int (*get_credits)(struct mid_q_entry *);
__u64 (*get_next_mid)(struct TCP_Server_Info *);
/* data offset from read response message */
unsigned int (*read_data_offset)(char *);
/* data length from read response message */
unsigned int (*read_data_length)(char *);
/* map smb to linux error */
int (*map_error)(char *, bool);
/* find mid corresponding to the response message */
struct mid_q_entry * (*find_mid)(struct TCP_Server_Info *, char *);
void (*dump_detail)(void *);
void (*clear_stats)(struct cifs_tcon *);
void (*print_stats)(struct seq_file *m, struct cifs_tcon *);
/* verify the message */
int (*check_message)(char *, unsigned int);
bool (*is_oplock_break)(char *, struct TCP_Server_Info *);
/* process transaction2 response */
bool (*check_trans2)(struct mid_q_entry *, struct TCP_Server_Info *,
char *, int);
/* check if we need to negotiate */
bool (*need_neg)(struct TCP_Server_Info *);
/* negotiate to the server */
int (*negotiate)(const unsigned int, struct cifs_ses *);
/* set negotiated write size */
unsigned int (*negotiate_wsize)(struct cifs_tcon *, struct smb_vol *);
/* set negotiated read size */
unsigned int (*negotiate_rsize)(struct cifs_tcon *, struct smb_vol *);
/* setup smb sessionn */
int (*sess_setup)(const unsigned int, struct cifs_ses *,
const struct nls_table *);
/* close smb session */
int (*logoff)(const unsigned int, struct cifs_ses *);
/* connect to a server share */
int (*tree_connect)(const unsigned int, struct cifs_ses *, const char *,
struct cifs_tcon *, const struct nls_table *);
/* close tree connecion */
int (*tree_disconnect)(const unsigned int, struct cifs_tcon *);
/* get DFS referrals */
int (*get_dfs_refer)(const unsigned int, struct cifs_ses *,
const char *, struct dfs_info3_param **,
unsigned int *, const struct nls_table *, int);
/* informational QFS call */
void (*qfs_tcon)(const unsigned int, struct cifs_tcon *);
/* check if a path is accessible or not */
int (*is_path_accessible)(const unsigned int, struct cifs_tcon *,
struct cifs_sb_info *, const char *);
/* query path data from the server */
int (*query_path_info)(const unsigned int, struct cifs_tcon *,
struct cifs_sb_info *, const char *,
FILE_ALL_INFO *, bool *);
/* query file data from the server */
int (*query_file_info)(const unsigned int, struct cifs_tcon *,
struct cifs_fid *, FILE_ALL_INFO *);
/* get server index number */
int (*get_srv_inum)(const unsigned int, struct cifs_tcon *,
struct cifs_sb_info *, const char *,
u64 *uniqueid, FILE_ALL_INFO *);
/* set size by path */
int (*set_path_size)(const unsigned int, struct cifs_tcon *,
const char *, __u64, struct cifs_sb_info *, bool);
/* set size by file handle */
int (*set_file_size)(const unsigned int, struct cifs_tcon *,
struct cifsFileInfo *, __u64, bool);
/* set attributes */
int (*set_file_info)(struct inode *, const char *, FILE_BASIC_INFO *,
const unsigned int);
/* check if we can send an echo or nor */
bool (*can_echo)(struct TCP_Server_Info *);
/* send echo request */
int (*echo)(struct TCP_Server_Info *);
/* create directory */
int (*mkdir)(const unsigned int, struct cifs_tcon *, const char *,
struct cifs_sb_info *);
/* set info on created directory */
void (*mkdir_setinfo)(struct inode *, const char *,
struct cifs_sb_info *, struct cifs_tcon *,
const unsigned int);
/* remove directory */
int (*rmdir)(const unsigned int, struct cifs_tcon *, const char *,
struct cifs_sb_info *);
/* unlink file */
int (*unlink)(const unsigned int, struct cifs_tcon *, const char *,
struct cifs_sb_info *);
/* open, rename and delete file */
int (*rename_pending_delete)(const char *, struct dentry *,
const unsigned int);
/* send rename request */
int (*rename)(const unsigned int, struct cifs_tcon *, const char *,
const char *, struct cifs_sb_info *);
/* send create hardlink request */
int (*create_hardlink)(const unsigned int, struct cifs_tcon *,
const char *, const char *,
struct cifs_sb_info *);
/* open a file for non-posix mounts */
int (*open)(const unsigned int, struct cifs_tcon *, const char *, int,
int, int, struct cifs_fid *, __u32 *, FILE_ALL_INFO *,
struct cifs_sb_info *);
/* set fid protocol-specific info */
void (*set_fid)(struct cifsFileInfo *, struct cifs_fid *, __u32);
/* close a file */
void (*close)(const unsigned int, struct cifs_tcon *,
struct cifs_fid *);
/* send a flush request to the server */
int (*flush)(const unsigned int, struct cifs_tcon *, struct cifs_fid *);
/* async read from the server */
int (*async_readv)(struct cifs_readdata *);
/* async write to the server */
int (*async_writev)(struct cifs_writedata *);
/* sync read from the server */
int (*sync_read)(const unsigned int, struct cifsFileInfo *,
struct cifs_io_parms *, unsigned int *, char **,
int *);
/* sync write to the server */
int (*sync_write)(const unsigned int, struct cifsFileInfo *,
struct cifs_io_parms *, unsigned int *, struct kvec *,
unsigned long);
/* open dir, start readdir */
int (*query_dir_first)(const unsigned int, struct cifs_tcon *,
const char *, struct cifs_sb_info *,
struct cifs_fid *, __u16,
struct cifs_search_info *);
/* continue readdir */
int (*query_dir_next)(const unsigned int, struct cifs_tcon *,
struct cifs_fid *,
__u16, struct cifs_search_info *srch_inf);
/* close dir */
int (*close_dir)(const unsigned int, struct cifs_tcon *,
struct cifs_fid *);
/* calculate a size of SMB message */
unsigned int (*calc_smb_size)(void *);
/* check for STATUS_PENDING and process it in a positive case */
bool (*is_status_pending)(char *, struct TCP_Server_Info *, int);
/* send oplock break response */
int (*oplock_response)(struct cifs_tcon *, struct cifs_fid *,
struct cifsInodeInfo *);
/* query remote filesystem */
int (*queryfs)(const unsigned int, struct cifs_tcon *,
struct kstatfs *);
/* send mandatory brlock to the server */
int (*mand_lock)(const unsigned int, struct cifsFileInfo *, __u64,
__u64, __u32, int, int, bool);
/* unlock range of mandatory locks */
int (*mand_unlock_range)(struct cifsFileInfo *, struct file_lock *,
const unsigned int);
/* push brlocks from the cache to the server */
int (*push_mand_locks)(struct cifsFileInfo *);
/* get lease key of the inode */
void (*get_lease_key)(struct inode *, struct cifs_fid *fid);
/* set lease key of the inode */
void (*set_lease_key)(struct inode *, struct cifs_fid *fid);
/* generate new lease key */
void (*new_lease_key)(struct cifs_fid *fid);
int (*calc_signature)(struct smb_rqst *rqst,
struct TCP_Server_Info *server);
ssize_t (*query_all_EAs)(const unsigned int, struct cifs_tcon *,
const unsigned char *, const unsigned char *, char *,
size_t, const struct nls_table *, int);
int (*set_EA)(const unsigned int, struct cifs_tcon *, const char *,
const char *, const void *, const __u16,
const struct nls_table *, int);
struct cifs_ntsd * (*get_acl)(struct cifs_sb_info *, struct inode *,
const char *, u32 *);
int (*set_acl)(struct cifs_ntsd *, __u32, struct inode *, const char *,
int);
/* check if we need to issue closedir */
bool (*dir_needs_close)(struct cifsFileInfo *);
};
struct smb_version_values {
char *version_string;
__u16 protocol_id;
__u32 req_capabilities;
__u32 large_lock_type;
__u32 exclusive_lock_type;
__u32 shared_lock_type;
__u32 unlock_lock_type;
size_t header_size;
size_t max_header_size;
size_t read_rsp_size;
__le16 lock_cmd;
unsigned int cap_unix;
unsigned int cap_nt_find;
unsigned int cap_large_files;
unsigned int oplock_read;
};
#define HEADER_SIZE(server) (server->vals->header_size)
#define MAX_HEADER_SIZE(server) (server->vals->max_header_size)
struct smb_vol {
char *username;
char *password;
char *domainname;
char *UNC;
char *iocharset; /* local code page for mapping to and from Unicode */
char source_rfc1001_name[RFC1001_NAME_LEN_WITH_NULL]; /* clnt nb name */
char target_rfc1001_name[RFC1001_NAME_LEN_WITH_NULL]; /* srvr nb name */
kuid_t cred_uid;
kuid_t linux_uid;
kgid_t linux_gid;
kuid_t backupuid;
kgid_t backupgid;
umode_t file_mode;
umode_t dir_mode;
unsigned secFlg;
bool retry:1;
bool intr:1;
bool setuids:1;
bool override_uid:1;
bool override_gid:1;
bool dynperm:1;
bool noperm:1;
bool no_psx_acl:1; /* set if posix acl support should be disabled */
bool cifs_acl:1;
bool backupuid_specified; /* mount option backupuid is specified */
bool backupgid_specified; /* mount option backupgid is specified */
bool no_xattr:1; /* set if xattr (EA) support should be disabled*/
bool server_ino:1; /* use inode numbers from server ie UniqueId */
bool direct_io:1;
bool strict_io:1; /* strict cache behavior */
bool remap:1; /* set to remap seven reserved chars in filenames */
bool posix_paths:1; /* unset to not ask for posix pathnames. */
bool no_linux_ext:1;
bool sfu_emul:1;
bool nullauth:1; /* attempt to authenticate with null user */
bool nocase:1; /* request case insensitive filenames */
bool nobrl:1; /* disable sending byte range locks to srv */
bool mand_lock:1; /* send mandatory not posix byte range lock reqs */
bool seal:1; /* request transport encryption on share */
bool nodfs:1; /* Do not request DFS, even if available */
bool local_lease:1; /* check leases only on local system, not remote */
bool noblocksnd:1;
bool noautotune:1;
bool nostrictsync:1; /* do not force expensive SMBflush on every sync */
bool fsc:1; /* enable fscache */
bool mfsymlinks:1; /* use Minshall+French Symlinks */
bool multiuser:1;
bool rwpidforward:1; /* pid forward for read/write operations */
unsigned int rsize;
unsigned int wsize;
bool sockopt_tcp_nodelay:1;
unsigned long actimeo; /* attribute cache timeout (jiffies) */
struct smb_version_operations *ops;
struct smb_version_values *vals;
char *prepath;
struct sockaddr_storage dstaddr; /* destination address */
struct sockaddr_storage srcaddr; /* allow binding to a local IP */
struct nls_table *local_nls;
};
#define CIFS_MOUNT_MASK (CIFS_MOUNT_NO_PERM | CIFS_MOUNT_SET_UID | \
CIFS_MOUNT_SERVER_INUM | CIFS_MOUNT_DIRECT_IO | \
CIFS_MOUNT_NO_XATTR | CIFS_MOUNT_MAP_SPECIAL_CHR | \
CIFS_MOUNT_UNX_EMUL | CIFS_MOUNT_NO_BRL | \
CIFS_MOUNT_CIFS_ACL | CIFS_MOUNT_OVERR_UID | \
CIFS_MOUNT_OVERR_GID | CIFS_MOUNT_DYNPERM | \
CIFS_MOUNT_NOPOSIXBRL | CIFS_MOUNT_NOSSYNC | \
CIFS_MOUNT_FSCACHE | CIFS_MOUNT_MF_SYMLINKS | \
CIFS_MOUNT_MULTIUSER | CIFS_MOUNT_STRICT_IO | \
CIFS_MOUNT_CIFS_BACKUPUID | CIFS_MOUNT_CIFS_BACKUPGID)
#define CIFS_MS_MASK (MS_RDONLY | MS_MANDLOCK | MS_NOEXEC | MS_NOSUID | \
MS_NODEV | MS_SYNCHRONOUS)
struct cifs_mnt_data {
struct cifs_sb_info *cifs_sb;
struct smb_vol *vol;
int flags;
};
static inline unsigned int
get_rfc1002_length(void *buf)
{
return be32_to_cpu(*((__be32 *)buf));
}
static inline void
inc_rfc1001_len(void *buf, int count)
{
be32_add_cpu((__be32 *)buf, count);
}
struct TCP_Server_Info {
struct list_head tcp_ses_list;
struct list_head smb_ses_list;
int srv_count; /* reference counter */
/* 15 character server name + 0x20 16th byte indicating type = srv */
char server_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
struct smb_version_operations *ops;
struct smb_version_values *vals;
enum statusEnum tcpStatus; /* what we think the status is */
char *hostname; /* hostname portion of UNC string */
struct socket *ssocket;
struct sockaddr_storage dstaddr;
struct sockaddr_storage srcaddr; /* locally bind to this IP */
#ifdef CONFIG_NET_NS
struct net *net;
#endif
wait_queue_head_t response_q;
wait_queue_head_t request_q; /* if more than maxmpx to srvr must block*/
struct list_head pending_mid_q;
bool noblocksnd; /* use blocking sendmsg */
bool noautotune; /* do not autotune send buf sizes */
bool tcp_nodelay;
int credits; /* send no more requests at once */
unsigned int in_flight; /* number of requests on the wire to server */
spinlock_t req_lock; /* protect the two values above */
struct mutex srv_mutex;
struct task_struct *tsk;
char server_GUID[16];
__u16 sec_mode;
bool session_estab; /* mark when very first sess is established */
#ifdef CONFIG_CIFS_SMB2
int echo_credits; /* echo reserved slots */
int oplock_credits; /* oplock break reserved slots */
bool echoes:1; /* enable echoes */
#endif
u16 dialect; /* dialect index that server chose */
enum securityEnum secType;
bool oplocks:1; /* enable oplocks */
unsigned int maxReq; /* Clients should submit no more */
/* than maxReq distinct unanswered SMBs to the server when using */
/* multiplexed reads or writes */
unsigned int maxBuf; /* maxBuf specifies the maximum */
/* message size the server can send or receive for non-raw SMBs */
/* maxBuf is returned by SMB NegotiateProtocol so maxBuf is only 0 */
/* when socket is setup (and during reconnect) before NegProt sent */
unsigned int max_rw; /* maxRw specifies the maximum */
/* message size the server can send or receive for */
/* SMB_COM_WRITE_RAW or SMB_COM_READ_RAW. */
unsigned int max_vcs; /* maximum number of smb sessions, at least
those that can be specified uniquely with
vcnumbers */
unsigned int capabilities; /* selective disabling of caps by smb sess */
int timeAdj; /* Adjust for difference in server time zone in sec */
__u64 CurrentMid; /* multiplex id - rotating counter */
char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlm, ntlmv2 etc */
/* 16th byte of RFC1001 workstation name is always null */
char workstation_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
__u32 sequence_number; /* for signing, protected by srv_mutex */
struct session_key session_key;
unsigned long lstrp; /* when we got last response from this server */
struct cifs_secmech secmech; /* crypto sec mech functs, descriptors */
/* extended security flavors that server supports */
bool sec_ntlmssp; /* supports NTLMSSP */
bool sec_kerberosu2u; /* supports U2U Kerberos */
bool sec_kerberos; /* supports plain Kerberos */
bool sec_mskerberos; /* supports legacy MS Kerberos */
bool large_buf; /* is current buffer large? */
struct delayed_work echo; /* echo ping workqueue job */
struct kvec *iov; /* reusable kvec array for receives */
unsigned int nr_iov; /* number of kvecs in array */
char *smallbuf; /* pointer to current "small" buffer */
char *bigbuf; /* pointer to current "big" buffer */
unsigned int total_read; /* total amount of data read in this pass */
#ifdef CONFIG_CIFS_FSCACHE
struct fscache_cookie *fscache; /* client index cache cookie */
#endif
#ifdef CONFIG_CIFS_STATS2
atomic_t in_send; /* requests trying to send */
atomic_t num_waiters; /* blocked waiting to get in sendrecv */
#endif
#ifdef CONFIG_CIFS_SMB2
unsigned int max_read;
unsigned int max_write;
#endif /* CONFIG_CIFS_SMB2 */
};
static inline unsigned int
in_flight(struct TCP_Server_Info *server)
{
unsigned int num;
spin_lock(&server->req_lock);
num = server->in_flight;
spin_unlock(&server->req_lock);
return num;
}
static inline bool
has_credits(struct TCP_Server_Info *server, int *credits)
{
int num;
spin_lock(&server->req_lock);
num = *credits;
spin_unlock(&server->req_lock);
return num > 0;
}
static inline void
add_credits(struct TCP_Server_Info *server, const unsigned int add,
const int optype)
{
server->ops->add_credits(server, add, optype);
}
static inline void
set_credits(struct TCP_Server_Info *server, const int val)
{
server->ops->set_credits(server, val);
}
static inline __u64
get_next_mid(struct TCP_Server_Info *server)
{
return server->ops->get_next_mid(server);
}
/*
* When the server supports very large reads and writes via POSIX extensions,
* we can allow up to 2^24-1, minus the size of a READ/WRITE_AND_X header, not
* including the RFC1001 length.
*
* Note that this might make for "interesting" allocation problems during
* writeback however as we have to allocate an array of pointers for the
* pages. A 16M write means ~32kb page array with PAGE_CACHE_SIZE == 4096.
*
* For reads, there is a similar problem as we need to allocate an array
* of kvecs to handle the receive, though that should only need to be done
* once.
*/
#define CIFS_MAX_WSIZE ((1<<24) - 1 - sizeof(WRITE_REQ) + 4)
#define CIFS_MAX_RSIZE ((1<<24) - sizeof(READ_RSP) + 4)
/*
* When the server doesn't allow large posix writes, only allow a rsize/wsize
* of 2^17-1 minus the size of the call header. That allows for a read or
* write up to the maximum size described by RFC1002.
*/
#define CIFS_MAX_RFC1002_WSIZE ((1<<17) - 1 - sizeof(WRITE_REQ) + 4)
#define CIFS_MAX_RFC1002_RSIZE ((1<<17) - 1 - sizeof(READ_RSP) + 4)
/*
* The default wsize is 1M. find_get_pages seems to return a maximum of 256
* pages in a single call. With PAGE_CACHE_SIZE == 4k, this means we can fill
* a single wsize request with a single call.
*/
#define CIFS_DEFAULT_IOSIZE (1024 * 1024)
/*
* Windows only supports a max of 60kb reads and 65535 byte writes. Default to
* those values when posix extensions aren't in force. In actuality here, we
* use 65536 to allow for a write that is a multiple of 4k. Most servers seem
* to be ok with the extra byte even though Windows doesn't send writes that
* are that large.
*
* Citation:
*
* http://blogs.msdn.com/b/openspecification/archive/2009/04/10/smb-maximum-transmit-buffer-size-and-performance-tuning.aspx
*/
#define CIFS_DEFAULT_NON_POSIX_RSIZE (60 * 1024)
#define CIFS_DEFAULT_NON_POSIX_WSIZE (65536)
/*
* Macros to allow the TCP_Server_Info->net field and related code to drop out
* when CONFIG_NET_NS isn't set.
*/
#ifdef CONFIG_NET_NS
static inline struct net *cifs_net_ns(struct TCP_Server_Info *srv)
{
return srv->net;
}
static inline void cifs_set_net_ns(struct TCP_Server_Info *srv, struct net *net)
{
srv->net = net;
}
#else
static inline struct net *cifs_net_ns(struct TCP_Server_Info *srv)
{
return &init_net;
}
static inline void cifs_set_net_ns(struct TCP_Server_Info *srv, struct net *net)
{
}
#endif
/*
* Session structure. One of these for each uid session with a particular host
*/
struct cifs_ses {
struct list_head smb_ses_list;
struct list_head tcon_list;
struct mutex session_mutex;
struct TCP_Server_Info *server; /* pointer to server info */
int ses_count; /* reference counter */
enum statusEnum status;
unsigned overrideSecFlg; /* if non-zero override global sec flags */
__u16 ipc_tid; /* special tid for connection to IPC share */
__u16 flags;
__u16 vcnum;
char *serverOS; /* name of operating system underlying server */
char *serverNOS; /* name of network operating system of server */
char *serverDomain; /* security realm of server */
__u64 Suid; /* remote smb uid */
kuid_t linux_uid; /* overriding owner of files on the mount */
kuid_t cred_uid; /* owner of credentials */
unsigned int capabilities;
char serverName[SERVER_NAME_LEN_WITH_NULL * 2]; /* BB make bigger for
TCP names - will ipv6 and sctp addresses fit? */
char *user_name; /* must not be null except during init of sess
and after mount option parsing we fill it */
char *domainName;
char *password;
struct session_key auth_key;
struct ntlmssp_auth *ntlmssp; /* ciphertext, flags, server challenge */
bool need_reconnect:1; /* connection reset, uid now invalid */
#ifdef CONFIG_CIFS_SMB2
__u16 session_flags;
#endif /* CONFIG_CIFS_SMB2 */
};
/* no more than one of the following three session flags may be set */
#define CIFS_SES_NT4 1
#define CIFS_SES_OS2 2
#define CIFS_SES_W9X 4
/* following flag is set for old servers such as OS2 (and Win95?)
which do not negotiate NTLM or POSIX dialects, but instead
negotiate one of the older LANMAN dialects */
#define CIFS_SES_LANMAN 8
static inline bool
cap_unix(struct cifs_ses *ses)
{
return ses->server->vals->cap_unix & ses->capabilities;
}
/*
* there is one of these for each connection to a resource on a particular
* session
*/
struct cifs_tcon {
struct list_head tcon_list;
int tc_count;
struct list_head openFileList;
struct cifs_ses *ses; /* pointer to session associated with */
char treeName[MAX_TREE_SIZE + 1]; /* UNC name of resource in ASCII */
char *nativeFileSystem;
char *password; /* for share-level security */
__u32 tid; /* The 4 byte tree id */
__u16 Flags; /* optional support bits */
enum statusEnum tidStatus;
#ifdef CONFIG_CIFS_STATS
atomic_t num_smbs_sent;
union {
struct {
atomic_t num_writes;
atomic_t num_reads;
atomic_t num_flushes;
atomic_t num_oplock_brks;
atomic_t num_opens;
atomic_t num_closes;
atomic_t num_deletes;
atomic_t num_mkdirs;
atomic_t num_posixopens;
atomic_t num_posixmkdirs;
atomic_t num_rmdirs;
atomic_t num_renames;
atomic_t num_t2renames;
atomic_t num_ffirst;
atomic_t num_fnext;
atomic_t num_fclose;
atomic_t num_hardlinks;
atomic_t num_symlinks;
atomic_t num_locks;
atomic_t num_acl_get;
atomic_t num_acl_set;
} cifs_stats;
#ifdef CONFIG_CIFS_SMB2
struct {
atomic_t smb2_com_sent[NUMBER_OF_SMB2_COMMANDS];
atomic_t smb2_com_failed[NUMBER_OF_SMB2_COMMANDS];
} smb2_stats;
#endif /* CONFIG_CIFS_SMB2 */
} stats;
#ifdef CONFIG_CIFS_STATS2
unsigned long long time_writes;
unsigned long long time_reads;
unsigned long long time_opens;
unsigned long long time_deletes;
unsigned long long time_closes;
unsigned long long time_mkdirs;
unsigned long long time_rmdirs;
unsigned long long time_renames;
unsigned long long time_t2renames;
unsigned long long time_ffirst;
unsigned long long time_fnext;
unsigned long long time_fclose;
#endif /* CONFIG_CIFS_STATS2 */
__u64 bytes_read;
__u64 bytes_written;
spinlock_t stat_lock;
#endif /* CONFIG_CIFS_STATS */
FILE_SYSTEM_DEVICE_INFO fsDevInfo;
FILE_SYSTEM_ATTRIBUTE_INFO fsAttrInfo; /* ok if fs name truncated */
FILE_SYSTEM_UNIX_INFO fsUnixInfo;
bool ipc:1; /* set if connection to IPC$ eg for RPC/PIPES */
bool retry:1;
bool nocase:1;
bool seal:1; /* transport encryption for this mounted share */
bool unix_ext:1; /* if false disable Linux extensions to CIFS protocol
for this mount even if server would support */
bool local_lease:1; /* check leases (only) on local system not remote */
bool broken_posix_open; /* e.g. Samba server versions < 3.3.2, 3.2.9 */
bool need_reconnect:1; /* connection reset, tid now invalid */
#ifdef CONFIG_CIFS_SMB2
bool print:1; /* set if connection to printer share */
bool bad_network_name:1; /* set if ret status STATUS_BAD_NETWORK_NAME */
__u32 capabilities;
__u32 share_flags;
__u32 maximal_access;
__u32 vol_serial_number;
__le64 vol_create_time;
#endif /* CONFIG_CIFS_SMB2 */
#ifdef CONFIG_CIFS_FSCACHE
u64 resource_id; /* server resource id */
struct fscache_cookie *fscache; /* cookie for share */
#endif
struct list_head pending_opens; /* list of incomplete opens */
/* BB add field for back pointer to sb struct(s)? */
};
/*
* This is a refcounted and timestamped container for a tcon pointer. The
* container holds a tcon reference. It is considered safe to free one of
* these when the tl_count goes to 0. The tl_time is the time of the last
* "get" on the container.
*/
struct tcon_link {
struct rb_node tl_rbnode;
kuid_t tl_uid;
unsigned long tl_flags;
#define TCON_LINK_MASTER 0
#define TCON_LINK_PENDING 1
#define TCON_LINK_IN_TREE 2
unsigned long tl_time;
atomic_t tl_count;
struct cifs_tcon *tl_tcon;
};
extern struct tcon_link *cifs_sb_tlink(struct cifs_sb_info *cifs_sb);
static inline struct cifs_tcon *
tlink_tcon(struct tcon_link *tlink)
{
return tlink->tl_tcon;
}
extern void cifs_put_tlink(struct tcon_link *tlink);
static inline struct tcon_link *
cifs_get_tlink(struct tcon_link *tlink)
{
if (tlink && !IS_ERR(tlink))
atomic_inc(&tlink->tl_count);
return tlink;
}
/* This function is always expected to succeed */
extern struct cifs_tcon *cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb);
#define CIFS_OPLOCK_NO_CHANGE 0xfe
struct cifs_pending_open {
struct list_head olist;
struct tcon_link *tlink;
__u8 lease_key[16];
__u32 oplock;
};
/*
* This info hangs off the cifsFileInfo structure, pointed to by llist.
* This is used to track byte stream locks on the file
*/
struct cifsLockInfo {
struct list_head llist; /* pointer to next cifsLockInfo */
struct list_head blist; /* pointer to locks blocked on this */
wait_queue_head_t block_q;
__u64 offset;
__u64 length;
__u32 pid;
__u32 type;
};
/*
* One of these for each open instance of a file
*/
struct cifs_search_info {
loff_t index_of_last_entry;
__u16 entries_in_buffer;
__u16 info_level;
__u32 resume_key;
char *ntwrk_buf_start;
char *srch_entries_start;
char *last_entry;
const char *presume_name;
unsigned int resume_name_len;
bool endOfSearch:1;
bool emptyDir:1;
bool unicode:1;
bool smallBuf:1; /* so we know which buf_release function to call */
};
struct cifs_fid {
__u16 netfid;
#ifdef CONFIG_CIFS_SMB2
__u64 persistent_fid; /* persist file id for smb2 */
__u64 volatile_fid; /* volatile file id for smb2 */
__u8 lease_key[SMB2_LEASE_KEY_SIZE]; /* lease key for smb2 */
#endif
struct cifs_pending_open *pending_open;
};
struct cifs_fid_locks {
struct list_head llist;
struct cifsFileInfo *cfile; /* fid that owns locks */
struct list_head locks; /* locks held by fid above */
};
struct cifsFileInfo {
struct list_head tlist; /* pointer to next fid owned by tcon */
struct list_head flist; /* next fid (file instance) for this inode */
struct cifs_fid_locks *llist; /* brlocks held by this fid */
kuid_t uid; /* allows finding which FileInfo structure */
__u32 pid; /* process id who opened file */
struct cifs_fid fid; /* file id from remote */
/* BB add lock scope info here if needed */ ;
/* lock scope id (0 if none) */
struct dentry *dentry;
unsigned int f_flags;
struct tcon_link *tlink;
bool invalidHandle:1; /* file closed via session abend */
bool oplock_break_cancelled:1;
int count; /* refcount protected by cifs_file_list_lock */
struct mutex fh_mutex; /* prevents reopen race after dead ses*/
struct cifs_search_info srch_inf;
struct work_struct oplock_break; /* work for oplock breaks */
};
struct cifs_io_parms {
__u16 netfid;
#ifdef CONFIG_CIFS_SMB2
__u64 persistent_fid; /* persist file id for smb2 */
__u64 volatile_fid; /* volatile file id for smb2 */
#endif
__u32 pid;
__u64 offset;
unsigned int length;
struct cifs_tcon *tcon;
};
struct cifs_readdata;
/* asynchronous read support */
struct cifs_readdata {
struct kref refcount;
struct list_head list;
struct completion done;
struct cifsFileInfo *cfile;
struct address_space *mapping;
__u64 offset;
unsigned int bytes;
pid_t pid;
int result;
struct work_struct work;
int (*read_into_pages)(struct TCP_Server_Info *server,
struct cifs_readdata *rdata,
unsigned int len);
struct kvec iov;
unsigned int pagesz;
unsigned int tailsz;
unsigned int nr_pages;
struct page *pages[];
};
struct cifs_writedata;
/* asynchronous write support */
struct cifs_writedata {
struct kref refcount;
struct list_head list;
struct completion done;
enum writeback_sync_modes sync_mode;
struct work_struct work;
struct cifsFileInfo *cfile;
__u64 offset;
pid_t pid;
unsigned int bytes;
int result;
unsigned int pagesz;
unsigned int tailsz;
unsigned int nr_pages;
struct page *pages[1];
};
/*
* Take a reference on the file private data. Must be called with
* cifs_file_list_lock held.
*/
static inline void
cifsFileInfo_get_locked(struct cifsFileInfo *cifs_file)
{
++cifs_file->count;
}
struct cifsFileInfo *cifsFileInfo_get(struct cifsFileInfo *cifs_file);
void cifsFileInfo_put(struct cifsFileInfo *cifs_file);
/*
* One of these for each file inode
*/
struct cifsInodeInfo {
bool can_cache_brlcks;
struct list_head llist; /* locks helb by this inode */
struct rw_semaphore lock_sem; /* protect the fields above */
/* BB add in lists for dirty pages i.e. write caching info for oplock */
struct list_head openFileList;
__u32 cifsAttrs; /* e.g. DOS archive bit, sparse, compressed, system */
bool clientCanCacheRead; /* read oplock */
bool clientCanCacheAll; /* read and writebehind oplock */
bool delete_pending; /* DELETE_ON_CLOSE is set */
bool invalid_mapping; /* pagecache is invalid */
unsigned long time; /* jiffies of last update of inode */
u64 server_eof; /* current file size on server -- protected by i_lock */
u64 uniqueid; /* server inode number */
u64 createtime; /* creation time on server */
#ifdef CONFIG_CIFS_SMB2
__u8 lease_key[SMB2_LEASE_KEY_SIZE]; /* lease key for this inode */
#endif
#ifdef CONFIG_CIFS_FSCACHE
struct fscache_cookie *fscache;
#endif
struct inode vfs_inode;
};
static inline struct cifsInodeInfo *
CIFS_I(struct inode *inode)
{
return container_of(inode, struct cifsInodeInfo, vfs_inode);
}
static inline struct cifs_sb_info *
CIFS_SB(struct super_block *sb)
{
return sb->s_fs_info;
}
static inline char CIFS_DIR_SEP(const struct cifs_sb_info *cifs_sb)
{
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)
return '/';
else
return '\\';
}
static inline void
convert_delimiter(char *path, char delim)
{
char old_delim, *pos;
if (delim == '/')
old_delim = '\\';
else
old_delim = '/';
pos = path;
while ((pos = strchr(pos, old_delim)))
*pos = delim;
}
#ifdef CONFIG_CIFS_STATS
#define cifs_stats_inc atomic_inc
static inline void cifs_stats_bytes_written(struct cifs_tcon *tcon,
unsigned int bytes)
{
if (bytes) {
spin_lock(&tcon->stat_lock);
tcon->bytes_written += bytes;
spin_unlock(&tcon->stat_lock);
}
}
static inline void cifs_stats_bytes_read(struct cifs_tcon *tcon,
unsigned int bytes)
{
spin_lock(&tcon->stat_lock);
tcon->bytes_read += bytes;
spin_unlock(&tcon->stat_lock);
}
#else
#define cifs_stats_inc(field) do {} while (0)
#define cifs_stats_bytes_written(tcon, bytes) do {} while (0)
#define cifs_stats_bytes_read(tcon, bytes) do {} while (0)
#endif
/*
* This is the prototype for the mid receive function. This function is for
* receiving the rest of the SMB frame, starting with the WordCount (which is
* just after the MID in struct smb_hdr). Note:
*
* - This will be called by cifsd, with no locks held.
* - The mid will still be on the pending_mid_q.
* - mid->resp_buf will point to the current buffer.
*
* Returns zero on a successful receive, or an error. The receive state in
* the TCP_Server_Info will also be updated.
*/
typedef int (mid_receive_t)(struct TCP_Server_Info *server,
struct mid_q_entry *mid);
/*
* This is the prototype for the mid callback function. This is called once the
* mid has been received off of the socket. When creating one, take special
* care to avoid deadlocks. Things to bear in mind:
*
* - it will be called by cifsd, with no locks held
* - the mid will be removed from any lists
*/
typedef void (mid_callback_t)(struct mid_q_entry *mid);
/* one of these for every pending CIFS request to the server */
struct mid_q_entry {
struct list_head qhead; /* mids waiting on reply from this server */
struct TCP_Server_Info *server; /* server corresponding to this mid */
__u64 mid; /* multiplex id */
__u32 pid; /* process id */
__u32 sequence_number; /* for CIFS signing */
unsigned long when_alloc; /* when mid was created */
#ifdef CONFIG_CIFS_STATS2
unsigned long when_sent; /* time when smb send finished */
unsigned long when_received; /* when demux complete (taken off wire) */
#endif
mid_receive_t *receive; /* call receive callback */
mid_callback_t *callback; /* call completion callback */
void *callback_data; /* general purpose pointer for callback */
void *resp_buf; /* pointer to received SMB header */
int mid_state; /* wish this were enum but can not pass to wait_event */
__le16 command; /* smb command code */
bool large_buf:1; /* if valid response, is pointer to large buf */
bool multiRsp:1; /* multiple trans2 responses for one request */
bool multiEnd:1; /* both received */
};
/* Make code in transport.c a little cleaner by moving
update of optional stats into function below */
#ifdef CONFIG_CIFS_STATS2
static inline void cifs_in_send_inc(struct TCP_Server_Info *server)
{
atomic_inc(&server->in_send);
}
static inline void cifs_in_send_dec(struct TCP_Server_Info *server)
{
atomic_dec(&server->in_send);
}
static inline void cifs_num_waiters_inc(struct TCP_Server_Info *server)
{
atomic_inc(&server->num_waiters);
}
static inline void cifs_num_waiters_dec(struct TCP_Server_Info *server)
{
atomic_dec(&server->num_waiters);
}
static inline void cifs_save_when_sent(struct mid_q_entry *mid)
{
mid->when_sent = jiffies;
}
#else
static inline void cifs_in_send_inc(struct TCP_Server_Info *server)
{
}
static inline void cifs_in_send_dec(struct TCP_Server_Info *server)
{
}
static inline void cifs_num_waiters_inc(struct TCP_Server_Info *server)
{
}
static inline void cifs_num_waiters_dec(struct TCP_Server_Info *server)
{
}
static inline void cifs_save_when_sent(struct mid_q_entry *mid)
{
}
#endif
/* for pending dnotify requests */
struct dir_notify_req {
struct list_head lhead;
__le16 Pid;
__le16 PidHigh;
__u16 Mid;
__u16 Tid;
__u16 Uid;
__u16 netfid;
__u32 filter; /* CompletionFilter (for multishot) */
int multishot;
struct file *pfile;
};
struct dfs_info3_param {
int flags; /* DFSREF_REFERRAL_SERVER, DFSREF_STORAGE_SERVER*/
int path_consumed;
int server_type;
int ref_flag;
char *path_name;
char *node_name;
};
/*
* common struct for holding inode info when searching for or updating an
* inode with new info
*/
#define CIFS_FATTR_DFS_REFERRAL 0x1
#define CIFS_FATTR_DELETE_PENDING 0x2
#define CIFS_FATTR_NEED_REVAL 0x4
#define CIFS_FATTR_INO_COLLISION 0x8
struct cifs_fattr {
u32 cf_flags;
u32 cf_cifsattrs;
u64 cf_uniqueid;
u64 cf_eof;
u64 cf_bytes;
u64 cf_createtime;
kuid_t cf_uid;
kgid_t cf_gid;
umode_t cf_mode;
dev_t cf_rdev;
unsigned int cf_nlink;
unsigned int cf_dtype;
struct timespec cf_atime;
struct timespec cf_mtime;
struct timespec cf_ctime;
};
static inline void free_dfs_info_param(struct dfs_info3_param *param)
{
if (param) {
kfree(param->path_name);
kfree(param->node_name);
kfree(param);
}
}
static inline void free_dfs_info_array(struct dfs_info3_param *param,
int number_of_items)
{
int i;
if ((number_of_items == 0) || (param == NULL))
return;
for (i = 0; i < number_of_items; i++) {
kfree(param[i].path_name);
kfree(param[i].node_name);
}
kfree(param);
}
#define MID_FREE 0
#define MID_REQUEST_ALLOCATED 1
#define MID_REQUEST_SUBMITTED 2
#define MID_RESPONSE_RECEIVED 4
#define MID_RETRY_NEEDED 8 /* session closed while this request out */
#define MID_RESPONSE_MALFORMED 0x10
#define MID_SHUTDOWN 0x20
/* Types of response buffer returned from SendReceive2 */
#define CIFS_NO_BUFFER 0 /* Response buffer not returned */
#define CIFS_SMALL_BUFFER 1
#define CIFS_LARGE_BUFFER 2
#define CIFS_IOVEC 4 /* array of response buffers */
/* Type of Request to SendReceive2 */
#define CIFS_BLOCKING_OP 1 /* operation can block */
#define CIFS_ASYNC_OP 2 /* do not wait for response */
#define CIFS_TIMEOUT_MASK 0x003 /* only one of above set in req */
#define CIFS_LOG_ERROR 0x010 /* log NT STATUS if non-zero */
#define CIFS_LARGE_BUF_OP 0x020 /* large request buffer */
#define CIFS_NO_RESP 0x040 /* no response buffer required */
/* Type of request operation */
#define CIFS_ECHO_OP 0x080 /* echo request */
#define CIFS_OBREAK_OP 0x0100 /* oplock break request */
#define CIFS_NEG_OP 0x0200 /* negotiate request */
#define CIFS_OP_MASK 0x0380 /* mask request type */
/* Security Flags: indicate type of session setup needed */
#define CIFSSEC_MAY_SIGN 0x00001
#define CIFSSEC_MAY_NTLM 0x00002
#define CIFSSEC_MAY_NTLMV2 0x00004
#define CIFSSEC_MAY_KRB5 0x00008
#ifdef CONFIG_CIFS_WEAK_PW_HASH
#define CIFSSEC_MAY_LANMAN 0x00010
#define CIFSSEC_MAY_PLNTXT 0x00020
#else
#define CIFSSEC_MAY_LANMAN 0
#define CIFSSEC_MAY_PLNTXT 0
#endif /* weak passwords */
#define CIFSSEC_MAY_SEAL 0x00040 /* not supported yet */
#define CIFSSEC_MAY_NTLMSSP 0x00080 /* raw ntlmssp with ntlmv2 */
#define CIFSSEC_MUST_SIGN 0x01001
/* note that only one of the following can be set so the
result of setting MUST flags more than once will be to
require use of the stronger protocol */
#define CIFSSEC_MUST_NTLM 0x02002
#define CIFSSEC_MUST_NTLMV2 0x04004
#define CIFSSEC_MUST_KRB5 0x08008
#ifdef CONFIG_CIFS_WEAK_PW_HASH
#define CIFSSEC_MUST_LANMAN 0x10010
#define CIFSSEC_MUST_PLNTXT 0x20020
#ifdef CONFIG_CIFS_UPCALL
#define CIFSSEC_MASK 0xBF0BF /* allows weak security but also krb5 */
#else
#define CIFSSEC_MASK 0xB70B7 /* current flags supported if weak */
#endif /* UPCALL */
#else /* do not allow weak pw hash */
#define CIFSSEC_MUST_LANMAN 0
#define CIFSSEC_MUST_PLNTXT 0
#ifdef CONFIG_CIFS_UPCALL
#define CIFSSEC_MASK 0x8F08F /* flags supported if no weak allowed */
#else
#define CIFSSEC_MASK 0x87087 /* flags supported if no weak allowed */
#endif /* UPCALL */
#endif /* WEAK_PW_HASH */
#define CIFSSEC_MUST_SEAL 0x40040 /* not supported yet */
#define CIFSSEC_MUST_NTLMSSP 0x80080 /* raw ntlmssp with ntlmv2 */
#define CIFSSEC_DEF (CIFSSEC_MAY_SIGN | CIFSSEC_MAY_NTLMSSP)
#define CIFSSEC_MAX (CIFSSEC_MUST_SIGN | CIFSSEC_MUST_NTLMV2)
#define CIFSSEC_AUTH_MASK (CIFSSEC_MAY_NTLM | CIFSSEC_MAY_NTLMV2 | CIFSSEC_MAY_LANMAN | CIFSSEC_MAY_PLNTXT | CIFSSEC_MAY_KRB5 | CIFSSEC_MAY_NTLMSSP)
/*
*****************************************************************
* All constants go here
*****************************************************************
*/
#define UID_HASH (16)
/*
* Note that ONE module should define _DECLARE_GLOBALS_HERE to cause the
* following to be declared.
*/
/****************************************************************************
* Locking notes. All updates to global variables and lists should be
* protected by spinlocks or semaphores.
*
* Spinlocks
* ---------
* GlobalMid_Lock protects:
* list operations on pending_mid_q and oplockQ
* updates to XID counters, multiplex id and SMB sequence numbers
* cifs_file_list_lock protects:
* list operations on tcp and SMB session lists and tCon lists
* f_owner.lock protects certain per file struct operations
* mapping->page_lock protects certain per page operations
*
* Semaphores
* ----------
* sesSem operations on smb session
* tconSem operations on tree connection
* fh_sem file handle reconnection operations
*
****************************************************************************/
#ifdef DECLARE_GLOBALS_HERE
#define GLOBAL_EXTERN
#else
#define GLOBAL_EXTERN extern
#endif
/*
* the list of TCP_Server_Info structures, ie each of the sockets
* connecting our client to a distinct server (ip address), is
* chained together by cifs_tcp_ses_list. The list of all our SMB
* sessions (and from that the tree connections) can be found
* by iterating over cifs_tcp_ses_list
*/
GLOBAL_EXTERN struct list_head cifs_tcp_ses_list;
/*
* This lock protects the cifs_tcp_ses_list, the list of smb sessions per
* tcp session, and the list of tcon's per smb session. It also protects
* the reference counters for the server, smb session, and tcon. Finally,
* changes to the tcon->tidStatus should be done while holding this lock.
*/
GLOBAL_EXTERN spinlock_t cifs_tcp_ses_lock;
/*
* This lock protects the cifs_file->llist and cifs_file->flist
* list operations, and updates to some flags (cifs_file->invalidHandle)
* It will be moved to either use the tcon->stat_lock or equivalent later.
* If cifs_tcp_ses_lock and the lock below are both needed to be held, then
* the cifs_tcp_ses_lock must be grabbed first and released last.
*/
GLOBAL_EXTERN spinlock_t cifs_file_list_lock;
#ifdef CONFIG_CIFS_DNOTIFY_EXPERIMENTAL /* unused temporarily */
/* Outstanding dir notify requests */
GLOBAL_EXTERN struct list_head GlobalDnotifyReqList;
/* DirNotify response queue */
GLOBAL_EXTERN struct list_head GlobalDnotifyRsp_Q;
#endif /* was needed for dnotify, and will be needed for inotify when VFS fix */
/*
* Global transaction id (XID) information
*/
GLOBAL_EXTERN unsigned int GlobalCurrentXid; /* protected by GlobalMid_Sem */
GLOBAL_EXTERN unsigned int GlobalTotalActiveXid; /* prot by GlobalMid_Sem */
GLOBAL_EXTERN unsigned int GlobalMaxActiveXid; /* prot by GlobalMid_Sem */
GLOBAL_EXTERN spinlock_t GlobalMid_Lock; /* protects above & list operations */
/* on midQ entries */
/*
* Global counters, updated atomically
*/
GLOBAL_EXTERN atomic_t sesInfoAllocCount;
GLOBAL_EXTERN atomic_t tconInfoAllocCount;
GLOBAL_EXTERN atomic_t tcpSesAllocCount;
GLOBAL_EXTERN atomic_t tcpSesReconnectCount;
GLOBAL_EXTERN atomic_t tconInfoReconnectCount;
/* Various Debug counters */
GLOBAL_EXTERN atomic_t bufAllocCount; /* current number allocated */
#ifdef CONFIG_CIFS_STATS2
GLOBAL_EXTERN atomic_t totBufAllocCount; /* total allocated over all time */
GLOBAL_EXTERN atomic_t totSmBufAllocCount;
#endif
GLOBAL_EXTERN atomic_t smBufAllocCount;
GLOBAL_EXTERN atomic_t midCount;
/* Misc globals */
GLOBAL_EXTERN bool enable_oplocks; /* enable or disable oplocks */
GLOBAL_EXTERN unsigned int lookupCacheEnabled;
GLOBAL_EXTERN unsigned int global_secflags; /* if on, session setup sent
with more secure ntlmssp2 challenge/resp */
GLOBAL_EXTERN unsigned int sign_CIFS_PDUs; /* enable smb packet signing */
GLOBAL_EXTERN unsigned int linuxExtEnabled;/*enable Linux/Unix CIFS extensions*/
GLOBAL_EXTERN unsigned int CIFSMaxBufSize; /* max size not including hdr */
GLOBAL_EXTERN unsigned int cifs_min_rcv; /* min size of big ntwrk buf pool */
GLOBAL_EXTERN unsigned int cifs_min_small; /* min size of small buf pool */
GLOBAL_EXTERN unsigned int cifs_max_pending; /* MAX requests at once to server*/
#ifdef CONFIG_CIFS_ACL
GLOBAL_EXTERN struct rb_root uidtree;
GLOBAL_EXTERN struct rb_root gidtree;
GLOBAL_EXTERN spinlock_t siduidlock;
GLOBAL_EXTERN spinlock_t sidgidlock;
GLOBAL_EXTERN struct rb_root siduidtree;
GLOBAL_EXTERN struct rb_root sidgidtree;
GLOBAL_EXTERN spinlock_t uidsidlock;
GLOBAL_EXTERN spinlock_t gidsidlock;
#endif /* CONFIG_CIFS_ACL */
void cifs_oplock_break(struct work_struct *work);
extern const struct slow_work_ops cifs_oplock_break_ops;
extern struct workqueue_struct *cifsiod_wq;
extern mempool_t *cifs_mid_poolp;
/* Operations for different SMB versions */
#define SMB1_VERSION_STRING "1.0"
extern struct smb_version_operations smb1_operations;
extern struct smb_version_values smb1_values;
#define SMB20_VERSION_STRING "2.0"
/*extern struct smb_version_operations smb20_operations; */ /* not needed yet */
extern struct smb_version_values smb20_values;
#define SMB21_VERSION_STRING "2.1"
extern struct smb_version_operations smb21_operations;
extern struct smb_version_values smb21_values;
#define SMB30_VERSION_STRING "3.0"
extern struct smb_version_operations smb30_operations;
extern struct smb_version_values smb30_values;
#endif /* _CIFS_GLOB_H */
|
wurikiji/ttFS
|
ulinux/linux-3.10.61/fs/cifs/cifsglob.h
|
C
|
gpl-2.0
| 49,769
|
//
// DDNSDictionary+Safe.m
// IOSDuoduo
//
// Created by 东邪 on 14-5-29.
// Copyright (c) 2014年 dujia. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDictionary(Safe)
- (id)safeObjectForKey:(id)key;
- (int)intValueForKey:(id)key;
- (double)doubleValueForKey:(id)key;
- (NSString*)stringValueForKey:(id)key;
@end
@interface NSMutableDictionary(Safe)
- (void)safeSetObject:(id)anObject forKey:(id)aKey;
- (void)setIntValue:(int)value forKey:(id)aKey;
- (void)setDoubleValue:(double)value forKey:(id)aKey;
- (void)setStringValueForKey:(NSString*)string forKey:(id)aKey;
@end
@interface NSArray (Exception)
- (id)objectForKey:(id)key;
@end
|
ouyang90/TeamTalk
|
mac/TeamTalk/Category/NSDictionary+Safe.h
|
C
|
apache-2.0
| 681
|
#include<gtk/gtk.h>
#include<glade/glade.h>
void
yes_button_enter_cb(GtkWidget *widget)
{
gtk_button_set_label(GTK_BUTTON(yes_button), "Zebbi 3aleik!");
gtk_widget_set_sensitive(GTK_BUTTON(yes_button), FALSE);
}
void
yes_button_leave_cb(GtkWidget *widget)
{
gtk_button_set_label(GTK_BUTTON(yes_button), "Of Course!");
gtk_widget_set_sensitive(GTK_BUTTON(yes_button), TRUE);
}
int
main(int argc, char **argv)
{
GladeXML *xml;
GtkWindow *window;
gtk_init(&argc, &argv);
xml = glade_xml_new("abbas-ui.xml", NULL, NULL);
window = glade_xml_get_widget(xml, "window1");
glade_xml_signal_autoconnect(xml);
gtk_main();
return 0;
}
|
fredmorcos/attic
|
snippets/c/gtk/abbas-glade/abbas.c
|
C
|
isc
| 642
|
#pragma once
#include <QMainWindow>
#include <QPalette>
#include <QSplitter>
#include <QStackedWidget>
#include <QTabBar>
#include "contextmenu.h"
#include "errorwidget.h"
#include "neovimconnector.h"
#include "scrollbar.h"
#include "shell.h"
#include "tabline.h"
#include "treeview.h"
namespace NeovimQt {
class MainWindow: public QMainWindow
{
Q_OBJECT
public:
enum DelayedShow {
Disabled,
Normal,
Maximized,
FullScreen,
};
MainWindow(NeovimConnector* c, QWidget* parent = nullptr) noexcept;
bool isNeovimAttached() const noexcept { return m_shell && m_shell->isNeovimAttached(); }
Shell* shell();
void restoreWindowGeometry();
bool active() const noexcept { return m_isActive; }
public slots:
void delayedShow(NeovimQt::MainWindow::DelayedShow type=DelayedShow::Normal);
signals:
void neovimAttachmentChanged(bool);
void closing(int);
void activeChanged(NeovimQt::MainWindow& window);
protected:
virtual void closeEvent(QCloseEvent *ev) Q_DECL_OVERRIDE;
virtual void changeEvent(QEvent *ev) Q_DECL_OVERRIDE;
private slots:
void neovimSetTitle(const QString &title);
void neovimWidgetResized();
void neovimMaximized(bool);
void neovimForeground();
void neovimSuspend();
void neovimFullScreen(bool);
void neovimFrameless(bool);
void neovimGuiCloseRequest(int);
void neovimExited(int status);
void neovimError(NeovimConnector::NeovimError);
void reconnectNeovim();
void showIfDelayed();
void handleNeovimAttachment(bool);
void neovimIsUnsupported();
void saveWindowGeometry();
// GuiAdaptive Color/Font/Style Slots
void setGuiAdaptiveColorEnabled(bool isEnabled);
void setGuiAdaptiveFontEnabled(bool isEnabled);
void setGuiAdaptiveStyle(const QString& style);
void showGuiAdaptiveStyleList();
private:
void init(NeovimConnector *);
NeovimConnector* m_nvim{ nullptr };
ErrorWidget* m_errorWidget{ nullptr };
QSplitter* m_window{ nullptr };
TreeView* m_tree{ nullptr };
Shell* m_shell{ nullptr };
DelayedShow m_delayedShow{ DelayedShow::Disabled };
QStackedWidget m_stack;
bool m_neovim_requested_close{ false };
ContextMenu* m_contextMenu{ nullptr };
ScrollBar* m_scrollbar{ nullptr };
Tabline m_tabline;
int m_exitStatus{ 0 };
// GuiAdaptive Color/Font/Style
bool m_isAdaptiveColorEnabled{ false };
bool m_isAdaptiveFontEnabled{ false };
QFont m_defaultFont;
QPalette m_defaultPalette;
bool m_isActive{ false };
void updateAdaptiveColor() noexcept;
void updateAdaptiveFont() noexcept;
};
} // namespace NeovimQt
|
equalsraf/neovim-qt
|
src/gui/mainwindow.h
|
C
|
isc
| 2,493
|
<!doctype html><html lang=''><head><meta charset='utf8'><meta name="viewport" resources="width=device-width, initial-scale=1"><link rel="stylesheet" href="markdown.css"><link rel="stylesheet" href="main.css"></head><body><div id="Main" class="markdown-body">
<h1>
<a id="user-content-command-line-arguments" class="anchor" href="#command-line-arguments" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Command Line Arguments</h1>
<hr>
<p>It is possible to read the command line arguments that were used to start your application.</p>
<h4>
<a id="user-content-exercise" class="anchor" href="#exercise" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Exercise</h4>
<ol>
<li>Create a JavaScript file called "command-line-args.js".</li>
<li>Log to the console <code>process.argv</code>.</li>
<li>Run your application with <code>node command-line-args</code> and look at the output.</li>
<li>Run it again with <code>node command-line-args foo bar --baz</code> and look at the output.</li>
</ol>
<h4>
<a id="user-content-questions" class="anchor" href="#questions" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Questions</h4>
<ol>
<li>From running your application, what does the first argument represent?</li>
<li>What does the second argument represent?</li>
</ol>
<hr>
<h2>
<a id="user-content-parsing-command-line-arguments" class="anchor" href="#parsing-command-line-arguments" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Parsing Command Line Arguments</h2>
<p>There are several modules that I recommend for parsing command line arguments.</p>
<ul>
<li>
<a href="https://www.npmjs.com/package/command-line-args">command-line-args</a> - A module for parsing command line arguments.</li>
<li>
<a href="https://www.npmjs.com/package/command-line-callback">command-line-callback</a> - A module for building applications that accepts git-style commands.</li>
<li>
<a href="https://www.npmjs.com/package/commander">commander</a> - A module that provides a complete (albiet complex) solution for command line arguments and git-style commands.</li>
</ul>
<hr>
<h2>
<a id="user-content-current-working-directory" class="anchor" href="#current-working-directory" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Current Working directory</h2>
<p>At times when using command line arguments an argument may include a file path that should be used by the application. If the file path is relative, you can use <code>process.cwd()</code> to get the directory from which the application was launched.</p>
<script src="main.js"></script></body></html>
|
Gi60s/IT410
|
instruction/dist/command-line-args.html
|
HTML
|
isc
| 2,733
|
using System.Collections.Generic;
using libcmdline;
using NUnit.Framework;
namespace test
{
[TestFixture]
public class CommandLineArgsTests
{
[TestCase("-a", "testarg")]
[TestCase("-a=testarg")]
public void Option_WithArg(params string[] args)
{
CommandLineProcessor cmdline = new CommandLineProcessor();
cmdline.RegisterOptionMatchHandler("a", true, (sender, e) => { });
cmdline.ProcessCommandLineArgs(args);
Assert.That(cmdline.ArgCount, Is.EqualTo(1));
IEnumerable<string> emptylist = new List<string>(0);
Assert.That(cmdline.InvalidArgs, Is.EquivalentTo(emptylist));
}
[TestCase("-a")]
[TestCase("/a")]
public void Option_NoArg_1(params string[] args)
{
CommandLineProcessor cmdline = new CommandLineProcessor();
cmdline.RegisterOptionMatchHandler("a", (sender, e) => { });
cmdline.ProcessCommandLineArgs(args);
Assert.That(cmdline.ArgCount, Is.EqualTo(1));
IEnumerable<string> emptylist = new List<string>(0);
Assert.That(cmdline.InvalidArgs, Is.EquivalentTo(emptylist));
}
[TestCase("-a", "testarg", "-b")]
[TestCase("-b", "-a", "testarg")]
[TestCase("-a=testarg", "-b")]
[TestCase("-b", "-a=testarg")]
public void Option_NoArg_2(params string[] args)
{
CommandLineProcessor cmdline = new CommandLineProcessor();
cmdline.RegisterOptionMatchHandler("a", true, (sender, e) => { });
cmdline.RegisterOptionMatchHandler("b", (sender, e) => { });
cmdline.ProcessCommandLineArgs(args);
Assert.That(cmdline.ArgCount, Is.EqualTo(2));
IEnumerable<string> emptylist = new List<string>(0);
Assert.That(cmdline.InvalidArgs, Is.EquivalentTo(emptylist));
}
[TestCase("-a", "testarg")]
[TestCase("-a=testarg")]
public void Invalid_Argument_1(params string[] args)
{
CommandLineProcessor cmdline = new CommandLineProcessor();
cmdline.RegisterOptionMatchHandler("a", (sender, e) => { });
cmdline.ProcessCommandLineArgs(args);
Assert.That(cmdline.ArgCount, Is.EqualTo(0));
Assert.That(cmdline.InvalidArgs, Is.Not.Empty);
}
[TestCase("-a", "testarg", "-invalid")]
[TestCase("-invalid", "-a", "testarg")]
public void Invalid_Argument_2(params string[] args)
{
CommandLineProcessor cmdline = new CommandLineProcessor();
cmdline.RegisterOptionMatchHandler("a", true, (sender, e) => { });
cmdline.ProcessCommandLineArgs(args);
Assert.That(cmdline.ArgCount, Is.EqualTo(1));
Assert.That(cmdline.InvalidArgs.Count, Is.EqualTo(1));
}
}
}
|
sbennett1990/libcmdline
|
test/CommandLineArgsTests.cs
|
C#
|
isc
| 3,009
|
<!doctype html>
<html>
<head>
<title>test page</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>
<script>
var socket = io(document.location.host);
// socket.on('connect', function () {
// var lightdata = [];
// for(var i=0;i<50;i++){
// lightdata.push(0);
// }
//var samples=[]
//for (var i = 0; i < lightdata.length; ++i) {
// samples.push([i, lightdata[i]])
//}
// var vis_ir_plot = $.plot("#light-data",[samples], {
// series: {
// shadowSize: 0 // Drawing is faster without shadows
// },
// yaxis: {
// min:0,
// max: 500
//},
//xaxis: {
// show: false
// }
//});
// socket.on('light', function (data) {
// console.log(data);
// $("#light").text(data.vis_ir);
// lightdata.shift();
// lightdata.push(data.vis_ir);
// samples=[];
// for (var i = 0; i < lightdata.length; ++i) {
// samples.push([i, lightdata[i]]);
// }
// vis_ir_plot.setData([samples]);
// vis_ir_plot.draw();
// });
// }); //end connect
$(document).ready(function() {
console.log('ready');
$("#clicklamp").click(function() {
console.log('lamptoggle');
socket.emit('lamptoggle', {
message: 'lamptoggle'
});
});
});
$(document).ready(function() {
console.log('ready');
$("#clickredled").click(function() {
console.log('redledtoggle');
socket.emit('redledtoggle', {
message: 'redledtoggle'
});
});
});
</script>
</head>
<body>
<div class="container">
<button id='clicklamp'>toggle lamp</button>
<button id='clickredled'>toggle led</button>
<h2>Light</h2>
<!--<div >Light: <span id="light">...</span> lux</div>-->
<h2>Graph</h2>
<div>
<!--<div id="light-data" style="width:540px;height:340px"></div>-->
</div>
</div>
</body>
</html>
|
saasmath/winter25
|
adam8.html
|
HTML
|
isc
| 3,014
|
<!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>
<title>Long Range Compressor (LRC)</title>
<style>
body{
font-family: Sans-Serif;
font-size:0.8em;
color:#333333;
}
#outer{
width:80%;
margin: 0 auto;
}
table{
border-spacing:0.8em;
margin-left:1em;
}
td{
vertical-align:top;
}
th{
text-align:left;
}
</style>
</head>
<body>
<div id="outer">
<h1>Long Range Compressor (LRC)</h1>
<p>Updated 27/02/2006</p>
<h2>Introduction</h2>
<p>Since creating this page I have been told about <a href="http://rzip.samba.org/">rzip</a>, so this idea isn't new after all.</p>
<p>This program attempts to detect and exploit duplication in streams
which normal compression programs such as gzip and bzip2 fail to. The
program uses a rolling checksum inspired by rsync to efficiently detect
large blocks of data repeated arbitrarily far apart, distances much
further than bzip2 notices. Imagine a tar / pax file of an application
directory. The same dll may appear more than once in the file structure
or the same library may have been statically linked to different
executables. These duplicated blocks may be arbitrarily far apart in the
archive.</p>
<p>I will not attempt to explain in detail how the algorithm works here
but feel free to download the source or email me. I will probably write
up a description once the source has settled down.</p>
<h2>Results</h2>
<h3>Absolute worst case for LRC</h3>
<p>A file of any size containing no repeated blocks large enough for LRC to
detect will result in LRC adding 4 bytes to the length of the file. Here random1
is a file generated from /dev/urandom.</p>
<table>
<tr><th>File</th><th>Size (in bytes)</th></tr>
<tr><td>random1</td><td>7,654,321</td></tr>
<tr><td>random1.bz2</td><td>7,688,794</td></tr>
<tr><td>random1.lrc</td><td>7,654,325</td></tr>
<tr><td>random1.lrc.bz2</td><td>7,687,749</td></tr>
</table>
<h3>Absolute best case for LRC</h3>
<p>A large block of random data several megabytes in size repeating itself is
ideal for LRC. The algorithm will spot the duplication of the entire block and
squash out all of the repetition. Here random2 is the above random1 file
repeated twice.</p>
<table>
<tr><th>File</th><th>Size (in bytes)</th></tr>
<tr><td>random2</td><td>15,308,642</td></tr>
<tr><td>random2.bz2</td><td>15,376,676</td></tr>
<tr><td>random2.lrc</td><td>7,774,358</td></tr>
<tr><td>random2.lrc.bz2</td><td>7,722,119</td></tr>
</table>
<p>LRC will demonstrate the same behaviour if the block is repeated many
more times, ie only one copy of the block will be kept. This is true even if
the copies of the block are spread throughout the input at large
distances.</p>
<h3>Some real data</h3>
<p>Here some real filesystem trees have been tested. The LRC program does not
attempt to duplicate what bzip2 and others already do for local compression. For
that reason LRC output still benefits from being compressed itself with
bzip2.</p>
<table>
<tr>
<th>File or directory</th>
<th>Original (.pax or .tar)</th>
<th>.bz2</th>
<th>.lrc</th>
<th>.lrc.bz2</th>
<th>Comments</th>
</tr>
<tr>
<td>/etc (approx 3100+ files)</td>
<td>23,265,280</td>
<td>2,985,250</td>
<td>22,129,132</td>
<td>2,961,793</td>
<td>As expected not much saving here as /etc doesn't contain large portions of
repeated data.</td>
</tr>
<tr>
<td>/usr/X11R6 (approx 3400+ files)</td>
<td>148,746,240</td>
<td>43,125,635</td>
<td>86,368,716</td>
<td>35,845,001</td>
<td>Better compression here as presumably chunks of libraries / binaries duplicate
compiled object code.</td>
</tr>
<tr>
<td>linux-2.6.14.7.tar (2.6.14.7 kernel source)</td>
<td>224,102,400</td>
<td>39,194,997</td>
<td>214,558,252</td>
<td>38,552,800</td>
<td>Not very great compression here, again the files are mostly text and not binary.</td>
</tr>
<tr>
<td>linux-2.6.14.7-2.6.15.4.tar (2.6.14.7 and 2.6.15.4 kernel source tar files concatenated)</td>
<td>452,270,080</td>
<td>79,018,004</td>
<td>253,090,140</td>
<td>44,601,962</td>
<td>Here LRC is doing an excellent job of spotting the similarities between the two
archives despite the repetitions being over 200 megabytes apart in the stream.
This is a good example of how LRC works well when used with bzip2.</td>
</tr>
</table>
<h2>Performance</h2>
<h3>Compression</h3>
<p>In terms of speed the current algorithm takes time O( N log( N ) ) where N is
the length of the input stream. This should be easy to improve to O( N ) by
replacing some tree maps with hash maps.</p>
<p>In terms of memory used during compression LRC currently uses O( N ). This
looks bad but in reality the memory used is really a small fraction of the input
stream size. The above 400 megabyte files required only 40 megs of memory during
compression. The constant fraction can no doubt be improved but the O( N ) is
unavoidable.</p>
<h3>Decompression</h3>
<p>This is easy but requires seeking around in the output file as it is
reconstructed.</p>
<h2>Issues</h2>
<p>The current implementation is not optimized or very well tested. Some of the
tunable parameters have not been tested across different settings.</p>
<h2>Download</h2>
<p>This is very much work in progress, use at your own risk. The file format is
likely to change in the near future so do not archive anything important.</p>
<p>Subversion: svn://pauldoo.dyndns.org/home/svn/Programs/LRC</p>
<h2>Contact</h2>
<p><a href="mailto:paul.richards@gmail.com">paul.richards@gmail.com</a></p>
</div>
</body>
</html>
|
pauldoo/scratch
|
LRC/index.html
|
HTML
|
isc
| 6,434
|
#!/usr/bin/env python
#
# BBB-Network-Ammeter
#
# Copyright (c) 2016, Forest Crossman <cyrozap@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from datetime import datetime
from lxml import etree
from flask import Flask, Response
from Adafruit_BBIO import ADC
app = Flask(__name__)
def get_current():
voltage = get_adc_voltage()
current = 109.2 * voltage + 5.3688
return current
def get_adc_voltage():
# Read a value from the ADC
value = ADC.read("P9_39") # AIN0
# Convert the number to a voltage
voltage = value * 1.8
return voltage
@app.route("/sample")
def sample():
voltage = get_adc_voltage()
return Response("{:.03f} V".format(voltage))
@app.route("/probe")
def probe():
'''Generate a response for probe requests'''
mtconnect_schema = "urn:mtconnect.org:MTConnectDevices:1.3"
schema_url = "http://www.mtconnect.org/schemas/MTConnectDevices_1.3.xsd"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
MTConnectDevices = etree.Element("MTConnectDevices",
nsmap={
None: mtconnect_schema,
"xsi": xsi,
"m": mtconnect_schema,
}
)
MTConnectDevices.attrib["{{{pre}}}schemaLocation".format(pre=xsi)] = \
"{schema} {schema_url}".format(schema=mtconnect_schema, schema_url=schema_url)
creation_time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
Header = etree.SubElement(MTConnectDevices, "Header",
creationTime=creation_time,
instanceId="0",
sender="mtcagent",
bufferSize="0",
version="0.1",
assetCount="1",
)
Devices = etree.SubElement(MTConnectDevices, "Devices")
Device = etree.SubElement(Devices, "Device",
id="dev",
iso841Class="6",
name="currentSensor",
sampleInterval="10",
uuid="0",
)
Description = etree.SubElement(Device, "Description",
manufacturer="RPI MILL",
)
DataItems_0 = etree.SubElement(Device, "DataItems")
DataItem_0 = etree.SubElement(DataItems_0, "DataItem",
category="EVENT",
id="avail",
type="MACHINE_ON",
)
Components_0 = etree.SubElement(Device, "Components")
Axes = etree.SubElement(Components_0, "Axes", id="ax", name="Axes")
Components_1 = etree.SubElement(Axes, "Components")
Linear = etree.SubElement(Components_1, "Linear", id="x1", name="X")
DataItems_1 = etree.SubElement(Linear, "DataItems")
DataItem_1 = etree.SubElement(DataItems_1, "DataItem",
category="SAMPLE",
id="current1",
name="current1",
nativeUnits="AMPERE",
subType="ACTUAL",
type="CURRENT",
units="AMPERE",
)
response = etree.tostring(MTConnectDevices,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8'
)
return Response(response, mimetype='text/xml')
@app.route("/current")
def current():
mtconnect_schema = "urn:mtconnect.org:MTConnectStreams:1.3"
schema_url = "http://www.mtconnect.org/schemas/MTConnectStreams_1.3.xsd"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
MTConnectStreams = etree.Element("MTConnectStreams",
nsmap={
None: mtconnect_schema,
"xsi": xsi,
"m": mtconnect_schema,
}
)
MTConnectStreams.attrib["{{{pre}}}schemaLocation".format(pre=xsi)] = \
"{schema} {schema_url}".format(schema=mtconnect_schema, schema_url=schema_url)
creation_time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
Header = etree.SubElement(MTConnectStreams, "Header",
creationTime=creation_time,
instanceId="0",
sender="mtcagent",
bufferSize="0",
version="0.1",
assetCount="1",
)
Streams = etree.SubElement(MTConnectStreams, "Streams")
DeviceStream = etree.SubElement(Streams, "DeviceStream",
name="VMC-3Axis",
uuid="0",
)
ComponentStream = etree.SubElement(DeviceStream, "ComponentStream",
component="Rotary",
name="C",
componentId="c1",
)
Samples = etree.SubElement(ComponentStream, "Samples")
Current = etree.SubElement(Samples, "Current",
dataItemId="c2",
timestamp=datetime.utcnow().isoformat(),
name="Scurrent",
sequence="8403169415",
subType="ACTUAL",
)
Current.text = "{current:.03f}".format(current=get_current())
Events = etree.SubElement(ComponentStream, "Events")
MachineMode = etree.SubElement(Events, "MachineMode",
dataItemId="machineMode",
timestamp=datetime.utcnow().isoformat(),
name="Cmode",
sequence="18"
)
MachineMode.text = "ON"
response = etree.tostring(MTConnectStreams,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8'
)
return Response(response, mimetype='text/xml')
if __name__ == "__main__":
ADC.setup()
app.run(host='0.0.0.0', debug=False)
|
cyrozap/BBB-Network-Ammeter
|
server.py
|
Python
|
isc
| 5,648
|
package Perl;
use strict;
use v5.10;
use Exporter;
use Module::Load;
our $VERSION = 0.01;
our @ISA = qw(Exporter);
our @keywords = qw(perl);
our @EXPORT = qw(init needs);
sub perl {
exec("perldoc", @_);
}
sub init {
my $hashref = shift;
$hashref->{"perl"} = \&Perl::perl;
}
sub needs {
return qw();
}
1;
|
tekktonic/walter
|
Perl.pm
|
Perl
|
isc
| 326
|
/* ISC license. */
#include <s6-dns/s6dns-domain.h>
unsigned int s6dns_domain_encodelist (s6dns_domain_t *list, unsigned int n)
{
unsigned int i = 0 ;
for (; i < n ; i++)
if (!s6dns_domain_encode(list + i)) break ;
return i ;
}
|
skarnet/s6-dns
|
src/libs6dns/s6dns_domain_encodelist.c
|
C
|
isc
| 240
|
import mod1770 from './mod1770';
var value=mod1770+1;
export default value;
|
MirekSz/webpack-es6-ts
|
app/mods/mod1771.js
|
JavaScript
|
isc
| 76
|
#include <stan/math/fwd/scal.hpp>
#include <gtest/gtest.h>
#include <boost/math/special_functions/digamma.hpp>
#include <test/unit/math/fwd/scal/fun/nan_util.hpp>
TEST(AgradFwdLbeta,Fvar) {
using stan::math::fvar;
using boost::math::digamma;
using stan::math::lbeta;
fvar<double> x(0.5,1.0);
fvar<double> y(1.2,2.0);
double w = 1.3;
fvar<double> a = lbeta(x, y);
EXPECT_FLOAT_EQ(lbeta(0.5, 1.2), a.val_);
EXPECT_FLOAT_EQ(digamma(0.5) + 2.0 * digamma(1.2)
- (1.0 + 2.0) * digamma(0.5 + 1.2), a.d_);
fvar<double> b = lbeta(x, w);
EXPECT_FLOAT_EQ(lbeta(0.5, 1.3), b.val_);
EXPECT_FLOAT_EQ(1.0 * digamma(0.5) - 1.0 * digamma(0.5 + 1.3), b.d_);
fvar<double> c = lbeta(w, x);
EXPECT_FLOAT_EQ(lbeta(1.3, 0.5), c.val_);
EXPECT_FLOAT_EQ(1.0 * digamma(0.5) - 1.0 * digamma(1.3 + 0.5), c.d_);
}
TEST(AgradFwdLbeta,FvarFvarDouble) {
using stan::math::fvar;
using boost::math::digamma;
using stan::math::lbeta;
fvar<fvar<double> > x;
x.val_.val_ = 3.0;
x.val_.d_ = 1.0;
fvar<fvar<double> > y;
y.val_.val_ = 6.0;
y.d_.val_ = 1.0;
fvar<fvar<double> > a = lbeta(x,y);
EXPECT_FLOAT_EQ(lbeta(3.0,6.0), a.val_.val_);
EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_);
EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_);
EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_);
}
struct lbeta_fun {
template <typename T0, typename T1>
inline
typename boost::math::tools::promote_args<T0,T1>::type
operator()(const T0 arg1,
const T1 arg2) const {
return lbeta(arg1,arg2);
}
};
TEST(AgradFwdLbeta, nan) {
lbeta_fun lbeta_;
test_nan_fwd(lbeta_,3.0,5.0,false);
}
|
ariddell/httpstan
|
httpstan/lib/stan/lib/stan_math/test/unit/math/fwd/scal/fun/lbeta_test.cpp
|
C++
|
isc
| 1,654
|
/* load all RexxUtil functions */
Call RxFuncAdd 'SysLoadFuncs', 'RexxUtil', 'SysLoadFuncs'
Call SysLoadFuncs
'@echo off'
/* invoke test program */
CurrentDirectory = directory()
CurrentDirectory'\hybrid.exe /a8/e81/nSNX$'
if rc \=0 then do
/* obtain and issue error message */
say SysGetMessage(rc, 'OSO001.MSG')
say 'ReturnCode:' rc
end
/* wait */
'@pause'
|
OS2World/DRV-USBECD
|
hybrid/hybrid.cmd
|
Batchfile
|
isc
| 370
|
package org.apollo.net.codec.login;
/**
* An enumeration with the different states the {@link LoginDecoder} can be in.
*
* @author Graham
*/
public enum LoginDecoderState {
/**
* The login handshake state will wait for the username hash to be received. Once it is, a server session key will
* be sent to the client and the state will be set to the login header state.
*/
LOGIN_HANDSHAKE,
/**
* The login header state will wait for the login type and payload length to be received. These are saved, and then
* the state will be set to the login payload state.
*/
LOGIN_HEADER,
/**
* The login payload state will wait for all login information (such as client release number, username and
* password).
*/
LOGIN_PAYLOAD;
}
|
DealerNextDoor/ApolloDev
|
src/org/apollo/net/codec/login/LoginDecoderState.java
|
Java
|
isc
| 753
|
$().ready(function () {
var $likeDislikeTripButton = $('#likeDislikeTripButton'),
$likesCount = $('#likesCount'),
ajaxAFT = $('#ajaxAFT input[name="__RequestVerificationToken"]:first').val();
$likeDislikeTripButton.on('click', function () {
var $this = $(this),
valueAsString = $this.attr('data-value'),
value = false
if (valueAsString == 'like') {
value = true;
}
$.ajax({
type: "POST",
url: '/TripAjax/LikeDislikeTrip',
data: {
__RequestVerificationToken: ajaxAFT,
tripId: tripId,
value: value
},
success: function (response) {
if (response.Status) {
if (value) {
addDislikeButton();
} else {
addLikeButton();
}
updateLikeCounts(response.Data);
toastr.success("You have successfully " + valueAsString + " this trip.");
} else {
if (response.ErrorMessage) {
toastr.error(response.ErrorMessage);
} else {
toastr.error("Unable to " + valueAsString + " this trip.");
}
}
}
})
});
function updateLikeCounts(likesCount) {
$likesCount.text(likesCount);
}
function addDislikeButton() {
$likeDislikeTripButton.removeClass('likeButton');
$likeDislikeTripButton.addClass('dislikeButton');
$likeDislikeTripButton.attr('data-value', 'dislike');
}
function addLikeButton() {
$likeDislikeTripButton.removeClass('dislikeButton');
$likeDislikeTripButton.addClass('likeButton');
$likeDislikeTripButton.attr('data-value', 'like');
}
})
|
simeonpp/Trip-Destination
|
Source/TripDestination/Web/TripDestination.Web.MVC/Assets/javascript/src/once/trip-detailed-like.js
|
JavaScript
|
isc
| 1,944
|
//
// Copyright (c) 2014, Andy Best
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#define kABShaderHasErrorsEvent @"kABShaderHasErrorsEvent"
#define kABFFTUpdatedEvent @"kABFFTUpdatedEvent"
|
andybest/ShaderFiddle
|
ShaderFiddle/ABEventList.h
|
C
|
isc
| 913
|
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sysexits.h>
#include <bsd/bsd.h>
#include "array.h"
#include "dir.h"
#include "dir-print.h"
#include "dir-parse.h"
#include "dir-diff.h"
#include "net.h"
#include "util.h"
int main(const int argc, char **argv) {
bool detach = false;
bool safe = false;
char *dirname = NULL;
char *port = NULL;
int sfd = 0;
int cfd = 0;
clock_t dir_print_cl;
clock_t gen_cl;
char *dirbuf = NULL;
size_t dirbuf_len = 0;
struct dir_print_params dir_print_p = {
.path = ".",
.len = &dirbuf_len,
.cflag = false,
.is_action_list = false
};
struct array actionsbuf;
struct array actions;
array_init(&actionsbuf, sizeof(char), NULL);
array_init(&actions, sizeof(struct dir), NULL);
if (argc <= 1)
errx(EX_USAGE, "No arguments given, see -h for help");
for (int arg = 0; (arg = getopt(argc, argv, ":hsdr:p:")) != -1;) {
if (arg == 'h') {
warnx("usage: %s [-h -d] -r DIR -p PORT", getprogname());
warnx("%s", "");
warnx("options:");
warnx(" -h Show this help");
warnx(" -d Detach/daemonize");
warnx(" -s Do not modify files and dirs (dry run)");
warnx(" -r DIR Sync onto DIR");
warnx(" -p PORT Listen on PORT");
return 0;
} else if (arg == 'd') {
if (detach)
warnx("Multiple -d options have no extra effect");
detach = true;
} else if (arg == 's') {
if (safe)
warnx("Multiple -s options have no extra effect");
safe = true;
} else if (arg == 'r') {
if (dirname)
errx(EX_USAGE, "Multiple -r arguments are not allowed");
dirname = optarg;
} else if (arg == 'p') {
if (port)
errx(EX_USAGE, "Multiple -p arguments are not allowed");
port = optarg;
} else if (arg == ':') {
errx(EX_USAGE, "No parameter given for -%c", optopt);
} else if (arg == '?') {
errx(EX_USAGE, "Unrecognized argument -%c", optopt);
}
}
if (!dirname)
errx(EX_USAGE, "No root directory given, use -r");
if (!port)
errx(EX_USAGE, "No port given, use -p");
if (chdir(dirname) == -1)
err(EX_CANTCREAT, "chdir(): %s", dirname);
if (detach) {
pid_t pid = -1;
switch((pid = fork())) {
case -1: err(EX_OSERR, "fork()");
case 0: break; /* child */
default: /* parent */
warnx("Forked child PID: %d", pid);
return 0;
}
}
dir_print_cl = clock();
if (pthread_create(&dir_print_p.thread, NULL,
(thread_cb) dir_print_thread,
&dir_print_p) != 0) {
warnx("Cannot create thread to load dir structure");
return EX_OSERR;
}
if ((sfd = socket_listen(port)) == -1) {
dir_print_p.cflag = true;
(void) pthread_join(dir_print_p.thread, (void **) &dirbuf);
if (dirbuf) free(dirbuf);
return EX_OSERR;
}
if ((cfd = socket_accept(sfd)) == -1) {
socket_close(cfd, "listening socket");
dir_print_p.cflag = true;
(void) pthread_join(dir_print_p.thread, (void **) &dirbuf);
if (dirbuf) free(dirbuf);
return EX_OSERR;
}
(void) pthread_join(dir_print_p.thread, (void **) &dirbuf);
if (!dirbuf) {
warnx("Could not get dir structure buffer: %s", dirname);
socket_close(cfd, "connection socket");
return EX_OSERR;
}
data_stats("Loaded dir structure", timediff(dir_print_cl), dirbuf_len);
gen_cl = clock();
if (socket_sendbuf(cfd, dirbuf, dirbuf_len) == -1) {
warn("send()");
socket_close(cfd, "connection socket");
free(dirbuf);
return EX_OSERR;
}
data_stats("Sent dir structure", timediff(gen_cl), dirbuf_len);
/* We don't need that anymore. */
free(dirbuf);
gen_cl = clock();
if (socket_recvbuf(cfd, 1024 * 1024, &actionsbuf) == -1) {
array_free(&actionsbuf);
socket_close(cfd, "connection socket");
return EX_OSERR;
}
data_stats("Received dir-diff action list", timediff(gen_cl), actionsbuf.len);
if (dir_parsebuf(true, actionsbuf.ptr, &actions) == -1) {
warnx("Could not parse dir-diff action list");
socket_close(cfd, "connection socket");
array_free(&actionsbuf);
return EX_OSERR;
}
if (actions.len == 0) {
assert(actions.alen == 0);
assert(actions.ptr == NULL);
warnx("Action list is empty, nothing to be done.");
array_free(&actions);
array_free(&actionsbuf);
socket_close(cfd, "connection socket");
return 0;
}
warnx("Action list has %zd elements", actions.len);
array_traverse1(&actions, (array_cb1) dir_diff_action, &safe);
array_free(&actions);
array_free(&actionsbuf);
socket_close(cfd, "connection socket");
return 0;
}
|
fredmorcos/attic
|
projects/backy/archive/original/backyd-original.c
|
C
|
isc
| 4,803
|
# Django settings for test_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 't^4dt#fkxftpborp@%lg*#h2wj%vizl)#pkkt$&0f7b87rbu6y'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'test_project.urls'
WSGI_APPLICATION = 'test_project.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'django.contrib.admin',
'djcelery',
'django_nose',
'useful', # Import the app to run tests
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
TEMPLATE_CONTEXT_PROCESSORS = (
'useful.context_processors.settings',
)
BROKER_BACKEND = 'memory'
CELERY_ALWAYS_EAGER = True
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'cleanup': {
'task': 'useful.tasks.call_management_command',
'schedule': timedelta(seconds=10),
'args': ('validate', ),
},
}
|
yprez/django-useful
|
test_project/test_project_py2/settings.py
|
Python
|
isc
| 1,842
|
{-# OPTIONS_GHC -Wno-overlapping-patterns -Wno-incomplete-patterns -Wno-incomplete-uni-patterns -Wno-incomplete-record-updates #-}
-- | Index simplification mechanics.
module Futhark.Optimise.Simplify.Rules.Index
( IndexResult (..),
simplifyIndexing,
)
where
import Data.Maybe
import Futhark.Analysis.PrimExp.Convert
import qualified Futhark.Analysis.SymbolTable as ST
import Futhark.Construct
import Futhark.IR
import Futhark.Optimise.Simplify.Rules.Simple
import Futhark.Util
isCt1 :: SubExp -> Bool
isCt1 (Constant v) = oneIsh v
isCt1 _ = False
isCt0 :: SubExp -> Bool
isCt0 (Constant v) = zeroIsh v
isCt0 _ = False
-- | Some index expressions can be simplified to t'SubExp's, while
-- others produce another index expression (which may be further
-- simplifiable).
data IndexResult
= IndexResult Certs VName (Slice SubExp)
| SubExpResult Certs SubExp
-- | Try to simplify an index operation.
simplifyIndexing ::
MonadBuilder m =>
ST.SymbolTable (Rep m) ->
TypeLookup ->
VName ->
Slice SubExp ->
Bool ->
Maybe (m IndexResult)
simplifyIndexing vtable seType idd (Slice inds) consuming =
case defOf idd of
_
| Just t <- seType (Var idd),
Slice inds == fullSlice t [] ->
Just $ pure $ SubExpResult mempty $ Var idd
| Just inds' <- sliceIndices (Slice inds),
Just (ST.Indexed cs e) <- ST.index idd inds' vtable,
worthInlining e,
all (`ST.elem` vtable) (unCerts cs) ->
Just $ SubExpResult cs <$> toSubExp "index_primexp" e
| Just inds' <- sliceIndices (Slice inds),
Just (ST.IndexedArray cs arr inds'') <- ST.index idd inds' vtable,
all (worthInlining . untyped) inds'',
arr `ST.available` vtable,
all (`ST.elem` vtable) (unCerts cs) ->
Just $
IndexResult cs arr . Slice . map DimFix
<$> mapM (toSubExp "index_primexp") inds''
Nothing -> Nothing
Just (SubExp (Var v), cs) ->
Just $ pure $ IndexResult cs v $ Slice inds
Just (Iota _ x s to_it, cs)
| [DimFix ii] <- inds,
Just (Prim (IntType from_it)) <- seType ii ->
Just $
let mul = BinOpExp $ Mul to_it OverflowWrap
add = BinOpExp $ Add to_it OverflowWrap
in fmap (SubExpResult cs) $
toSubExp "index_iota" $
( sExt to_it (primExpFromSubExp (IntType from_it) ii)
`mul` primExpFromSubExp (IntType to_it) s
)
`add` primExpFromSubExp (IntType to_it) x
| [DimSlice i_offset i_n i_stride] <- inds ->
Just $ do
i_offset' <- asIntS to_it i_offset
i_stride' <- asIntS to_it i_stride
let mul = BinOpExp $ Mul to_it OverflowWrap
add = BinOpExp $ Add to_it OverflowWrap
i_offset'' <-
toSubExp "iota_offset" $
( primExpFromSubExp (IntType to_it) x
`mul` primExpFromSubExp (IntType to_it) s
)
`add` primExpFromSubExp (IntType to_it) i_offset'
i_stride'' <-
letSubExp "iota_offset" $
BasicOp $ BinOp (Mul Int64 OverflowWrap) s i_stride'
fmap (SubExpResult cs) $
letSubExp "slice_iota" $
BasicOp $ Iota i_n i_offset'' i_stride'' to_it
-- A rotate cannot be simplified away if we are slicing a rotated dimension.
Just (Rotate offsets a, cs)
| not $ or $ zipWith rotateAndSlice offsets inds -> Just $ do
dims <- arrayDims <$> lookupType a
let adjustI i o d = do
i_p_o <- letSubExp "i_p_o" $ BasicOp $ BinOp (Add Int64 OverflowWrap) i o
letSubExp "rot_i" (BasicOp $ BinOp (SMod Int64 Unsafe) i_p_o d)
adjust (DimFix i, o, d) =
DimFix <$> adjustI i o d
adjust (DimSlice i n s, o, d) =
DimSlice <$> adjustI i o d <*> pure n <*> pure s
IndexResult cs a . Slice <$> mapM adjust (zip3 inds offsets dims)
where
rotateAndSlice r DimSlice {} = not $ isCt0 r
rotateAndSlice _ _ = False
Just (Index aa ais, cs) ->
Just $
IndexResult cs aa
<$> subExpSlice (sliceSlice (primExpSlice ais) (primExpSlice (Slice inds)))
Just (Replicate (Shape [_]) (Var vv), cs)
| [DimFix {}] <- inds,
not consuming,
ST.available vv vtable ->
Just $ pure $ SubExpResult cs $ Var vv
| DimFix {} : is' <- inds,
not consuming,
ST.available vv vtable ->
Just $ pure $ IndexResult cs vv $ Slice is'
Just (Replicate (Shape [_]) val@(Constant _), cs)
| [DimFix {}] <- inds, not consuming -> Just $ pure $ SubExpResult cs val
Just (Replicate (Shape ds) v, cs)
| (ds_inds, rest_inds) <- splitAt (length ds) inds,
(ds', ds_inds') <- unzip $ mapMaybe index ds_inds,
ds' /= ds ->
Just $ do
arr <- letExp "smaller_replicate" $ BasicOp $ Replicate (Shape ds') v
return $ IndexResult cs arr $ Slice $ ds_inds' ++ rest_inds
where
index DimFix {} = Nothing
index (DimSlice _ n s) = Just (n, DimSlice (constant (0 :: Int64)) n s)
Just (Rearrange perm src, cs)
| rearrangeReach perm <= length (takeWhile isIndex inds) ->
let inds' = rearrangeShape (rearrangeInverse perm) inds
in Just $ pure $ IndexResult cs src $ Slice inds'
where
isIndex DimFix {} = True
isIndex _ = False
Just (Copy src, cs)
| Just dims <- arrayDims <$> seType (Var src),
length inds == length dims,
-- It is generally not safe to simplify a slice of a copy,
-- because the result may be used in an in-place update of the
-- original. But we know this can only happen if the original
-- is bound the same depth as we are!
all (isJust . dimFix) inds
|| maybe True ((ST.loopDepth vtable /=) . ST.entryDepth) (ST.lookup src vtable),
not consuming,
ST.available src vtable ->
Just $ pure $ IndexResult cs src $ Slice inds
Just (Reshape newshape src, cs)
| Just newdims <- shapeCoercion newshape,
Just olddims <- arrayDims <$> seType (Var src),
changed_dims <- zipWith (/=) newdims olddims,
not $ or $ drop (length inds) changed_dims ->
Just $ pure $ IndexResult cs src $ Slice inds
| Just newdims <- shapeCoercion newshape,
Just olddims <- arrayDims <$> seType (Var src),
length newshape == length inds,
length olddims == length newdims ->
Just $ pure $ IndexResult cs src $ Slice inds
Just (Reshape [_] v2, cs)
| Just [_] <- arrayDims <$> seType (Var v2) ->
Just $ pure $ IndexResult cs v2 $ Slice inds
Just (Concat d x xs _, cs)
| -- HACK: simplifying the indexing of an N-array concatenation
-- is going to produce an N-deep if expression, which is bad
-- when N is large. To try to avoid that, we use the
-- heuristic not to simplify as long as any of the operands
-- are themselves Concats. The hope it that this will give
-- simplification some time to cut down the concatenation to
-- something smaller, before we start inlining.
not $ any isConcat $ x : xs,
Just (ibef, DimFix i, iaft) <- focusNth d inds,
Just (Prim res_t) <-
(`setArrayDims` sliceDims (Slice inds))
<$> ST.lookupType x vtable -> Just $ do
x_len <- arraySize d <$> lookupType x
xs_lens <- mapM (fmap (arraySize d) . lookupType) xs
let add n m = do
added <- letSubExp "index_concat_add" $ BasicOp $ BinOp (Add Int64 OverflowWrap) n m
return (added, n)
(_, starts) <- mapAccumLM add x_len xs_lens
let xs_and_starts = reverse $ zip xs starts
let mkBranch [] =
letSubExp "index_concat" $ BasicOp $ Index x $ Slice $ ibef ++ DimFix i : iaft
mkBranch ((x', start) : xs_and_starts') = do
cmp <- letSubExp "index_concat_cmp" $ BasicOp $ CmpOp (CmpSle Int64) start i
(thisres, thisstms) <- collectStms $ do
i' <- letSubExp "index_concat_i" $ BasicOp $ BinOp (Sub Int64 OverflowWrap) i start
letSubExp "index_concat" . BasicOp . Index x' $
Slice $ ibef ++ DimFix i' : iaft
thisbody <- mkBodyM thisstms [subExpRes thisres]
(altres, altstms) <- collectStms $ mkBranch xs_and_starts'
altbody <- mkBodyM altstms [subExpRes altres]
letSubExp "index_concat_branch" $
If cmp thisbody altbody $
IfDec [primBodyType res_t] IfNormal
SubExpResult cs <$> mkBranch xs_and_starts
Just (ArrayLit ses _, cs)
| DimFix (Constant (IntValue (Int64Value i))) : inds' <- inds,
Just se <- maybeNth i ses ->
case inds' of
[] -> Just $ pure $ SubExpResult cs se
_ | Var v2 <- se -> Just $ pure $ IndexResult cs v2 $ Slice inds'
_ -> Nothing
-- Indexing single-element arrays. We know the index must be 0.
_
| Just t <- seType $ Var idd,
isCt1 $ arraySize 0 t,
DimFix i : inds' <- inds,
not $ isCt0 i ->
Just . pure . IndexResult mempty idd . Slice $
DimFix (constant (0 :: Int64)) : inds'
_ -> Nothing
where
defOf v = do
(BasicOp op, def_cs) <- ST.lookupExp v vtable
return (op, def_cs)
worthInlining e
| primExpSizeAtLeast 20 e = False -- totally ad-hoc.
| otherwise = worthInlining' e
worthInlining' (BinOpExp Pow {} _ _) = False
worthInlining' (BinOpExp FPow {} _ _) = False
worthInlining' (BinOpExp _ x y) = worthInlining' x && worthInlining' y
worthInlining' (CmpOpExp _ x y) = worthInlining' x && worthInlining' y
worthInlining' (ConvOpExp _ x) = worthInlining' x
worthInlining' (UnOpExp _ x) = worthInlining' x
worthInlining' FunExp {} = False
worthInlining' _ = True
isConcat v
| Just (Concat {}, _) <- defOf v =
True
| otherwise =
False
|
HIPERFIT/futhark
|
src/Futhark/Optimise/Simplify/Rules/Index.hs
|
Haskell
|
isc
| 10,142
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Rekanban</title>
<!-- le styles -->
<link rel="stylesheet" href="../stylesheets/profitably-branding.css">
<link href="../stylesheets/gitban.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- le main nav -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://www.gitban.com">Rekanban</a>
</div>
<div class="navbar-text">
<i class="fa fa-tasks"></i>
Account
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<!-- hidden
<li class="navbar-text">
<i class="fa fa-search"></i> Filter by:
</li>
<li style="margin-top:7px; width:300px;">
<select class="chosen-select" multiple>
<option value="1">Description</option>
<option value="2">Assignee</option>
<option value="3">Tag</option>
<option value="4">Type</option>
</select>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bookmark"></i>
Saved Filters
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Filter 1 <i class="fa fa-times pull-right"></i></a></li>
<li><a href="#">Filter 2 <i class="fa fa-times pull-right"></i></a></li>
<li><a href="#">Filter 3 <i class="fa fa-times pull-right"></i></a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-times"></i> Reset filters</a></li>
<li><a href="#"><i class="fa fa-save"></i> Save this filter</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-tasks"></i>
Boards
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu" role="menu">
<li class="dropdown-header"><i class="fa fa-tasks"></i> Boards</li>
<li><a href="#">Board 1</a></li>
<li><a href="#">Board 2</a></li>
<li><a href="#">Board 3</a></li>
<li class="dropdown-header"><i class="fa fa-files-o"></i> Recipes</li>
<li><a href="#">Apply Recipe 1</a></li>
<li><a href="#">Apply Recipe 2</a></li>
<li><a href="#">Apply Recipe 3</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-archive"></i> Archive</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-plus"></i> Create new Board</a></li>
<li><a href="#"><i class="fa fa-save"></i> Save this board as a recipe</a></li>
</ul>
</li>
-->
<li>
<a href="#notifications" data-toggle="modal">
<i class="fa fa-bell"></i>
Notifications
<span class="label label-default">10</span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="https://2.gravatar.com/avatar/8a81be5788345ffdf759aeae606ff716?d=https%3A%2F%2Fidenticons.github.com%2F0fd1f4d6a647daf66b2a3f79ecd7eb36.png&s=20">
adamrneary
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu">
<li class="dropdown-header">Account</li>
<li><a href="index.html" class='disabled'><i class="fa fa-gears"></i> Account</a></li>
<li><a href="boards.html" class='disabled'><i class="fa fa-tasks"></i> Boards</a></li>
<li><a href="recipes.html" class='disabled'><i class="fa fa-files-o"></i> Recipes</a></li>
<li><a href="tasks.html" class='disabled'><i class="fa fa-tasks"></i> Tasks</a></li>
<li><a href="notifications.html" class='disabled'><i class="fa fa-bell"></i> Notifications</a></li>
<li><a href="#" class='disabled'><i class="fa fa-money"></i> Account</a></li>
<li class="divider"></li>
<li><a href="#" class='disabled'><i class="fa fa-question"></i> Help</a></li>
<li><a href="#"><i class="fa fa-power-off"></i> Log out</a></li>
</ul>
</li>
</ul>
</div>
</nav><!-- end navigation -->
<div class="container">
<div class="row">
<div class="col-lg-9">
<div class="page-title">
<h1><i class="fa fa-bell"></i> Notifications</h1>
</div>
<div class="well well-sm">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="https://2.gravatar.com/avatar/8a81be5788345ffdf759aeae606ff716?d=https%3A%2F%2Fidenticons.github.com%2F0fd1f4d6a647daf66b2a3f79ecd7eb36.png&s=40">
</a>
<div class="media-body">
<h4 class="media-heading">adamneary</h4>
<p>
<span class="label label-primary">@kusic</span>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
</div>
</div>
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="https://1.gravatar.com/avatar/e55c09439e68fbaaf1231c9e725a8bdc?d=https%3A%2F%2Fidenticons.github.com%2F6789e600d8abaf5d52d427355d513fd2.png&s=40">
</a>
<div class="media-body">
<h4 class="media-heading">kusic</h4>
<p>
<span class="label label-primary">@adamneary</span>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
</div>
</div>
<button class="btn btn-success btn-block">Load more</button>
</div>
</div>
<div class="col-lg-3">
<div class="well text-center">
<img src="https://2.gravatar.com/avatar/8a81be5788345ffdf759aeae606ff716?d=https%3A%2F%2Fidenticons.github.com%2F0fd1f4d6a647daf66b2a3f79ecd7eb36.png&s=125">
<p>
Adam Neary
<br>
<span class="label label-primary">@adamneary</span>
</p>
<button class="btn btn-default btn-block">Change</button>
</div>
<ul class="list-group">
<li class="list-group-item"><a href="index.html">Profile</a></li>
<li class="list-group-item"><a href="boards.html">Boards</a></li>
<li class="list-group-item"><a href="recipes.html">Recipes</a></li>
<li class="list-group-item"><a href="tasks.html">Tasks</a></li>
<li class="list-group-item active"><a href="notifications.html">Notifications</a></li>
</ul>
<button class="btn btn-danger btn-block">Log out</button>
</div>
</div>
</div><!-- end .container -->
<!-- le footer -->
<div class="footer">
<p>© Profitably, Inc. 2013</p>
</div>
<!-- le notification modal -->
<div class="modal fade" id="notifications" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Notifications</h4>
</div>
<div class="modal-body">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="https://2.gravatar.com/avatar/8a81be5788345ffdf759aeae606ff716?d=https%3A%2F%2Fidenticons.github.com%2F0fd1f4d6a647daf66b2a3f79ecd7eb36.png&s=40">
</a>
<div class="media-body">
<h4 class="media-heading"><span class="label label-primary">adamneary</span> commented on a tasks
<a data-toggle="modal" href="#itemDetail">#1 Jack-in-the-box lorem</a></h4>
<hr>
<p>
<span class="label label-primary">@kusic</span>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
<span title="11/8/2013 7:30:07 PM">Nov 8 at 7:30 pm</span>
</div>
</div>
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="https://1.gravatar.com/avatar/e55c09439e68fbaaf1231c9e725a8bdc?d=https%3A%2F%2Fidenticons.github.com%2F6789e600d8abaf5d52d427355d513fd2.png&s=40">
</a>
<div class="media-body">
<h4 class="media-heading"><span class="label label-primary">@kusic</span> commented on a tasks
<a data-toggle="modal" href="#itemDetail">#1 Jack-in-the-box lorem</a></h4>
<hr>
<p>
<span class="label label-primary">@adamneary</span>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
<span title="11/8/2013 7:32:07 PM">Nov 8 at 7:32 pm</span>
</div>
</div><!-- end .modal-body -->
</div><!-- end .modal-content -->
<div class="modal-footer">
<button type="button" class="btn btn-danger">Close</button>
</div><!-- end .modal-footer -->
</div><!-- end .modal-dialog -->
</div><!-- end .modal -->
<!-- le javascript -->
<script src="http://code.jquery.com/jquery.js"></script>
<script src="../javascripts/profitably-branding.js"></script>
<script src="../javascripts/gitban.js"></script>
<!-- Typekit -->
<script type="text/javascript" src="//use.typekit.net/xff3ece.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
</body>
</html>
|
activecell/rekanban
|
static/account/notifications.html
|
HTML
|
isc
| 11,596
|
# Browser Games
A group of little games / experiments running in the browser : either with Canvas, WebGL or by manipulating the DOM.
## Canvas Snake
Taken from a [CSS Tricks guest post](http://css-tricks.com/learn-canvas-snake-game/) by [Nick Morgan aka Skilldrick](http://skilldrick.co.uk/). Introduces the Canvas API and basic game structures (game loop, collision detection).
## FPS meter
A homemade FPS meter. For a real one, see [this repository](https://github.com/Darsain/fpsmeter).
## Pixi.js sprites
Trying out the [pixi.js](http://www.pixijs.com/) animation framework.
## Letterpaint
Concept taken in [this tutorial](https://hacks.mozilla.org/2013/06/building-a-simple-paint-game-with-html5-canvas-and-vanilla-javascript/) by [Christian Heilmann](http://christianheilmann.com/). Another approach at the Canvas API, well suited for mobile devices.
## JS Platformer
Another implementation of [this game](https://github.com/jakesgordon/javascript-tiny-platformer) by Jake Gordon. Great game physics !
## JS Hero
Original game engine / experiment by [Inline Block](https://github.com/inlineblock/javascript-hero).
## Canvas Cosmos
Made by [Professor Cloud](http://www.professorcloud.com/mainsite/canvas-nebula.htm).
## Three.js trails
Inspired by [one of the experiments](http://hakim.se/experiments/html5/trail/01/) of Hakimel.
## Color Shmup
Prototype for the JS13K 2014 contest.
## Phaser Platformer
Experiments while [learning Phaser](http://www.photonstorm.com/phaser/tutorial-making-your-first-phaser-game).
## Reactive Pacman
Implementation of a tutorial on Bacon.js from [SitePoint](www.sitepoint.com/building-pacman-with-bacon-js/).
|
ThibWeb/browser-games
|
README.md
|
Markdown
|
isc
| 1,671
|
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var Module = require('module');
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var glob = require('glob');
var minimatch = require('minimatch');
var babel = require('babel');
var Istanbul = require('istanbul');
var Mocha = require('mocha');
var run;
function padRight(str, length) {
return str + Array(length - str.length + 1).join(' ');
}
function addSourceComments(source) {
var sourceComment;
var sourceMap;
var originalLines;
var generatedSource;
var line;
var lines = [];
var longestLine = 0;
var longestLineNumber = 0;
var outputItems = [];
var output = [];
var tmp;
var i;
var j;
generatedSource = source.split('\n');
sourceComment = source.match(/\n\/\/# sourceMappingURL=data:application\/json;base64,(.+)/);
if (!sourceComment) {
return source;
}
sourceMap = new SourceMapConsumer(new Buffer(sourceComment[1], 'base64').toString('utf8'));
originalLines = sourceMap.sourceContentFor(sourceMap.sources[0]).split('\n');
for (i = 1; i <= generatedSource.length; i++) {
lines.push([]);
}
sourceMap.eachMapping(function sourceMapIterator(mapping) {
if (lines[mapping.generatedLine].indexOf(mapping.originalLine) === -1) {
lines[mapping.generatedLine].push(mapping.originalLine);
}
});
for (i = 1; i < generatedSource.length; i++) {
tmp = {
generated: generatedSource[i - 1],
original: false
};
line = '';
for (j = 0; j < lines[i].length; j++) {
line += originalLines[lines[i][j] - 1];
}
if (line !== '') {
tmp.original = line;
if (lines[i].length === 1) {
tmp.lineNumbers = '// Line: ' + lines[i][0];
}
else {
tmp.lineNumbers = '// Lines: ' + lines[i].join(',');
}
if (tmp.lineNumbers.length > longestLineNumber) {
longestLineNumber = tmp.lineNumbers.length;
}
}
// get the longest line length
if (generatedSource[i - 1].length > longestLine) {
longestLine = generatedSource[i - 1].length;
}
outputItems.push(tmp);
}
for (i = 0; i < outputItems.length; i++) {
if (outputItems[i].original) {
output.push(
padRight(outputItems[i].generated, longestLine + 3) +
padRight(outputItems[i].lineNumbers, longestLineNumber + 1) +
'| ' + outputItems[i].original
);
}
else {
output.push(outputItems[i].generated);
}
}
return output.join('\n');
}
function initMocha(mocha, testGlobs, options) {
var i;
var j;
var files;
for (i = 0; i < options.require.length; i++) {
require(options.require[i]);
}
for (i = 0; i < testGlobs.length; i++) {
files = glob.sync(testGlobs[i]);
for (j = 0; j < files.length; j++) {
mocha.addFile(files[j]);
}
}
return mocha;
}
function initIstanbulCallback(sourceStore, collector, options) {
global[options.istanbul.coverageVariable] = {};
function reporterCallback() {
collector.add(global[options.istanbul.coverageVariable]);
_.forOwn(options.istanbul.reporters, function reporterIterator(reporterOptions, name) {
Istanbul.Report
.create(name, _.defaults({
sourceStore: sourceStore, // include this always, not used by every reporter
dir: options.istanbul.directory // most (all?) reporters use this
}, reporterOptions))
.writeReport(collector, true);
});
}
return reporterCallback;
}
function initModuleRequire(instrumenter, sourceStore, options) {
Module._extensions['.js'] = function moduleExtension(module, filename) {
var matcher = minimatch.bind(null, filename);
var src = fs.readFileSync(filename, {
encoding: 'utf8'
});
// replace tabs with spaces
src = src.replace(/^\t+/gm, function tabsReplace(match) {
// hard code to 2 spaces per tabs for now, istanbul uses 2
return match.replace(/\t/g, ' ');
});
if (_.any(options.babelInclude, matcher) && !_.any(options.babelExclude, matcher)) {
options.babel.filename = filename;
try {
src = babel.transform(src, options.babel).code;
} catch (e) {
throw new Error('Error during babel transform - ' + filename + ': \n' + e.message);
}
}
if (!_.any(options.istanbul.exclude, matcher)) {
sourceStore.set(filename, addSourceComments(src));
try {
src = instrumenter.instrumentSync(src, filename);
} catch (e) {
throw new Error('Error during istanbul instrument - ' + filename + ': \n' + e.message);
}
}
module._compile(src, filename);
};
return Module._extensions['.js'];
}
function defaults(options) {
var i;
var opts = {};
opts.tests = options.tests? options.tests: ['test/**/*.js'];
opts.istanbul = _.defaults({}, options.istanbul, {
directory: 'coverage',
reporters: {
html: {},
text: {}
},
collector: {},
instrumenter: {},
coverageVariable: '__istanbul_coverage__',
exclude: []
});
opts.istanbul.instrumenter.coverageVariable = opts.istanbul.coverageVariable;
if (!_.isArray(opts.tests)) {
opts.tests = [opts.tests];
}
if (options.istanbul && options.istanbul.reporters) {
opts.istanbul.reporters = options.istanbul.reporters;
}
// add tests directories and node modules to the istanbul ignore
for (i = 0; i < opts.tests.length; i++) {
if (opts.tests[i][0] !== '/' && opts.tests[i].substr(0, 2) !== '**') {
opts.istanbul.exclude.push('**/' + opts.tests[i]);
}
else {
opts.istanbul.exclude.push(opts.tests[i]);
}
}
opts.istanbul.exclude.push('**/node_modules/**/*');
opts.mocha = _.defaults({}, options.mocha, {
require: []
});
if (!_.isArray(opts.mocha.require)) {
opts.mocha.require = [opts.mocha.require];
}
for (i = 0; i < opts.mocha.require.length; i++) {
opts.mocha.require[i] = path.resolve(opts.mocha.require[i]);
}
// convert greps to regex
if (opts.mocha.grep) {
if (!_.isArray(opts.mocha.grep)) {
opts.mocha.grep = [opts.mocha.grep];
}
for (i = 0; i < opts.mocha.grep.length; i++) {
if (!_.isRegExp(opts.mocha.grep[i])) {
opts.mocha.grep[i] = new RegExp(opts.mocha.grep[i]);
}
}
}
opts.babel = _.defaults({
sourceMap: 'inline'
}, options.babel, {
include: ['**/*.jsx', '**/*.js'],
exclude: []
}
);
opts.babelInclude = opts.babel.include;
opts.babelExclude = opts.babel.exclude;
delete opts.babel.include;
delete opts.babel.exclude;
if (!_.isArray(opts.babelInclude)) {
opts.babelInclude = [opts.babelInclude];
}
if (!_.isArray(opts.babelExclude)) {
opts.babelExclude = [opts.babelExclude];
}
opts.babelExclude.push('**/node_modules/**/*');
return _.cloneDeep(opts);
}
run = function run(options) {
var mocha;
var istanbulCallback;
var instrumenter;
var collector;
var sourceStore = Istanbul.Store.create('memory');
var opts = defaults(options);
instrumenter = new Istanbul.Instrumenter(opts.istanbul.instrumenter);
collector = new Istanbul.Collector(opts.istanbul.collector);
mocha = new Mocha(opts.mocha);
initMocha(mocha, opts.tests, opts.mocha);
initModuleRequire(instrumenter, sourceStore, opts);
istanbulCallback = initIstanbulCallback(
sourceStore, collector, opts
);
mocha.run(istanbulCallback);
};
module.exports = run;
|
MitMaro/MochaBabelCoverage
|
src/runner.js
|
JavaScript
|
isc
| 7,065
|
# react-tests-globals-setup
If you want to unit test react components with node & mocha, some globals need to be set up to make the environment more browser-like.
This will set up those globals.
The current version of this module uses a fake DOM provided by `jsdom@3`, which works with node 0.10 and 0.12. A future version will use newer jsdom and require node 4.
## Usage
```
npm install react-tests-globals-setup --save-dev
```
Then add it as an argument to `mocha`, probably in your package.json:
```
"scripts": {
"test": "mocha --require react-tests-globals-setup"
}
```
Or in `mocha.opts`
```
--require react-tests-globals-setup
```
## Testing
```
npm test
```
## Linting
```
npm run lint
```
|
holidayextras/react-tests-globals-setup
|
README.md
|
Markdown
|
isc
| 720
|
import CDGPlayer from './CDGPlayer'
export default CDGPlayer
|
bhj/karaoke-forever
|
src/routes/Player/components/Player/CDGPlayer/index.js
|
JavaScript
|
isc
| 62
|
// Copyright (c) 2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package mining
import (
"container/heap"
"math/rand"
"testing"
"github.com/btcsuite/btcd/btcutil"
)
// TestTxFeePrioHeap ensures the priority queue for transaction fees and
// priorities works as expected.
func TestTxFeePrioHeap(t *testing.T) {
// Create some fake priority items that exercise the expected sort
// edge conditions.
testItems := []*txPrioItem{
{feePerKB: 5678, priority: 3},
{feePerKB: 5678, priority: 1},
{feePerKB: 5678, priority: 1}, // Duplicate fee and prio
{feePerKB: 5678, priority: 5},
{feePerKB: 5678, priority: 2},
{feePerKB: 1234, priority: 3},
{feePerKB: 1234, priority: 1},
{feePerKB: 1234, priority: 5},
{feePerKB: 1234, priority: 5}, // Duplicate fee and prio
{feePerKB: 1234, priority: 2},
{feePerKB: 10000, priority: 0}, // Higher fee, smaller prio
{feePerKB: 0, priority: 10000}, // Higher prio, lower fee
}
// Add random data in addition to the edge conditions already manually
// specified.
randSeed := rand.Int63()
defer func() {
if t.Failed() {
t.Logf("Random numbers using seed: %v", randSeed)
}
}()
prng := rand.New(rand.NewSource(randSeed))
for i := 0; i < 1000; i++ {
testItems = append(testItems, &txPrioItem{
feePerKB: int64(prng.Float64() * btcutil.SatoshiPerBitcoin),
priority: prng.Float64() * 100,
})
}
// Test sorting by fee per KB then priority.
var highest *txPrioItem
priorityQueue := newTxPriorityQueue(len(testItems), true)
for i := 0; i < len(testItems); i++ {
prioItem := testItems[i]
if highest == nil {
highest = prioItem
}
if prioItem.feePerKB >= highest.feePerKB &&
prioItem.priority > highest.priority {
highest = prioItem
}
heap.Push(priorityQueue, prioItem)
}
for i := 0; i < len(testItems); i++ {
prioItem := heap.Pop(priorityQueue).(*txPrioItem)
if prioItem.feePerKB >= highest.feePerKB &&
prioItem.priority > highest.priority {
t.Fatalf("fee sort: item (fee per KB: %v, "+
"priority: %v) higher than than prev "+
"(fee per KB: %v, priority %v)",
prioItem.feePerKB, prioItem.priority,
highest.feePerKB, highest.priority)
}
highest = prioItem
}
// Test sorting by priority then fee per KB.
highest = nil
priorityQueue = newTxPriorityQueue(len(testItems), false)
for i := 0; i < len(testItems); i++ {
prioItem := testItems[i]
if highest == nil {
highest = prioItem
}
if prioItem.priority >= highest.priority &&
prioItem.feePerKB > highest.feePerKB {
highest = prioItem
}
heap.Push(priorityQueue, prioItem)
}
for i := 0; i < len(testItems); i++ {
prioItem := heap.Pop(priorityQueue).(*txPrioItem)
if prioItem.priority >= highest.priority &&
prioItem.feePerKB > highest.feePerKB {
t.Fatalf("priority sort: item (fee per KB: %v, "+
"priority: %v) higher than than prev "+
"(fee per KB: %v, priority %v)",
prioItem.feePerKB, prioItem.priority,
highest.feePerKB, highest.priority)
}
highest = prioItem
}
}
|
btcsuite/btcd
|
mining/mining_test.go
|
GO
|
isc
| 3,095
|
/*
* %ISC_START_LICENSE%
* ---------------------------------------------------------------------
* Copyright 2006-2018, Pittsburgh Supercomputing Center
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
* --------------------------------------------------------------------
* %END_LICENSE%
*/
#define _PFL_ASM(code, ...) __asm__ __volatile__("lock; " code, ## __VA_ARGS__)
#define _PFL_NL_ASM(code, ...) __asm__ __volatile__(code, ## __VA_ARGS__)
#define PSC_ATOMIC16_INIT(i) { i }
#define PSC_ATOMIC32_INIT(i) { i }
#define PSC_ATOMIC64_INIT(i) { i }
#define _PFL_GETA16(v) ((v)->value16)
#define _PFL_GETA32(v) ((v)->value32)
#define _PFL_GETA64(v) ((v)->value64)
#undef psc_atomic16_init
static __inline void
psc_atomic16_init(__unusedx psc_atomic16_t *v)
{
}
#undef psc_atomic32_init
static __inline void
psc_atomic32_init(__unusedx psc_atomic32_t *v)
{
}
#undef psc_atomic64_init
static __inline void
psc_atomic64_init(__unusedx psc_atomic64_t *v)
{
}
#undef psc_atomic16_read
static __inline int16_t
psc_atomic16_read(psc_atomic16_t *v)
{
return (_PFL_GETA16(v));
}
#undef psc_atomic32_read
static __inline int32_t
psc_atomic32_read(psc_atomic32_t *v)
{
return (_PFL_GETA32(v));
}
#undef psc_atomic64_read
static __inline int64_t
psc_atomic64_read(const psc_atomic64_t *v)
{
return (_PFL_GETA64(v));
}
#undef psc_atomic16_set
static __inline void
psc_atomic16_set(psc_atomic16_t *v, int16_t i)
{
_PFL_GETA16(v) = i;
}
#undef psc_atomic32_set
static __inline void
psc_atomic32_set(psc_atomic32_t *v, int32_t i)
{
_PFL_GETA32(v) = i;
}
#undef psc_atomic64_set
static __inline void
psc_atomic64_set(psc_atomic64_t *v, int64_t i)
{
_PFL_GETA64(v) = i;
}
#undef psc_atomic16_add
static __inline void
psc_atomic16_add(psc_atomic16_t *v, int16_t i)
{
_PFL_ASM("addw %1,%0" : "=m" _PFL_GETA16(v) : "ir" (i), "m" _PFL_GETA16(v));
}
#undef psc_atomic32_add
static __inline void
psc_atomic32_add(psc_atomic32_t *v, int32_t i)
{
_PFL_ASM("addl %1,%0" : "=m" _PFL_GETA32(v) : "ir" (i), "m" _PFL_GETA32(v));
}
#undef psc_atomic64_add
static __inline void
psc_atomic64_add(psc_atomic64_t *v, int64_t i)
{
_PFL_ASM("addq %1,%0" : "=m" _PFL_GETA64(v) : "ir" (i), "m" _PFL_GETA64(v));
}
#undef psc_atomic16_sub
static __inline void
psc_atomic16_sub(psc_atomic16_t *v, int16_t i)
{
_PFL_ASM("subw %1,%0" : "=m" _PFL_GETA16(v) : "ir" (i), "m" _PFL_GETA16(v));
}
#undef psc_atomic32_sub
static __inline void
psc_atomic32_sub(psc_atomic32_t *v, int32_t i)
{
_PFL_ASM("subl %1,%0" : "=m" _PFL_GETA32(v) : "ir" (i), "m" _PFL_GETA32(v));
}
#undef psc_atomic64_sub
static __inline void
psc_atomic64_sub(psc_atomic64_t *v, int64_t i)
{
_PFL_ASM("subq %1,%0" : "=m" _PFL_GETA64(v) : "ir" (i), "m" _PFL_GETA64(v));
}
#undef psc_atomic16_sub_and_test0
static __inline int
psc_atomic16_sub_and_test0(psc_atomic16_t *v, int16_t i)
{
unsigned char c;
_PFL_ASM("subw %2, %0; sete %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_sub_and_test0
static __inline int
psc_atomic32_sub_and_test0(psc_atomic32_t *v, int32_t i)
{
unsigned char c;
_PFL_ASM("subl %2, %0; sete %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_sub_and_test0
static __inline int
psc_atomic64_sub_and_test0(psc_atomic64_t *v, int64_t i)
{
unsigned char c;
_PFL_ASM("subq %2, %0; sete %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_add_and_test0
static __inline int
psc_atomic16_add_and_test0(psc_atomic16_t *v, int16_t i)
{
unsigned char c;
_PFL_ASM("addw %2, %0; sete %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_add_and_test0
static __inline int
psc_atomic32_add_and_test0(psc_atomic32_t *v, int32_t i)
{
unsigned char c;
_PFL_ASM("addl %2, %0; sete %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_add_and_test0
static __inline int
psc_atomic64_add_and_test0(psc_atomic64_t *v, int64_t i)
{
unsigned char c;
_PFL_ASM("addq %2, %0; sete %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_inc
static __inline void
psc_atomic16_inc(psc_atomic16_t *v)
{
_PFL_ASM("incw %0" : "=m" _PFL_GETA16(v) : "m" _PFL_GETA16(v));
}
#undef psc_atomic32_inc
static __inline void
psc_atomic32_inc(psc_atomic32_t *v)
{
_PFL_ASM("incl %0" : "=m" _PFL_GETA32(v) : "m" _PFL_GETA32(v));
}
#undef psc_atomic64_inc
static __inline void
psc_atomic64_inc(psc_atomic64_t *v)
{
_PFL_ASM("incq %0" : "=m" _PFL_GETA64(v) : "m" _PFL_GETA64(v));
}
#undef psc_atomic16_dec
static __inline void
psc_atomic16_dec(psc_atomic16_t *v)
{
_PFL_ASM("decw %0" : "=m" _PFL_GETA16(v) : "m" _PFL_GETA16(v));
}
#undef psc_atomic32_dec
static __inline void
psc_atomic32_dec(psc_atomic32_t *v)
{
_PFL_ASM("decl %0" : "=m" _PFL_GETA32(v) : "m" _PFL_GETA32(v));
}
#undef psc_atomic64_dec
static __inline void
psc_atomic64_dec(psc_atomic64_t *v)
{
_PFL_ASM("decq %0" : "=m" _PFL_GETA64(v) : "m" _PFL_GETA64(v));
}
#undef psc_atomic16_inc_and_test0
static __inline int
psc_atomic16_inc_and_test0(psc_atomic16_t *v)
{
unsigned char c;
_PFL_ASM("incw %0; sete %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_inc_and_test0
static __inline int
psc_atomic32_inc_and_test0(psc_atomic32_t *v)
{
unsigned char c;
_PFL_ASM("incl %0; sete %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_inc_and_test0
static __inline int
psc_atomic64_inc_and_test0(psc_atomic64_t *v)
{
unsigned char c;
_PFL_ASM("incq %0; sete %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_dec_and_test0
static __inline int
psc_atomic16_dec_and_test0(psc_atomic16_t *v)
{
unsigned char c;
_PFL_ASM("decw %0; sete %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_dec_and_test0
static __inline int
psc_atomic32_dec_and_test0(psc_atomic32_t *v)
{
unsigned char c;
_PFL_ASM("decl %0; sete %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_dec_and_test0
static __inline int
psc_atomic64_dec_and_test0(psc_atomic64_t *v)
{
unsigned char c;
_PFL_ASM("decq %0; sete %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_add_and_test_neg
static __inline int
psc_atomic16_add_and_test_neg(psc_atomic16_t *v, int16_t i)
{
unsigned char c;
_PFL_ASM("addw %2, %0; sets %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_add_and_test_neg
static __inline int
psc_atomic32_add_and_test_neg(psc_atomic32_t *v, int32_t i)
{
unsigned char c;
_PFL_ASM("addl %2, %0; sets %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_add_and_test_neg
static __inline int
psc_atomic64_add_and_test_neg(psc_atomic64_t *v, int64_t i)
{
unsigned char c;
_PFL_ASM("addq %2, %0; sets %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_sub_and_test_neg
static __inline int
psc_atomic16_sub_and_test_neg(psc_atomic16_t *v, int16_t i)
{
unsigned char c;
_PFL_ASM("subw %2, %0; sets %1" : "=m" _PFL_GETA16(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA16(v) : "memory");
return (c);
}
#undef psc_atomic32_sub_and_test_neg
static __inline int
psc_atomic32_sub_and_test_neg(psc_atomic32_t *v, int32_t i)
{
unsigned char c;
_PFL_ASM("subl %2, %0; sets %1" : "=m" _PFL_GETA32(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA32(v) : "memory");
return (c);
}
#undef psc_atomic64_sub_and_test_neg
static __inline int
psc_atomic64_sub_and_test_neg(psc_atomic64_t *v, int64_t i)
{
unsigned char c;
_PFL_ASM("subq %2, %0; sets %1" : "=m" _PFL_GETA64(v),
"=qm" (c) : "ir" (i), "m" _PFL_GETA64(v) : "memory");
return (c);
}
#undef psc_atomic16_add_getnew
static __inline int16_t
psc_atomic16_add_getnew(psc_atomic16_t *v, int16_t i)
{
int16_t adj = i;
_PFL_ASM("xaddw %0, %1" : "+r" (i),
"+m" _PFL_GETA16(v) : : "memory");
return (i + adj);
}
#undef psc_atomic32_add_getnew
static __inline int32_t
psc_atomic32_add_getnew(psc_atomic32_t *v, int32_t i)
{
int32_t adj = i;
_PFL_ASM("xaddl %0, %1" : "+r" (i),
"+m" _PFL_GETA32(v) : : "memory");
return (i + adj);
}
#undef psc_atomic64_add_getnew
static __inline int64_t
psc_atomic64_add_getnew(psc_atomic64_t *v, int64_t i)
{
int64_t adj = i;
_PFL_ASM("xaddq %0, %1" : "+r" (i),
"+m" _PFL_GETA64(v) : : "memory");
return (i + adj);
}
#undef psc_atomic16_clearmask
static __inline void
psc_atomic16_clearmask(psc_atomic16_t *v, int16_t mask)
{
mask = ~mask;
_PFL_ASM("andw %0, %1" : : "r" (mask),
"m" _PFL_GETA16(v) : "memory");
}
#undef psc_atomic32_clearmask
static __inline void
psc_atomic32_clearmask(psc_atomic32_t *v, int32_t mask)
{
mask = ~mask;
_PFL_ASM("andl %0, %1" : : "r" (mask),
"m" _PFL_GETA32(v) : "memory");
}
#undef psc_atomic64_clearmask
static __inline void
psc_atomic64_clearmask(psc_atomic64_t *v, int64_t mask)
{
mask = ~mask;
_PFL_ASM("andq %0, %1" : : "r" (mask),
"m" _PFL_GETA64(v) : "memory");
}
#undef psc_atomic16_setmask
static __inline void
psc_atomic16_setmask(psc_atomic16_t *v, int16_t mask)
{
_PFL_ASM("orw %0, %1" : : "r" (mask),
"m" _PFL_GETA16(v) : "memory");
}
#undef psc_atomic32_setmask
static __inline void
psc_atomic32_setmask(psc_atomic32_t *v, int32_t mask)
{
_PFL_ASM("orl %0, %1" : : "r" (mask),
"m" _PFL_GETA32(v) : "memory");
}
#undef psc_atomic64_setmask
static __inline void
psc_atomic64_setmask(psc_atomic64_t *v, int64_t mask)
{
_PFL_ASM("orq %0, %1" : : "r" (mask),
"m" _PFL_GETA64(v) : "memory");
}
#undef psc_atomic16_clearmask_getnew
static __inline int16_t
psc_atomic16_clearmask_getnew(psc_atomic16_t *v, int16_t mask)
{
int16_t oldv = mask;
mask = ~mask;
_PFL_ASM("andw %0, %1;" : "=r" (mask)
: "m" _PFL_GETA16(v), "0" (oldv));
return (oldv & ~mask);
}
#undef psc_atomic32_clearmask_getnew
static __inline int32_t
psc_atomic32_clearmask_getnew(psc_atomic32_t *v, int32_t mask)
{
int32_t oldv = mask;
mask = ~mask;
_PFL_ASM("andl %0, %1;" : "=r" (mask)
: "m" _PFL_GETA32(v), "0" (oldv));
return (oldv & ~mask);
}
#undef psc_atomic64_clearmask_getnew
static __inline int64_t
psc_atomic64_clearmask_getnew(psc_atomic64_t *v, int64_t mask)
{
int64_t oldv = mask;
mask = ~mask;
_PFL_ASM("andq %0, %1;" : "=r" (mask)
: "m" _PFL_GETA64(v), "0" (oldv));
return (oldv & ~mask);
}
#undef psc_atomic16_setmask_getnew
static __inline int16_t
psc_atomic16_setmask_getnew(psc_atomic16_t *v, int16_t i)
{
int16_t oldv = i;
_PFL_ASM("orw %0, %1;" : "=r" (i)
: "m" _PFL_GETA16(v), "0" (oldv));
return (oldv | i);
}
#undef psc_atomic32_setmask_getnew
static __inline int32_t
psc_atomic32_setmask_getnew(psc_atomic32_t *v, int32_t i)
{
int32_t oldv = i;
_PFL_ASM("orl %0, %1;" : "=r" (i)
: "m" _PFL_GETA32(v), "0" (oldv));
return (oldv | i);
}
#undef psc_atomic64_setmask_getnew
static __inline int64_t
psc_atomic64_setmask_getnew(psc_atomic64_t *v, int64_t i)
{
int64_t oldv = i;
_PFL_ASM("orq %0, %1;" : "=r" (i)
: "m" _PFL_GETA64(v), "0" (oldv));
return (oldv | i);
}
#undef psc_atomic16_xchg
static __inline int16_t
psc_atomic16_xchg(psc_atomic16_t *v, int16_t i)
{
_PFL_NL_ASM("xchgw %0, %1" : "=r" (i)
: "m" _PFL_GETA16(v), "0" (i) : "memory");
return (i);
}
#undef psc_atomic32_xchg
static __inline int32_t
psc_atomic32_xchg(psc_atomic32_t *v, int32_t i)
{
_PFL_NL_ASM("xchgl %0, %1" : "=r" (i)
: "m" _PFL_GETA32(v), "0" (i) : "memory");
return (i);
}
#undef PSC_ATOMIC32_XCHG
#define PSC_ATOMIC32_XCHG(v, i) \
_PFL_RVSTART { \
int32_t _aval = (i); \
\
_PFL_NL_ASM("xchgl %0, %1" : "=r" (_aval) \
: "m" _PFL_GETA32(v), "0" (_aval) : "memory"); \
_aval; \
} _PFL_RVEND
#undef psc_atomic64_xchg
static __inline int64_t
psc_atomic64_xchg(psc_atomic64_t *v, int64_t i)
{
_PFL_NL_ASM("xchgq %0, %1" : "=r" (i)
: "m" _PFL_GETA64(v), "0" (i) : "memory");
return (i);
}
static __inline int16_t
psc_atomic16_cmpxchg(psc_atomic16_t *v, int16_t cmpv, int16_t newv)
{
int16_t oldv;
_PFL_ASM("cmpxchgw %1, %2" : "=a" (oldv) : "r" (newv),
"m" _PFL_GETA16(v), "0" (cmpv) : "memory");
return (oldv);
}
static __inline int32_t
psc_atomic32_cmpxchg(psc_atomic32_t *v, int32_t cmpv, int32_t newv)
{
int32_t oldv;
_PFL_ASM("cmpxchgl %k1,%2" : "=a" (oldv) : "r" (newv),
"m" _PFL_GETA32(v), "0" (cmpv) : "memory");
return (oldv);
}
static __inline int64_t
psc_atomic64_cmpxchg(psc_atomic64_t *v, int64_t cmpv, int64_t newv)
{
int64_t oldv;
_PFL_ASM("cmpxchgq %1, %2" : "=a" (oldv) : "r" (newv),
"m" _PFL_GETA64(v), "0" (cmpv) : "memory");
return (oldv);
}
|
pscedu/pfl
|
pfl/compat/amd64/atomic.h
|
C
|
isc
| 13,919
|
from flatten import *
POS_SIZE = 2**23 - 1
NEG_SIZE = -2**23
OPTIMIZE = True
OPTIMIZERS = {
'set': 'SET',
'setglobal': 'SET_GLOBAL',
'local': 'SET_LOCAL',
'get': 'GET',
'getglobal': 'GET_GLOBAL',
'return': 'RETURN',
'recurse': 'RECURSE',
'drop': 'DROP',
'dup': 'DUP',
'[]': 'NEW_LIST',
'{}': 'NEW_DICT',
'swap': 'SWAP',
'rot': 'ROT',
'over': 'OVER',
'pop-from': 'POP_FROM',
'push-to': 'PUSH_TO',
'push-through': 'PUSH_THROUGH',
'has': 'HAS_DICT',
'get-from': 'GET_DICT',
'set-to': 'SET_DICT',
'raise': 'RAISE',
'reraise': 'RERAISE',
'call': 'CALL',
}
ARGED_OPT = set('SET SET_LOCAL SET_GLOBAL GET GET_GLOBAL'.split())
positional_instructions = set('JMP JMPZ LABDA JMPEQ JMPNE ENTER_ERRHAND'.split())
def convert(filename, flat):
bytecode = [SingleInstruction('SOURCE_FILE', String(None, '"' + filename))]
for k in flat:
if isinstance(k, SingleInstruction):
bytecode.append(k)
elif isinstance(k, Code):
for w in k.words:
if isinstance(w, ProperWord):
if OPTIMIZE and w.value in OPTIMIZERS:
if OPTIMIZERS[w.value] in ARGED_OPT:
if bytecode and bytecode[-1].opcode == 'PUSH_LITERAL' and isinstance(bytecode[-1].ref, Ident):
s = bytecode.pop().ref
else:
bytecode.append(SingleInstruction('PUSH_WORD', w))
continue
else:
s = 0
bytecode.append(SingleInstruction(OPTIMIZERS[w.value], s))
elif w.value == 'for':
mstart = Marker()
mend = Marker()
bytecode.extend([
mstart,
SingleInstruction('DUP', 0),
SingleInstruction('JMPZ', mend),
SingleInstruction('CALL', 0),
SingleInstruction('JMP', mstart),
mend,
SingleInstruction('DROP', 0)
])
elif w.value == '(:split:)':
mparent = Marker()
mchild = Marker()
bytecode.extend([
SingleInstruction('LABDA', mparent),
SingleInstruction('JMP', mchild),
mparent,
SingleInstruction('RETURN', 0),
mchild,
])
elif w.value == '\xce\xbb': #U+03BB GREEK SMALL LETTER LAMDA
for i in range(len(bytecode) - 1, -1, -1):
l = bytecode[i]
if isinstance(l, SingleInstruction) and l.opcode == 'PUSH_WORD' and l.ref.value == ';':
l.opcode = 'LABDA'
l.ref = Marker()
bytecode.extend([
SingleInstruction('RETURN', 0),
l.ref,
])
break
else:
raise DejaSyntaxError('Inline lambda without closing semi-colon.')
elif '!' in w.value:
if w.value.startswith('!'):
w.value = 'eva' + w.value
if w.value.endswith('!'):
w.value = w.value[:-1]
args = w.value.split('!')
base = args.pop(0)
bytecode.extend(SingleInstruction('PUSH_LITERAL', x) for x in reversed(args))
bytecode.extend([
SingleInstruction('PUSH_WORD', base),
SingleInstruction('GET_DICT', 0),
SingleInstruction('CALL', 0)
])
else:
bytecode.append(SingleInstruction('PUSH_WORD', w))
elif isinstance(w, Number) and w.value.is_integer() and w.value <= POS_SIZE and w.value >= NEG_SIZE:
bytecode.append(SingleInstruction('PUSH_INTEGER', int(w.value)))
else:
bytecode.append(SingleInstruction('PUSH_LITERAL', w))
elif isinstance(k, Marker):
bytecode.append(k)
elif isinstance(k, GoTo):
bytecode.append(SingleInstruction('JMP', k.index))
elif isinstance(k, Branch):
bytecode.append(SingleInstruction('JMPZ', k.index))
elif isinstance(k, LabdaNode):
bytecode.append(SingleInstruction('LABDA', k.index))
bytecode.append(SingleInstruction('RETURN', 0))
return bytecode
def is_return(node):
return isinstance(node, SingleInstruction) and node.opcode == 'RETURN'
def is_jump_to(node, marker):
return isinstance(node, SingleInstruction) and node.opcode == 'JMP' and node.ref is marker
def is_pass(node):
return isinstance(node, SingleInstruction) and node.opcode == 'PUSH_WORD' and (node.ref == 'pass' or (isinstance(node.ref, ProperWord) and node.ref.value == 'pass'))
def is_linenr(node):
return isinstance(node, SingleInstruction) and node.opcode == 'LINE_NUMBER'
def get(l, i):
try:
return l[i]
except IndexError:
return None
def optimize(flattened): #optimize away superfluous RETURN statements
for i, instruction in reversed(list(enumerate(flattened))):
if (is_return(instruction) and (is_return(get(flattened, i + 1)) or (isinstance(get(flattened, i + 1), Marker) and is_return(get(flattened, i + 2))))
or isinstance(get(flattened, i + 1), Marker) and is_jump_to(instruction, get(flattened, i + 1))
or isinstance(get(flattened, i + 2), Marker) and isinstance(get(flattened, i + 1), Marker) and is_jump_to(instruction, get(flattened, i + 2))
or is_pass(instruction)
or is_linenr(instruction) and is_linenr(get(flattened, i + 1))
):
flattened.pop(i)
return flattened
def refine(flattened): #removes all markers and replaces them by indices
#first pass: fill dictionary
memo = {}
i = 0
while i < len(flattened):
item = flattened[i]
if isinstance(item, Marker):
memo[item] = i
del flattened[i]
else:
i += 1
#second pass: change all goto and branches
for i, item in enumerate(flattened):
if item.opcode in positional_instructions:
item.ref = memo[item.ref] - i
return flattened
|
gvx/deja
|
convert.py
|
Python
|
isc
| 5,277
|
module Extras where
import Data.Char
class Show a => PrettyShow a where
prettyShow :: a -> String
prettyShow x = show x
unique :: Eq a => [a] -> [a]
unique [] = []
unique (x:xs) = if x `elem` xs then unique xs else (x:unique xs)
toLowercase :: String -> String
toLowercase = map toLower
trimLeft :: String -> String
trimLeft [] = []
trimLeft xx@(x:xs)
| isSpace x = trimLeft xs
| otherwise = xx
trimRight :: String -> String
trimRight = reverse . trimLeft . reverse
trim :: String -> String
trim = trimLeft . trimRight
|
fredmorcos/attic
|
snippets/haskell/QuickCheck/Extras.hs
|
Haskell
|
isc
| 538
|
var structdbs_1_1i_1_1_r1 =
[
[ "nodes", "structdbs_1_1i_1_1_r1.html#a249eb273e89b4e1a053dea78ec1f2a3c", null ]
];
|
ukoloff/docpad.ukoloff.tk
|
src/raw/dbs/structdbs_1_1i_1_1_r1.js
|
JavaScript
|
isc
| 118
|
# lodash.some v3.2.2
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.some` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.some
```
In Node.js/io.js:
```js
var some = require('lodash.some');
```
See the [documentation](https://lodash.com/docs#some) or [package source](https://github.com/lodash/lodash/blob/3.2.2-npm-packages/lodash.some) for more details.
|
gyaresu/labelr
|
node_modules/ampersand-rest-collection/node_modules/ampersand-collection-lodash-mixin/node_modules/lodash.some/README.md
|
Markdown
|
isc
| 545
|
PREFIX ?= /usr/local
MANPREFIX ?= $(PREFIX)/man
BIN = bootstrap
install:
install -d $(DESTDIR)$(PREFIX)/bin
install -m 755 $(BIN) $(DESTDIR)$(PREFIX)/bin
install -d $(DESTDIR)$(MANPREFIX)/man1
install -m 444 $(BIN).1 $(DESTDIR)$(MANPREFIX)/man1
uninstall:
rm -f $(DESTDIR)$(PREFIX)/bin/$(BIN)
rm -f $(DESTDIR)$(MANPREFIX)/man1/$(BIN).1
setPermissions:
@command -v git > /dev/null && git --git-dir=.git rev-parse 2>/dev/null ||\
(chmod +x $(BIN) && chmod +x $(BIN)_test)
unsetPermissions:
@command -v git > /dev/null && git --git-dir=.git rev-parse 2>/dev/null ||\
(chmod -x $(BIN) && chmod -x $(BIN)_test)
runTest:
@./$(BIN)_test
test: setPermissions runTest unsetPermissions
|
adriangrigore/bootstrap
|
Makefile
|
Makefile
|
isc
| 695
|
#ifndef CARP_INSTRUCTIONS_H
#define CARP_INSTRUCTIONS_H
/* make instruction numbers easier on the eyes */
typedef enum {
CARP_INSTR_UNDEF = -1,
CARP_INSTR_HALT ,
CARP_INSTR_NOP ,
CARP_INSTR_LOADR,
CARP_INSTR_LOAD ,
CARP_INSTR_STORE,
CARP_INSTR_MOV ,
CARP_INSTR_ADD ,
CARP_INSTR_SUB ,
CARP_INSTR_MUL ,
CARP_INSTR_MOD ,
CARP_INSTR_SHR ,
CARP_INSTR_SHL ,
CARP_INSTR_NOT ,
CARP_INSTR_XOR ,
CARP_INSTR_OR ,
CARP_INSTR_AND ,
CARP_INSTR_INCR ,
CARP_INSTR_DECR ,
CARP_INSTR_INC ,
CARP_INSTR_DEC ,
CARP_INSTR_PUSHR,
CARP_INSTR_PUSH ,
CARP_INSTR_POP ,
CARP_INSTR_CMP ,
CARP_INSTR_LT ,
CARP_INSTR_GT ,
CARP_INSTR_JZ ,
CARP_INSTR_RJZ ,
CARP_INSTR_JNZ ,
CARP_INSTR_RJNZ ,
CARP_INSTR_JMP ,
CARP_INSTR_RJMP ,
CARP_INSTR_CALL ,
CARP_INSTR_RET ,
CARP_INSTR_PREG ,
CARP_INSTR_PTOP ,
CARP_NUM_INSTRS,
} carp_instr;
extern char carp_reverse_instr[][6];
#endif
|
fredmorcos/attic
|
projects/carp/carp-master/src/carp/instructions.h
|
C
|
isc
| 946
|
/* See LICENSE file for copyright and license details. */
#include "key.h"
static void key_handleplay(struct info *, int, wint_t);
static void key_handlesearch(struct info *, int, wint_t);
static void key_handleselect(struct info *, int, wint_t);
static void key_handlestart(struct info *, int, wint_t);
void
key_handle(struct info *data)
{
int errn;
int step;
wint_t c;
if (data == NULL)
return;
/* Get key */
errn = get_wch(&c);
if (errn == ERR)
return;
if (c == KEY_RESIZE) {
data->scroll = 0;
draw_redraw(data);
return;
}
/* Always allow scrolling */
if (errn == KEY_CODE_YES) {
step = (LINES-7)/3;
if (step <= 0)
step = 1;
if (c == KEY_PPAGE) {
data->scroll -= step;
if (data->scroll < 0)
data->scroll = 0;
return;
} else if (c == KEY_NPAGE) {
data->scroll += step;
return;
}
}
switch (data->state) {
case START: key_handlestart(data, errn, c); break;
case PLAY: key_handleplay(data, errn, c); break;
case SEARCH: key_handlesearch(data, errn, c); break;
case SELECT: key_handleselect(data, errn, c); break;
default: break;
}
}
static void
key_handlestart(struct info *data, int errn, wint_t c)
{
if (errn != OK)
return;
switch (c) {
case 'q': data->quit = TRUE; break;
case 's': search_init(data); break;
default: break;
}
}
static void
key_handleplay(struct info *data, int errn, wint_t c)
{
if (errn != OK)
return;
switch (c) {
case 'q': data->quit = TRUE; break;
case 's': search_init(data); break;
case 'n': play_skip(data); break;
case 'p': play_togglepause(data); break;
case 'N': play_nextmix(data); break;
default: break;
}
}
static void
key_handlesearch(struct info *data, int errn, wint_t c)
{
switch (errn) {
case KEY_CODE_YES:
switch(c) {
case KEY_BACKSPACE: search_backspace(data); break;
case KEY_DC: search_delete(data); break;
case KEY_ENTER: search_search(data); break;
case KEY_LEFT: /* FALLTHROUGH */
case KEY_RIGHT: search_changepos(data, c); break;
default: break;
}
break;
case OK:
switch (c) {
case L'\n': /* FALLTHROUGH */
case L'\r': search_search(data); break;
case 0x1b: /* ESC */ search_exit(data); break;
case 127: /* FALLTHROUGH */
case L'\b': search_backspace(data); break;
default: search_addchar(data, c); break;
}
break;
default:
break;
}
}
static void
key_handleselect(struct info *data, int errn, wint_t c)
{
switch (errn) {
case KEY_CODE_YES:
switch (c) {
case KEY_UP: /* FALLTHROUGH */
case KEY_DOWN: select_changepos(data, c); break;
case KEY_ENTER: select_select(data); break;
default: break;
}
break;
case OK:
switch (c) {
case L'\r': /* FALLTHROUGH */
case L'\n': select_select(data); break;
case 0x1b: /* ESC */ select_exit(data); break;
default: break;
}
break;
default:
break;
}
}
|
jgmp/8p
|
key.c
|
C
|
isc
| 2,813
|
'use strict';
import React, { Component, PropTypes } from 'react';
class Package extends Component {
static propTypes = {
children: PropTypes.node,
billItems: PropTypes.object
}
render() {
const { billItems } = this.props;
const { subscriptions } = this.props.billItems.package;
const packages = subscriptions.map((val, key) =>
<tr key={key}>
<td>{val.name}</td>
<td>{val.type}</td>
<td>{val.cost}</td>
</tr>
);
return (
<section>
<h1>Latest Bill</h1>
<h3>Package</h3>
<table>
<thead>
<tr>
<th>Subscription</th>
<th>Type</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{packages}
</tbody>
</table>
<p><strong>Sub Total</strong> {billItems.package.total}</p>
{this.props.children}
</section>
);
}
}
export default Package;
|
hyphenbash/customer-bill
|
app/js/components/Package.js
|
JavaScript
|
isc
| 1,205
|
/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef EXT2FILESYSTEM_H
#define EXT2FILESYSTEM_H
#include <vfs/VFS.h>
#include <vfs/Filesystem.h>
#include <utilities/List.h>
#include <process/Mutex.h>
#include <utilities/Tree.h>
#include <utilities/Vector.h>
#include "ext2.h"
/** This class provides an implementation of the second extended filesystem. */
class Ext2Filesystem : public Filesystem
{
friend class Ext2File;
friend class Ext2Node;
friend class Ext2Directory;
friend class Ext2Symlink;
public:
Ext2Filesystem();
virtual ~Ext2Filesystem();
//
// Filesystem interface.
//
virtual bool initialise(Disk *pDisk);
static Filesystem *probe(Disk *pDisk);
virtual File* getRoot();
virtual String getVolumeLabel();
protected:
virtual bool createFile(File* parent, String filename, uint32_t mask);
virtual bool createDirectory(File* parent, String filename);
virtual bool createSymlink(File* parent, String filename, String value);
virtual bool remove(File* parent, File* file);
private:
virtual bool createNode(File* parent, String filename, uint32_t mask, String value, size_t type);
/** Inaccessible copy constructor and operator= */
Ext2Filesystem(const Ext2Filesystem&);
void operator =(const Ext2Filesystem&);
/** Reads a block of data from the disk. */
uintptr_t readBlock(uint32_t block);
uint32_t findFreeBlock(uint32_t inode);
uint32_t findFreeInode();
void releaseBlock(uint32_t block);
Inode *getInode(uint32_t num);
void ensureFreeBlockBitmapLoaded(size_t group);
void ensureFreeInodeBitmapLoaded(size_t group);
void ensureInodeTableLoaded(size_t group);
/** Our superblock. */
Superblock *m_pSuperblock;
/** Group descriptors, in a tree because each GroupDesc* may be in a different block. */
GroupDesc **m_pGroupDescriptors;
/** Inode tables, indexed by group descriptor. */
Vector<size_t> *m_pInodeTables;
/** Free inode bitmaps, indexed by group descriptor. */
Vector<size_t> *m_pInodeBitmaps;
/** Free block bitmaps, indexed by group descriptor. */
Vector<size_t> *m_pBlockBitmaps;
/** Size of a block. */
uint32_t m_BlockSize;
/** Size of an Inode. */
uint32_t m_InodeSize;
/** Number of group descriptors. */
size_t m_nGroupDescriptors;
/** Write lock - we're finding some inodes and updating the superblock and block group structures. */
Mutex m_WriteLock;
/** The root filesystem node. */
File *m_pRoot;
};
#endif
|
jmolloy/pedigree
|
src/modules/system/ext2/Ext2Filesystem.h
|
C
|
isc
| 3,317
|
'use strict';
require('nightingale-app-console');
var _pool = require('koack/pool');
var _pool2 = _interopRequireDefault(_pool);
var _server = require('koack/server');
var _server2 = _interopRequireDefault(_server);
var _memory = require('koack/storages/memory');
var _memory2 = _interopRequireDefault(_memory);
var _interactiveMessages = require('koack/interactive-messages');
var _interactiveMessages2 = _interopRequireDefault(_interactiveMessages);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pool = new _pool2.default({
size: 100,
path: require.resolve('./bot')
});
const server = new _server2.default({
pool,
scopes: ['bot'],
slackClient: _config2.default.slackClient,
storage: (0, _memory2.default)()
});
server.proxy = true;
server.use((0, _interactiveMessages2.default)({
pool,
token: _config2.default.verificationToken
}));
server.listen({ port: process.env.PORT || 3000 });
//# sourceMappingURL=index.js.map
|
koack/koack
|
examples/node6/interactive-message/index.js
|
JavaScript
|
isc
| 1,092
|
// Package rpctest provides a hcashd-specific RPC testing harness crafting and
// executing integration tests by driving a `hcashd` instance via the `RPC`
// interface. Each instance of an active harness comes equipped with a simple
// in-memory HD wallet capable of properly syncing to the generated chain,
// creating new addresses, and crafting fully signed transactions paying to an
// arbitrary set of outputs.
//
// This package was designed specifically to act as an RPC testing harness for
// `hcashd`. However, the constructs presented are general enough to be adapted to
// any project wishing to programmatically drive a `hcashd` instance of its
// systems/integration tests.
package rpctest
|
HcashOrg/hcashd
|
rpctest/doc.go
|
GO
|
isc
| 703
|
# Generated by Django 2.2.10 on 2020-04-29 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0020_auto_20200421_0851'),
]
operations = [
migrations.AddField(
model_name='localconfig',
name='need_dovecot_update',
field=models.BooleanField(default=False),
),
]
|
modoboa/modoboa
|
modoboa/core/migrations/0021_localconfig_need_dovecot_update.py
|
Python
|
isc
| 403
|
package main
// store global values here
import (
"github.com/gokyle/adn"
"os"
"path/filepath"
)
const (
AppName = "The Social Gopher"
AppUnixName = "socialgopher"
AppVersion = "0.1"
)
var (
homeDir = os.ExpandEnv("${HOME}/." + AppUnixName)
authDatabaseFile = filepath.Join(homeDir, "profiles.db")
)
// The desktop experience should mimic in functionality the web experience.
// Accordingly, we need to be able to do everything.
var Scopes = []string{
adn.ScopeBasic,
adn.ScopeStream,
adn.ScopeEmail,
adn.ScopeWritePost,
adn.ScopeFollow,
adn.ScopeMessages,
adn.ScopeExport,
}
// App represents the Social Gopher, and stores our client information.
var App = &adn.Application{
"STUdQHPA8EC9zeKpqd3hWGUC2VzJASxG", // client ID
"placeholder_secret", // client secret
"", // redirect URI
Scopes, // scopes
"hgq6MjvtePat6ZZwDsJxAMX4Vvq5PvCE", // password secret
}
// Profiles is a list of all the users the app knows about.
var Profiles []*Profile
var (
BodyTypeJSON = "application/json"
)
|
kisom/socialgopher
|
data.go
|
GO
|
isc
| 1,102
|
<?php
namespace TMDB\Request;
/**
* Class StrictPageRequest
*
* Used in cases where the endpoint requires certain variables to be sent, or none at all.
*
* See \TMDB\Request\StrictPageRequest if you require validation
*
* @package TMDB
*/
class PageRequest extends TMDBService {
/**
* @var \TMDB\Request\TMDBService
*/
protected $TMDBService;
/**
* Holds query string values until request()
*
* @var array
*/
protected static $params = array();
/**
* Array of required params
*
* @var array
*/
protected static $required = array();
/**
* PageRequest constructor.
*
* @param null $cacheExpiry
*/
public function __construct($cacheExpiry = NULL)
{
$this->APIService = new TMDBService();
parent::__construct($cacheExpiry = NULL);
}
/**
* Quick override to set the query string with our args
*
* @param string $subURL
* @param string $method
* @param null $data
* @param null $headers
* @param array $curlOptions
*
* @return PageRequestResponse
*/
public function request($subURL = '', $method = "GET", $data = NULL, $headers = NULL, $curlOptions = array())
{
$this->validateRequired();
$this->setQueryString(static::$params);
return new PageRequestResponse(parent::request($subURL, $method, $data, $headers, $curlOptions)->getResponse());
}
/**
* Checks that the keys in $required isset in $args
*
* @throws \RuntimeException
* @return bool;
*/
public function validateRequired()
{
if (empty(static::$required) || empty(static::$params)) {
return TRUE;
}
foreach (static::$required as $key) {
if (!isset(static::$params[ $key ])) {
throw new \RuntimeException("$key must be set for " . get_called_class());
}
}
return TRUE;
}
/**
* @return bool
*/
public function hasRequired()
{
return (!is_array(static::$required) || empty(static::$required));
}
/**
* @param $key
*
* @return bool
*/
public function isRequired($key)
{
return (is_array(static::$required) && in_array($key, static::$required));
}
/**
* @param $array
*
* @return $this
*/
public function setParams($array)
{
if (!empty(static::$params) && !\ArrayLib::is_associative(static::$params)) {
throw new \RuntimeException(get_called_class() . "::\$params must be an associative array.");
}
if (!\ArrayLib::is_associative($array)) {
throw new \RuntimeException("setArgs() parameter must be an associative array.");
}
foreach ($array as $k => $v) {
$this->setParam($k, $v);
}
return $this;
}
/**
* @param $key
* @param $value
*
* @return void
*/
public function setParam($key, $value)
{
if (!empty(static::$params) && !\ArrayLib::is_associative(static::$params)) {
throw new \RuntimeException(get_called_class() . "::\$params must be an associative array.");
}
static::$params[ $key ] = $value;
}
/**
* @return mixed
*/
public function getParams()
{
return static::$params;
}
/**
* Sets the page
*
* @param int $page
*
* @return $this
*/
public function setPage($page = 1)
{
static::$params[ 'page' ] = $page;
return $this;
}
}
|
zanderwar/silverstripe-tmdb
|
code/system/Request/PageRequest.php
|
PHP
|
isc
| 3,658
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module defines a convenience typeclass for creating
-- normalised programs.
--
-- See "Futhark.Construct" for a high-level description.
module Futhark.Builder.Class
( Buildable (..),
mkLet,
mkLet',
MonadBuilder (..),
insertStms,
insertStm,
letBind,
letBindNames,
collectStms_,
bodyBind,
attributing,
auxing,
module Futhark.MonadFreshNames,
)
where
import qualified Data.Kind
import Futhark.IR
import Futhark.MonadFreshNames
-- | The class of representations that can be constructed solely from
-- an expression, within some monad. Very important: the methods
-- should not have any significant side effects! They may be called
-- more often than you think, and the results thrown away. If used
-- exclusively within a 'MonadBuilder' instance, it is acceptable for
-- them to create new bindings, however.
class
( ASTRep rep,
FParamInfo rep ~ DeclType,
LParamInfo rep ~ Type,
RetType rep ~ DeclExtType,
BranchType rep ~ ExtType,
SetType (LetDec rep)
) =>
Buildable rep
where
mkExpPat :: [Ident] -> Exp rep -> Pat rep
mkExpDec :: Pat rep -> Exp rep -> ExpDec rep
mkBody :: Stms rep -> Result -> Body rep
mkLetNames ::
(MonadFreshNames m, HasScope rep m) =>
[VName] ->
Exp rep ->
m (Stm rep)
-- | A monad that supports the creation of bindings from expressions
-- and bodies from bindings, with a specific rep. This is the main
-- typeclass that a monad must implement in order for it to be useful
-- for generating or modifying Futhark code. Most importantly
-- maintains a current state of 'Stms' (as well as a 'Scope') that
-- have been added with 'addStm'.
--
-- Very important: the methods should not have any significant side
-- effects! They may be called more often than you think, and the
-- results thrown away. It is acceptable for them to create new
-- bindings, however.
class
( ASTRep (Rep m),
MonadFreshNames m,
Applicative m,
Monad m,
LocalScope (Rep m) m
) =>
MonadBuilder m
where
type Rep m :: Data.Kind.Type
mkExpDecM :: Pat (Rep m) -> Exp (Rep m) -> m (ExpDec (Rep m))
mkBodyM :: Stms (Rep m) -> Result -> m (Body (Rep m))
mkLetNamesM :: [VName] -> Exp (Rep m) -> m (Stm (Rep m))
-- | Add a statement to the 'Stms' under construction.
addStm :: Stm (Rep m) -> m ()
addStm = addStms . oneStm
-- | Add multiple statements to the 'Stms' under construction.
addStms :: Stms (Rep m) -> m ()
-- | Obtain the statements constructed during a monadic action,
-- instead of adding them to the state.
collectStms :: m a -> m (a, Stms (Rep m))
-- | Add the provided certificates to any statements added during
-- execution of the action.
certifying :: Certs -> m a -> m a
certifying = censorStms . fmap . certify
-- | Apply a function to the statements added by this action.
censorStms ::
MonadBuilder m =>
(Stms (Rep m) -> Stms (Rep m)) ->
m a ->
m a
censorStms f m = do
(x, stms) <- collectStms m
addStms $ f stms
return x
-- | Add the given attributes to any statements added by this action.
attributing :: MonadBuilder m => Attrs -> m a -> m a
attributing attrs = censorStms $ fmap onStm
where
onStm (Let pat aux e) =
Let pat aux {stmAuxAttrs = attrs <> stmAuxAttrs aux} e
-- | Add the certificates and attributes to any statements added by
-- this action.
auxing :: MonadBuilder m => StmAux anyrep -> m a -> m a
auxing (StmAux cs attrs _) = censorStms $ fmap onStm
where
onStm (Let pat aux e) =
Let pat aux' e
where
aux' =
aux
{ stmAuxAttrs = attrs <> stmAuxAttrs aux,
stmAuxCerts = cs <> stmAuxCerts aux
}
-- | Add a statement with the given pattern and expression.
letBind ::
MonadBuilder m =>
Pat (Rep m) ->
Exp (Rep m) ->
m ()
letBind pat e =
addStm =<< Let pat <$> (defAux <$> mkExpDecM pat e) <*> pure e
-- | Construct a 'Stm' from identifiers for the context- and value
-- part of the pattern, as well as the expression.
mkLet :: Buildable rep => [Ident] -> Exp rep -> Stm rep
mkLet ids e =
let pat = mkExpPat ids e
dec = mkExpDec pat e
in Let pat (defAux dec) e
-- | Like mkLet, but also take attributes and certificates from the
-- given 'StmAux'.
mkLet' :: Buildable rep => [Ident] -> StmAux a -> Exp rep -> Stm rep
mkLet' ids (StmAux cs attrs _) e =
let pat = mkExpPat ids e
dec = mkExpDec pat e
in Let pat (StmAux cs attrs dec) e
-- | Add a statement with the given pattern element names and
-- expression.
letBindNames :: MonadBuilder m => [VName] -> Exp (Rep m) -> m ()
letBindNames names e = addStm =<< mkLetNamesM names e
-- | As 'collectStms', but throw away the ordinary result.
collectStms_ :: MonadBuilder m => m a -> m (Stms (Rep m))
collectStms_ = fmap snd . collectStms
-- | Add the statements of the body, then return the body result.
bodyBind :: MonadBuilder m => Body (Rep m) -> m Result
bodyBind (Body _ stms res) = do
addStms stms
pure res
-- | Add several bindings at the outermost level of a t'Body'.
insertStms :: Buildable rep => Stms rep -> Body rep -> Body rep
insertStms stms1 (Body _ stms2 res) = mkBody (stms1 <> stms2) res
-- | Add a single binding at the outermost level of a t'Body'.
insertStm :: Buildable rep => Stm rep -> Body rep -> Body rep
insertStm = insertStms . oneStm
|
HIPERFIT/futhark
|
src/Futhark/Builder/Class.hs
|
Haskell
|
isc
| 5,424
|
// External modules
var del = require('del');
var critical = require('critical').stream;
// Import config
var config = require('./_config');
// Html module
module.exports = function(gulp, livereload) {
gulp.task('html', function() {
return gulp.src(config.html)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('html--deploy', function() {
return gulp.src(config.html)
.pipe(critical({
base: 'dist/',
inline: true,
css: ['dist/app.css']
}))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function() {
return gulp.src(config.images)
.pipe(gulp.dest('dist/images'))
.pipe(livereload());
});
gulp.task('assets', function() {
return gulp.src(config.assets)
.pipe(gulp.dest('dist/assets'))
.pipe(livereload());
});
gulp.task('fixtures', function() {
return gulp.src(config.fixtures)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('clean-html-tmp', function () {
return del(['dist/tmp-**']);
});
gulp.task('clean-dist', function () {
return del(['dist/**']);
});
};
|
sp90/prototype-builder
|
gulp/copy.js
|
JavaScript
|
isc
| 1,068
|
-- | Multicore imperative code.
module Futhark.CodeGen.ImpCode.Multicore
( Program,
Function,
FunctionT (Function),
Code,
Multicore (..),
Scheduling (..),
SchedulerInfo (..),
AtomicOp (..),
ParallelTask (..),
module Futhark.CodeGen.ImpCode,
)
where
import Futhark.CodeGen.ImpCode hiding (Code, Function)
import qualified Futhark.CodeGen.ImpCode as Imp
import Futhark.Util.Pretty
-- | An imperative program.
type Program = Imp.Functions Multicore
-- | An imperative function.
type Function = Imp.Function Multicore
-- | A piece of imperative code, with multicore operations inside.
type Code = Imp.Code Multicore
-- | A multicore operation.
data Multicore
= Segop String [Param] ParallelTask (Maybe ParallelTask) [Param] SchedulerInfo
| ParLoop String VName Code Code Code [Param] VName
| Atomic AtomicOp
-- | Atomic operations return the value stored before the update.
-- This old value is stored in the first 'VName'. The second 'VName'
-- is the memory block to update. The 'Exp' is the new value.
data AtomicOp
= AtomicAdd IntType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicSub IntType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicAnd IntType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicOr IntType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicXor IntType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicXchg PrimType VName VName (Count Elements (Imp.TExp Int32)) Exp
| AtomicCmpXchg PrimType VName VName (Count Elements (Imp.TExp Int32)) VName Exp
deriving (Show)
instance FreeIn AtomicOp where
freeIn' (AtomicAdd _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
freeIn' (AtomicSub _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
freeIn' (AtomicAnd _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
freeIn' (AtomicOr _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
freeIn' (AtomicXor _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
freeIn' (AtomicCmpXchg _ _ arr i retval x) = freeIn' arr <> freeIn' i <> freeIn' x <> freeIn' retval
freeIn' (AtomicXchg _ _ arr i x) = freeIn' arr <> freeIn' i <> freeIn' x
data SchedulerInfo = SchedulerInfo
{ nsubtasks :: VName, -- The variable that describes how many subtasks the scheduler created
iterations :: Imp.Exp, -- The number of total iterations for a task
scheduling :: Scheduling -- The type scheduling for the task
}
data ParallelTask = ParallelTask
{ task_code :: Code,
flatTid :: VName -- The variable for the thread id execution the code
}
-- | Whether the Scheduler should schedule the tasks as Dynamic
-- or it is restainted to Static
data Scheduling
= Dynamic
| Static
instance Pretty Scheduling where
ppr Dynamic = text "Dynamic"
ppr Static = text "Static"
-- TODO fix all of this!
instance Pretty SchedulerInfo where
ppr (SchedulerInfo nsubtask i sched) =
text "SchedulingInfo"
<+> text "number of subtasks"
<+> ppr nsubtask
<+> text "scheduling"
<+> ppr sched
<+> text "iter"
<+> ppr i
instance Pretty ParallelTask where
ppr (ParallelTask code _) =
ppr code
instance Pretty Multicore where
ppr (Segop s free _par_code seq_code retval scheduler) =
text "parfor"
<+> ppr scheduler
<+> ppr free
<+> text s
<+> text "seq_code"
<+> nestedBlock "{" "}" (ppr seq_code)
<+> text "retvals"
<+> ppr retval
ppr (ParLoop s i prebody body postbody params info) =
text "parloop" <+> ppr s <+> ppr i
<+> ppr prebody
<+> ppr params
<+> ppr info
<+> langle
<+> nestedBlock "{" "}" (ppr body)
<+> ppr postbody
ppr (Atomic _) = text "AtomicOp"
instance FreeIn SchedulerInfo where
freeIn' (SchedulerInfo nsubtask iter _) =
freeIn' iter <> freeIn' nsubtask
instance FreeIn ParallelTask where
freeIn' (ParallelTask code _) =
freeIn' code
instance FreeIn Multicore where
freeIn' (Segop _ _ par_code seq_code _ info) =
freeIn' par_code <> freeIn' seq_code <> freeIn' info
freeIn' (ParLoop _ _ prebody body postbody _ _) =
freeIn' prebody <> fvBind (Imp.declaredIn prebody) (freeIn' $ body <> postbody)
freeIn' (Atomic aop) = freeIn' aop
|
HIPERFIT/futhark
|
src/Futhark/CodeGen/ImpCode/Multicore.hs
|
Haskell
|
isc
| 4,250
|
/** @license ISC License (c) copyright 2017 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
const Pair = require('../core/types').proxy('Pair')
const isFoldable = require('../core/isFoldable')
const isSameType = require('../core/isSameType')
const isString = require('../core/isString')
function foldPairs(acc, pair) {
if(!isSameType(Pair, pair)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
const key = pair.fst()
const value = pair.snd()
if(!isString(key)) {
throw new TypeError('fromPairs: String required for fst of every Pair')
}
return value !== undefined
? Object.assign(acc, { [key]: value })
: acc
}
/** fromPairs :: Foldable f => f (Pair String a) -> Object */
function fromPairs(xs) {
if(!isFoldable(xs)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
return xs.reduce(foldPairs, {})
}
module.exports = fromPairs
|
evilsoft/crocks
|
src/helpers/fromPairs.js
|
JavaScript
|
isc
| 961
|
var fs = require('fs');
var tapOut = require('tap-out');
var through = require('through2');
var duplexer = require('duplexer');
var format = require('chalk');
var prettyMs = require('pretty-ms');
var _ = require('lodash');
var repeat = require('repeat-string');
var symbols = require('./lib/utils/symbols');
var lTrimList = require('./lib/utils/l-trim-list');
module.exports = function (spec) {
spec = spec || {};
// TODO: document
var OUTPUT_PADDING = spec.padding || ' ';
var output = through();
var parser = tapOut();
var stream = duplexer(parser, output);
var startTime = new Date().getTime();
output.push('\n');
parser.on('test', function (test) {
output.push('\n' + pad(test.name) + '\n\n');
});
// Passing assertions
parser.on('pass', function (assertion) {
var glyph = format.green(symbols.ok);
var name = format.dim(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
});
// Failing assertions
parser.on('fail', function (assertion) {
var glyph = format.red(symbols.err);
var name = format.red.bold(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
stream.failed = true;
});
// All done
parser.on('output', function (results) {
output.push('\n\n');
if (results.fail.length > 0) {
output.push(formatErrors(results));
output.push('\n');
}
output.push(formatTotals(results));
output.push('\n\n\n');
});
// Utils
function formatErrors (results) {
var failCount = results.fail.length;
var past = (failCount === 1) ? 'was' : 'were';
var plural = (failCount === 1) ? 'failure' : 'failures';
var out = '\n' + pad(format.red.bold('Failed Tests:') + ' There ' + past + ' ' + format.red.bold(failCount) + ' ' + plural + '\n');
out += formatFailedAssertions(results);
return out;
}
function formatTotals (results) {
return _.filter([
pad('total: ' + results.asserts.length),
pad(format.green('passing: ' + results.pass.length)),
results.fail.length > 0 ? pad(format.red('failing: ' + results.fail.length)) : null,
pad('duration: ' + prettyMs(new Date().getTime() - startTime)) // TODO: actually calculate this
], _.identity).join('\n');
}
function formatFailedAssertions (results) {
var out = '';
var groupedAssertions = _.groupBy(results.fail, function (assertion) {
return assertion.test;
});
_.each(groupedAssertions, function (assertions, testNumber) {
// Wrie failed assertion's test name
var test = _.find(results.tests, {number: parseInt(testNumber)});
out += '\n' + pad(' ' + test.name + '\n\n');
// Write failed assertion
_.each(assertions, function (assertion) {
out += pad(' ' + format.red(symbols.err) + ' ' + format.red(assertion.name)) + '\n';
out += formatFailedAssertionDetail(assertion) + '\n';
});
});
return out;
}
function formatFailedAssertionDetail (assertion) {
var out = '';
var filepath = assertion.error.at.file;
var contents = fs.readFileSync(filepath).toString().split('\n');
var line = contents[assertion.error.at.line - 1];
var previousLine = contents[assertion.error.at.line - 2];
var nextLine = contents[assertion.error.at.line];
var lineNumber = parseInt(assertion.error.at.line);
var previousLineNumber = parseInt(assertion.error.at.line) - 1;
var nextLineNumber = parseInt(assertion.error.at.line) + 1;
var lines = lTrimList([
line,
previousLine,
nextLine
]);
var atCharacterPadding = parseInt(assertion.error.at.character) + parseInt(lineNumber.toString().length) + 2;
out += pad(' ' + format.dim(filepath)) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('v') + "\n");
out += pad(' ' + format.dim(previousLineNumber + '. ' + lines[1])) + '\n';
out += pad(' ' + lineNumber + '. ' + lines[0]) + '\n';
out += pad(' ' + format.dim(nextLineNumber + '. ' + lines[2])) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('^') + "\n");
return out;
}
function pad (str) {
return OUTPUT_PADDING + str;
}
return stream;
};
|
Belrestro/GolemStoneAntAttack_browser
|
node_modules/le_node/node_modules/tap-spec/index.js
|
JavaScript
|
isc
| 4,422
|
from . import meta_selector # noqa
from .pg import PatternGenerator
from .selector import Selector
PatternGenerator('')
Selector('')
|
stack-of-tasks/sot-pattern-generator
|
src/dynamic_graph/sot/pattern_generator/__init__.py
|
Python
|
isc
| 136
|
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for csv2json/libs/core/defaultParsers/parser_flat.js</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../../../../prettify.css" />
<link rel="stylesheet" href="../../../../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../../../../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../../../../index.html">All files</a> / <a href="index.html">csv2json/libs/core/defaultParsers</a> parser_flat.js
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Statements</span>
<span class='fraction'>0/4</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Branches</span>
<span class='fraction'>0/0</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Functions</span>
<span class='fraction'>0/1</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Lines</span>
<span class='fraction'>0/4</span>
</div>
</div>
<p class="quiet">
Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
</p>
</div>
<div class='status-line low'></div>
<pre><table class="coverage">
<tr><td class="line-count quiet"><a name='L1'></a><a href='#L1'>1</a>
<a name='L2'></a><a href='#L2'>2</a>
<a name='L3'></a><a href='#L3'>3</a>
<a name='L4'></a><a href='#L4'>4</a>
<a name='L5'></a><a href='#L5'>5</a>
<a name='L6'></a><a href='#L6'>6</a>
<a name='L7'></a><a href='#L7'>7</a>
<a name='L8'></a><a href='#L8'>8</a>
<a name='L9'></a><a href='#L9'>9</a>
<a name='L10'></a><a href='#L10'>10</a>
<a name='L11'></a><a href='#L11'>11</a>
<a name='L12'></a><a href='#L12'>12</a></td><td class="line-coverage quiet"><span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span>
<span class="cline-any cline-no">0</span></td><td class="text"><pre class="prettyprint lang-js">Unable to lookup source: /Users/kxiang/work/projects/csv2json/libs/core/defaultParsers/parser_flat.js(ENOENT: no such file or directory, open '/Users/kxiang/work/projects/csv2json/libs/core/defaultParsers/parser_flat.js')
Error: Unable to lookup source: /Users/kxiang/work/projects/csv2json/libs/core/defaultParsers/parser_flat.js(ENOENT: no such file or directory, open '/Users/kxiang/work/projects/csv2json/libs/core/defaultParsers/parser_flat.js')
at Context.defaultSourceLookup [as sourceFinder] (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/context.js:15:15)
at Context.getSource (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/context.js:74:17)
at Object.annotateSourceCode (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-reports/lib/html/annotator.js:172:38)
at HtmlReport.onDetail (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-reports/lib/html/index.js:237:39)
at Visitor.(anonymous function) [as onDetail] (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/tree.js:34:30)
at ReportNode.Node.visit (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/tree.js:123:17)
at /Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/tree.js:116:23
at Array.forEach (native)
at visitChildren (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/tree.js:115:32)
at ReportNode.Node.visit (/Users/kxiang/work/projects/csv2json/node_modules/nyc/node_modules/istanbul-lib-report/lib/tree.js:126:5)</pre></td></tr>
</table></pre>
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="https://istanbul.js.org/" target="_blank">istanbul</a> at Fri May 11 2018 21:36:07 GMT+0100 (IST)
</div>
</div>
<script src="../../../../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../../../../sorter.js"></script>
<script src="../../../../block-navigation.js"></script>
</body>
</html>
|
pVelocity/pvserverhelper
|
node_modules/csvtojson/coverage/csv2json/libs/core/defaultParsers/parser_flat.js.html
|
HTML
|
isc
| 5,158
|
/*jshint esnext: true */
let plugins;
export default class DevicePlugin {
constructor(_plugins) {
plugins = _plugins;
plugins.registerCommand('Device', 'getDeviceInfo', this.getDeviceInfo);
}
getDeviceInfo(sender) {
return {
platform: sender.device.preset.platform,
version: sender.device.preset.platformVersion,
uuid: sender.device.uuid,
model: sender.device.preset.model
};
}
}
DevicePlugin.$inject = ['plugins'];
|
ozsay/cordova-simulator
|
plugins/cordova-plugin-device/renderer/js/service.js
|
JavaScript
|
mit
| 469
|
module Ayatsuri
class Application
class TreeView < ControlBase
def select(item_no)
driver.select_tree_view_item(window.title, id, item_no)
end
end
end
end
|
haazime/ayatsuri
|
lib/ayatsuri/application/tree_view.rb
|
Ruby
|
mit
| 172
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.internal.directconnectivity.rntbd;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public final class RntbdResponseDecoder extends ByteToMessageDecoder {
private static final Logger Logger = LoggerFactory.getLogger(RntbdResponseDecoder.class);
/**
* Deserialize from an input {@link ByteBuf} to an {@link RntbdResponse} instance
* <p>
* This method is called till it reads no bytes from the {@link ByteBuf} or there is no more data to be readTree.
*
* @param context the {@link ChannelHandlerContext} to which this {@link RntbdResponseDecoder} belongs
* @param in the {@link ByteBuf} to which data to be decoded is readTree
* @param out the {@link List} to which decoded messages are added
*/
@Override
protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) {
if (RntbdFramer.canDecodeHead(in)) {
final RntbdResponse response = RntbdResponse.decode(in);
if (response != null) {
Logger.debug("{} DECODE COMPLETE: {}", context.channel(), response);
in.discardReadBytes();
response.retain();
out.add(response);
}
}
}
}
|
navalev/azure-sdk-for-java
|
sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java
|
Java
|
mit
| 1,545
|
using abremir.AllMyBricks.Onboarding.Shared.Extensions;
using System;
namespace abremir.AllMyBricks.Onboarding.Shared.Models
{
public class Device
{
public string AppId { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Version { get; set; }
public string Platform { get; set; }
public string Idiom { get; set; }
public string DeviceHash { get; set; }
public DateTimeOffset? DeviceHashDate { get; set; }
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
if (!(obj is Device device))
{
return false;
}
return string.Equals(device.AppId, AppId)
&& string.Equals(device.Manufacturer, Manufacturer)
&& string.Equals(device.Model, Model)
&& string.Equals(device.Version, Version)
&& string.Equals(device.Platform, Platform)
&& string.Equals(device.Idiom, Idiom)
&& string.Equals(device.DeviceHash, DeviceHash)
&& Equals(device.DeviceHashDate?.ToHundredthOfSecond(), DeviceHashDate?.ToHundredthOfSecond());
}
public override int GetHashCode()
{
return new
{
AppId,
Manufacturer,
Model,
Version,
Platform,
Idiom,
DeviceHash,
DeviceHashDate = DeviceHashDate?.ToHundredthOfSecond()
}.GetHashCode();
}
}
}
|
zmira/abremir.AllMyBricks
|
abremir.AllMyBricks.Onboarding.Shared/Models/Device.cs
|
C#
|
mit
| 1,699
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06_Strings and Objects")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06_Strings and Objects")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("10c45dcc-1ad1-472b-b0fa-e330b63fb6b4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
akkirilov/SoftUniProject
|
01_ProgrammingFundamentals/Homeworks/02_Data Types and Variables-Ex/06_Strings and Objects/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,420
|
require 'rubygems'
require 'test/unit'
require 'shoulda'
require 'mocha'
require 'matchy'
require 'pp'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'fifth_column'
class Test::Unit::TestCase
end
|
tobias/fifth_column
|
test/test_helper.rb
|
Ruby
|
mit
| 269
|
## Notes on chapter 2: Getting started
We assume in this chapter that you have the Scala compiler and interpreter already up and running. See [the documentation page of Scala's website](http://www.scala-lang.org/documentation/) for more details about how to get Scala set up and links to lots of supplementary material about Scala itself.
### Factorial and Fibonacci ###
We also assume some familiarity with the [factorial function](http://en.wikipedia.org/wiki/Factorial) and we give only a brief explanation of the [Fibonacci sequence](http://en.wikipedia.org/wiki/Fibonacci_number).
I'd suggest that when asking for the nth fibonacci number it should be based from 1, not 0 like the current solution. i.e.
~~~ scala
def fib(n: Int): Int = {
@annotation.tailrec
def loop(n: Int, prev: Int, curr: Int): Int =
if (n <= 1) prev //instead of n == 0. Really n at 0 should be undefined but I'm just returning 0 here...
else loop(n-1, curr, prev + curr)
loop(n, 0, 1)
}
~~~
### Lambda calculus ###
The notions of first-class and higher-order functions are formalized by the [lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus).
### Parametric polymorphism ###
For more on parametric polymorphism, see [the Wikipedia article.](http://en.wikipedia.org/wiki/Type_variable)
### Parametricity ###
When we can "follow the type" of a function to derive the only possible implementation, we say that the definition is _given by parametricity_. See [the Wikipedia article on parametricity](http://en.wikipedia.org/wiki/Parametricity), and Philip Wadler's paper [Theorems for free!](http://homepages.inf.ed.ac.uk/wadler/topics/parametricity.html)
### Curry ###
The idea of [Currying](http://en.wikipedia.org/wiki/Currying) is named after the mathematician [Haskell Curry.](http://en.wikipedia.org/wiki/Haskell_Curry) He also discovered one of the most important results in computer science, the [Curry-Howard isomorphism](http://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence) which says that _a program is a logical proof, and the hypothesis that it proves is its type_.
### Function composition ###
Function composition in functional programming is closely related to [function composition in mathematics.](http://en.wikipedia.org/wiki/Function_composition)
## FAQ
#### Are tail calls optimized if the `@annotation.tailrec` annotation isn't there?
They are still optimized, but the compiler won't warn you if it can't do the tail call optimization.
#### Is there a list of other annotation types somewhere?
See the [Scaladoc for the Annotation class](http://www.scala-lang.org/api/current/index.html#scala.annotation.Annotation), and expand the 'known subclasses section'.
#### Is the common style to define loops using local function, rather than a (private) standalone function?
Yes, this is much more common. There's no need to pollute the namespace with helper functions you aren't expecting to be called by anyone.
#### Is `a || go(x)` considered a tail call? What about `a && go(x)`?
Yes
|
runarorama/fpiscompanion
|
notes/Chapter-2:-Getting-started.md
|
Markdown
|
mit
| 3,117
|
#include "IOverlay.hpp"
namespace duke {
IOverlay::~IOverlay() {}
} /* namespace duke */
|
mikrosimage/duke
|
src/duke/engine/overlay/IOverlay.cpp
|
C++
|
mit
| 92
|
<?php
namespace Bankrot\SiteBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* @Entity()
* @Table(name="users")
*/
class User extends BaseUser
{
/**
* @Column(type="integer")
* @Id()
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="string")
*/
protected $lastName;
/**
* @Column(type="string")
*/
protected $firstName;
/**
* @Column(type="string", nullable=true)
*/
protected $surName;
/**
* @Column(type="string", nullable=true)
*/
protected $phone;
/**
* @ORM\OneToMany(targetEntity="Subscription", mappedBy="user")
*/
protected $subscriptions;
/**
* @ORM\OneToMany(targetEntity="Registry", mappedBy="user")
*/
protected $registries;
/**
* @ORM\OneToMany(targetEntity="Arbitration", mappedBy="user")
*/
protected $arbitrations;
/**
* @Column(type="datetime", nullable=true)
*/
protected $subscriptionDate;
/**
* @ORM\OneToMany(targetEntity="ForumQuestion", mappedBy="author")
*/
protected $forumQuestions;
/**
* @ORM\OneToMany(targetEntity="Lot", mappedBy="owner")
*/
private $lots;
/**
* @ORM\OneToMany(targetEntity="ForumAnswer", mappedBy="author")
*/
protected $forumAnswers;
/**
* @ORM\OneToMany(targetEntity="WarningComment", mappedBy="user")
*/
protected $comments;
/**
* @ORM\OneToMany(targetEntity="Bankrot\SiteBundle\Entity\Task", mappedBy="user")
*/
protected $tasks;
public function __construct(){
parent::__construct();
$this->forumQuestions = new ArrayCollection();
$this->forumAnswers = new ArrayCollection();
$this->arbitrations = new ArrayCollection();
$this->registries = new ArrayCollection();
$this->lots = new ArrayCollection();
$this->subscriptions = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->tasks = new ArrayCollection();
$this->addRole('ROLE_SUBSCRIPTION');
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getForumQuestions()
{
return $this->forumQuestions;
}
/**
* @param mixed $forumQuestions
*/
public function setForumQuestions($forumQuestions)
{
$this->forumQuestions = $forumQuestions;
}
/**
* @return mixed
*/
public function getForumAnswers()
{
return $this->forumAnswers;
}
/**
* @param mixed $forumAnswers
*/
public function setForumAnswers($forumAnswers)
{
$this->forumAnswers = $forumAnswers;
}
/**
* @return mixed
*/
public function getSubscriptionDate()
{
return $this->subscriptionDate;
}
/**
* @param mixed $subscriptionDate
*/
public function setSubscriptionDate($subscriptionDate)
{
$this->subscriptionDate = $subscriptionDate;
}
public function addLot(Lot $lot) { $this->lots[] = $lot; }
public function removeLot(Lot $lot) { $this->lots->removeElement($lot); }
public function getLots() { return $this->lots; }
/**
* @return mixed
*/
public function getSubscriptions()
{
return $this->subscriptions;
}
/**
* @param mixed $subscriptions
*/
public function setSubscriptions($subscriptions)
{
$this->subscriptions = $subscriptions;
}
/**
* @return mixed
*/
public function getRegistries()
{
return $this->registries;
}
/**
* @param mixed $registries
*/
public function setRegistries($registries)
{
$this->registries = $registries;
}
/**
* @return mixed
*/
public function getArbitrations()
{
return $this->arbitrations;
}
/**
* @param mixed $arbitrations
*/
public function setArbitrations($arbitrations)
{
$this->arbitrations = $arbitrations;
}
/**
* @return mixed
*/
public function getLastName()
{
return $this->lastName;
}
/**
* @param mixed $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* @return mixed
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* @param mixed $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* @return mixed
*/
public function getSurName()
{
return $this->surName;
}
/**
* @param mixed $surName
*/
public function setSurName($surName)
{
$this->surName = $surName;
}
/**
* @return mixed
*/
public function getPhone()
{
return $this->phone;
}
/**
* @param mixed $phone
*/
public function setPhone($phone)
{
$this->phone = $phone;
}
/**
* @return mixed
*/
public function getComments()
{
return $this->comments;
}
/**
* @param mixed $comments
*/
public function setComments($comments)
{
$this->comments = $comments;
}
/**
* @return mixed
*/
public function getTasks()
{
return $this->tasks;
}
/**
* @param mixed $tasks
*/
public function setTasks($tasks)
{
$this->tasks = $tasks;
}
}
|
bhdm/bankrot
|
src/Bankrot/SiteBundle/Entity/User.php
|
PHP
|
mit
| 6,012
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { faCaretRight } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'section-title',
template: `
<div fxLayout fxLayoutAlign="start center">
<h2>
<i class="fas fa-caret-right" aria-hidden="true"></i>
<fa-icon [icon]="iconCaretRight" size="lg"></fa-icon>
<ng-content></ng-content>
</h2>
</div>
`,
styleUrls: ['section-title.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SectionTitleComponent {
iconCaretRight = faCaretRight;
}
|
MurhafSousli/ng-gallery
|
projects/demo/src/app/shared/section-title/section-title.component.ts
|
TypeScript
|
mit
| 609
|
/* ----------------------------------------------------------------------------
** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved.
**
** Class.cpp
** --------------------------------------------------------------------------*/
#include "Precompiled.h"
#include "LanguageTypes/Class.h"
#include "ReservedTypes.h"
namespace
{
const std::vector<std::string> nativeTypes
{
kTypeObject,
kTypeMetaProperty
};
bool isNativeType(const std::string &qualifiedName)
{
return std::find(
nativeTypes.begin( ),
nativeTypes.end( ),
qualifiedName
) != nativeTypes.end( );
}
}
BaseClass::BaseClass(const Cursor &cursor)
: name( cursor.GetType( ).GetCanonicalType( ).GetDisplayName( ) )
{
}
Class::Class(const Cursor &cursor, const Namespace ¤tNamespace)
: LanguageType( cursor, currentNamespace )
, m_name( cursor.GetDisplayName( ) )
, m_qualifiedName( cursor.GetType( ).GetDisplayName( ) )
{
auto displayName = m_metaData.GetNativeString( native_property::DisplayName );
if (displayName.empty( ))
{
m_displayName = m_qualifiedName;
}
else
{
m_displayName = displayName;
}
for (auto &child : cursor.GetChildren( ))
{
switch (child.GetKind( ))
{
case CXCursor_CXXBaseSpecifier:
{
auto baseClass = new BaseClass( child );
m_baseClasses.emplace_back( baseClass );
// automatically enable the type if not explicitly disabled
if (isNativeType( baseClass->name ))
m_enabled = !m_metaData.GetFlag( native_property::Disable );
}
break;
// constructor
case CXCursor_Constructor:
m_constructors.emplace_back(
new Constructor( child, currentNamespace, this )
);
break;
// field
case CXCursor_FieldDecl:
m_fields.emplace_back(
new Field( child, currentNamespace, this )
);
break;
// static field
case CXCursor_VarDecl:
m_staticFields.emplace_back(
new Global( child, Namespace( ), this )
);
break;
// method / static method
case CXCursor_CXXMethod:
if (child.IsStatic( ))
{
m_staticMethods.emplace_back(
new Function( child, Namespace( ), this )
);
}
else
{
m_methods.emplace_back(
new Method( child, currentNamespace, this )
);
}
break;
default:
break;
}
}
}
bool Class::ShouldCompile(void) const
{
return isAccessible( ) && !isNativeType( m_qualifiedName );
}
TemplateData Class::CompileTemplate(const ReflectionParser *context) const
{
TemplateData data { TemplateData::Type::Object };
data[ "displayName" ] = m_displayName;
data[ "qualifiedName" ] = m_qualifiedName;
data[ "ptrTypeEnabled" ] = utils::TemplateBool( m_ptrTypeEnabled );
data[ "constPtrTypeEnabled" ] =
utils::TemplateBool( m_constPtrTypeEnabled );
data[ "arrayTypeEnabled" ] =
utils::TemplateBool( m_arrayTypeEnabled );
m_metaData.CompileTemplateData( data, context );
// base classes
{
TemplateData baseClasses { TemplateData::Type::List };
int i = 0;
for (auto &baseClass : m_baseClasses)
{
// ignore native types
if (isNativeType( baseClass->name ))
continue;
TemplateData item { TemplateData::Type::Object };
item[ "name" ] = baseClass->name;
item[ "isLast" ] =
utils::TemplateBool( i == m_baseClasses.size( ) - 1 );
baseClasses << item;
++i;
}
data[ "baseClass" ] = baseClasses;
}
// don't do anything else if only registering
if (m_metaData.GetFlag( native_property::Register ))
return data;
// constructors
{
TemplateData constructors { TemplateData::Type::List };
for (auto &ctor : m_constructors)
{
if (ctor->ShouldCompile( ))
constructors << ctor->CompileTemplate( context );
}
data[ "constructor" ] = constructors;
data[ "dynamicConstructor" ] = constructors;
}
// fields
{
TemplateData fields { TemplateData::Type::List };
for (auto &field : m_fields)
{
if (field->ShouldCompile( ))
fields << field->CompileTemplate( context );
}
data[ "field" ] = fields;
}
// static fields
{
TemplateData staticFields { TemplateData::Type::List };
for (auto &staticField : m_staticFields)
{
if (staticField->ShouldCompile( ))
staticFields << staticField->CompileTemplate( context );
}
data[ "staticField" ] = staticFields;
}
// static fields
{
TemplateData methods { TemplateData::Type::List };
for (auto &method : m_methods)
{
if (method->ShouldCompile( ))
methods << method->CompileTemplate( context );
}
data[ "method" ] = methods;
}
// static fields
{
TemplateData staticMethods { TemplateData::Type::List };
for (auto &staticMethod : m_staticMethods)
{
if (staticMethod->ShouldCompile( ))
staticMethods << staticMethod->CompileTemplate( context );
}
data[ "staticMethod" ] = staticMethods;
}
return data;
}
bool Class::isAccessible(void) const
{
return m_enabled || m_metaData.GetFlag( native_property::Register );
}
|
AustinBrunkhorst/CPP-Reflection
|
Source/Parser/LanguageTypes/Class.cpp
|
C++
|
mit
| 5,934
|
RSpec.describe Section, :type => :model do
pending "add some examples to (or delete) #{__FILE__}"
end
|
chrisvfritz/codekwondo
|
spec/models/section_spec.rb
|
Ruby
|
mit
| 104
|
<!doctype html>
<html>
<head>
<title>Histories 2.166</title>
<meta charset="utf-8">
<link rel="stylesheet" href="reader.css">
</head>
<body class="plain">
<div class="container">
<h1>Histories 2.166</h1>
<div class="text">
<p><span class="section">1</span>
The Kalasiries are from the districts of Thebes
, Bubastis, Aphthis, Tanis, Mendes, Sebennys, Athribis, Pharbaïthis, Thmuis, Onuphis, Anytis, Myecphoris (this last is in an island opposite the city of Bubastis)—
<p><span class="section">2</span>
from all of these; their number, at its greatest, attained to two hundred and fifty thousand men. These too may practise no trade but war, which is their hereditary calling.
</div>
<div class="page-nav-2">
<a class="prev" href="./165.html"><</a>
<a class="next" href="./167.html">></a>
</div>
</div>
</body>
</html>
|
jtauber/online-reader
|
docs/static-paginated-perseus4/166.html
|
HTML
|
mit
| 914
|
/* -*- C -*-
* $Id$
*/
#include <ruby/ruby.h>
#include <ruby/io.h>
#include <ctype.h>
#include <fiddle.h>
#ifdef PRIsVALUE
# define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj)
# define RB_OBJ_STRING(obj) (obj)
#else
# define PRIsVALUE "s"
# define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj)
# define RB_OBJ_STRING(obj) StringValueCStr(obj)
#endif
VALUE rb_cPointer;
typedef void (*freefunc_t)(void*);
struct ptr_data {
void *ptr;
long size;
freefunc_t free;
VALUE wrap[2];
};
#define RPTR_DATA(obj) ((struct ptr_data *)(DATA_PTR(obj)))
static inline freefunc_t
get_freefunc(VALUE func, volatile VALUE *wrap)
{
VALUE addrnum;
if (NIL_P(func)) {
*wrap = 0;
return NULL;
}
addrnum = rb_Integer(func);
*wrap = (addrnum != func) ? func : 0;
return (freefunc_t)(VALUE)NUM2PTR(addrnum);
}
static ID id_to_ptr;
static void
fiddle_ptr_mark(void *ptr)
{
struct ptr_data *data = ptr;
if (data->wrap[0]) {
rb_gc_mark(data->wrap[0]);
}
if (data->wrap[1]) {
rb_gc_mark(data->wrap[1]);
}
}
static void
fiddle_ptr_free(void *ptr)
{
struct ptr_data *data = ptr;
if (data->ptr) {
if (data->free) {
(*(data->free))(data->ptr);
}
}
xfree(ptr);
}
static size_t
fiddle_ptr_memsize(const void *ptr)
{
const struct ptr_data *data = ptr;
return sizeof(*data) + data->size;
}
static const rb_data_type_t fiddle_ptr_data_type = {
"fiddle/pointer",
{fiddle_ptr_mark, fiddle_ptr_free, fiddle_ptr_memsize,},
};
static VALUE
rb_fiddle_ptr_new2(VALUE klass, void *ptr, long size, freefunc_t func)
{
struct ptr_data *data;
VALUE val;
val = TypedData_Make_Struct(klass, struct ptr_data, &fiddle_ptr_data_type, data);
data->ptr = ptr;
data->free = func;
data->size = size;
return val;
}
static VALUE
rb_fiddle_ptr_new(void *ptr, long size, freefunc_t func)
{
return rb_fiddle_ptr_new2(rb_cPointer, ptr, size, func);
}
static VALUE
rb_fiddle_ptr_malloc(long size, freefunc_t func)
{
void *ptr;
ptr = ruby_xmalloc((size_t)size);
memset(ptr,0,(size_t)size);
return rb_fiddle_ptr_new(ptr, size, func);
}
static void *
rb_fiddle_ptr2cptr(VALUE val)
{
struct ptr_data *data;
void *ptr;
if (rb_obj_is_kind_of(val, rb_cPointer)) {
TypedData_Get_Struct(val, struct ptr_data, &fiddle_ptr_data_type, data);
ptr = data->ptr;
}
else if (val == Qnil) {
ptr = NULL;
}
else{
rb_raise(rb_eTypeError, "Fiddle::Pointer was expected");
}
return ptr;
}
static VALUE
rb_fiddle_ptr_s_allocate(VALUE klass)
{
VALUE obj;
struct ptr_data *data;
obj = TypedData_Make_Struct(klass, struct ptr_data, &fiddle_ptr_data_type, data);
data->ptr = 0;
data->size = 0;
data->free = 0;
return obj;
}
/*
* call-seq:
* Fiddle::Pointer.new(address) => fiddle_cptr
* new(address, size) => fiddle_cptr
* new(address, size, freefunc) => fiddle_cptr
*
* Create a new pointer to +address+ with an optional +size+ and +freefunc+.
*
* +freefunc+ will be called when the instance is garbage collected.
*/
static VALUE
rb_fiddle_ptr_initialize(int argc, VALUE argv[], VALUE self)
{
VALUE ptr, sym, size, wrap = 0, funcwrap = 0;
struct ptr_data *data;
void *p = NULL;
freefunc_t f = NULL;
long s = 0;
if (rb_scan_args(argc, argv, "12", &ptr, &size, &sym) >= 1) {
VALUE addrnum = rb_Integer(ptr);
if (addrnum != ptr) wrap = ptr;
p = NUM2PTR(addrnum);
}
if (argc >= 2) {
s = NUM2LONG(size);
}
if (argc >= 3) {
f = get_freefunc(sym, &funcwrap);
}
if (p) {
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
if (data->ptr && data->free) {
/* Free previous memory. Use of inappropriate initialize may cause SEGV. */
(*(data->free))(data->ptr);
}
data->wrap[0] = wrap;
data->wrap[1] = funcwrap;
data->ptr = p;
data->size = s;
data->free = f;
}
return Qnil;
}
/*
* call-seq:
*
* Fiddle::Pointer.malloc(size, freefunc = nil) => fiddle pointer instance
*
* Allocate +size+ bytes of memory and associate it with an optional
* +freefunc+ that will be called when the pointer is garbage collected.
*
* +freefunc+ must be an address pointing to a function or an instance of
* Fiddle::Function
*/
static VALUE
rb_fiddle_ptr_s_malloc(int argc, VALUE argv[], VALUE klass)
{
VALUE size, sym, obj, wrap = 0;
long s;
freefunc_t f;
switch (rb_scan_args(argc, argv, "11", &size, &sym)) {
case 1:
s = NUM2LONG(size);
f = NULL;
break;
case 2:
s = NUM2LONG(size);
f = get_freefunc(sym, &wrap);
break;
default:
rb_bug("rb_fiddle_ptr_s_malloc");
}
obj = rb_fiddle_ptr_malloc(s,f);
if (wrap) RPTR_DATA(obj)->wrap[1] = wrap;
return obj;
}
/*
* call-seq: to_i
*
* Returns the integer memory location of this pointer.
*/
static VALUE
rb_fiddle_ptr_to_i(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return PTR2NUM(data->ptr);
}
/*
* call-seq: to_value
*
* Cast this pointer to a ruby object.
*/
static VALUE
rb_fiddle_ptr_to_value(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return (VALUE)(data->ptr);
}
/*
* call-seq: ptr
*
* Returns a new Fiddle::Pointer instance that is a dereferenced pointer for
* this pointer.
*
* Analogous to the star operator in C.
*/
static VALUE
rb_fiddle_ptr_ptr(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return rb_fiddle_ptr_new(*((void**)(data->ptr)),0,0);
}
/*
* call-seq: ref
*
* Returns a new Fiddle::Pointer instance that is a reference pointer for this
* pointer.
*
* Analogous to the ampersand operator in C.
*/
static VALUE
rb_fiddle_ptr_ref(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return rb_fiddle_ptr_new(&(data->ptr),0,0);
}
/*
* call-seq: null?
*
* Returns +true+ if this is a null pointer.
*/
static VALUE
rb_fiddle_ptr_null_p(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return data->ptr ? Qfalse : Qtrue;
}
/*
* call-seq: free=(function)
*
* Set the free function for this pointer to +function+ in the given
* Fiddle::Function.
*/
static VALUE
rb_fiddle_ptr_free_set(VALUE self, VALUE val)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
data->free = get_freefunc(val, &data->wrap[1]);
return Qnil;
}
/*
* call-seq: free => Fiddle::Function
*
* Get the free function for this pointer.
*
* Returns a new instance of Fiddle::Function.
*
* See Fiddle::Function.new
*/
static VALUE
rb_fiddle_ptr_free_get(VALUE self)
{
struct ptr_data *pdata;
VALUE address;
VALUE arg_types;
VALUE ret_type;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, pdata);
if (!pdata->free)
return Qnil;
address = PTR2NUM(pdata->free);
ret_type = INT2NUM(TYPE_VOID);
arg_types = rb_ary_new();
rb_ary_push(arg_types, INT2NUM(TYPE_VOIDP));
return rb_fiddle_new_function(address, arg_types, ret_type);
}
/*
* call-seq:
*
* ptr.to_s => string
* ptr.to_s(len) => string
*
* Returns the pointer contents as a string.
*
* When called with no arguments, this method will return the contents until
* the first NULL byte.
*
* When called with +len+, a string of +len+ bytes will be returned.
*
* See to_str
*/
static VALUE
rb_fiddle_ptr_to_s(int argc, VALUE argv[], VALUE self)
{
struct ptr_data *data;
VALUE arg1, val;
int len;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
switch (rb_scan_args(argc, argv, "01", &arg1)) {
case 0:
val = rb_str_new2((char*)(data->ptr));
break;
case 1:
len = NUM2INT(arg1);
val = rb_str_new((char*)(data->ptr), len);
break;
default:
rb_bug("rb_fiddle_ptr_to_s");
}
return val;
}
/*
* call-seq:
*
* ptr.to_str => string
* ptr.to_str(len) => string
*
* Returns the pointer contents as a string.
*
* When called with no arguments, this method will return the contents with the
* length of this pointer's +size+.
*
* When called with +len+, a string of +len+ bytes will be returned.
*
* See to_s
*/
static VALUE
rb_fiddle_ptr_to_str(int argc, VALUE argv[], VALUE self)
{
struct ptr_data *data;
VALUE arg1, val;
int len;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
switch (rb_scan_args(argc, argv, "01", &arg1)) {
case 0:
val = rb_str_new((char*)(data->ptr),data->size);
break;
case 1:
len = NUM2INT(arg1);
val = rb_str_new((char*)(data->ptr), len);
break;
default:
rb_bug("rb_fiddle_ptr_to_str");
}
return val;
}
/*
* call-seq: inspect
*
* Returns a string formatted with an easily readable representation of the
* internal state of the pointer.
*/
static VALUE
rb_fiddle_ptr_inspect(VALUE self)
{
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
return rb_sprintf("#<%"PRIsVALUE":%p ptr=%p size=%ld free=%p>",
RB_OBJ_CLASSNAME(self), (void *)data, data->ptr, data->size, (void *)data->free);
}
/*
* call-seq:
* ptr == other => true or false
* ptr.eql?(other) => true or false
*
* Returns true if +other+ wraps the same pointer, otherwise returns
* false.
*/
static VALUE
rb_fiddle_ptr_eql(VALUE self, VALUE other)
{
void *ptr1, *ptr2;
if(!rb_obj_is_kind_of(other, rb_cPointer)) return Qfalse;
ptr1 = rb_fiddle_ptr2cptr(self);
ptr2 = rb_fiddle_ptr2cptr(other);
return ptr1 == ptr2 ? Qtrue : Qfalse;
}
/*
* call-seq:
* ptr <=> other => -1, 0, 1, or nil
*
* Returns -1 if less than, 0 if equal to, 1 if greater than +other+.
*
* Returns nil if +ptr+ cannot be compared to +other+.
*/
static VALUE
rb_fiddle_ptr_cmp(VALUE self, VALUE other)
{
void *ptr1, *ptr2;
SIGNED_VALUE diff;
if(!rb_obj_is_kind_of(other, rb_cPointer)) return Qnil;
ptr1 = rb_fiddle_ptr2cptr(self);
ptr2 = rb_fiddle_ptr2cptr(other);
diff = (SIGNED_VALUE)ptr1 - (SIGNED_VALUE)ptr2;
if (!diff) return INT2FIX(0);
return diff > 0 ? INT2NUM(1) : INT2NUM(-1);
}
/*
* call-seq:
* ptr + n => new cptr
*
* Returns a new pointer instance that has been advanced +n+ bytes.
*/
static VALUE
rb_fiddle_ptr_plus(VALUE self, VALUE other)
{
void *ptr;
long num, size;
ptr = rb_fiddle_ptr2cptr(self);
size = RPTR_DATA(self)->size;
num = NUM2LONG(other);
return rb_fiddle_ptr_new((char *)ptr + num, size - num, 0);
}
/*
* call-seq:
* ptr - n => new cptr
*
* Returns a new pointer instance that has been moved back +n+ bytes.
*/
static VALUE
rb_fiddle_ptr_minus(VALUE self, VALUE other)
{
void *ptr;
long num, size;
ptr = rb_fiddle_ptr2cptr(self);
size = RPTR_DATA(self)->size;
num = NUM2LONG(other);
return rb_fiddle_ptr_new((char *)ptr - num, size + num, 0);
}
/*
* call-seq:
* ptr[index] -> an_integer
* ptr[start, length] -> a_string
*
* Returns integer stored at _index_.
*
* If _start_ and _length_ are given, a string containing the bytes from
* _start_ of _length_ will be returned.
*/
static VALUE
rb_fiddle_ptr_aref(int argc, VALUE argv[], VALUE self)
{
VALUE arg0, arg1;
VALUE retval = Qnil;
size_t offset, len;
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
if (!data->ptr) rb_raise(rb_eFiddleError, "NULL pointer dereference");
switch( rb_scan_args(argc, argv, "11", &arg0, &arg1) ){
case 1:
offset = NUM2ULONG(arg0);
retval = INT2NUM(*((char *)data->ptr + offset));
break;
case 2:
offset = NUM2ULONG(arg0);
len = NUM2ULONG(arg1);
retval = rb_str_new((char *)data->ptr + offset, len);
break;
default:
rb_bug("rb_fiddle_ptr_aref()");
}
return retval;
}
/*
* call-seq:
* ptr[index] = int -> int
* ptr[start, length] = string or cptr or addr -> string or dl_cptr or addr
*
* Set the value at +index+ to +int+.
*
* Or, set the memory at +start+ until +length+ with the contents of +string+,
* the memory from +dl_cptr+, or the memory pointed at by the memory address
* +addr+.
*/
static VALUE
rb_fiddle_ptr_aset(int argc, VALUE argv[], VALUE self)
{
VALUE arg0, arg1, arg2;
VALUE retval = Qnil;
size_t offset, len;
void *mem;
struct ptr_data *data;
TypedData_Get_Struct(self, struct ptr_data, &fiddle_ptr_data_type, data);
if (!data->ptr) rb_raise(rb_eFiddleError, "NULL pointer dereference");
switch( rb_scan_args(argc, argv, "21", &arg0, &arg1, &arg2) ){
case 2:
offset = NUM2ULONG(arg0);
((char*)data->ptr)[offset] = NUM2UINT(arg1);
retval = arg1;
break;
case 3:
offset = NUM2ULONG(arg0);
len = NUM2ULONG(arg1);
if (RB_TYPE_P(arg2, T_STRING)) {
mem = StringValuePtr(arg2);
}
else if( rb_obj_is_kind_of(arg2, rb_cPointer) ){
mem = rb_fiddle_ptr2cptr(arg2);
}
else{
mem = NUM2PTR(arg2);
}
memcpy((char *)data->ptr + offset, mem, len);
retval = arg2;
break;
default:
rb_bug("rb_fiddle_ptr_aset()");
}
return retval;
}
/*
* call-seq: size=(size)
*
* Set the size of this pointer to +size+
*/
static VALUE
rb_fiddle_ptr_size_set(VALUE self, VALUE size)
{
RPTR_DATA(self)->size = NUM2LONG(size);
return size;
}
/*
* call-seq: size
*
* Get the size of this pointer.
*/
static VALUE
rb_fiddle_ptr_size_get(VALUE self)
{
return LONG2NUM(RPTR_DATA(self)->size);
}
/*
* call-seq:
* Fiddle::Pointer[val] => cptr
* to_ptr(val) => cptr
*
* Get the underlying pointer for ruby object +val+ and return it as a
* Fiddle::Pointer object.
*/
static VALUE
rb_fiddle_ptr_s_to_ptr(VALUE self, VALUE val)
{
VALUE ptr, wrap = val, vptr;
if (RTEST(rb_obj_is_kind_of(val, rb_cIO))){
rb_io_t *fptr;
FILE *fp;
GetOpenFile(val, fptr);
fp = rb_io_stdio_file(fptr);
ptr = rb_fiddle_ptr_new(fp, 0, NULL);
}
else if (RTEST(rb_obj_is_kind_of(val, rb_cString))){
char *str = StringValuePtr(val);
ptr = rb_fiddle_ptr_new(str, RSTRING_LEN(val), NULL);
}
else if ((vptr = rb_check_funcall(val, id_to_ptr, 0, 0)) != Qundef){
if (rb_obj_is_kind_of(vptr, rb_cPointer)){
ptr = vptr;
wrap = 0;
}
else{
rb_raise(rb_eFiddleError, "to_ptr should return a Fiddle::Pointer object");
}
}
else{
VALUE num = rb_Integer(val);
if (num == val) wrap = 0;
ptr = rb_fiddle_ptr_new(NUM2PTR(num), 0, NULL);
}
if (wrap) RPTR_DATA(ptr)->wrap[0] = wrap;
return ptr;
}
void
Init_fiddle_pointer(void)
{
#undef rb_intern
id_to_ptr = rb_intern("to_ptr");
/* Document-class: Fiddle::Pointer
*
* Fiddle::Pointer is a class to handle C pointers
*
*/
rb_cPointer = rb_define_class_under(mFiddle, "Pointer", rb_cObject);
rb_define_alloc_func(rb_cPointer, rb_fiddle_ptr_s_allocate);
rb_define_singleton_method(rb_cPointer, "malloc", rb_fiddle_ptr_s_malloc, -1);
rb_define_singleton_method(rb_cPointer, "to_ptr", rb_fiddle_ptr_s_to_ptr, 1);
rb_define_singleton_method(rb_cPointer, "[]", rb_fiddle_ptr_s_to_ptr, 1);
rb_define_method(rb_cPointer, "initialize", rb_fiddle_ptr_initialize, -1);
rb_define_method(rb_cPointer, "free=", rb_fiddle_ptr_free_set, 1);
rb_define_method(rb_cPointer, "free", rb_fiddle_ptr_free_get, 0);
rb_define_method(rb_cPointer, "to_i", rb_fiddle_ptr_to_i, 0);
rb_define_method(rb_cPointer, "to_int", rb_fiddle_ptr_to_i, 0);
rb_define_method(rb_cPointer, "to_value", rb_fiddle_ptr_to_value, 0);
rb_define_method(rb_cPointer, "ptr", rb_fiddle_ptr_ptr, 0);
rb_define_method(rb_cPointer, "+@", rb_fiddle_ptr_ptr, 0);
rb_define_method(rb_cPointer, "ref", rb_fiddle_ptr_ref, 0);
rb_define_method(rb_cPointer, "-@", rb_fiddle_ptr_ref, 0);
rb_define_method(rb_cPointer, "null?", rb_fiddle_ptr_null_p, 0);
rb_define_method(rb_cPointer, "to_s", rb_fiddle_ptr_to_s, -1);
rb_define_method(rb_cPointer, "to_str", rb_fiddle_ptr_to_str, -1);
rb_define_method(rb_cPointer, "inspect", rb_fiddle_ptr_inspect, 0);
rb_define_method(rb_cPointer, "<=>", rb_fiddle_ptr_cmp, 1);
rb_define_method(rb_cPointer, "==", rb_fiddle_ptr_eql, 1);
rb_define_method(rb_cPointer, "eql?", rb_fiddle_ptr_eql, 1);
rb_define_method(rb_cPointer, "+", rb_fiddle_ptr_plus, 1);
rb_define_method(rb_cPointer, "-", rb_fiddle_ptr_minus, 1);
rb_define_method(rb_cPointer, "[]", rb_fiddle_ptr_aref, -1);
rb_define_method(rb_cPointer, "[]=", rb_fiddle_ptr_aset, -1);
rb_define_method(rb_cPointer, "size", rb_fiddle_ptr_size_get, 0);
rb_define_method(rb_cPointer, "size=", rb_fiddle_ptr_size_set, 1);
/* Document-const: NULL
*
* A NULL pointer
*/
rb_define_const(mFiddle, "NULL", rb_fiddle_ptr_new(0, 0, 0));
}
|
pmq20/ruby-compiler
|
ruby/ext/fiddle/pointer.c
|
C
|
mit
| 17,182
|
package org.learning.by.example.reactive.microservices.routers;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.learning.by.example.reactive.microservices.test.BasicIntegrationTest;
import org.learning.by.example.reactive.microservices.test.tags.IntegrationTest;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.core.IsNot.not;
@IntegrationTest
@DisplayName(" StaticRouter Integration Tests")
class StaticRouterTest extends BasicIntegrationTest {
private static final String STATIC_PATH = "/index.html";
private static final String DEFAULT_TITLE = "Swagger UI";
private static final String TITLE_TAG = "title";
@BeforeEach
void setup() {
super.bindToRouterFunction(StaticRouter.doRoute());
}
@BeforeAll
static void setupAll() {
final StaticRouter staticRouter = new StaticRouter();
}
@Test
void staticContentTest() {
String result = get(builder -> builder.path(STATIC_PATH).build());
assertThat(result, not(isEmptyOrNullString()));
verifyTitleIs(result, DEFAULT_TITLE);
}
private void verifyTitleIs(final String html, final String title) {
Document doc = Jsoup.parse(html);
Element element = doc.head().getElementsByTag(TITLE_TAG).get(0);
String text = element.text();
assertThat(text, is(title));
}
}
|
LearningByExample/reactive-ms-example
|
src/test/java/org/learning/by/example/reactive/microservices/routers/StaticRouterTest.java
|
Java
|
mit
| 1,676
|
## Command line
**doctest** works quite nicely without any command line options at all - but for more control a bunch are available.
**Query flags** - after the result is printed the program quits without executing any test cases (and if the framework is integrated into a client codebase which [**supplies it's own ```main()``` entry point**](main.md) - the program should check the result of ```shouldExit()``` method after calling ```run()``` on a ```doctest::Context``` object and should exit - this is left up to the user).
**Int/String options** - they require a value after the ```=``` sign - without spaces! For example: ```--order-by=rand```.
**Bool options** - they expect ```1```/```yes```/```on```/```true``` or ```0```/```no```/```off```/```false``` after the ```=``` sign - but they can also be used like flags and the ```=value``` part can be skipped - then ```true``` is assumed.
**Filters** - a comma-separated list of wildcards for matching values - where ```*``` means "match any sequence" and ```?``` means "match any one character".
To pass patterns with intervals use ```""``` like this: ```--test-case="*no sound*,vaguely named test number ?"```. Patterns that contain a comma can be escaped with ```\``` (example: ```--test-case=this\,test\,has\,commas```).
All the options can also be set with code (defaults/overrides) if the user [**supplies the ```main()``` function**](main.md).
| Query Flags | Description |
|:------------|-------------|
| ```-?``` ```--help``` ```-h``` | Prints a help message listing all these flags/options |
| ```-v``` ```--version``` | Prints the version of the **doctest** framework |
| ```-c``` ```--count``` | Prints the number of test cases matching the current filters (see below) |
| ```-ltc``` ```--list-test-cases``` | Lists all test cases by name which match the current filters (see below) |
| ```-lts``` ```--list-test-suites``` | Lists all test suites by name which have at least one test case matching the current filters (see below) |
| ```-lr``` ```--list-reporters``` | Lists all registered [**reporters**](reporters.md) |
| **Int/String Options** | <hr> |
| ```-tc``` ```--test-case=<filters>``` | Filters test cases based on their name. By default all test cases match but if a value is given to this filter like ```--test-case=*math*,*sound*``` then only test cases who match at least one of the patterns in the comma-separated list with wildcards will get executed/counted/listed |
| ```-tce``` ```--test-case-exclude=<filters>``` | Same as the ```-test-case=<filters>``` option but if any of the patterns in the comma-separated list of values matches - then the test case is skipped |
| ```-sf``` ```--source-file=<filters>``` | Same as ```--test-case=<filters>``` but filters based on the file in which test cases are written |
| ```-sfe``` ```--source-file-exclude=<filters>``` | Same as ```--test-case-exclude=<filters>``` but filters based on the file in which test cases are written |
| ```-ts``` ```--test-suite=<filters>``` | Same as ```--test-case=<filters>``` but filters based on the test suite in which test cases are in |
| ```-tse``` ```--test-suite-exclude=<filters>``` | Same as ```--test-case-exclude=<filters>``` but filters based on the test suite in which test cases are in |
| ```-sc``` ```--subcase=<filters>``` | Same as ```--test-case=<filters>``` but filters subcases based on their names. Does not filter test cases (they have to be executed for subcases to be discovered) so you might want to use this together with ```--test-case=<filters>```. |
| ```-sce``` ```--subcase-exclude=<filters>``` | Same as ```--test-case-exclude=<filters>``` but filters based on subcase names |
| ```-r``` ```--reporters=<filters>``` | List of [**reporters**](reporters.md) to use (default is ```console```) |
| ```-o``` ```--out=<string>``` | Output filename |
| ```-ob``` ```--order-by=<string>``` | Test cases will be sorted before being executed either by **the file in which they are** / **the test suite they are in** / **their name** / **random**. The possible values of ```<string>``` are ```file```/```suite```/```name```/```rand```/```none```. The default is ```file```. **NOTE: the order produced by the ```file```, ```suite``` and ```name``` options is compiler-dependent and might differ depending on the compiler used.** |
| ```-rs``` ```--rand-seed=<int>``` | The seed for random ordering |
| ```-f``` ```--first=<int>``` | The **first** test case to execute which passes the current filters - for range-based execution - see [**the example python script**](../../examples/range_based_execution.py) |
| ```-l``` ```--last=<int>``` | The **last** test case to execute which passes the current filters - for range-based execution - see [**the example python script**](../../examples/range_based_execution.py) |
| ```-aa``` ```--abort-after=<int>``` | The testing framework will stop executing test cases/assertions after this many failed assertions. The default is 0 which means don't stop at all. Note that the framework uses an exception to stop the current test case regardless of the level of the assert (```CHECK```/```REQUIRE```) - so be careful with asserts in destructors... |
| ```-scfl``` ```--subcase-filter-levels=<int>``` | Apply subcase filters only for the first ```<int>``` levels of nested subcases and just run the ones nested deeper. Default is a very high number which means *filter any subcase* |
| **Bool Options** | <hr> |
| ```-s``` ```--success=<bool>``` | To include successful assertions in the output |
| ```-cs``` ```--case-sensitive=<bool>``` | Filters being treated as case sensitive |
| ```-e``` ```--exit=<bool>``` | Exits after the tests finish - this is meaningful only when the client has [**provided the ```main()``` entry point**](main.md) - the program should check the ```shouldExit()``` method after calling ```run()``` on a ```doctest::Context``` object and should exit - this is left up to the user. The idea is to be able to execute just the tests in a client program and to not continue with it's execution |
| ```-d``` ```--duration=<bool>``` | Prints the time each test case took in seconds |
| ```-m``` ```--minimal=<bool>``` | Only prints failing tests |
| ```-q``` ```--quiet=<bool>``` | Does not print any output |
| ```-nt``` ```--no-throw=<bool>``` | Skips [**exceptions-related assertion**](assertions.md#exceptions) checks |
| ```-ne``` ```--no-exitcode=<bool>``` | Always returns a successful exit code - even if a test case has failed |
| ```-nr``` ```--no-run=<bool>``` | Skips all runtime **doctest** operations (except the test registering which happens before the program enters ```main()```). This is useful if the testing framework is integrated into a client codebase which has [**provided the ```main()``` entry point**](main.md) and the user wants to skip running the tests and just use the program |
| ```-ni``` ```--no-intro=<bool>``` | Omits the framework intro in the output |
| ```-nv``` ```--no-version=<bool>``` | Omits the framework version in the output |
| ```-nc``` ```--no-colors=<bool>``` | Disables colors in the output |
| ```-fc``` ```--force-colors=<bool>``` | Forces the use of colors even when a tty cannot be detected |
| ```-nb``` ```--no-breaks=<bool>``` | Disables breakpoints in debuggers when an assertion fails |
| ```-ns``` ```--no-skip=<bool>``` | Don't skip test cases marked as skip with a decorator |
| ```-gfl``` ```--gnu-file-line=<bool>``` | ```:n:``` vs ```(n):``` for line numbers in output (gnu mode is usually for linux tools/IDEs and is with the ```:``` separator) |
| ```-npf``` ```--no-path-filenames=<bool>``` | Paths are removed from the output when a filename is printed - useful if you want the same output from the testing framework on different environments |
| ```-nln``` ```--no-line-numbers=<bool>``` | Line numbers are replaced with ```0``` in the output when a source location is printed - useful if you want the same output from the testing framework even when test positions change within a source file |
| ```-ndo``` ```--no-debug-output=<bool>``` | Disables output in the debug console when a debugger is attached |
| | |
All the flags/options also come with a prefixed version (with ```--dt-``` at the front by default) - for example ```--version``` can be used also with ```--dt-version``` or ```--dt-v```.
The default prefix is ```--dt-```, but this can be changed by setting the [**```DOCTEST_CONFIG_OPTIONS_PREFIX```**](configuration.md#doctest_config_options_prefix) define.
All the unprefixed versions listed here can be disabled with the [**```DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS```**](configuration.md#doctest_config_no_unprefixed_options) define.
This is done for easy interoperability with client command line option handling when the testing framework is integrated within a client codebase - all **doctest** related flags/options can be prefixed so there are no clashes and so that the user can exclude everything starting with ```--dt-``` from their option parsing.
If there isn't an option to exclude those starting with ```--dt-``` then the ```dt_removed``` helper class might help to filter them out:
```c++
#define DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
class dt_removed {
std::vector<const char*> vec;
public:
dt_removed(const char** argv_in) {
for(; *argv_in; ++argv_in)
if(strncmp(*argv_in, "--dt-", strlen("--dt-")) != 0)
vec.push_back(*argv_in);
vec.push_back(NULL);
}
int argc() { return static_cast<int>(vec.size()) - 1; }
const char** argv() { return &vec[0]; } // Note: non-const char **:
};
int program(int argc, const char** argv);
int main(int argc, const char** argv) {
doctest::Context context(argc, argv);
int test_result = context.run(); // run queries, or run tests unless --no-run
if(context.shouldExit()) // honor query flags and --exit
return test_result;
dt_removed args(argv);
int app_result = program(args.argc(), args.argv());
return test_result + app_result; // combine the 2 results
}
int program(int argc, const char** argv) {
printf("Program: %d arguments received:\n", argc - 1);
while(*++argv)
printf("'%s'\n", *argv);
return EXIT_SUCCESS;
}
```
When ran like this:
```
program.exe --dt-test-case=math* --my-option -s --dt-no-breaks
```
Will output this:
```
Program: 2 arguments received:
'--my-option'
'-s'
```
---------------
[Home](readme.md#reference)
<p align="center"><img src="../../scripts/data/logo/icon_2.svg"></p>
|
onqtam/doctest
|
doc/markdown/commandline.md
|
Markdown
|
mit
| 11,270
|
-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 29, 2014 at 01:21 PM
-- Server version: 5.5.37
-- PHP Version: 5.3.10-1ubuntu3.12
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `Visor`
--
-- --------------------------------------------------------
--
-- Stand-in structure for view `trending_hashtags`
--
DROP VIEW IF EXISTS `trending_hashtags`;
CREATE TABLE IF NOT EXISTS `trending_hashtags` (
`hashtag` varchar(256)
,`count` bigint(21)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `trending_user_mentions`
--
DROP VIEW IF EXISTS `trending_user_mentions`;
CREATE TABLE IF NOT EXISTS `trending_user_mentions` (
`user` varchar(64)
,`mentions` bigint(21)
);
-- --------------------------------------------------------
--
-- Table structure for table `tweets`
--
DROP TABLE IF EXISTS `tweets`;
CREATE TABLE IF NOT EXISTS `tweets` (
`tweet_id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`text` varchar(256) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`retweet_count` int(11) NOT NULL,
`favorite_count` int(11) NOT NULL,
`source` varchar(256) DEFAULT NULL,
`coordinates` geometry DEFAULT NULL,
PRIMARY KEY (`tweet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_area`
--
DROP TABLE IF EXISTS `tweet_area`;
CREATE TABLE IF NOT EXISTS `tweet_area` (
`tweet_id` bigint(20) NOT NULL,
`area` varchar(64) NOT NULL,
PRIMARY KEY (`tweet_id`,`area`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_hashtags`
--
DROP TABLE IF EXISTS `tweet_hashtags`;
CREATE TABLE IF NOT EXISTS `tweet_hashtags` (
`tweet_id` bigint(20) NOT NULL,
`hashtag` varchar(256) NOT NULL,
PRIMARY KEY (`tweet_id`,`hashtag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_media`
--
DROP TABLE IF EXISTS `tweet_media`;
CREATE TABLE IF NOT EXISTS `tweet_media` (
`media_id` bigint(20) NOT NULL,
`tweet_id` bigint(20) NOT NULL,
`url` varchar(512) NOT NULL,
`type` varchar(16) DEFAULT NULL,
PRIMARY KEY (`media_id`,`tweet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_symbols`
--
DROP TABLE IF EXISTS `tweet_symbols`;
CREATE TABLE IF NOT EXISTS `tweet_symbols` (
`tweet_id` bigint(20) NOT NULL,
`symbol` varchar(256) NOT NULL,
PRIMARY KEY (`tweet_id`,`symbol`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_urls`
--
DROP TABLE IF EXISTS `tweet_urls`;
CREATE TABLE IF NOT EXISTS `tweet_urls` (
`tweet_id` bigint(20) NOT NULL,
`url` varchar(256) NOT NULL,
PRIMARY KEY (`tweet_id`,`url`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `tweet_user_mentions`
--
DROP TABLE IF EXISTS `tweet_user_mentions`;
CREATE TABLE IF NOT EXISTS `tweet_user_mentions` (
`tweet_id` bigint(20) NOT NULL,
`user_id` int(11) NOT NULL,
`screen_name` varchar(64) NOT NULL,
PRIMARY KEY (`tweet_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `twitter_users`
--
DROP TABLE IF EXISTS `twitter_users`;
CREATE TABLE IF NOT EXISTS `twitter_users` (
`user_id` bigint(20) NOT NULL,
`name` varchar(64) DEFAULT NULL,
`screen_name` varchar(64) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`location` varchar(64) DEFAULT NULL,
`description` varchar(256) DEFAULT NULL,
`url` varchar(256) DEFAULT NULL,
`followers_count` int(11) NOT NULL,
`friends_count` int(11) NOT NULL,
`listed_count` int(11) NOT NULL,
`favourites_count` int(11) NOT NULL,
`statuses_count` int(11) NOT NULL,
`utc_offset` int(11) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure for view `trending_hashtags`
--
DROP TABLE IF EXISTS `trending_hashtags`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `trending_hashtags` AS select `tweet_hashtags`.`hashtag` AS `hashtag`,count(0) AS `count` from `tweet_hashtags` group by `tweet_hashtags`.`hashtag` order by count(0) desc limit 20;
-- --------------------------------------------------------
--
-- Structure for view `trending_user_mentions`
--
DROP TABLE IF EXISTS `trending_user_mentions`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `trending_user_mentions` AS select `tweet_user_mentions`.`screen_name` AS `user`,count(0) AS `mentions` from `tweet_user_mentions` group by `tweet_user_mentions`.`screen_name` order by count(0) desc limit 20;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
AmnestyInternational/visor
|
db_setup.sql
|
SQL
|
mit
| 5,625
|
package report
type Report struct {
System SystemReport `json:"system"`
Reports map[string]interface{} `json:"reports"`
}
|
hooroo/cartographer
|
report/report.go
|
GO
|
mit
| 127
|
<!DOCTYPE html>
<html lang="en">
{% include head.html %}
<body>
{% include header.html %}
</body>
</html>
|
asongyu/asongyu.github.io
|
_layouts/front.html
|
HTML
|
mit
| 119
|
namespace LVMS.FactuurSturen
{
public enum InvoiceFilters
{
/// <summary>
/// Get open invoice (all invoices that are not fully paid yet)
/// </summary>
Open,
/// <summary>
/// Get overdue invoices
/// </summary>
Overdue,
/// <summary>
/// Get sent invoices
/// </summary>
Sent,
/// <summary>
/// Get party paid invoices
/// </summary>
Partly,
/// <summary>
/// Get invoices with too much paid
/// </summary>
TooMuch,
/// <summary>
/// Get paid invoices
/// </summary>
Paid,
/// <summary>
/// Get invoices that couldn't be collected
/// </summary>
Uncollectible
}
}
|
leonmeijer/Factuursturen.NET
|
LVMS.FactuurSturen.NET/LVMS.FactuurSturen.NET/InvoiceFilters.cs
|
C#
|
mit
| 801
|
#include "../mk.h"
typedef struct _mk_writer_context {
uint8_t *buffer;
uv_fs_t *write_req;
} mk_writer_context;
static mk_page *mk_get_writable_page(mk_collection *collection)
{
if (collection->writable_page == NULL) {
#if MK_DEBUG
fprintf(stderr, "Debug: Allocating new page for collection %s\n", collection->name);
#endif
collection->writable_page = mk_allocate_page();
}
return collection->writable_page;
}
static void mk_append_document_to_coll_cb(uv_fs_t *req)
{
mk_writer_context *context = (mk_writer_context*) req->data;
if (req->result < 0) {
fprintf(stderr, "Error: Error writing to file: %s\n", uv_strerror((int)req->result));
return;
}
uv_fs_req_cleanup(context->write_req);
free(context->write_req);
free(context->buffer);
free(context);
}
void mk_append_document_to_coll(mk_collection *collection, mk_document *document)
{
mk_page *writable_page = mk_get_writable_page(collection);
#if MK_DEBUG
fprintf(stderr, "Debug: Set write pointer in %s to: %d\n", collection->name, writable_page->pointer);
#endif
memcpy(writable_page->data + writable_page->pointer, document, sizeof(mk_document));
writable_page->pointer += sizeof(mk_document);
mk_writer_context *context = (mk_writer_context *) malloc(sizeof(mk_writer_context));
context->write_req = malloc(sizeof(uv_fs_t));
context->write_req->data = context;
context->buffer = malloc(sizeof(mk_page));
memcpy(context->buffer, writable_page, sizeof(mk_page));
uv_buf_t iov = uv_buf_init((char *)context->buffer, sizeof(mk_page));
uv_fs_write(uv_default_loop(), context->write_req, collection->open_req->result, &iov, 1, 0, mk_append_document_to_coll_cb);
}
|
andresgutierrez/mazikeen
|
src/engine/writer.c
|
C
|
mit
| 1,662
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { SafeVideo } from './core/filters/safeVideo/filter.safe-video';
import { Percentage } from './core/filters/percentage/filter.percentage';
import { TMDBAPIService } from './core/services/tmdb/tmdb-api.service';
import { SearchService } from './core/services/search/search.service';
import { AppComponent } from './app.component';
import { HomeComponent } from './core/components/home/home.component'
import { MoviesComponent } from './core/components/movies/movies.component';
import { MovieTileComponent } from './core/components/movieTile/movie-tile.component'
import { MovieComponent } from './core/components/movie/movie.component'
import { PersonComponent } from './core/components/person/person.component'
import { FooterComponent } from './core/components/footer/footer.component'
import { HeaderComponent } from './core/components/header/header.component'
import { PeopleComponent } from './core/components/people/people.component';
import { RecommendComponent } from './core/components/recommend/recommend.component';
import { AboutmeComponent } from './core/components/aboutme/aboutme.component';
@NgModule({
imports:[
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
AppRoutingModule
],
declarations:[
AppComponent,
HomeComponent,
MoviesComponent,
MovieTileComponent,
MovieComponent,
PersonComponent,
PeopleComponent,
HeaderComponent,
FooterComponent,
RecommendComponent,
AboutmeComponent,
Percentage,
SafeVideo
],
providers: [
TMDBAPIService,
SearchService
],
bootstrap:[
AppComponent
]
})
export class AppModule { }
|
juannarvaez/Movie_center_2
|
src/app/app.module.ts
|
TypeScript
|
mit
| 1,928
|
//
// UIViewController+DimBankground.h
// DimBackgroundOC
//
// Created by GK on 2016/11/16.
// Copyright © 2016年 GK. All rights reserved.
//
#import <UIKit/UIKit.h>
enum Direction {
kIn , kOut
};
@interface UIViewController (DimBankground)
- (void)dim:(enum Direction) direction color:(UIColor *)color alpha:(CGFloat) alpha speed:(CGFloat)speed;
@end
|
OneBestWay/EasyCode
|
PopView/DimBackgroundOC/DimBackgroundOC/UIViewController+DimBankground.h
|
C
|
mit
| 368
|
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160525135217 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE SEQUENCE reasons_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE appointment_reasons_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE reasons (id INT NOT NULL, name VARCHAR(255) NOT NULL, alias VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE TABLE appointment_reasons (id INT NOT NULL, appointment_id INT DEFAULT NULL, user_id INT DEFAULT NULL, reason_id INT DEFAULT NULL, created TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_83A00980E5B533F9 ON appointment_reasons (appointment_id)');
$this->addSql('CREATE INDEX IDX_83A00980A76ED395 ON appointment_reasons (user_id)');
$this->addSql('CREATE INDEX IDX_83A0098059BB1592 ON appointment_reasons (reason_id)');
$this->addSql('ALTER TABLE appointment_reasons ADD CONSTRAINT FK_83A00980E5B533F9 FOREIGN KEY (appointment_id) REFERENCES appointments (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE appointment_reasons ADD CONSTRAINT FK_83A00980A76ED395 FOREIGN KEY (user_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE appointment_reasons ADD CONSTRAINT FK_83A0098059BB1592 FOREIGN KEY (reason_id) REFERENCES reasons (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE appointments ADD bold BOOLEAN DEFAULT FALSE');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE appointment_reasons DROP CONSTRAINT FK_83A0098059BB1592');
$this->addSql('DROP SEQUENCE reasons_id_seq CASCADE');
$this->addSql('DROP SEQUENCE appointment_reasons_id_seq CASCADE');
$this->addSql('DROP TABLE reasons');
$this->addSql('DROP TABLE appointment_reasons');
$this->addSql('ALTER TABLE appointments DROP bold');
}
}
|
rsmakota/ortofit_backoffice
|
app/DoctrineMigrations/Version20160525135217.php
|
PHP
|
mit
| 2,854
|
/**
* Created by larus on 15/2/9.
*/
angular.module('myApp').directive('taginput', function () {
return {
restrict: 'E',
template: '<input name="{{name}}" class="tagsinput tagsinput-primary" ng-value="values" />',
replace: true,
scope: {
tags: '=',
name: '@',
id: '@'
},
link: function ($scope, element, attrs) {
$scope.name = attrs.name;
$scope.id = attrs.id;
$scope.$watch('tags', function (value) {
if (!value)
value = [];
$scope.values = value;
element.tagsInput(value.toString());
});
element.tagsInput({
onAddTag: function (value) {
$scope.values.push(value);
$scope.$apply(function () {
$scope.tags = $scope.values;
});
}
});
},
controller: function ($scope) {
}
}
});
|
larusx/yunmark
|
static/taginput_directive.js
|
JavaScript
|
mit
| 1,053
|
<?php
echo "<html>";
echo "<head>";
echo "<title>";
echo "About Us";
echo "</title>";
echo "</head>";
echo "<body>";
echo "About Content goes here";
echo "</body>";
echo "</html>";
?>
|
akamaotto/yopitest
|
about.php
|
PHP
|
mit
| 183
|
/** @file Cuckoo_Hashing.hh
@brief Classe Bloom_Filter
*/
#define CUCKOO_HASHING_HH
#include <sstream>
#include <vector>
#include <string>
#include "stdlib.h"
#include <random>
#include <iostream>
#include "Hash_Func_Mod.hh"
using namespace std;
/** @class Cuckoo_Hashing
@brief Representa un filtre de bloom.
*/
class Cuckoo_Hashing {
private:
vector<vector<int> > vector_tables;
vector<Hash_Func_Mod> hash_func;
int p;
int m;
int mida;
public:
// Constructor
Cuckoo_Hashing(int& tsize);
void setFamilyHashFunc(int& pFamily, int& mFamily);
//genera una nova funcio de hash a,b de la familia p,m i la inserta en el vector de hash_func
void generateHashFunc();
//retorna true si l'ha insertat normalment, false si ja hi era
void insertValue(int key);
//retorna true si el conté, false en cas contrari
bool contains(int& key);
void printFilter();
};
|
erikkvam/A
|
Experiment 2/Cuckoo/Cuckoo_Hashing.hh
|
C++
|
mit
| 936
|
package com.psychic_engine.cmput301w17t10.feelsappman.Controllers;
import android.util.Log;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.MoodEvent;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.Participant;
import com.psychic_engine.cmput301w17t10.feelsappman.Models.ParticipantSingleton;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
/**
* Created by adong on 3/20/17.
* Comments by adong on 3/28/2017.
*/
public class ParticipantController {
private ParticipantController(){}
/**
* checkUniqueParticipant is a method that will determine whether or not a certain participant
* name is taken upon sign up or log in. When you sign up, we need this method to be false, to
* ensure that there are no other names in the server and that the unique quality is satisfied.
* When you log in, the method should be true, to ensure that there is a participant stored
* in the server and its information can be retrieved for use in the app.
* @param participantName
* @return true if name is found
* @return false if name is not found
*/
public static boolean checkUniqueParticipant(String participantName) {
Participant foundParticipant = null;
ElasticParticipantController.FindParticipantTask spt = new ElasticParticipantController.FindParticipantTask();
try {
foundParticipant = spt.execute(participantName).get();
} catch (Exception e) {
Log.i("CheckParticipantName", "Failed connection with the elastic server");
}
return foundParticipant == null;
}
/**
* updateSingletonList will attempt to pull the most up to date list of participants from the
* elastic server in attempt to try and log in to the app as some participant that is already
* registered. This makes it so that the app user will be able to login from any phone so long
* an internet connection is there.
*/
public static void updateSingletonList() {
Log.i("Update", "Updating current list to elastic servers");
ElasticParticipantController.FindAllParticipantsTask fpt = new ElasticParticipantController
.FindAllParticipantsTask();
ArrayList<Participant> singletonList = ParticipantSingleton.getInstance().getParticipantList();
ArrayList<Participant> tempList;
singletonList.clear();
try {
tempList = fpt.execute().get();
for (Participant storedParticipant : tempList) {
singletonList.add(storedParticipant);
}
} catch (Exception e) {
Log.i("Error", "Unable to editMoodEvent singleton list with elastic");
}
}
/**
* Access the singleton participant's mood list to add a mood event
* @param moodEvent
*/
public static void addMoodEvent(MoodEvent moodEvent) {
Participant participant = ParticipantSingleton.getInstance().getSelfParticipant();
participant.getMoodList().add(moodEvent);
}
}
|
CMPUT301W17T10/psychic-engine
|
app/src/main/java/com/psychic_engine/cmput301w17t10/feelsappman/Controllers/ParticipantController.java
|
Java
|
mit
| 3,074
|
namespace TiledImporter {
using System;
using System.Xml.Linq;
public static class XElementExtensions {
public static T ParseAttribute<T>(this XElement element, string attribute) where T : struct {
Enum.TryParse(element.Attribute(attribute)?.Value.Replace("-", string.Empty), true, out T value);
return value;
}
public static int ParseAttribute(this XElement element, string attribute) {
return Convert.ToInt32(element.Attribute(attribute)?.Value);
}
}
}
|
ericrrichards/monorpg
|
src/MonoRpg/TiledImporter/XElementExtensions.cs
|
C#
|
mit
| 540
|
package net.ruippeixotog.akka.testkit.specs2
import net.ruippeixotog.akka.testkit.specs2.mutable.AkkaTypedSpecification
class MyTypedSpec extends AkkaTypedSpecification {
"my typed test probe" should {
"receive messages" in {
val probe = testKit.createTestProbe[String]()
probe.ref ! "hello" // expect any message
probe must receiveMessage
probe.ref ! "hello" // expect a specific message
probe must receive("hello")
// any of the following are type errors:
// probe.ref ! 3
// probe must receive(3)
// (...)
}
}
}
|
ruippeixotog/akka-testkit-specs2
|
typed/src/test/scala/net/ruippeixotog/akka/testkit/specs2/MyTypedSpec.scala
|
Scala
|
mit
| 589
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./b3414a0b755728c4b2d997365f3c6197e77f87ceac9496f685911125c9f120a8.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html>
|
simonmysun/praxis
|
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/4a8dc3735cfb30dfe67df1e81b34cc2874bb35249f86e97f47f7b6c4c8a513b9.html
|
HTML
|
mit
| 550
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./3aa5b4d4d39afa78e2d1c816fbb44e4ac1de98756c4d241a22a035473c3b6074.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html>
|
simonmysun/praxis
|
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/681d9847ad2cd7ce4b8bb15ea4303f3d7502166a9726c56a7fe97eeaca10762a.html
|
HTML
|
mit
| 550
|
package com.lotaris.jee.rest.mappers;
import com.lotaris.jee.validation.IErrorCode;
import com.lotaris.jee.validation.IErrorLocationType;
/**
* Mapping definition to bind an ExceptionMapper with an ErrorCode and LocationType
*
* @author Laurent Prevost <laurent.prevost@lotaris.com>
*/
public class MapperMappingDefinition {
/**
* Class of an ExceptionMapper
*/
private Class<? extends AbstractApiExceptionMapper> mapper;
/**
* Error code bound
*/
private IErrorCode code;
/**
* Location type bound
*/
private IErrorLocationType locationType;
/**
* Constructor
*
* @param mapper ExceptionMapper class
* @param code Error code
*/
public MapperMappingDefinition(Class<? extends AbstractApiExceptionMapper> mapper, IErrorCode code) {
this.mapper = mapper;
this.code = code;
final DefaultLocationType configuration = mapper.getAnnotation(DefaultLocationType.class);
if (configuration != null) {
locationType = new IErrorLocationType() {
@Override
public String getLocationType() {
return configuration.value();
}
};
}
}
public IErrorCode getCode() {
return code;
}
public IErrorLocationType getLocationType() {
return locationType;
}
public Class<? extends AbstractApiExceptionMapper> getMapper() {
return mapper;
}
/**
* Set the location type and return itself as a builder pattern
*
* @param locationType Location type to set
* @return this
*/
public MapperMappingDefinition locationType(IErrorLocationType locationType) {
this.locationType = locationType;
return this;
}
}
|
lotaris/jee-rest
|
src/main/java/com/lotaris/jee/rest/mappers/MapperMappingDefinition.java
|
Java
|
mit
| 1,590
|
/* eslint-disable consistent-this */
var cscript = require('../lib/cscript.js')
describe('cscript', function() {
var mockFs, mockExecFile
it('must be initialized', function() {
(function() {
cscript.path()
}).should.throw('must initialize first')
})
it('if cscript.exe is successfully spawned then no more checks are conducted', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['cscript.exe'].args[0].should.eql('cscript.exe')
done()
})
})
it('initializes only once', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(0)
done()
})
})
})
it('if cscript.exe fails to execute, try to run "where cscript.exe"', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['where cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].err = new Error()
mockExecFile['cscript.exe'].err.code = 'ENOENT'
mockExecFile['where cscript.exe'].stdout = '123'
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(1)
cscript.path().should.eql('123')
done()
})
})
beforeEach(function() {
mockFs = {
err: null,
calls: 0,
stat: function(name, cb) {
this.calls++
var self = this
setImmediate(function() {
cb(self.err, {})
})
},
}
mockExecFile = function(command, args, options, callback) {
if (!mockExecFile[command]) {
throw new Error('unexpected command ' + command)
}
mockExecFile[command].args = arguments
mockExecFile[command].calls++
if (typeof args === 'function') {
callback = args
args = undefined
options = undefined
}
if (typeof options === 'function') {
callback = options
args = undefined
options = undefined
}
if (typeof callback !== 'function') {
throw new Error('missing callback')
}
setImmediate(function() {
callback(mockExecFile[command].err, mockExecFile[command].stdout, mockExecFile[command].stderr)
})
}
mockExecFile['cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
mockExecFile['where cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
cscript._mock(mockFs, mockExecFile, false)
})
afterEach(function() {
cscript._mockReset()
})
})
|
ironSource/node-regedit
|
test/cscript.test.js
|
JavaScript
|
mit
| 2,931
|
var SpecHelper = function(){};
|
patocallaghan/questionnaire-js
|
original/assets/scripts/test/spec/helpers/SpecHelper.js
|
JavaScript
|
mit
| 31
|
<style>
.ng-invalid { background-color: lightpink; }
.ng-valid { background-color: lightgreen; }
span.error { color: red; font-weight: bold; }
</style>
<h2>现在付款</h2>
<p>请输入您的详细信息,我们将尽快发货!</p>
<form name="shippingForm" novalidate>
<div class="well">
<h3>收货人:</h3>
<div class="form-group">
<label>姓名:</label>
<input name="name" class="form-control" ng-model="data.shipping.name" required/>
<span class="error" ng-show="shippingForm.name.$error.required && shippingForm.name.$dirty">请输入姓名</span>
</div>
<h3>收货地址:</h3>
<div class="form-group">
<label>国家:</label>
<input name="country" class="form-control" ng-model="data.shipping.country" required />
<span class="error" ng-show="shippingForm.country.$error.required && shippingForm.country.$dirty">请输入国家名</span>
</div>
<div class="form-group">
<label>省份:</label>
<input name="state" class="form-control" ng-model="data.shipping.state" required />
<span class="error" ng-show="shippingForm.state.$error.required && shippingForm.state.$dirty">请输入一个省份</span>
</div>
<div class="form-group">
<label>城市:</label>
<input name="city" class="form-control" ng-model="data.shipping.city" required />
<span class="error" ng-show="shippingForm.city.$error.required && shippingForm.city.$dirty">请输入一个城市名称</span>
</div>
<div class="form-group">
<label>街道地址:</label>
<input name="street" class="form-control" ng-model="data.shipping.street" required/>
<span class="error" ng-show="shippingForm.street.$error.required && shippingForm.street.$dirty">请输入一个街道地址</span>
</div>
<div class="form-group">
<label>邮政编码:</label>
<input name="zip" class="form-control" ng-model="data.shipping.zip" required />
<span class="error" ng-show="shippingForm.zip.$error.required && shippingForm.zip.$dirty">请输入邮政编码</span>
</div>
<h3>选择:</h3>
<div class="checkbox">
<label>
<input name="giftwrap" type="checkbox"/>
包装成礼物
</label>
</div>
<div class="text-center">
<button ng-disabled="shippingForm.$invalid"
class="btn btn-primary"
ng-click="sendOrder(data.shipping)">
完成订单
</button>
</div>
</div>
</form>
|
attraction11/projects
|
angular-node-sportsMall/public/views/placeOrder.html
|
HTML
|
mit
| 2,756
|
var add = function( part ){
this._value.push(part);
}
var resolved = function( is ){
if( undefined === is ) return this._resolved;
this._resolved = !!is;
return this._resolved;
}
var getValue = function(){
return this._value;
}
var setValue = function( value ){
this._value = value;
}
var Wildcard = function(){
_oop(this,"Espresso/Bag/Resolver/Wildcard");
this._value = [];
this._resolved = false;
this._parent;
}
Wildcard.prototype.add = add;
Wildcard.prototype.resolved = resolved;
Wildcard.prototype.getValue = getValue;
Wildcard.prototype.setValue = setValue;
module.exports = Wildcard;
|
quimsy/espresso
|
Bag/Resolver/Wildcard.js
|
JavaScript
|
mit
| 607
|
<?php
$parentNav="jquery-home";
$pageName="jquery-carousel-1";
$category="jquery-carousel";
?>
<?php include '../../includes/header.php'; ?>
<style rel="stylesheet" type="text/css" />
.my_carousel { position: relative; width: 760px; margin: 0px; background-color: #fff; margin: 30px auto 20px auto; }
.carousel_container { height: 340px; margin: 0px; background: #a00 url(../../../../assets/img/carousel-1/background.jpg) no-repeat 0px 0px; }
#carousel { margin: 0px auto 0px auto; width: 600px; height: 300px; }
#carousel img { width: 300px; height: 225px; cursor: pointer; }
.nextItem { position: absolute; top: 230px; left: 0px; z-index: 1001; cursor: pointer; }
.prevItem { position: absolute; top: 230px; right: 0px; z-index: 1002; cursor: pointer; }
.caption_container { width: 435px; border-left: 3px solid #713e1b; margin: 0px 0px 0px 165px; padding: 0px 0px 0px 20px; }
#captions h2 { font-family: Georgia; font-size: 32px; font-weight: normal; margin: 0px 0px 5px 0px; color: #6d8824; }
#captions p { font-family: Arial; font-size: 14px; color: #444; margin: 0px 0px 0px 3px; }
.leaves { position: absolute; top: 270px; left: 102px; z-index: 1000; }
.carousel_data { display: none; }
</style>
<script type="text/javascript">
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
</script>
<section id="rightCol1">
<!-- PAGE CODE STARTS HERE-->
<h1>JQUERY Carousel</h1>
<!-- Carousel -->
<div class="my_carousel">
<!-- Carousel Containter -->
<div class="carousel_container">
<div id="carousel"></div>
<img class="nextItem" src="../../assets/img/carousel-1/arrow_left.png"/>
<img class="prevItem" src="../../assets/img/carousel-1/arrow_right.png"/>
</div>
<!-- Caption Container -->
<div class="caption_container">
<div id="captions"></div>
</div>
<img class="leaves" src="../../assets/img/carousel-1/leaves.png"/>
<!-- Carousel Data -->
<div class="carousel_data">
<!-- begin items -->
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_green.png" alt="teapot_green" />
</div>
<div class="caption">
<h2>Green Teapot</h2>
<p>Duis aute irure dolor in reprehenderit in voluptate cat.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_steel.png" alt="teapot_steel" />
</div>
<div class="caption">
<h2>Steel Teapot</h2>
<p>Voluptate velit esse cillum dolore eu fugiat nulla pariatur ollit anim id est laborum ipsum dolor sit amet consectetur adipisicing.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_gold.png" alt="teapot_gold" />
</div>
<div class="caption">
<h2>Golden Teapot</h2>
<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_orange.png" alt="teapot_orange" />
</div>
<div class="caption">
<h2>Orange Teapot</h2>
<p>Lorem ipsum dolor dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_blue.png" alt="teapot_blue" />
</div>
<div class="caption">
<h2>Blue Teapot</h2>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehender. Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt nostrud exercitation ullamco laboris ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_iron.png" alt="teapot_iron" />
</div>
<div class="caption">
<h2>Iron Teapot</h2>
<p>Ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehender.</p>
</div>
</div>
<!-- Item -->
<div class="carousel_item">
<div class="image">
<img src="../../assets/img/carousel-1/teapots_clay.png" alt="teapot_clay" />
</div>
<div class="caption">
<h2>Clay Teapot</h2>
<p>Duis aute irure dolor in reprehender. Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt nostrud exercitation ullamco.</p>
</div>
</div>
<!-- end items -->
</div>
</div>
<blockquote>
<p>
//CSS
.my_carousel { position: relative; width: 760px; margin: 0px; background-color: #fff; margin: 30px auto 20px auto; }
.carousel_container { height: 340px; margin: 0px; background: #a00 url(../../images/background.jpg) no-repeat 0px 0px; }
#carousel { margin: 0px auto 0px auto; width: 600px; height: 300px; }
#carousel img { width: 300px; height: 225px; cursor: pointer; }
.nextItem { position: absolute; top: 230px; left: 0px; z-index: 1001; cursor: pointer; }
.prevItem { position: absolute; top: 230px; right: 0px; z-index: 1002; cursor: pointer; }
.caption_container { width: 435px; border-left: 3px solid #713e1b; margin: 0px 0px 0px 165px; padding: 0px 0px 0px 20px; }
#captions h2 { font-family: Georgia; font-size: 32px; font-weight: normal; margin: 0px 0px 5px 0px; color: #6d8824; }
#captions p { font-family: Arial; font-size: 14px; color: #444; margin: 0px 0px 0px 3px; }
.leaves { position: absolute; top: 270px; left: 102px; z-index: 1000; }
.carousel_data { display: none; }
// JavaScript Document
// Written by Chris Converse for lynda.com
var startingItem = 3;
// ATTACH IMAGES TO CAROUSEL
// EACH TIME WE FIND .carousel_item INSIDE .carousel_data
// TARGET #carousel AND APPEND ANY DIV WITH .image AND ADD THE HTML
$(document).ready(function() {
$('.carousel_data .carousel_item').each(function(){
$('#carousel').append( $(this).find('.image').html() );
});
// ADD THE createCarousel(); FUNCTION
createCarousel();
// ADD THE createCarousel(); FUNCTION
showCaption();
});
// CREATE THE CAROUSEL
// TARGET div#carousel AND ADD .roundabout SETTINGS
function createCarousel(){
$('div#carousel').roundabout({
startingChild: window.startingItem, // STARTING ITEM IS SET AT THE TOP TO 3
childSelector: 'img', // TURN ALL IMG INTO THE ROUNDABOUT
tilt: -4.5, // ADD A TILT
minOpacity:1, // SET BACKGROUND TEA POTS
minScale: .45, // SCALE FOR BACKGROUND IMAGES
duration: 1200, // SET SPEED
// ADD CLICK FUNCTIONS
clickToFocus: true,
clickToFocusCallback: showCaption
});
// ACTIVATE THE createCustomButtons(); functions
createCustomButtons();
}
// CREATING THE BUTTONS
function createCustomButtons(){
$('.nextItem').click(function(){
hideCaption();
$('div#carousel').roundabout('animateToNextChild', showCaption);
});
$('.prevItem').click(function(){
hideCaption();
$('div#carousel').roundabout('animateToPreviousChild', showCaption);
});
$('div#carousel img').click(function(){
hideCaption();
});
}
// CREATE HIDE CAPTION FUNCTION
function hideCaption(){
$('#captions').animate({'opacity':0}, 250);
}
// CREATE SHOW CAPTION FUNCTION
function showCaption(){
// GET WHICH CHILD IMG IS IN FOCUS
var childInFocus = $('div#carousel').data('roundabout').childInFocus
// SET CAPTION TO SAME AS childInFocus
var setCaption = $('.carousel_data .carousel_item .caption:eq('+childInFocus+')').html();
//ADD setCaption TO #captions
$('#captions').html(setCaption);
//ANIMATE CAPTION BOX IN TO VIEW
var newHeight = $('#captions').height()+'px';
$('.caption_container').animate({'height':newHeight}, 500, function(){
$('#captions').animate({'opacity':1}, 250);
});
}
</p>
</blockquote>
<!-- PAGE CODE ENDS HERE-->
</section><!-- END RIGHTCOL1 -->
<script src="../../assets/js/vendor/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../../assets/js/plugins/carousel.js"></script>
<script type="text/javascript" src="../../assets/js/plugins/jquery.roundabout.min.js"></script>
<?php include '../../includes/footer.php'; ?>
|
rickyspires/training-and-code-examples
|
pages/jquery/ex-carousel.php
|
PHP
|
mit
| 9,788
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.