code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tab 2</title>
</head>
<body>
<div style="margin: auto;text-align:center; font-size:5em; margin-top: 100px">
<img src="icon_128.png" style="vertical-align:middle;"> pop-tabs
</div>
</body>
</html> | Java |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop.Multivendor
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct PhysicalDevicePCIBusInfoProperties
{
/// <summary>
/// The type of this structure
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or a pointer to an extension-specific structure
/// </summary>
public void* Next;
/// <summary>
/// The PCI bus domain
/// </summary>
public uint PciDomain;
/// <summary>
/// The PCI bus identifier
/// </summary>
public uint PciBus;
/// <summary>
/// The PCI device identifier
/// </summary>
public uint PciDevice;
/// <summary>
/// The PCI device function identifier
/// </summary>
public uint PciFunction;
}
}
| Java |
student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'}
def Handler() :
while (1) :
choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n"))
print(choice)
if (choice == 1) :
if (student_phoneNumber_name) :
phone_number = input("Enter student's phone number : ")
name = SearchRecord(phone_number)
if (name) :
print("name : " + name )
else :
print(str(phone_number) + "Does not exist in record" + str(name))
else :
print("Record is empty ")
elif (choice == 2) :
phone_number = input("Enter student's phone number : ")
name = input("Enter student's name : ") #best example to understand input() and raw_input()
InsertRecord(phone_number, name)
elif (choice == 0) :
break
else:
print("Enter correct choice")
def InsertRecord(x, y):
student_phoneNumber_name[x] = y
return;
def SearchRecord(x):
print(x)
if (x in student_phoneNumber_name) :
return student_phoneNumber_name[x]
return False
Handler()
print(student_phoneNumber_name) | Java |
#!/bin/bash
set -xv
## MACS0429
export ending=OCFSRI
export SUBARUDIR=/gpfs/slac/kipac/fs1/u/awright/SUBARU/
export cluster="MACS1115+01"
. ${cluster}.ini
export config="10_3"
export lens='pretty'
export ending="OCFI"
export filter="W-J-B"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a scratch/OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSI"
export filter="W-C-IC"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a scratch/OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSRI"
export filter="W-C-RC"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a scratch/OUT-coadd_${cluster}.${filter}_pretty.log
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-J-V/SCIENCE/SUPA0043650_9OCFSI.sub.fits
export ending="OCFSI"
export filter="W-J-V"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a scratch/OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSFI"
export filter="W-S-Z+"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a scratch/OUT-coadd_${cluster}.${filter}_pretty.log
exit 0;
export cluster=MACS0429-02
. ${cluster}.ini
export config="10_3"
export lens='pretty'
export ending="OCFI"
export filter="W-J-B"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
exit 0;
#./do_coadd_pretty.sh ${cluster} W-C-RC 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-C-RC_pretty.log
export ending="OCFSFI"
export filter="W-C-IC_2006-12-21_CALIB"
./do_coadd_pretty.sh ${cluster} ${filter} 'all 3s ' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSFI"
export filter="W-C-IC"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSI"
export filter="W-C-RC_2009-01-23_CALIB"
./do_coadd_pretty.sh ${cluster} ${filter} 'all 3s ' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-C-RC/SCIENCE/SUPA0043342_9OCFSRI.sub.fits
export ending="OCFSRI"
export filter="W-C-RC"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFI"
export filter="W-J-B_2015-12-15_CALIB"
./do_coadd_pretty.sh ${cluster} ${filter} 'all 3s ' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-J-V/SCIENCE/SUPA0043650_9OCFSI.sub.fits
export ending="OCFSI"
export filter="W-J-V_2009-01-23_CALIB"
./do_coadd_pretty.sh ${cluster} ${filter} 'all 3s' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSI"
export filter="W-J-V"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export ending="OCFSFI"
export filter="W-S-Z+_2015-12-15_CALIB"
./do_coadd_pretty.sh ${cluster} ${filter} 'all 3s' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
export filter="W-S-Z+"
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
exit 0;
## RXJ2129
. RXJ2129.ini
export ending=OCFSRI
export SUBARUDIR=/gpfs/slac/kipac/fs1/u/awright/SUBARU/
export cluster=RXJ2129
export filter=W-C-RC
export config="10_3"
export lens='pretty'
#./do_coadd_pretty.sh ${cluster} W-C-RC 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-C-RC_pretty.log
export ending=OCFSRI
./do_coadd_pretty.sh ${cluster} W-J-V 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.W-J-V_pretty.log
export ending=OCFSFI
./do_coadd_pretty.sh ${cluster} W-S-I+ 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.W-S-I+_pretty.log
export ending=OCFSI
./do_coadd_pretty.sh ${cluster} W-J-B 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.W-J-B_pretty.log
export ending=OCFSFI
./do_coadd_pretty.sh ${cluster} W-S-Z+ 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.W-S-Z+_pretty.log
exit 0;
export lens='pretty'
./do_coadd_pretty.sh ${cluster} W-C-RC 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-C-RC_pretty.log
. Zw2089.ini
export cluster=Zw2089
export ending="OCFI"
#./do_coadd_pretty.sh ${cluster} W-C-RC 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-C-RC_pretty.log
#./do_coadd_pretty.sh ${cluster} W-S-I+ 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-S-I+_pretty.log
export ending=OCFSFI
./do_coadd_pretty.sh ${cluster} W-S-Z+ 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-S-Z+_pretty.log
export ending="OCFI"
./do_coadd_pretty.sh ${cluster} W-J-B 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-J-B_pretty.log
#./do_coadd_pretty.sh ${cluster} W-J-V 'pretty' 'none' ${ending} 'yes' 'yes' 2>&1 | tee -a OUT-coadd_${cluster}.W-J-V_pretty.log
exit 0;
export cluster=Zw2089
export ending="OCFSIR"
filter=W-S-I+
#./adam_pre_coadd_cleanup.sh Zw2089 W-S-I+
./do_coadd_pretty.sh Zw2089 W-S-I+ "pretty" 'none' ${ending} 2>&1 | tee -a OUT-coadd_Zw2089.${filter}.log
export cluster=Zw2089
export ending=OCFSIR
export filter=W-J-V
rm OUT-coadd_${cluster}.${filter}.log
./adam_pre_coadd_cleanup.sh ${cluster} ${filter}
./do_coadd_batch.sh Zw2089 W-J-V "all good exposure gabodsid" 'Zw2089_good_coadd_conditions.txt' ${ending} 2>&1 | tee -a OUT-coadd_${cluster}.${filter}.log
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-S-Z+/SCIENCE/SUPA0154653_9OCFSFI.sub.fits
export ending="OCFSFI"
export filter="W-S-Z+"
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-S-Z+_2015-12-15_CALIB/SCIENCE/SUPA0154638_9OCFSFI.sub.fits
#/gpfs/slac/kipac/fs1/u/awright/SUBARU/MACS0429-02/W-S-Z+_2015-12-15_CALIB/SCIENCE/SUPA0154639_9OCFSFI.sub.fits
./do_coadd_pretty.sh ${cluster} ${filter} 'pretty' 'none' ${ending} 'no' 'no' 2>&1 | tee -a OUT-coadd_${cluster}.${filter}_pretty.log
| Java |
import {Utils} from "../service/Utils";
Template.registerHelper(
"displayHours", function (date) {
return new moment(date).format("H[h]");
}
);
Template.registerHelper(
"displayHoursMinute", function (date) {
return new moment(date).format("H[h]mm");
}
);
Template.registerHelper(
"displayHoursMinuteSeconde", function (date) {
return new moment(date).format("H[h]mm ss[sec]");
}
);
Template.registerHelper(
"displayDateTime", function (date) {
return new moment(date).format("ddd DD MMM HH[h]mm");
}
);
Template.registerHelper(
"displayDay", function (date) {
return new moment(date).format("DD MMM");
}
);
Template.registerHelper(
"skillLabel", function () {
return Skills.findOne({_id: this.toString()}).label;
}
);
Template.registerHelper(
"onUpdateError", function (error) {
return function (error) {
Utils.onUpdateError(error.reason)
}
});
Template.registerHelper(
"onUpdateSuccess", function (message) {
return function (message) {
Utils.onUpdateSuccess(message);
}
});
Template.registerHelper(
"onDeleteError", function (error) {
return function (error) {
Utils.onUpdateError(error.reason)
}
});
Template.registerHelper(
"onDeleteSuccess", function (message) {
return function (message) {
Utils.onUpdateSuccess(message);
}
});
Template.registerHelper(
"allTeams", function () {
return Teams.find();
}
);
Template.registerHelper('equals', function (a, b) {
return a === b;
});
Template.registerHelper('adds', function (a, b) {
return a + b;
});
Template.registerHelper(
"allOptionsTeams", function () {
return Teams.find({
name: {
$ne: ASSIGNMENTREADYTEAM
}
});
}
);
Template.registerHelper(
"allSkills", function (userId) {
var userTeams = Meteor.users.findOne({_id: userId}).teams;
return Skills.find({
teams: {
$in: userTeams
}
});
}
);
Template.registerHelper('ifNotEmpty', function (item, options) {
if (item) {
if (item instanceof Array) {
if (item.length > 0) {
return options.fn(this);
} else {
return options.inverse(this);
}
} else {
if (item.fetch().length > 0) {
return options.fn(this);
} else {
return options.inverse(this);
}
}
} else {
return options.inverse(this);
}
});
Template.registerHelper("equals", function (a, b) {
return a === b;
}
);
Template.registerHelper("isMore", function (a, b) {
return a > b;
}
);
Template.registerHelper("displayValidationState", function (state) {
return DisplayedValidationState[state];
});
Template.registerHelper("RolesEnum", function () {
return RolesEnum;
});
Template.registerHelper(
"currentUserId", function () {
return Meteor.users.findOne({_id: Meteor.userId()})._id;
}
);
Template.registerHelper(
"isCurrentUserTheOneLogged", function (currentUserId) {
return currentUserId === Meteor.users.findOne({_id: Meteor.userId()})._id;
}
)
Template.registerHelper(
"currentUserIdObject", function () {
return {
_id: Meteor.users.findOne({_id: Meteor.userId()})._id
}
}
);
Template.registerHelper("cursorLength", function (array) {
return array.fetch().length;
}
); | Java |
# To be PS 2.0 compatible, dont use Invoke-WebRequest
$packageName = "DotNet3_5.exe"
$downloadUrl = "https://download.microsoft.com/download/7/0/3/703455ee-a747-4cc8-bd3e-98a615c3aedb/dotNetFx35setup.exe"
$targetFile = "C:\tmp\$packageName"
# Download installer
Write-Host "Downloading $packageName" -ForegroundColor Green
(New-Object System.Net.WebClient).DownloadFile($downloadUrl, $targetFile)
Write-Host "Installing $packageName" -ForegroundColor Green
Start-Process -FilePath $targetFile -ArgumentList "/q","/norestart" -Wait
Write-Host "Finished installing $packageName" -ForegroundColor Green | Java |
// +build windows
package sers
// taken from https://github.com/tarm/goserial
// and slightly modified
// (C) 2011, 2012 Tarmigan Casebolt, Benjamin Siegert, Michael Meier
// All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
import (
"fmt"
"os"
"sync"
"syscall"
"unsafe"
)
type serialPort struct {
f *os.File
fd syscall.Handle
rl sync.Mutex
wl sync.Mutex
ro *syscall.Overlapped
wo *syscall.Overlapped
}
type structDCB struct {
DCBlength, BaudRate uint32
flags [4]byte
wReserved, XonLim, XoffLim uint16
ByteSize, Parity, StopBits byte
XonChar, XoffChar, ErrorChar, EofChar, EvtChar byte
wReserved1 uint16
}
type structTimeouts struct {
ReadIntervalTimeout uint32
ReadTotalTimeoutMultiplier uint32
ReadTotalTimeoutConstant uint32
WriteTotalTimeoutMultiplier uint32
WriteTotalTimeoutConstant uint32
}
//func openPort(name string) (rwc io.ReadWriteCloser, err error) { // TODO
func Open(name string) (rwc SerialPort, err error) {
if len(name) > 0 && name[0] != '\\' {
name = "\\\\.\\" + name
}
h, err := syscall.CreateFile(syscall.StringToUTF16Ptr(name),
syscall.GENERIC_READ|syscall.GENERIC_WRITE,
0,
nil,
syscall.OPEN_EXISTING,
syscall.FILE_ATTRIBUTE_NORMAL|syscall.FILE_FLAG_OVERLAPPED,
0)
if err != nil {
return nil, err
}
f := os.NewFile(uintptr(h), name)
defer func() {
if err != nil {
f.Close()
}
}()
/*if err = setCommState(h, baud); err != nil {
return
}*/
if err = setupComm(h, 64, 64); err != nil {
return
}
if err = setCommTimeouts(h, 0.0); err != nil {
return
}
if err = setCommMask(h); err != nil {
return
}
ro, err := newOverlapped()
if err != nil {
return
}
wo, err := newOverlapped()
if err != nil {
return
}
port := new(serialPort)
port.f = f
port.fd = h
port.ro = ro
port.wo = wo
return port, nil
}
func (p *serialPort) Close() error {
return p.f.Close()
}
func (p *serialPort) Write(buf []byte) (int, error) {
p.wl.Lock()
defer p.wl.Unlock()
if err := resetEvent(p.wo.HEvent); err != nil {
return 0, err
}
var n uint32
err := syscall.WriteFile(p.fd, buf, &n, p.wo)
//fmt.Printf("n %d err %v\n", n, err)
_ = fmt.Printf
if err != nil && err != syscall.ERROR_IO_PENDING {
//fmt.Printf("returning...\n")
return int(n), err
}
return getOverlappedResult(p.fd, p.wo)
}
func (p *serialPort) Read(buf []byte) (int, error) {
//fmt.Printf("read(<%d bytes>)\n", len(buf))
if p == nil || p.f == nil {
return 0, fmt.Errorf("Invalid port on read %v %v", p, p.f)
}
p.rl.Lock()
defer p.rl.Unlock()
if err := resetEvent(p.ro.HEvent); err != nil {
return 0, err
}
var done uint32
//fmt.Printf("calling ReadFile... ")
err := syscall.ReadFile(p.fd, buf, &done, p.ro)
//fmt.Printf(" done. %d, %v\n", done, err)
if err != nil && err != syscall.ERROR_IO_PENDING {
return int(done), err
}
//fmt.Printf("getting OverlappedResult... ")
n, err := getOverlappedResult(p.fd, p.ro)
//fmt.Printf(" done. n %d err %v\n", n, err)
if n == 0 && err == nil {
return n, winSersTimeout{}
}
return n, err
}
var (
nSetCommState,
nSetCommTimeouts,
nSetCommMask,
nSetupComm,
nGetOverlappedResult,
nCreateEvent,
nResetEvent uintptr
)
func init() {
k32, err := syscall.LoadLibrary("kernel32.dll")
if err != nil {
panic("LoadLibrary " + err.Error())
}
defer syscall.FreeLibrary(k32)
nSetCommState = getProcAddr(k32, "SetCommState")
nSetCommTimeouts = getProcAddr(k32, "SetCommTimeouts")
nSetCommMask = getProcAddr(k32, "SetCommMask")
nSetupComm = getProcAddr(k32, "SetupComm")
nGetOverlappedResult = getProcAddr(k32, "GetOverlappedResult")
nCreateEvent = getProcAddr(k32, "CreateEventW")
nResetEvent = getProcAddr(k32, "ResetEvent")
}
func getProcAddr(lib syscall.Handle, name string) uintptr {
addr, err := syscall.GetProcAddress(lib, name)
if err != nil {
panic(name + " " + err.Error())
}
return addr
}
func setCommState(h syscall.Handle, baud, databits, parity, handshake int) error {
var params structDCB
params.DCBlength = uint32(unsafe.Sizeof(params))
params.flags[0] = 0x01 // fBinary
params.flags[0] |= 0x10 // Assert DSR
params.ByteSize = byte(databits)
params.BaudRate = uint32(baud)
//params.ByteSize = 8
switch parity {
case N:
params.flags[0] &^= 0x02
params.Parity = 0 // NOPARITY
case E:
params.flags[0] |= 0x02
params.Parity = 2 // EVENPARITY
case O:
params.flags[0] |= 0x02
params.Parity = 1 // ODDPARITY
default:
return StringError("invalid parity setting")
}
switch handshake {
case NO_HANDSHAKE:
// TODO: reset handshake
default:
return StringError("only NO_HANDSHAKE is supported on windows")
}
r, _, err := syscall.Syscall(nSetCommState, 2, uintptr(h), uintptr(unsafe.Pointer(¶ms)), 0)
if r == 0 {
return err
}
return nil
}
func setCommTimeouts(h syscall.Handle, constTimeout float64) error {
var timeouts structTimeouts
const MAXDWORD = 1<<32 - 1
timeouts.ReadIntervalTimeout = MAXDWORD
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD
//timeouts.ReadTotalTimeoutConstant = MAXDWORD - 1
if constTimeout == 0 {
timeouts.ReadTotalTimeoutConstant = MAXDWORD - 1
} else {
timeouts.ReadTotalTimeoutConstant = uint32(constTimeout * 1000.0)
}
/* From http://msdn.microsoft.com/en-us/library/aa363190(v=VS.85).aspx
For blocking I/O see below:
Remarks:
If an application sets ReadIntervalTimeout and
ReadTotalTimeoutMultiplier to MAXDWORD and sets
ReadTotalTimeoutConstant to a value greater than zero and
less than MAXDWORD, one of the following occurs when the
ReadFile function is called:
If there are any bytes in the input buffer, ReadFile returns
immediately with the bytes in the buffer.
If there are no bytes in the input buffer, ReadFile waits
until a byte arrives and then returns immediately.
If no bytes arrive within the time specified by
ReadTotalTimeoutConstant, ReadFile times out.
*/
r, _, err := syscall.Syscall(nSetCommTimeouts, 2, uintptr(h), uintptr(unsafe.Pointer(&timeouts)), 0)
if r == 0 {
return err
}
return nil
}
func setupComm(h syscall.Handle, in, out int) error {
r, _, err := syscall.Syscall(nSetupComm, 3, uintptr(h), uintptr(in), uintptr(out))
if r == 0 {
return err
}
return nil
}
func setCommMask(h syscall.Handle) error {
const EV_RXCHAR = 0x0001
r, _, err := syscall.Syscall(nSetCommMask, 2, uintptr(h), EV_RXCHAR, 0)
if r == 0 {
return err
}
return nil
}
func resetEvent(h syscall.Handle) error {
r, _, err := syscall.Syscall(nResetEvent, 1, uintptr(h), 0, 0)
if r == 0 {
return err
}
return nil
}
func newOverlapped() (*syscall.Overlapped, error) {
var overlapped syscall.Overlapped
r, _, err := syscall.Syscall6(nCreateEvent, 4, 0, 1, 0, 0, 0, 0)
if r == 0 {
return nil, err
}
overlapped.HEvent = syscall.Handle(r)
return &overlapped, nil
}
func getOverlappedResult(h syscall.Handle, overlapped *syscall.Overlapped) (int, error) {
var n int
r, _, err := syscall.Syscall6(nGetOverlappedResult, 4,
uintptr(h),
uintptr(unsafe.Pointer(overlapped)),
uintptr(unsafe.Pointer(&n)), 1, 0, 0)
if r == 0 {
return n, err
}
//fmt.Printf("n %d err %v\n", n, err)
return n, nil
}
func (sp *serialPort) SetMode(baudrate, databits, parity, stopbits, handshake int) error {
if err := setCommState(syscall.Handle(sp.f.Fd()), baudrate, databits, parity, handshake); err != nil {
return err
}
//return StringError("SetMode not implemented yet on Windows")
return nil
}
func (sp *serialPort) SetReadParams(minread int, timeout float64) error {
// TODO: minread is ignored!
return setCommTimeouts(sp.fd, timeout)
//return StringError("SetReadParams not implemented yet on Windows")
}
type winSersTimeout struct{}
func (wst winSersTimeout) Error() string {
return "a timeout has occured"
}
func (wst winSersTimeout) Timeout() bool {
return true
}
| Java |
DrawListBuddy
=============
A buddy for doing sort order on 2d objects in XNA/MonoGame
| Java |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DOCUMENT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Essential LaTeX headers
\documentclass{standalone}
\usepackage{tikz}
% Graph
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIKZ STYLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Colors
\definecolor{nothing}{HTML}{FFFFFF}
\definecolor{player1}{HTML}{FF0000}
\definecolor{player2}{HTML}{00FF00}
\definecolor{coin}{HTML}{E9DF42}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIKZ FIGURE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{tikzpicture}
% Nodes
\node[draw, circle, fill=nothing] at (0, 8) (0-8) {};
\node[draw, circle, fill=nothing] at (1, 8) (1-8) {};
\node[draw, circle, fill=nothing] at (2, 8) (2-8) {};
\node[draw, circle, fill=nothing] at (3, 8) (3-8) {};
\node[draw, circle, fill=nothing] at (4, 8) (4-8) {};
\node[draw, circle, fill=nothing] at (5, 8) (5-8) {};
\node[draw, circle, fill=nothing] at (6, 8) (6-8) {};
\node[draw, circle, fill=nothing] at (7, 8) (7-8) {};
\node[draw, circle, fill=coin] at (8, 8) (8-8) {};
\node[draw, circle, fill=nothing] at (0, 7) (0-7) {};
\node[draw, circle, fill=nothing] at (1, 7) (1-7) {};
\node[draw, circle, fill=nothing] at (2, 7) (2-7) {};
\node[draw, circle, fill=nothing] at (3, 7) (3-7) {};
\node[draw, circle, fill=nothing] at (4, 7) (4-7) {};
\node[draw, circle, fill=nothing] at (5, 7) (5-7) {};
\node[draw, circle, fill=nothing] at (6, 7) (6-7) {};
\node[draw, circle, fill=nothing] at (7, 7) (7-7) {};
\node[draw, circle, fill=nothing] at (8, 7) (8-7) {};
\node[draw, circle, fill=nothing] at (0, 6) (0-6) {};
\node[draw, circle, fill=nothing] at (1, 6) (1-6) {};
\node[draw, circle, fill=nothing] at (2, 6) (2-6) {};
\node[draw, circle, fill=nothing] at (3, 6) (3-6) {};
\node[draw, circle, fill=nothing] at (4, 6) (4-6) {};
\node[draw, circle, fill=nothing] at (5, 6) (5-6) {};
\node[draw, circle, fill=nothing] at (6, 6) (6-6) {};
\node[draw, circle, fill=nothing] at (7, 6) (7-6) {};
\node[draw, circle, fill=nothing] at (8, 6) (8-6) {};
\node[draw, circle, fill=nothing] at (0, 5) (0-5) {};
\node[draw, circle, fill=nothing] at (1, 5) (1-5) {};
\node[draw, circle, fill=nothing] at (2, 5) (2-5) {};
\node[draw, circle, fill=nothing] at (3, 5) (3-5) {};
\node[draw, circle, fill=nothing] at (4, 5) (4-5) {};
\node[draw, circle, fill=nothing] at (5, 5) (5-5) {};
\node[draw, circle, fill=nothing] at (6, 5) (6-5) {};
\node[draw, circle, fill=nothing] at (7, 5) (7-5) {};
\node[draw, circle, fill=nothing] at (8, 5) (8-5) {};
\node[draw, circle, fill=nothing] at (0, 4) (0-4) {};
\node[draw, circle, fill=nothing] at (1, 4) (1-4) {};
\node[draw, circle, fill=nothing] at (2, 4) (2-4) {};
\node[draw, circle, fill=nothing] at (3, 4) (3-4) {};
\node[draw, circle, fill=nothing] at (4, 4) (4-4) {};
\node[draw, circle, fill=nothing] at (5, 4) (5-4) {};
\node[draw, circle, fill=nothing] at (6, 4) (6-4) {};
\node[draw, circle, fill=nothing] at (7, 4) (7-4) {};
\node[draw, circle, fill=nothing] at (8, 4) (8-4) {};
\node[draw, circle, fill=nothing] at (0, 3) (0-3) {};
\node[draw, circle, fill=nothing] at (1, 3) (1-3) {};
\node[draw, circle, fill=nothing] at (2, 3) (2-3) {};
\node[draw, circle, fill=nothing] at (3, 3) (3-3) {};
\node[draw, circle, fill=nothing] at (4, 3) (4-3) {};
\node[draw, circle, fill=nothing] at (5, 3) (5-3) {};
\node[draw, circle, fill=nothing] at (6, 3) (6-3) {};
\node[draw, circle, fill=nothing] at (7, 3) (7-3) {};
\node[draw, circle, fill=nothing] at (8, 3) (8-3) {};
\node[draw, circle, fill=nothing] at (0, 2) (0-2) {};
\node[draw, circle, fill=nothing] at (1, 2) (1-2) {};
\node[draw, circle, fill=nothing] at (2, 2) (2-2) {};
\node[draw, circle, fill=nothing] at (3, 2) (3-2) {};
\node[draw, circle, fill=nothing] at (4, 2) (4-2) {};
\node[draw, circle, fill=nothing] at (5, 2) (5-2) {};
\node[draw, circle, fill=nothing] at (6, 2) (6-2) {};
\node[draw, circle, fill=nothing] at (7, 2) (7-2) {};
\node[draw, circle, fill=nothing] at (8, 2) (8-2) {};
\node[draw, circle, fill=nothing] at (0, 1) (0-1) {};
\node[draw, circle, fill=nothing] at (1, 1) (1-1) {};
\node[draw, circle, fill=nothing] at (2, 1) (2-1) {};
\node[draw, circle, fill=nothing] at (3, 1) (3-1) {};
\node[draw, circle, fill=nothing] at (4, 1) (4-1) {};
\node[draw, circle, fill=nothing] at (5, 1) (5-1) {};
\node[draw, circle, fill=nothing] at (6, 1) (6-1) {};
\node[draw, circle, fill=nothing] at (7, 1) (7-1) {};
\node[draw, circle, fill=nothing] at (8, 1) (8-1) {};
\node[draw, circle, fill=player1] at (0, 0) (0-0) {};
\node[draw, circle, fill=nothing] at (1, 0) (1-0) {};
\node[draw, circle, fill=nothing] at (2, 0) (2-0) {};
\node[draw, circle, fill=nothing] at (3, 0) (3-0) {};
\node[draw, circle, fill=nothing] at (4, 0) (4-0) {};
\node[draw, circle, fill=nothing] at (5, 0) (5-0) {};
\node[draw, circle, fill=nothing] at (6, 0) (6-0) {};
\node[draw, circle, fill=nothing] at (7, 0) (7-0) {};
\node[draw, circle, fill=nothing] at (8, 0) (8-0) {};
% Edges
\draw[] (0-8) -- (0-7);
\draw[] (1-8) -- (2-8);
\draw[] (1-8) -- (1-7);
\draw[] (2-8) -- (3-8);
\draw[] (2-8) -- (2-7);
\draw[] (3-8) -- (3-7);
\draw[] (4-8) -- (5-8);
\draw[] (4-8) -- (4-7);
\draw[] (5-8) -- (6-8);
\draw[] (5-8) -- (5-7);
\draw[] (6-8) -- (7-8);
\draw[] (6-8) -- (6-7);
\draw[] (7-8) -- (8-8);
\draw[] (7-8) -- (7-7);
\draw[] (8-8) -- (8-7);
\draw[] (0-7) -- (1-7);
\draw[] (0-7) -- (0-6);
\draw[] (1-7) -- (2-7);
\draw[] (1-7) -- (1-6);
\draw[] (2-7) -- (3-7);
\draw[] (2-7) -- (2-6);
\draw[] (4-7) -- (5-7);
\draw[] (4-7) -- (4-6);
\draw[] (5-7) -- (6-7);
\draw[] (5-7) -- (5-6);
\draw[] (6-7) -- (6-6);
\draw[] (0-6) -- (0-5);
\draw[] (1-6) -- (2-6);
\draw[] (1-6) -- (1-5);
\draw[] (2-6) -- (3-6);
\draw[] (2-6) -- (2-5);
\draw[] (3-6) -- (4-6);
\draw[] (3-6) -- (3-5);
\draw[] (4-6) -- (5-6);
\draw[] (4-6) -- (4-5);
\draw[] (5-6) -- (6-6);
\draw[] (6-6) -- (7-6);
\draw[] (6-6) -- (6-5);
\draw[] (7-6) -- (8-6);
\draw[] (7-6) -- (7-5);
\draw[] (8-6) -- (8-5);
\draw[] (0-5) -- (1-5);
\draw[] (0-5) -- (0-4);
\draw[] (1-5) -- (2-5);
\draw[] (1-5) -- (1-4);
\draw[] (2-5) -- (3-5);
\draw[] (2-5) -- (2-4);
\draw[] (3-5) -- (3-4);
\draw[] (4-5) -- (5-5);
\draw[] (5-5) -- (5-4);
\draw[] (6-5) -- (7-5);
\draw[] (6-5) -- (6-4);
\draw[] (7-5) -- (8-5);
\draw[] (8-5) -- (8-4);
\draw[] (0-4) -- (1-4);
\draw[] (0-4) -- (0-3);
\draw[] (1-4) -- (1-3);
\draw[] (2-4) -- (3-4);
\draw[] (2-4) -- (2-3);
\draw[] (4-4) -- (4-3);
\draw[] (5-4) -- (6-4);
\draw[] (6-4) -- (7-4);
\draw[] (6-4) -- (6-3);
\draw[] (7-4) -- (8-4);
\draw[] (0-3) -- (0-2);
\draw[] (1-3) -- (1-2);
\draw[] (2-3) -- (3-3);
\draw[] (3-3) -- (4-3);
\draw[] (3-3) -- (3-2);
\draw[] (4-3) -- (4-2);
\draw[] (5-3) -- (5-2);
\draw[] (6-3) -- (7-3);
\draw[] (6-3) -- (6-2);
\draw[] (7-3) -- (8-3);
\draw[] (7-3) -- (7-2);
\draw[] (8-3) -- (8-2);
\draw[] (2-2) -- (3-2);
\draw[] (2-2) -- (2-1);
\draw[] (3-2) -- (4-2);
\draw[] (3-2) -- (3-1);
\draw[] (4-2) -- (5-2);
\draw[] (4-2) -- (4-1);
\draw[] (5-2) -- (6-2);
\draw[] (5-2) -- (5-1);
\draw[] (6-2) -- (7-2);
\draw[] (6-2) -- (6-1);
\draw[] (7-2) -- (7-1);
\draw[] (8-2) -- (8-1);
\draw[] (0-1) -- (1-1);
\draw[] (0-1) -- (0-0);
\draw[] (1-1) -- (1-0);
\draw[] (2-1) -- (2-0);
\draw[] (3-1) -- (4-1);
\draw[] (3-1) -- (3-0);
\draw[] (4-1) -- (5-1);
\draw[] (4-1) -- (4-0);
\draw[] (5-1) -- (6-1);
\draw[] (5-1) -- (5-0);
\draw[] (6-1) -- (7-1);
\draw[] (6-1) -- (6-0);
\draw[] (8-1) -- (8-0);
\draw[] (0-0) -- (1-0);
\draw[] (1-0) -- (2-0);
\draw[] (3-0) -- (4-0);
\draw[] (6-0) -- (7-0);
\draw[] (7-0) -- (8-0);
\end{tikzpicture}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | Java |
/* Aranea
* Copyright (c) 2011-2012, Quoc-Viet Nguyen
* See LICENSE file for copyright and license details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <aranea/aranea.h>
#define CGI_EXT_LEN_ ((int)sizeof(CGI_EXT) - 1)
/** Buffer for CGI environment variables */
#define CGI_BUFF g_buff
int cgi_hit(const char *name, const int len) {
if (len > CGI_EXT_LEN_) {
if (memcmp(name + len - CGI_EXT_LEN_, CGI_EXT, CGI_EXT_LEN_) == 0) {
return 1;
}
}
return 0;
}
/** Check if file is executable.
* HTTP error code is set to client->response.status_code.
*/
static
int cgi_is_executable(const char *path, struct client_t *client) {
struct stat st;
if (access(path, X_OK) != 0) {
client->response.status_code = HTTP_STATUS_FORBIDDEN;
return -1;
}
if (stat(path, &st) == -1) {
A_ERR("stat: %s", strerror(errno));
client->response.status_code = HTTP_STATUS_SERVERERROR;
return -1;
}
if (S_ISDIR(st.st_mode)) {
client->response.status_code = HTTP_STATUS_FORBIDDEN;
return -1;
}
return 0;
}
#define CGI_ADD_ENV_(env, cnt, buf, ...) \
do { \
*env = buf; \
len = sizeof(CGI_BUFF) - (buf - CGI_BUFF); \
if (len > 0) { \
len = snprintf(buf, len, __VA_ARGS__); \
buf += len + 1; /* skip NULL */ \
++env; \
++cnt; \
} \
} while (0)
/** Generate CGI environment from HTTP request.
* Values are saved in g_buff (g_cgienv)
*/
static
int cgi_gen_env(const struct request_t *req, char **env) {
int cnt, len;
char *buf;
cnt = 0;
buf = CGI_BUFF;
#ifdef CGI_DOCUMENT_ROOT
CGI_ADD_ENV_(env, cnt, buf, "DOCUMENT_ROOT=%s", g_config.root);
#endif
#ifdef CGI_REQUEST_METHOD
CGI_ADD_ENV_(env, cnt, buf, "REQUEST_METHOD=%s", req->method);
#endif
#ifdef CGI_REQUEST_URI
CGI_ADD_ENV_(env, cnt, buf, "REQUEST_URI=%s", req->url);
#endif
if (req->query_string) {
CGI_ADD_ENV_(env, cnt, buf, "QUERY_STRING=%s", req->query_string);
}
if (req->header[HEADER_CONTENTTYPE]) {
CGI_ADD_ENV_(env, cnt, buf, "CONTENT_TYPE=%s", req->header[HEADER_CONTENTTYPE]);
}
if (req->header[HEADER_CONTENTLENGTH]) {
CGI_ADD_ENV_(env, cnt, buf, "CONTENT_LENGTH=%s", req->header[HEADER_CONTENTLENGTH]);
}
#ifdef CGI_HTTP_COOKIE
if (req->header[HEADER_COOKIE]) {
CGI_ADD_ENV_(env, cnt, buf, "HTTP_COOKIE=%s", req->header[HEADER_COOKIE]);
}
#endif
*env = NULL;
return cnt;
}
#if HAVE_VFORK == 1
# define FORK_() vfork()
# define EXIT_(x) _exit(x)
#else
# define FORK_() fork()
# define EXIT_(x) exit(x)
#endif /* HAVE_VFORK */
/** Execute file.
* HTTP error code is set to client->response.status_code.
*/
static
int cgi_exec(const char *path, struct client_t *client) {
char *argv[2];
char *envp[MAX_CGIENV_ITEM];
pid_t pid;
int newio;
/* set socket back to blocking */
newio = fcntl(client->remote_fd, F_GETFL, NULL);
if (newio == -1
|| fcntl(client->remote_fd, F_SETFL, newio & (~O_NONBLOCK)) == -1) {
A_ERR("fcntl: F_SETFL O_NONBLOCK %s", strerror(errno));
client->response.status_code = HTTP_STATUS_SERVERERROR;
return -1;
}
pid = FORK_();
if (pid < 0) {
client->response.status_code = HTTP_STATUS_SERVERERROR;
return -1;
}
if (pid == 0) { /* child */
/* Generate CGI parameters before touching to the buffer */
cgi_gen_env(&client->request, envp);
/* Send minimal header */
client->response.status_code = HTTP_STATUS_OK;
client->data_length = http_gen_header(&client->response, client->data,
sizeof(client->data), 0);
if (send(client->remote_fd, client->data, client->data_length, 0) < 0) {
EXIT_(1);
}
/* Tie CGI's stdin to the socket */
if (client->flags & CLIENT_FLAG_POST) {
if (dup2(client->remote_fd, STDIN_FILENO) < 0) {
EXIT_(1);
}
}
/* Tie CGI's stdout to the socket */
if (dup2(client->remote_fd, STDOUT_FILENO) < 0) {
EXIT_(1);
}
/* close unused FDs */
server_close_fds();
/* No error log */
newio = open("/dev/null", O_WRONLY);
if (newio != STDERR_FILENO) {
dup2(newio, STDERR_FILENO);
close(newio);
}
/* Execute cgi script */
argv[0] = (char *)path;
argv[1] = NULL;
execve(path, argv, envp);
EXIT_(1); /* exec error */
}
/* parent */
client->state = STATE_NONE; /* Remove this client */
return 0;
}
int cgi_process(struct client_t *client, const char *path) {
if (cgi_is_executable(path, client) != 0) {
return -1;
}
if (client->flags & CLIENT_FLAG_HEADERONLY) {
client->response.status_code = HTTP_STATUS_OK;
client->data_length = http_gen_header(&client->response, client->data,
sizeof(client->data), HTTP_FLAG_END);
client->state = STATE_SEND_HEADER;
return 0;
}
return cgi_exec(path, client);
}
/* vim: set ts=4 sw=4 expandtab: */
| Java |
ESPSlider
=========
ESPSlider is a custom UIView that works like a rating UISlider, it changes values by touching or by draging inside.
See it in action: https://vimeo.com/92618816
To install you can basically drag .h and .m files to your project, import and configure or you can simple add to your Podfile
```ruby
pod 'ESPSlider', '~> 1.0'
```
For use it, you can simply instantiate ESPSlider programatically:
```objc
ESPSlider *slider = [[ESPSlider alloc] initWithFrame:CGRectMake(20.0, 20.0, 300.0, 30.0)];
[self.view addSubview:slider];
```
Or you can add a UIView to your Storyboard/xib, set Custom Class to ESPSlider and add an IBOutlet to configure the component.

```objc
@property (nonatomic, strong) IBOutlet ESPSlider *slider;
```

After that, you only need to do is to configure component:
```objc
slider.minimumSize = CGSizeMake(20.0, 30.0);
[slider setImage:[UIImage imageNamed:@"normal"] forState:ESPSliderStateNormal];
[slider setImage:[UIImage imageNamed:@"selected"] forState:ESPSliderStateSelected];
slider.minimumValue = 2;
slider.maximumValue = 7;
```
And set the value change block:
```objc
[self.slider setValueChangedBlock:^(CGFloat value){
// Do something with current value
}];
```
**The whole component is based on Ray Wenderlich 5 Star Rating View tutorial:**
http://www.raywenderlich.com/1768/uiview-tutorial-for-ios-how-to-make-a-custom-uiview-in-ios-5-a-5-star-rating-view
| Java |
<?php
namespace Soy\Phinx;
use League\CLImate\CLImate;
use Soy\Task\CliTask;
class CreateTask extends CliTask
{
use ConfigTrait;
/**
* @var string
*/
protected $name;
/**
* @param CLImate $climate
* @param Config $config
*/
public function __construct(CLImate $climate, Config $config)
{
parent::__construct($climate);
$this->config = $config;
}
/**
* @return string
*/
public function getCommand()
{
$command = $this->getBinary() . ' create ' . $this->getName() . ' ' . $this->config->getDefaultArguments();
if (count($this->getArguments()) > 0) {
$command .= ' ' . implode($this->getArguments());
}
return $command;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
| Java |
"use strict";
/*
* Copyright (c) 2013-2019 Bert Freudenberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
Object.extend(Squeak.Primitives.prototype,
'ScratchPluginAdditions', {
// methods not handled by generated ScratchPlugin
scratch_primitiveOpenURL: function(argCount) {
var url = this.stackNonInteger(0).bytesAsString();
if (url == "") return false;
if (/^\/SqueakJS\//.test(url)) {
url = url.slice(10); // remove file root
var path = Squeak.splitFilePath(url),
template = Squeak.Settings["squeak-template:" + path.dirname];
if (template) url = JSON.parse(template).url + "/" + path.basename;
}
window.open(url, "_blank"); // likely blocked as pop-up, but what can we do?
return this.popNIfOK(argCount);
},
scratch_primitiveGetFolderPath: function(argCount) {
var index = this.stackInteger(0);
if (!this.success) return false;
var path;
switch (index) {
case 1: path = '/'; break; // home dir
// case 2: path = '/desktop'; break; // desktop
// case 3: path = '/documents'; break; // documents
// case 4: path = '/pictures'; break; // my pictures
// case 5: path = '/music'; break; // my music
}
if (!path) return false;
this.vm.popNandPush(argCount + 1, this.makeStString(this.filenameToSqueak(path)));
return true;
},
});
| Java |
<?php
/* TwigBundle:Exception:traces.html.twig */
class __TwigTemplate_172db66ae695714ab527ff22427d903f9649fdf96e97dbc795a82cac4ba36f2f extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"block\">
";
// line 2
if (($this->getContext($context, "count") > 0)) {
// line 3
echo " <h2>
<span><small>[";
// line 4
echo twig_escape_filter($this->env, (($this->getContext($context, "count") - $this->getContext($context, "position")) + 1), "html", null, true);
echo "/";
echo twig_escape_filter($this->env, ($this->getContext($context, "count") + 1), "html", null, true);
echo "]</small></span>
";
// line 5
echo $this->env->getExtension('code')->abbrClass($this->getAttribute($this->getContext($context, "exception"), "class"));
echo ": ";
echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "exception"), "message"), "html", null, true)));
echo "
";
// line 6
ob_start();
// line 7
echo " <a href=\"#\" onclick=\"toggle('traces-";
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "', 'traces'); switchIcons('icon-traces-";
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "-open', 'icon-traces-";
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-";
// line 8
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: ";
echo (((0 == $this->getContext($context, "count"))) ? ("inline") : ("none"));
echo "\" />
<img class=\"toggle\" id=\"icon-traces-";
// line 9
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: ";
echo (((0 == $this->getContext($context, "count"))) ? ("none") : ("inline"));
echo "\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 12
echo " </h2>
";
} else {
// line 14
echo " <h2>Stack Trace</h2>
";
}
// line 16
echo "
<a id=\"traces-link-";
// line 17
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "\"></a>
<ol class=\"traces list-exception\" id=\"traces-";
// line 18
echo twig_escape_filter($this->env, $this->getContext($context, "position"), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == $this->getContext($context, "count"))) ? ("block") : ("none"));
echo "\">
";
// line 19
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getContext($context, "exception"), "trace"));
foreach ($context['_seq'] as $context["i"] => $context["trace"]) {
// line 20
echo " <li>
";
// line 21
$this->env->loadTemplate("TwigBundle:Exception:trace.html.twig")->display(array("prefix" => $this->getContext($context, "position"), "i" => $this->getContext($context, "i"), "trace" => $this->getContext($context, "trace")));
// line 22
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 24
echo " </ol>
</div>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 27 => 4, 24 => 3, 22 => 2, 201 => 92, 199 => 91, 196 => 90, 187 => 84, 183 => 82, 173 => 74, 171 => 73, 168 => 72, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 133 => 55, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 112 => 42, 105 => 40, 101 => 24, 91 => 31, 86 => 28, 69 => 25, 66 => 24, 62 => 23, 51 => 20, 49 => 19, 39 => 6, 32 => 12, 19 => 1, 57 => 12, 54 => 21, 43 => 8, 40 => 7, 33 => 5, 30 => 3,);
}
}
| Java |
<?php
namespace CallFire\Common\Resource;
class RetryResults extends AbstractResource
{
}
| Java |
const React = require('react');
const { ViewPropTypes } = ReactNative = require('react-native');
const {
View,
Animated,
StyleSheet,
ScrollView,
Text,
Platform,
Dimensions,
I18nManager
} = ReactNative;
const Button = require('./Button');
//import { PropTypes } from 'react'
const WINDOW_WIDTH = Dimensions.get('window').width;
const ScrollableTabBar = React.createClass({
propTypes: {
goToPage: React.PropTypes.func,
activeTab: React.PropTypes.number,
tabs: React.PropTypes.array,
backgroundColor: React.PropTypes.string,
activeTextColor: React.PropTypes.string,
inactiveTextColor: React.PropTypes.string,
scrollOffset: React.PropTypes.number,
//style: ViewPropTypes.style,
//tabStyle: ViewPropTypes.style,
//tabsContainerStyle: ViewPropTypes.style,
//tabStyle: ViewPropTypes.style,
textStyle: Text.propTypes.style,
renderTab: React.PropTypes.func,
//underlineStyle: ViewPropTypes.style,
onScroll:React.PropTypes.func,
},
getDefaultProps() {
return {
scrollOffset: 52,
activeTextColor: 'navy',
inactiveTextColor: 'black',
backgroundColor: null,
style: {},
tabStyle: {},
tabsContainerStyle: {},
tabStyle: {},
underlineStyle: {},
};
},
getInitialState() {
this._tabsMeasurements = [];
return {
_leftTabUnderline: new Animated.Value(0),
_widthTabUnderline: new Animated.Value(0),
_containerWidth: null,
};
},
componentDidMount() {
this.props.scrollValue.addListener(this.updateView);
},
updateView(offset) {
//console.log("updateView="+JSON.stringify(offset));
//console.log("updateView="+JSON.stringify(this.props));
const position = Math.floor(offset.value);
const pageOffset = offset.value % 1;
const tabCount = this.props.tabs.length;
const lastTabPosition = tabCount - 1;
if (tabCount === 0 || offset.value < 0 || offset.value > lastTabPosition) {
return;
}
if (this.necessarilyMeasurementsCompleted(position, position === lastTabPosition)) {
this.updateTabPanel(position, pageOffset);
this.updateTabUnderline(position, pageOffset, tabCount);
}
},
necessarilyMeasurementsCompleted(position, isLastTab) {
return this._tabsMeasurements[position] &&
(isLastTab || this._tabsMeasurements[position + 1]) &&
this._tabContainerMeasurements &&
this._containerMeasurements;
},
updateTabPanel(position, pageOffset) {
const containerWidth = this._containerMeasurements.width;
const tabWidth = this._tabsMeasurements[position].width;
//console.log("containerWidth="+containerWidth+" tabWidth="+tabWidth);
const nextTabMeasurements = this._tabsMeasurements[position + 1];
const nextTabWidth = nextTabMeasurements && nextTabMeasurements.width || 0;
const tabOffset = this._tabsMeasurements[position].left;
const absolutePageOffset = pageOffset * tabWidth;
let newScrollX = tabOffset + absolutePageOffset;
// center tab and smooth tab change (for when tabWidth changes a lot between two tabs)
newScrollX -= (containerWidth - (1 - pageOffset) * tabWidth - pageOffset * nextTabWidth) / 2;
newScrollX = newScrollX >= 0 ? newScrollX : 0;
if (Platform.OS === 'android') {
this._scrollView.scrollTo({x: newScrollX, y: 0, animated: false, });
} else {
const rightBoundScroll = this._tabContainerMeasurements.width - (this._containerMeasurements.width);
newScrollX = newScrollX > rightBoundScroll ? rightBoundScroll : newScrollX;
this._scrollView.scrollTo({x: newScrollX, y: 0, animated: false, });
}
},
updateTabUnderline(position, pageOffset, tabCount) {
const tabPad = this.props.underlineAlignText?this.props.tabPadding:0;
const lineLeft = this._tabsMeasurements[position].left;
const lineRight = this._tabsMeasurements[position].right;
if (position < tabCount - 1) {
const nextTabLeft = this._tabsMeasurements[position + 1].left;
const nextTabRight = this._tabsMeasurements[position + 1].right;
const newLineLeft = (pageOffset * nextTabLeft + (1 - pageOffset) * lineLeft);
const newLineRight = (pageOffset * nextTabRight + (1 - pageOffset) * lineRight);
this.state._leftTabUnderline.setValue(newLineLeft+tabPad);
this.state._widthTabUnderline.setValue(newLineRight - newLineLeft -tabPad*2);
} else {
this.state._leftTabUnderline.setValue(lineLeft+tabPad);
this.state._widthTabUnderline.setValue(lineRight - lineLeft-tabPad*2);
}
},
renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler) {
const { activeTextColor, inactiveTextColor, textStyle, } = this.props;
const textColor = isTabActive ? activeTextColor : inactiveTextColor;
const fontWeight = isTabActive ? 'bold' : 'normal';
return <Button
key={`${name}_${page}`}
accessible={true}
accessibilityLabel={name}
accessibilityTraits='button'
onPress={() => onPressHandler(page)}
onLayout={onLayoutHandler}
>
<View style={[this.props.tabStyle||styles.tab, ]}>
<Text style={[{color: textColor, fontWeight, }, textStyle, ]}>
{name}
</Text>
</View>
</Button>;
},
measureTab(page, event) {
console.log("measureTab="+page+"layout "+JSON.stringify(event.nativeEvent.layout));
const { x, width, height, } = event.nativeEvent.layout;
this._tabsMeasurements[page] = {left: x, right: x + width, width, height, };
this.updateView({value: this.props.scrollValue._value, });
},
render() {
const tabUnderlineStyle = {
position: 'absolute',
height: 1,
backgroundColor: 'navy',
bottom: 0,
};
const key = I18nManager.isRTL ? 'right' : 'left';
const dynamicTabUnderline = {
[`${key}`]: this.state._leftTabUnderline,
width: this.state._widthTabUnderline
}
return <View
style={[this.props.tabsContainerStyle||styles.container, ]}
onLayout={this.onContainerLayout}
>
<ScrollView
automaticallyAdjustContentInsets={false}
ref={(scrollView) => { this._scrollView = scrollView; }}
horizontal={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
directionalLockEnabled={true}
onScroll={this.props.onScroll}
bounces={false}
scrollsToTop={false}
>
<View
style={[styles.tabs, {width: this.state._containerWidth, }, ]}
ref={'tabContainer'}
onLayout={this.onTabContainerLayout}
>
{this.props.tabs.map((name, page) => {
const isTabActive = this.props.activeTab === page;
const renderTab = this.props.renderTab || this.renderTab;
return renderTab(name, page, isTabActive, this.props.goToPage, this.measureTab.bind(this, page));
})}
<Animated.View style={[tabUnderlineStyle, dynamicTabUnderline, this.props.underlineStyle, ]} />
</View>
</ScrollView>
</View>;
},
componentWillReceiveProps(nextProps) {
// If the tabs change, force the width of the tabs container to be recalculated
if (JSON.stringify(this.props.tabs) !== JSON.stringify(nextProps.tabs) && this.state._containerWidth) {
this.setState({ _containerWidth: null, });
}
},
onTabContainerLayout(e) {
this._tabContainerMeasurements = e.nativeEvent.layout;
let width = this._tabContainerMeasurements.width;
if (width < WINDOW_WIDTH) {
width = WINDOW_WIDTH;
}
this.setState({ _containerWidth: width, });
this.updateView({value: this.props.scrollValue._value, });
},
onContainerLayout(e) {
this._containerMeasurements = e.nativeEvent.layout;
this.updateView({value: this.props.scrollValue._value, });
},
});
module.exports = ScrollableTabBar;
const styles = StyleSheet.create({
tab: {
height: 49,
alignItems: 'center',
justifyContent: 'center',
paddingLeft: 20,
paddingRight: 20,
},
container: {
height: 50,
borderWidth: 1,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
borderColor: '#ccc',
},
tabs: {
flexDirection: 'row',
// justifyContent: 'space-around', android设备可能撞车
},
});
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("eXpand.XafMVVM.Module.Win")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("-")]
[assembly: AssemblyProduct("eXpand.XafMVVM.Module.Win")]
[assembly: AssemblyCopyright("Copyright © - 2007")]
[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)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
| Java |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.webodf;
import android.os.Bundle;
import org.apache.cordova.*;
public class WebODF extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
}
}
| Java |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace murlok_uwp
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
LaunchBackgroundProcess();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
private async void LaunchBackgroundProcess()
{
try
{
await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("BackgroundProcess failed to launch");
}
}
}
}
| Java |
<?php
namespace jk204\SIMalliance\ASN1\FileSystem;
use FG\ASN1\Universal\OctetString;
class filePath extends OctetString
{
} | Java |
class ExercisesController < ApplicationController
load_and_authorize_resource
before_action :set_exercise, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@exercises = Exercise.all
respond_with(@exercises)
end
def show
respond_with(@exercise)
end
def new
@exercise = Exercise.new
respond_with(@exercise)
end
def edit
end
def create
@exercise = Exercise.new(exercise_params)
@exercise.save
respond_with(@exercise)
end
def update
@exercise.update(exercise_params)
respond_with(@exercise)
end
def destroy
@exercise.destroy
respond_with(@exercise)
end
private
def set_exercise
@exercise = Exercise.find(params[:id])
end
def exercise_params
params.require(:exercise).permit(:title, :content)
end
end
| Java |
---
layout: post
status: publish
published: true
title: Bad Boys for Life
author:
display_name: Dylan
login: dylan
email: dylan@dylanreed.com
url: /
author_login: dylan
author_email: dylan@dylanreed.com
author_url: /
wordpress_id: 54
wordpress_url: http://dylanreed.org/?p=54
date: '2003-07-27 09:29:35 -0500'
date_gmt: '2003-07-27 15:29:35 -0500'
categories:
- Awesome
tags: []
comments: []
---
I saw Bad Boys II today. It was pretty good, not as good as legally blonde II, but good. Lots of explosions and a few good car chases. lots of gross morgue humor so thats good. I had fun on saturday at the arts picnic. I dressed up as a clown and ran a muck. a muck a muck a muck thats how i ran. i did probably three 30 min shows and did some crazy unicycling. I am so sleepy.
dylan
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W30206_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page31.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 165px; margin-top: 220px;">
<p class="styleSans428.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">238% A??? AMEN; R003 ROAD LOCATION PLAT CONTINENTAL RESOURCES INC. <br/>SECTIONS 4, T152N, R99W MCKENZIE COUNTY, NORTH DAKOTA <br/>LAWRENCE & ULA W/DDEL - 57/25E7/4 SECTION 4 | 440.0 FEET 0/? 26.67 RODS t <br/>‘ 7 — 2 N 02' 36: 16: 77.1’ I 2 — 3 N 64' 10, 28” E 268.; ;3—4 N44'14 74 94.2 <br/>I I <br/> <br/>I I m ...... ELI <br/>BOULDER 2—4H BOULDER 3—4H1 <br/>N 87’ 33"44” w 7394.8 <br/>I CERT/FY THAT THIS PLAT CORRECTLY REPRESENTS PERSON AUTHORIZING SURVEY; WORK PEREQRMED BY ME OR UNDER MY RESPONSIBLE CHAD NE WBY <br/>BASIS OF BEAR/N0: TRUE NORTH <br/>BROS! ENC/WEIRIJVG' IJVCI <br/>BOX 357 BOWMAN, ND. 58623 PHONE: 70]—523~334O FAX: 701—523—5243 <br/>PROJECT NO. 12—10 <br/> </p>
</div>
<div style="position: absolute; margin-left: 2530px; margin-top: 330px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
</body>
</html>
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W21828_extracted</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page42.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 55px; margin-top: 110px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 0px; margin-top: 275px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 219px; margin-top: 137px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 247px; margin-top: 440px;">
<p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">TRIANGLE <br/>PETROLEUM CORPORATION </p>
</div>
<div style="position: absolute; margin-left: 495px; margin-top: 715px;">
<p class="styleSans19.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Triangle Petroleum Corporation <br/>Bravo Prospect Gullickson Trust 150-101-36-25 Gullickson Trust 150-101-36-25-4H <br/>Gullickson Trust 150-101-36-25-4H </p>
</div>
<div style="position: absolute; margin-left: 495px; margin-top: 1292px;">
<p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Plan: Plan #1_Triang|e Petroleum </p>
</div>
<div style="position: absolute; margin-left: 495px; margin-top: 1595px;">
<p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Standard Planning Report - Geographic <br/>10 January, 2012 </p>
</div>
</body>
</html>
| Java |
/*
Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hip/hip_runtime_api.h>
#include "test_common.h"
int main() {
int val;
hipDeviceAttribute_t attr =
hipDeviceAttributeMaxThreadsPerBlock; ///< Maximum number of threads per block.
HIP_PRINT_STATUS(hipDeviceGetAttribute(NULL, attr, 0));
HIP_PRINT_STATUS(hipDeviceGetAttribute(&val, attr, 0));
HIP_PRINT_STATUS(hipDeviceGetAttribute(NULL, attr, -1));
HIP_PRINT_STATUS(hipDeviceGetAttribute(&val, attr, -1));
attr = hipDeviceAttribute_t(91);
HIP_PRINT_STATUS(hipDeviceGetAttribute(NULL, attr, 0));
HIP_PRINT_STATUS(hipDeviceGetAttribute(&val, attr, 0));
HIP_PRINT_STATUS(hipDeviceGetAttribute(NULL, attr, -1));
HIP_PRINT_STATUS(hipDeviceGetAttribute(&val, attr, -1));
}
| Java |
<?php
namespace Oro\Bundle\FlexibleEntityBundle\AttributeType;
use Oro\Bundle\FlexibleEntityBundle\AttributeType\AbstractAttributeType;
use Oro\Bundle\FlexibleEntityBundle\Model\FlexibleValueInterface;
/**
* Datetime attribute type
*/
class DateTimeType extends AbstractAttributeType
{
/**
* {@inheritdoc}
*/
protected function prepareValueFormOptions(FlexibleValueInterface $value)
{
$options = parent::prepareValueFormOptions($value);
$options['widget'] = 'single_text';
$options['input'] = 'datetime';
return $options;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'oro_flexibleentity_datetime';
}
}
| Java |
$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"
Describe "$commandname Unit Tests" -Tag "UnitTests" {
$global:object = [PSCustomObject]@{
Foo = 42
Bar = 18
Tara = 21
}
$global:object2 = [PSCustomObject]@{
Foo = 42000
Bar = 23
}
$global:list = @()
$global:list += $object
$global:list += [PSCustomObject]@{
Foo = 23
Bar = 88
Tara = 28
}
It "renames Bar to Bar2" {
($object | Select-DbaObject -Property 'Foo', 'Bar as Bar2').PSObject.Properties.Name | Should -Be 'Foo', 'Bar2'
}
It "changes Bar to string" {
($object | Select-DbaObject -Property 'Bar to string').Bar.GetType().FullName | Should -Be 'System.String'
}
it "converts numbers to sizes" {
($object2 | Select-DbaObject -Property 'Foo size KB:1').Foo | Should -Be 41
($object2 | Select-DbaObject -Property 'Foo size KB:1:1').Foo | Should -Be "41 KB"
}
it "picks values from other variables" {
($object2 | Select-DbaObject -Property 'Tara from object').Tara | Should -Be 21
}
it "picks values from the properties of the right object in a list" {
($object2 | Select-DbaObject -Property 'Tara from List where Foo = Bar').Tara | Should -Be 28
}
} | Java |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace T2rkus.Spark.Core.Cli
{
public class CommandOption
{
public CommandOption(string template, CommandOptionType optionType)
{
Template = template;
OptionType = optionType;
Values = new List<string>();
foreach (var part in Template.Split(new[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries))
{
if (part.StartsWith("--"))
{
LongName = part.Substring(2);
}
else if (part.StartsWith("-"))
{
var optName = part.Substring(1);
// If there is only one char and it is not an English letter, it is a symbol option (e.g. "-?")
if (optName.Length == 1 && !IsEnglishLetter(optName[0]))
{
SymbolName = optName;
}
else
{
ShortName = optName;
}
}
else if (part.StartsWith("<") && part.EndsWith(">"))
{
ValueName = part.Substring(1, part.Length - 2);
}
else
{
throw new ArgumentException($"Invalid template pattern '{template}'", nameof(template));
}
}
if (string.IsNullOrEmpty(LongName) && string.IsNullOrEmpty(ShortName) && string.IsNullOrEmpty(SymbolName))
{
throw new ArgumentException($"Invalid template pattern '{template}'", nameof(template));
}
}
public string Template { get; set; }
public string ShortName { get; set; }
public string LongName { get; set; }
public string SymbolName { get; set; }
public string ValueName { get; set; }
public string Description { get; set; }
public List<string> Values { get; private set; }
public CommandOptionType OptionType { get; private set; }
public bool ShowInHelpText { get; set; } = true;
public bool Inherited { get; set; }
public bool TryParse(string value)
{
switch (OptionType)
{
case CommandOptionType.MultipleValue:
Values.Add(value);
break;
case CommandOptionType.SingleValue:
if (Values.Any())
{
return false;
}
Values.Add(value);
break;
case CommandOptionType.NoValue:
if (value != null)
{
return false;
}
// Add a value to indicate that this option was specified
Values.Add("on");
break;
default:
break;
}
return true;
}
public bool HasValue()
{
return Values.Any();
}
public string Value()
{
return HasValue() ? Values[0] : null;
}
private bool IsEnglishLetter(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
} | Java |
/*
* This file is part of jGui API, licensed under the MIT License (MIT).
*
* Copyright (c) 2016 johni0702 <https://github.com/johni0702>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.johni0702.minecraft.gui.element;
import de.johni0702.minecraft.gui.GuiRenderer;
import de.johni0702.minecraft.gui.RenderInfo;
import de.johni0702.minecraft.gui.container.GuiContainer;
import de.johni0702.minecraft.gui.utils.lwjgl.Dimension;
import de.johni0702.minecraft.gui.utils.lwjgl.Point;
import de.johni0702.minecraft.gui.utils.lwjgl.ReadableDimension;
import de.johni0702.minecraft.gui.versions.MCVer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
public abstract class AbstractGuiElement<T extends AbstractGuiElement<T>> implements GuiElement<T> {
protected static final Identifier TEXTURE = new Identifier("jgui", "gui.png");
private final MinecraftClient minecraft = MCVer.getMinecraft();
private GuiContainer container;
private GuiElement tooltip;
private boolean enabled = true;
protected Dimension minSize, maxSize;
/**
* The last size this element was render at layer 0.
* May be {@code null} when this element has not yet been rendered.
*/
private ReadableDimension lastSize;
public AbstractGuiElement() {
}
public AbstractGuiElement(GuiContainer container) {
container.addElements(null, this);
}
protected abstract T getThis();
@Override
public void layout(ReadableDimension size, RenderInfo renderInfo) {
if (size == null) {
if (getContainer() == null) {
throw new RuntimeException("Any top containers must implement layout(null, ...) themselves!");
}
getContainer().layout(size, renderInfo.layer(renderInfo.layer + getLayer()));
return;
}
if (renderInfo.layer == 0) {
lastSize = size;
}
}
@Override
public void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo) {
}
@Override
public T setEnabled(boolean enabled) {
this.enabled = enabled;
return getThis();
}
@Override
public T setEnabled() {
return setEnabled(true);
}
@Override
public T setDisabled() {
return setEnabled(false);
}
@Override
public GuiElement getTooltip(RenderInfo renderInfo) {
if (tooltip != null && lastSize != null) {
Point mouse = new Point(renderInfo.mouseX, renderInfo.mouseY);
if (container != null) {
container.convertFor(this, mouse);
}
if (mouse.getX() > 0
&& mouse.getY() > 0
&& mouse.getX() < lastSize.getWidth()
&& mouse.getY() < lastSize.getHeight()) {
return tooltip;
}
}
return null;
}
@Override
public T setTooltip(GuiElement tooltip) {
this.tooltip = tooltip;
return getThis();
}
@Override
public T setContainer(GuiContainer container) {
this.container = container;
return getThis();
}
public T setMinSize(ReadableDimension minSize) {
this.minSize = new Dimension(minSize);
return getThis();
}
public T setMaxSize(ReadableDimension maxSize) {
this.maxSize = new Dimension(maxSize);
return getThis();
}
public T setSize(ReadableDimension size) {
setMinSize(size);
return setMaxSize(size);
}
public T setSize(int width, int height) {
return setSize(new Dimension(width, height));
}
public T setWidth(int width) {
if (minSize == null) {
minSize = new Dimension(width, 0);
} else {
minSize.setWidth(width);
}
if (maxSize == null) {
maxSize = new Dimension(width, Integer.MAX_VALUE);
} else {
maxSize.setWidth(width);
}
return getThis();
}
public T setHeight(int height) {
if (minSize == null) {
minSize = new Dimension(0, height);
} else {
minSize.setHeight(height);
}
if (maxSize == null) {
maxSize = new Dimension(Integer.MAX_VALUE, height);
} else {
maxSize.setHeight(height);
}
return getThis();
}
public int getLayer() {
return 0;
}
@Override
public ReadableDimension getMinSize() {
ReadableDimension calcSize = calcMinSize();
if (minSize == null) {
return calcSize;
} else {
if (minSize.getWidth() >= calcSize.getWidth() && minSize.getHeight() >= calcSize.getHeight()) {
return minSize;
} else {
return new Dimension(
Math.max(calcSize.getWidth(), minSize.getWidth()),
Math.max(calcSize.getHeight(), minSize.getHeight())
);
}
}
}
protected abstract ReadableDimension calcMinSize();
@Override
public ReadableDimension getMaxSize() {
return maxSize == null ? new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE) : maxSize;
}
public MinecraftClient getMinecraft() {
return this.minecraft;
}
public GuiContainer getContainer() {
return this.container;
}
public boolean isEnabled() {
return this.enabled;
}
protected ReadableDimension getLastSize() {
return this.lastSize;
}
}
| Java |
#-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require File.expand_path('../../test_helper', __FILE__)
class EnabledModuleTest < ActiveSupport::TestCase
def test_enabling_wiki_should_create_a_wiki
CustomField.delete_all
FactoryGirl.create(:type_standard)
project = Project.create!(:name => 'Project with wiki', :identifier => 'wikiproject')
assert_nil project.wiki
project.enabled_module_names = ['wiki']
wiki = FactoryGirl.create :wiki, :project => project
project.reload
assert_not_nil project.wiki
assert_equal 'Wiki', project.wiki.start_page
end
def test_reenabling_wiki_should_not_create_another_wiki
project = FactoryGirl.create :project
wiki = FactoryGirl.create :wiki, :project => project
project.reload
assert_not_nil project.wiki
project.enabled_module_names = []
project.reload
assert_no_difference 'Wiki.count' do
project.enabled_module_names = ['wiki']
end
assert_not_nil project.wiki
end
end
| Java |
var expect = require('chai').expect,
sinon = require('sinon'),
EventEmitter = require('../src/EventEmitter');
describe('EventEmitter tests', function() {
var emitter,
foo,
bar;
beforeEach(function() {
emitter = new EventEmitter();
foo = sinon.spy();
bar = sinon.spy();
});
describe('.on', function() {
it('should throw error if foo is not a function', function() {
var fn = emitter.on.bind(null, 'abc', 'abc');
expect(fn).to.throw(TypeError);
});
it('should register event with emitter._events', function() {
emitter.on('data', foo);
expect(emitter._events.data[0]).to.equal(foo);
});
it('should be able to register multiple foos', function() {
emitter.on('data', foo);
emitter.on('data', bar);
expect(emitter._events.data[0]).to.equal(foo);
expect(emitter._events.data[1]).to.equal(bar);
});
it('should return itself', function() {
expect(emitter.on('data', foo)).to.equal(emitter);
});
it('emits newListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.on('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo);
});
});
describe('.emit', function() {
beforeEach(function() {
emitter.on('data', foo);
emitter.on('data', bar);
});
it('should trigger listeners bound to event', function() {
emitter.emit('data');
expect(foo.calledOnce).to.be.true;
expect(bar.calledOnce).to.be.true;
});
it('should trigger listeners in order', function() {
emitter.emit('data');
expect(foo.calledBefore(bar)).to.be.true;
});
it('should apply arguments to each listener', function() {
var arg1 = 1,
arg2 = '2',
arg3 = {};
emitter.emit('data', arg1, arg2, arg3);
sinon.assert.calledWithExactly(foo, arg1, arg2, arg3);
});
it('should bind "this" to the emitter in listener', function(done) {
var fn = function() {
expect(this).to.equal(emitter);
done();
};
emitter.on('data', fn);
emitter.emit('data');
});
it('should return true if listeners were fired', function() {
expect(emitter.emit('data')).to.be.true;
});
it('should return false if no listeners fired', function() {
expect(emitter.emit('adf')).to.be.false;
});
});
describe('.removeAllListeners', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('foo', function() {});
emitter.on('bar', bar);
});
it('should remove all listeners if no parameter', function() {
emitter.removeAllListeners();
expect(emitter._events).to.be.empty;
});
it('should only remove listeners to specified event', function() {
emitter.removeAllListeners('foo');
expect(emitter._events.foo).to.be.undefined;
expect(emitter._events.bar).to.not.be.undefined;
});
it('should return the emitter', function() {
expect(emitter.removeAllListeners()).to.equal(emitter);
});
});
describe('.removeListener', function() {
var baz;
beforeEach(function() {
baz = sinon.spy();
emitter.on('foo', foo);
emitter.on('foo', baz);
emitter.on('bar', bar);
});
it('should remove only one listener for event', function() {
emitter.removeListener('foo', baz);
expect(emitter._events.foo.length).to.equal(1);
expect(emitter._events.foo[0]).to.equal(foo);
});
it('should throw error if listener is not a function', function() {
var fn = emitter.removeListener.bind(emitter, 'foo', 'foo');
expect(fn).to.throw(TypeError);
});
it('should return the emitter', function() {
expect(emitter.removeListener('foo', foo)).to.equal(emitter);
});
it('should be able to remove listener added by .once', function() {
var qux = sinon.spy();
emitter.once('bar', qux);
emitter.removeListener('bar', qux);
expect(emitter._events.bar.length).to.equal(1);
expect(emitter._events.bar[0]).to.equal(bar);
});
it('should emit removeListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.removeListener('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'removeListener', 'foo', foo);
});
});
describe('.once', function() {
it('should throw error if listener is not a function', function() {
var fn = emitter.once.bind(null, 'abc', 'abc');
expect(fn).to.throw(TypeError);
});
it('should register a listener', function() {
emitter.once('foo', foo);
expect(emitter._events.foo.length).to.equal(1);
});
it('should run registered function', function() {
emitter.once('foo', foo);
emitter.emit('foo');
expect(foo.calledOnce).to.be.true;
});
it('should remove listener after .emit', function() {
emitter.once('foo', foo);
emitter.emit('foo');
expect(emitter._events.foo).to.be.empty;
});
it('should pass all parameters from listener', function() {
var arg1 = 1,
arg2 = '2',
arg3 = {};
emitter.once('foo', foo);
emitter.emit('foo', arg1, arg2, arg3);
sinon.assert.calledWithExactly(foo, arg1, arg2, arg3);
});
it('should return the emitter', function() {
expect(emitter.once('foo', foo)).to.equal(emitter);
});
it('emits newListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.once('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo);
});
});
describe('.listeners', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('bar', bar);
});
it('should return an array of listeners for an event', function() {
expect(emitter.listeners('foo')).to.deep.equal([foo]);
});
it('should return an empty array for unregistered events', function() {
expect(emitter.listeners('abcd')).to.deep.equal([]);
});
});
describe('.addListener', function() {
it('should be alias to .on', function() {
expect(emitter.addListener).to.equal(emitter.on);
});
});
describe('.off', function() {
it('should alias to .removeListener', function() {
expect(emitter.off).to.equal(emitter.removeListener);
});
});
describe('EventEmitter.listenerCount', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('foo', function() {});
emitter.on('bar', bar);
});
it('should return 0 for non emitters', function() {
expect(EventEmitter.listenerCount(1)).to.equal(0);
});
it('should return 0 for no listeners', function() {
expect(EventEmitter.listenerCount(emitter, 'baz')).to.equal(0);
});
it('should return number of listeners', function() {
expect(EventEmitter.listenerCount(emitter, 'foo')).to.equal(2);
});
});
});
| Java |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.logger = Logger.new(STDOUT)
end
| Java |
#!/bin/bash
. 'functions.sh'
print "Building site............"
GIT=`which git`
# Clone repo and add symblink
if [ ! -d $ROOTFS/app/project/docroot ]
then
print "Downloading latest Drupal Core ..."
exec 'wget -O - http://ftp.drupal.org/files/projects/drupal-7.39.tar.gz | tar zxf -'
exec 'mv drupal-7.39 app/project/docroot'
exec 'ln -s project/docroot app/docroot'
print "Cloning git repo ..."
exec "$GIT clone git@bitbucket.org:kurobits/condo-profile.git app/project/docroot/profiles/condo"
DEFAULT_DIR="$ROOTFS/app/project/docroot/sites/default"
print "Adding config and files directory ..."
exec "mkdir -p $DEFAULT_DIR/files"
exec "chmod a+rw $DEFAULT_DIR/files"
exec "cp $DEFAULT_DIR/default.settings.php $DEFAULT_DIR/settings.php"
echo '' >> $DEFAULT_DIR/settings.php
echo '// read local settings' >> $DEFAULT_DIR/settings.php
echo 'if (file_exists(__DIR__ . "/local.settings.php")) {' >> $DEFAULT_DIR/settings.php
echo ' require(__DIR__ . "/local.settings.php");' >> $DEFAULT_DIR/settings.php
echo '}' >> $DEFAULT_DIR/settings.php
print "Copying local settings for site ..."
exec "cp $ROOTFS/local.settings.php $DEFAULT_DIR"
print ''
print '----------------------------------------------------------------------'
print 'Levantar contenedores con ./d4d up y luego entrar a:'
print 'http://localhost:8000/install.php'
fi
# Add local settings and files directory
| Java |
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.Object}
* @param {string} id
* @param {string} name
*/
WebInspector.ProfileType = function(id, name)
{
WebInspector.Object.call(this);
this._id = id;
this._name = name;
/** @type {!Array.<!WebInspector.ProfileHeader>} */
this._profiles = [];
/** @type {?WebInspector.ProfileHeader} */
this._profileBeingRecorded = null;
this._nextProfileUid = 1;
window.addEventListener("unload", this._clearTempStorage.bind(this), false);
}
/**
* @enum {string}
*/
WebInspector.ProfileType.Events = {
AddProfileHeader: "add-profile-header",
ProfileComplete: "profile-complete",
RemoveProfileHeader: "remove-profile-header",
ViewUpdated: "view-updated"
}
WebInspector.ProfileType.prototype = {
/**
* @return {boolean}
*/
hasTemporaryView: function()
{
return false;
},
/**
* @return {?string}
*/
fileExtension: function()
{
return null;
},
get statusBarItems()
{
return [];
},
get buttonTooltip()
{
return "";
},
get id()
{
return this._id;
},
get treeItemTitle()
{
return this._name;
},
get name()
{
return this._name;
},
/**
* @return {boolean}
*/
buttonClicked: function()
{
return false;
},
get description()
{
return "";
},
/**
* @return {boolean}
*/
isInstantProfile: function()
{
return false;
},
/**
* @return {boolean}
*/
isEnabled: function()
{
return true;
},
/**
* @return {!Array.<!WebInspector.ProfileHeader>}
*/
getProfiles: function()
{
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {boolean}
* @this {WebInspector.ProfileType}
*/
function isFinished(profile)
{
return this._profileBeingRecorded !== profile;
}
return this._profiles.filter(isFinished.bind(this));
},
/**
* @return {?Element}
*/
decorationElement: function()
{
return null;
},
/**
* @nosideeffects
* @param {number} uid
* @return {?WebInspector.ProfileHeader}
*/
getProfile: function(uid)
{
for (var i = 0; i < this._profiles.length; ++i) {
if (this._profiles[i].uid === uid)
return this._profiles[i];
}
return null;
},
/**
* @param {!File} file
*/
loadFromFile: function(file)
{
var name = file.name;
if (name.endsWith(this.fileExtension()))
name = name.substr(0, name.length - this.fileExtension().length);
var profile = this.createProfileLoadedFromFile(name);
profile.setFromFile();
this.setProfileBeingRecorded(profile);
this.addProfile(profile);
profile.loadFromFile(file);
},
/**
* @param {string} title
* @return {!WebInspector.ProfileHeader}
*/
createProfileLoadedFromFile: function(title)
{
throw new Error("Needs implemented.");
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
addProfile: function(profile)
{
this._profiles.push(profile);
this.dispatchEventToListeners(WebInspector.ProfileType.Events.AddProfileHeader, profile);
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
removeProfile: function(profile)
{
var index = this._profiles.indexOf(profile);
if (index === -1)
return;
this._profiles.splice(index, 1);
this._disposeProfile(profile);
},
_clearTempStorage: function()
{
for (var i = 0; i < this._profiles.length; ++i)
this._profiles[i].removeTempFile();
},
/**
* @nosideeffects
* @return {?WebInspector.ProfileHeader}
*/
profileBeingRecorded: function()
{
return this._profileBeingRecorded;
},
/**
* @param {?WebInspector.ProfileHeader} profile
*/
setProfileBeingRecorded: function(profile)
{
if (this._profileBeingRecorded)
this._profileBeingRecorded.target().profilingLock.release();
if (profile)
profile.target().profilingLock.acquire();
this._profileBeingRecorded = profile;
},
profileBeingRecordedRemoved: function()
{
},
_reset: function()
{
var profiles = this._profiles.slice(0);
for (var i = 0; i < profiles.length; ++i)
this._disposeProfile(profiles[i]);
this._profiles = [];
this._nextProfileUid = 1;
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
_disposeProfile: function(profile)
{
this.dispatchEventToListeners(WebInspector.ProfileType.Events.RemoveProfileHeader, profile);
profile.dispose();
if (this._profileBeingRecorded === profile) {
this.profileBeingRecordedRemoved();
this.setProfileBeingRecorded(null);
}
},
__proto__: WebInspector.Object.prototype
}
/**
* @interface
*/
WebInspector.ProfileType.DataDisplayDelegate = function()
{
}
WebInspector.ProfileType.DataDisplayDelegate.prototype = {
/**
* @param {?WebInspector.ProfileHeader} profile
* @return {?WebInspector.View}
*/
showProfile: function(profile) { },
/**
* @param {!HeapProfilerAgent.HeapSnapshotObjectId} snapshotObjectId
* @param {string} perspectiveName
*/
showObject: function(snapshotObjectId, perspectiveName) { }
}
/**
* @constructor
* @extends {WebInspector.TargetAwareObject}
* @param {!WebInspector.Target} target
* @param {!WebInspector.ProfileType} profileType
* @param {string} title
*/
WebInspector.ProfileHeader = function(target, profileType, title)
{
WebInspector.TargetAwareObject.call(this, target);
this._profileType = profileType;
this.title = title;
this.uid = profileType._nextProfileUid++;
this._fromFile = false;
}
/**
* @constructor
* @param {?string} subtitle
* @param {boolean|undefined} wait
*/
WebInspector.ProfileHeader.StatusUpdate = function(subtitle, wait)
{
/** @type {?string} */
this.subtitle = subtitle;
/** @type {boolean|undefined} */
this.wait = wait;
}
WebInspector.ProfileHeader.Events = {
UpdateStatus: "UpdateStatus",
ProfileReceived: "ProfileReceived"
}
WebInspector.ProfileHeader.prototype = {
/**
* @return {!WebInspector.ProfileType}
*/
profileType: function()
{
return this._profileType;
},
/**
* @param {?string} subtitle
* @param {boolean=} wait
*/
updateStatus: function(subtitle, wait)
{
this.dispatchEventToListeners(WebInspector.ProfileHeader.Events.UpdateStatus, new WebInspector.ProfileHeader.StatusUpdate(subtitle, wait));
},
/**
* Must be implemented by subclasses.
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @return {!WebInspector.ProfileSidebarTreeElement}
*/
createSidebarTreeElement: function(dataDisplayDelegate)
{
throw new Error("Needs implemented.");
},
/**
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @return {!WebInspector.View}
*/
createView: function(dataDisplayDelegate)
{
throw new Error("Not implemented.");
},
removeTempFile: function()
{
if (this._tempFile)
this._tempFile.remove();
},
dispose: function()
{
},
/**
* @param {!Function} callback
*/
load: function(callback)
{
},
/**
* @return {boolean}
*/
canSaveToFile: function()
{
return false;
},
saveToFile: function()
{
throw new Error("Needs implemented");
},
/**
* @param {!File} file
*/
loadFromFile: function(file)
{
throw new Error("Needs implemented");
},
/**
* @return {boolean}
*/
fromFile: function()
{
return this._fromFile;
},
setFromFile: function()
{
this._fromFile = true;
},
__proto__: WebInspector.TargetAwareObject.prototype
}
/**
* @constructor
* @implements {WebInspector.Searchable}
* @implements {WebInspector.ProfileType.DataDisplayDelegate}
* @extends {WebInspector.PanelWithSidebarTree}
*/
WebInspector.ProfilesPanel = function()
{
WebInspector.PanelWithSidebarTree.call(this, "profiles");
this.registerRequiredCSS("panelEnablerView.css");
this.registerRequiredCSS("heapProfiler.css");
this.registerRequiredCSS("profilesPanel.css");
this._target = /** @type {!WebInspector.Target} */ (WebInspector.targetManager.activeTarget());
this._target.profilingLock.addEventListener(WebInspector.Lock.Events.StateChanged, this._onProfilingStateChanged, this);
this._searchableView = new WebInspector.SearchableView(this);
var mainView = new WebInspector.VBox();
this._searchableView.show(mainView.element);
mainView.show(this.mainElement());
this.profilesItemTreeElement = new WebInspector.ProfilesSidebarTreeElement(this);
this.sidebarTree.appendChild(this.profilesItemTreeElement);
this.profileViews = document.createElement("div");
this.profileViews.id = "profile-views";
this.profileViews.classList.add("vbox");
this._searchableView.element.appendChild(this.profileViews);
var statusBarContainer = document.createElementWithClass("div", "profiles-status-bar");
mainView.element.insertBefore(statusBarContainer, mainView.element.firstChild);
this._statusBarElement = statusBarContainer.createChild("div", "status-bar");
this.sidebarElement().classList.add("profiles-sidebar-tree-box");
var statusBarContainerLeft = document.createElementWithClass("div", "profiles-status-bar");
this.sidebarElement().insertBefore(statusBarContainerLeft, this.sidebarElement().firstChild);
this._statusBarButtons = statusBarContainerLeft.createChild("div", "status-bar");
this.recordButton = new WebInspector.StatusBarButton("", "record-profile-status-bar-item");
this.recordButton.addEventListener("click", this.toggleRecordButton, this);
this._statusBarButtons.appendChild(this.recordButton.element);
this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear all profiles."), "clear-status-bar-item");
this.clearResultsButton.addEventListener("click", this._reset, this);
this._statusBarButtons.appendChild(this.clearResultsButton.element);
this._profileTypeStatusBarItemsContainer = this._statusBarElement.createChild("div");
this._profileViewStatusBarItemsContainer = this._statusBarElement.createChild("div");
this._profileGroups = {};
this._launcherView = new WebInspector.MultiProfileLauncherView(this);
this._launcherView.addEventListener(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected, this._onProfileTypeSelected, this);
this._profileToView = [];
this._typeIdToSidebarSection = {};
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++)
this._registerProfileType(types[i]);
this._launcherView.restoreSelectedProfileType();
this.profilesItemTreeElement.select();
this._showLauncherView();
this._createFileSelectorElement();
this.element.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true);
this._registerShortcuts();
this._configureCpuProfilerSamplingInterval();
WebInspector.settings.highResolutionCpuProfiling.addChangeListener(this._configureCpuProfilerSamplingInterval, this);
}
/**
* @constructor
*/
WebInspector.ProfileTypeRegistry = function() {
this._profileTypes = [];
this.cpuProfileType = new WebInspector.CPUProfileType();
this._addProfileType(this.cpuProfileType);
this.heapSnapshotProfileType = new WebInspector.HeapSnapshotProfileType();
this._addProfileType(this.heapSnapshotProfileType);
this.trackingHeapSnapshotProfileType = new WebInspector.TrackingHeapSnapshotProfileType();
this._addProfileType(this.trackingHeapSnapshotProfileType);
HeapProfilerAgent.enable();
if (Capabilities.isMainFrontend && WebInspector.experimentsSettings.canvasInspection.isEnabled()) {
this.canvasProfileType = new WebInspector.CanvasProfileType();
this._addProfileType(this.canvasProfileType);
}
}
WebInspector.ProfileTypeRegistry.prototype = {
/**
* @param {!WebInspector.ProfileType} profileType
*/
_addProfileType: function(profileType)
{
this._profileTypes.push(profileType);
},
/**
* @return {!Array.<!WebInspector.ProfileType>}
*/
profileTypes: function()
{
return this._profileTypes;
}
}
WebInspector.ProfilesPanel.prototype = {
/**
* @return {!WebInspector.SearchableView}
*/
searchableView: function()
{
return this._searchableView;
},
_createFileSelectorElement: function()
{
if (this._fileSelectorElement)
this.element.removeChild(this._fileSelectorElement);
this._fileSelectorElement = WebInspector.createFileSelectorElement(this._loadFromFile.bind(this));
this.element.appendChild(this._fileSelectorElement);
},
_findProfileTypeByExtension: function(fileName)
{
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++) {
var type = types[i];
var extension = type.fileExtension();
if (!extension)
continue;
if (fileName.endsWith(type.fileExtension()))
return type;
}
return null;
},
_registerShortcuts: function()
{
this.registerShortcuts(WebInspector.ShortcutsScreen.ProfilesPanelShortcuts.StartStopRecording, this.toggleRecordButton.bind(this));
},
_configureCpuProfilerSamplingInterval: function()
{
var intervalUs = WebInspector.settings.highResolutionCpuProfiling.get() ? 100 : 1000;
ProfilerAgent.setSamplingInterval(intervalUs, didChangeInterval);
function didChangeInterval(error)
{
if (error)
WebInspector.messageSink.addErrorMessage(error, true);
}
},
/**
* @param {!File} file
*/
_loadFromFile: function(file)
{
this._createFileSelectorElement();
var profileType = this._findProfileTypeByExtension(file.name);
if (!profileType) {
var extensions = [];
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++) {
var extension = types[i].fileExtension();
if (!extension || extensions.indexOf(extension) !== -1)
continue;
extensions.push(extension);
}
WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load file. Only files with extensions '%s' can be loaded.", extensions.join("', '")));
return;
}
if (!!profileType.profileBeingRecorded()) {
WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load profile while another profile is recording."));
return;
}
profileType.loadFromFile(file);
},
/**
* @return {boolean}
*/
toggleRecordButton: function()
{
if (!this.recordButton.enabled())
return true;
var type = this._selectedProfileType;
var isProfiling = type.buttonClicked();
this._updateRecordButton(isProfiling);
if (isProfiling) {
this._launcherView.profileStarted();
if (type.hasTemporaryView())
this.showProfile(type.profileBeingRecorded());
} else {
this._launcherView.profileFinished();
}
return true;
},
_onProfilingStateChanged: function()
{
this._updateRecordButton(this.recordButton.toggled);
},
/**
* @param {boolean} toggled
*/
_updateRecordButton: function(toggled)
{
var enable = toggled || !this._target.profilingLock.isAcquired();
this.recordButton.setEnabled(enable);
this.recordButton.toggled = toggled;
if (enable)
this.recordButton.title = this._selectedProfileType ? this._selectedProfileType.buttonTooltip : "";
else
this.recordButton.title = WebInspector.UIString("Another profiler is already active");
if (this._selectedProfileType)
this._launcherView.updateProfileType(this._selectedProfileType, enable);
},
_profileBeingRecordedRemoved: function()
{
this._updateRecordButton(false);
this._launcherView.profileFinished();
},
/**
* @param {!WebInspector.Event} event
*/
_onProfileTypeSelected: function(event)
{
this._selectedProfileType = /** @type {!WebInspector.ProfileType} */ (event.data);
this._updateProfileTypeSpecificUI();
},
_updateProfileTypeSpecificUI: function()
{
this._updateRecordButton(this.recordButton.toggled);
this._profileTypeStatusBarItemsContainer.removeChildren();
var statusBarItems = this._selectedProfileType.statusBarItems;
if (statusBarItems) {
for (var i = 0; i < statusBarItems.length; ++i)
this._profileTypeStatusBarItemsContainer.appendChild(statusBarItems[i]);
}
},
_reset: function()
{
WebInspector.Panel.prototype.reset.call(this);
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++)
types[i]._reset();
delete this.visibleView;
delete this.currentQuery;
this.searchCanceled();
this._profileGroups = {};
this._updateRecordButton(false);
this._launcherView.profileFinished();
this.sidebarTree.element.classList.remove("some-expandable");
this._launcherView.detach();
this.profileViews.removeChildren();
this._profileViewStatusBarItemsContainer.removeChildren();
this.removeAllListeners();
this.recordButton.visible = true;
this._profileViewStatusBarItemsContainer.classList.remove("hidden");
this.clearResultsButton.element.classList.remove("hidden");
this.profilesItemTreeElement.select();
this._showLauncherView();
},
_showLauncherView: function()
{
this.closeVisibleView();
this._profileViewStatusBarItemsContainer.removeChildren();
this._launcherView.show(this.profileViews);
this.visibleView = this._launcherView;
},
_garbageCollectButtonClicked: function()
{
HeapProfilerAgent.collectGarbage();
},
/**
* @param {!WebInspector.ProfileType} profileType
*/
_registerProfileType: function(profileType)
{
this._launcherView.addProfileType(profileType);
var profileTypeSection = new WebInspector.ProfileTypeSidebarSection(this, profileType);
this._typeIdToSidebarSection[profileType.id] = profileTypeSection
this.sidebarTree.appendChild(profileTypeSection);
profileTypeSection.childrenListElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true);
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function onAddProfileHeader(event)
{
this._addProfileHeader(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function onRemoveProfileHeader(event)
{
this._removeProfileHeader(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function profileComplete(event)
{
this.showProfile(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
profileType.addEventListener(WebInspector.ProfileType.Events.ViewUpdated, this._updateProfileTypeSpecificUI, this);
profileType.addEventListener(WebInspector.ProfileType.Events.AddProfileHeader, onAddProfileHeader, this);
profileType.addEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader, onRemoveProfileHeader, this);
profileType.addEventListener(WebInspector.ProfileType.Events.ProfileComplete, profileComplete, this);
var profiles = profileType.getProfiles();
for (var i = 0; i < profiles.length; i++)
this._addProfileHeader(profiles[i]);
},
/**
* @param {?Event} event
*/
_handleContextMenuEvent: function(event)
{
var element = event.srcElement;
while (element && !element.treeElement && element !== this.element)
element = element.parentElement;
if (!element)
return;
if (element.treeElement && element.treeElement.handleContextMenuEvent) {
element.treeElement.handleContextMenuEvent(event, this);
return;
}
var contextMenu = new WebInspector.ContextMenu(event);
if (this.visibleView instanceof WebInspector.HeapSnapshotView) {
this.visibleView.populateContextMenu(contextMenu, event);
}
if (element !== this.element || event.srcElement === this.sidebarElement()) {
contextMenu.appendItem(WebInspector.UIString("Load\u2026"), this._fileSelectorElement.click.bind(this._fileSelectorElement));
}
contextMenu.show();
},
showLoadFromFileDialog: function()
{
this._fileSelectorElement.click();
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
_addProfileHeader: function(profile)
{
var profileType = profile.profileType();
var typeId = profileType.id;
this._typeIdToSidebarSection[typeId].addProfileHeader(profile);
if (!this.visibleView || this.visibleView === this._launcherView)
this.showProfile(profile);
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
_removeProfileHeader: function(profile)
{
if (profile.profileType()._profileBeingRecorded === profile)
this._profileBeingRecordedRemoved();
var i = this._indexOfViewForProfile(profile);
if (i !== -1)
this._profileToView.splice(i, 1);
var profileType = profile.profileType();
var typeId = profileType.id;
var sectionIsEmpty = this._typeIdToSidebarSection[typeId].removeProfileHeader(profile);
// No other item will be selected if there aren't any other profiles, so
// make sure that view gets cleared when the last profile is removed.
if (sectionIsEmpty) {
this.profilesItemTreeElement.select();
this._showLauncherView();
}
},
/**
* @param {?WebInspector.ProfileHeader} profile
* @return {?WebInspector.View}
*/
showProfile: function(profile)
{
if (!profile || (profile.profileType().profileBeingRecorded() === profile) && !profile.profileType().hasTemporaryView())
return null;
var view = this._viewForProfile(profile);
if (view === this.visibleView)
return view;
this.closeVisibleView();
view.show(this.profileViews);
this.visibleView = view;
var profileTypeSection = this._typeIdToSidebarSection[profile.profileType().id];
var sidebarElement = profileTypeSection.sidebarElementForProfile(profile);
sidebarElement.revealAndSelect();
this._profileViewStatusBarItemsContainer.removeChildren();
var statusBarItems = view.statusBarItems;
if (statusBarItems)
for (var i = 0; i < statusBarItems.length; ++i)
this._profileViewStatusBarItemsContainer.appendChild(statusBarItems[i]);
return view;
},
/**
* @param {!HeapProfilerAgent.HeapSnapshotObjectId} snapshotObjectId
* @param {string} perspectiveName
*/
showObject: function(snapshotObjectId, perspectiveName)
{
var heapProfiles = WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles();
for (var i = 0; i < heapProfiles.length; i++) {
var profile = heapProfiles[i];
// FIXME: allow to choose snapshot if there are several options.
if (profile.maxJSObjectId >= snapshotObjectId) {
this.showProfile(profile);
var view = this._viewForProfile(profile);
view.highlightLiveObject(perspectiveName, snapshotObjectId);
break;
}
}
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {!WebInspector.View}
*/
_viewForProfile: function(profile)
{
var index = this._indexOfViewForProfile(profile);
if (index !== -1)
return this._profileToView[index].view;
var view = profile.createView(this);
view.element.classList.add("profile-view");
this._profileToView.push({ profile: profile, view: view});
return view;
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {number}
*/
_indexOfViewForProfile: function(profile)
{
for (var i = 0; i < this._profileToView.length; i++) {
if (this._profileToView[i].profile === profile)
return i;
}
return -1;
},
closeVisibleView: function()
{
if (this.visibleView)
this.visibleView.detach();
delete this.visibleView;
},
/**
* @param {string} query
* @param {boolean} shouldJump
* @param {boolean=} jumpBackwards
*/
performSearch: function(query, shouldJump, jumpBackwards)
{
this.searchCanceled();
var visibleView = this.visibleView;
if (!visibleView)
return;
/**
* @this {WebInspector.ProfilesPanel}
*/
function finishedCallback(view, searchMatches)
{
if (!searchMatches)
return;
this._searchableView.updateSearchMatchesCount(searchMatches);
this._searchResultsView = view;
if (shouldJump) {
if (jumpBackwards)
view.jumpToLastSearchResult();
else
view.jumpToFirstSearchResult();
this._searchableView.updateCurrentMatchIndex(view.currentSearchResultIndex());
}
}
visibleView.currentQuery = query;
visibleView.performSearch(query, finishedCallback.bind(this));
},
jumpToNextSearchResult: function()
{
if (!this._searchResultsView)
return;
if (this._searchResultsView !== this.visibleView)
return;
this._searchResultsView.jumpToNextSearchResult();
this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex());
},
jumpToPreviousSearchResult: function()
{
if (!this._searchResultsView)
return;
if (this._searchResultsView !== this.visibleView)
return;
this._searchResultsView.jumpToPreviousSearchResult();
this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex());
},
searchCanceled: function()
{
if (this._searchResultsView) {
if (this._searchResultsView.searchCanceled)
this._searchResultsView.searchCanceled();
this._searchResultsView.currentQuery = null;
this._searchResultsView = null;
}
this._searchableView.updateSearchMatchesCount(0);
},
/**
* @param {!Event} event
* @param {!WebInspector.ContextMenu} contextMenu
* @param {!Object} target
*/
appendApplicableItems: function(event, contextMenu, target)
{
if (!(target instanceof WebInspector.RemoteObject))
return;
if (WebInspector.inspectorView.currentPanel() !== this)
return;
var object = /** @type {!WebInspector.RemoteObject} */ (target);
var objectId = object.objectId;
if (!objectId)
return;
var heapProfiles = WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles();
if (!heapProfiles.length)
return;
/**
* @this {WebInspector.ProfilesPanel}
*/
function revealInView(viewName)
{
HeapProfilerAgent.getHeapObjectId(objectId, didReceiveHeapObjectId.bind(this, viewName));
}
/**
* @this {WebInspector.ProfilesPanel}
*/
function didReceiveHeapObjectId(viewName, error, result)
{
if (WebInspector.inspectorView.currentPanel() !== this)
return;
if (!error)
this.showObject(result, viewName);
}
if (WebInspector.settings.showAdvancedHeapSnapshotProperties.get())
contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in Dominators view" : "Reveal in Dominators View"), revealInView.bind(this, "Dominators"));
contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in Summary view" : "Reveal in Summary View"), revealInView.bind(this, "Summary"));
},
__proto__: WebInspector.PanelWithSidebarTree.prototype
}
/**
* @constructor
* @extends {WebInspector.SidebarSectionTreeElement}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {!WebInspector.ProfileType} profileType
*/
WebInspector.ProfileTypeSidebarSection = function(dataDisplayDelegate, profileType)
{
WebInspector.SidebarSectionTreeElement.call(this, profileType.treeItemTitle, null, true);
this._dataDisplayDelegate = dataDisplayDelegate;
this._profileTreeElements = [];
this._profileGroups = {};
this.hidden = true;
}
/**
* @constructor
*/
WebInspector.ProfileTypeSidebarSection.ProfileGroup = function()
{
this.profileSidebarTreeElements = [];
this.sidebarTreeElement = null;
}
WebInspector.ProfileTypeSidebarSection.prototype = {
/**
* @param {!WebInspector.ProfileHeader} profile
*/
addProfileHeader: function(profile)
{
this.hidden = false;
var profileType = profile.profileType();
var sidebarParent = this;
var profileTreeElement = profile.createSidebarTreeElement(this._dataDisplayDelegate);
this._profileTreeElements.push(profileTreeElement);
if (!profile.fromFile() && profileType.profileBeingRecorded() !== profile) {
var profileTitle = profile.title;
var group = this._profileGroups[profileTitle];
if (!group) {
group = new WebInspector.ProfileTypeSidebarSection.ProfileGroup();
this._profileGroups[profileTitle] = group;
}
group.profileSidebarTreeElements.push(profileTreeElement);
var groupSize = group.profileSidebarTreeElements.length;
if (groupSize === 2) {
// Make a group TreeElement now that there are 2 profiles.
group.sidebarTreeElement = new WebInspector.ProfileGroupSidebarTreeElement(this._dataDisplayDelegate, profile.title);
var firstProfileTreeElement = group.profileSidebarTreeElements[0];
// Insert at the same index for the first profile of the group.
var index = this.children.indexOf(firstProfileTreeElement);
this.insertChild(group.sidebarTreeElement, index);
// Move the first profile to the group.
var selected = firstProfileTreeElement.selected;
this.removeChild(firstProfileTreeElement);
group.sidebarTreeElement.appendChild(firstProfileTreeElement);
if (selected)
firstProfileTreeElement.revealAndSelect();
firstProfileTreeElement.small = true;
firstProfileTreeElement.mainTitle = WebInspector.UIString("Run %d", 1);
this.treeOutline.element.classList.add("some-expandable");
}
if (groupSize >= 2) {
sidebarParent = group.sidebarTreeElement;
profileTreeElement.small = true;
profileTreeElement.mainTitle = WebInspector.UIString("Run %d", groupSize);
}
}
sidebarParent.appendChild(profileTreeElement);
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {boolean}
*/
removeProfileHeader: function(profile)
{
var index = this._sidebarElementIndex(profile);
if (index === -1)
return false;
var profileTreeElement = this._profileTreeElements[index];
this._profileTreeElements.splice(index, 1);
var sidebarParent = this;
var group = this._profileGroups[profile.title];
if (group) {
var groupElements = group.profileSidebarTreeElements;
groupElements.splice(groupElements.indexOf(profileTreeElement), 1);
if (groupElements.length === 1) {
// Move the last profile out of its group and remove the group.
var pos = sidebarParent.children.indexOf(group.sidebarTreeElement);
this.insertChild(groupElements[0], pos);
groupElements[0].small = false;
groupElements[0].mainTitle = group.sidebarTreeElement.title;
this.removeChild(group.sidebarTreeElement);
}
if (groupElements.length !== 0)
sidebarParent = group.sidebarTreeElement;
}
sidebarParent.removeChild(profileTreeElement);
profileTreeElement.dispose();
if (this.children.length)
return false;
this.hidden = true;
return true;
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {?WebInspector.ProfileSidebarTreeElement}
*/
sidebarElementForProfile: function(profile)
{
var index = this._sidebarElementIndex(profile);
return index === -1 ? null : this._profileTreeElements[index];
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {number}
*/
_sidebarElementIndex: function(profile)
{
var elements = this._profileTreeElements;
for (var i = 0; i < elements.length; i++) {
if (elements[i].profile === profile)
return i;
}
return -1;
},
__proto__: WebInspector.SidebarSectionTreeElement.prototype
}
/**
* @constructor
* @implements {WebInspector.ContextMenu.Provider}
*/
WebInspector.ProfilesPanel.ContextMenuProvider = function()
{
}
WebInspector.ProfilesPanel.ContextMenuProvider.prototype = {
/**
* @param {!Event} event
* @param {!WebInspector.ContextMenu} contextMenu
* @param {!Object} target
*/
appendApplicableItems: function(event, contextMenu, target)
{
WebInspector.inspectorView.panel("profiles").appendApplicableItems(event, contextMenu, target);
}
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {!WebInspector.ProfileHeader} profile
* @param {string} className
*/
WebInspector.ProfileSidebarTreeElement = function(dataDisplayDelegate, profile, className)
{
this._dataDisplayDelegate = dataDisplayDelegate;
this.profile = profile;
WebInspector.SidebarTreeElement.call(this, className, profile.title, "", profile, false);
this.refreshTitles();
profile.addEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this);
if (profile.canSaveToFile())
this._createSaveLink();
else
profile.addEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this);
}
WebInspector.ProfileSidebarTreeElement.prototype = {
_createSaveLink: function()
{
this._saveLinkElement = this.titleContainer.createChild("span", "save-link");
this._saveLinkElement.textContent = WebInspector.UIString("Save");
this._saveLinkElement.addEventListener("click", this._saveProfile.bind(this), false);
},
_onProfileReceived: function(event)
{
this._createSaveLink();
},
/**
* @param {!WebInspector.Event} event
*/
_updateStatus: function(event)
{
var statusUpdate = event.data;
if (statusUpdate.subtitle !== null)
this.subtitle = statusUpdate.subtitle;
if (typeof statusUpdate.wait === "boolean")
this.wait = statusUpdate.wait;
this.refreshTitles();
},
dispose: function()
{
this.profile.removeEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this);
this.profile.removeEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this);
},
onselect: function()
{
this._dataDisplayDelegate.showProfile(this.profile);
},
/**
* @return {boolean}
*/
ondelete: function()
{
this.profile.profileType().removeProfile(this.profile);
return true;
},
/**
* @param {!Event} event
* @param {!WebInspector.ProfilesPanel} panel
*/
handleContextMenuEvent: function(event, panel)
{
var profile = this.profile;
var contextMenu = new WebInspector.ContextMenu(event);
// FIXME: use context menu provider
contextMenu.appendItem(WebInspector.UIString("Load\u2026"), panel._fileSelectorElement.click.bind(panel._fileSelectorElement));
if (profile.canSaveToFile())
contextMenu.appendItem(WebInspector.UIString("Save\u2026"), profile.saveToFile.bind(profile));
contextMenu.appendItem(WebInspector.UIString("Delete"), this.ondelete.bind(this));
contextMenu.show();
},
_saveProfile: function(event)
{
this.profile.saveToFile();
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {string} title
* @param {string=} subtitle
*/
WebInspector.ProfileGroupSidebarTreeElement = function(dataDisplayDelegate, title, subtitle)
{
WebInspector.SidebarTreeElement.call(this, "profile-group-sidebar-tree-item", title, subtitle, null, true);
this._dataDisplayDelegate = dataDisplayDelegate;
}
WebInspector.ProfileGroupSidebarTreeElement.prototype = {
onselect: function()
{
if (this.children.length > 0)
this._dataDisplayDelegate.showProfile(this.children[this.children.length - 1].profile);
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfilesPanel} panel
*/
WebInspector.ProfilesSidebarTreeElement = function(panel)
{
this._panel = panel;
this.small = false;
WebInspector.SidebarTreeElement.call(this, "profile-launcher-view-tree-item", WebInspector.UIString("Profiles"), "", null, false);
}
WebInspector.ProfilesSidebarTreeElement.prototype = {
onselect: function()
{
this._panel._showLauncherView();
},
get selectable()
{
return true;
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
importScript("../sdk/CPUProfileModel.js");
importScript("CPUProfileDataGrid.js");
importScript("CPUProfileBottomUpDataGrid.js");
importScript("CPUProfileTopDownDataGrid.js");
importScript("CPUProfileFlameChart.js");
importScript("CPUProfileView.js");
importScript("HeapSnapshotCommon.js");
importScript("HeapSnapshotProxy.js");
importScript("HeapSnapshotDataGrids.js");
importScript("HeapSnapshotGridNodes.js");
importScript("HeapSnapshotView.js");
importScript("ProfileLauncherView.js");
importScript("CanvasProfileView.js");
importScript("CanvasReplayStateView.js");
WebInspector.ProfileTypeRegistry.instance = new WebInspector.ProfileTypeRegistry();
| Java |
//=============================================================================
// Darken Region
// LAX_DarkenRegion.js
// v0.02
//=============================================================================
//=============================================================================
/*:
* @plugindesc v0.02 Use regions to black out areas.
* @author LuciusAxelrod
*
*
* @help
* Place regions on the map in the editor, then either add them to the default
* list or add them to the dark region list using the add command listed below.
* Note: Tiles without a region are in region 0. Adding region 0 to the dark
* region list will black out every tile
*
* Plugin Commands:
* DarkenRegion add [region list] # Adds the listed regions to the dark
* region list. The list is space
* separated. For example:
* DarkenRegion add 1 3 5 78
* DarkenRegion remove [region list] # Removes the listed regions from the
* dark region list. The list is space
* separated. For example:
* DarkenRegion remove 4 7 200 2
* DarkenRegion toggle [region list] # Toggle on/off each of the listed
* regions. For example:
* DarkenRegion toggle 1 5 7 112 250
* DarkenRegion clear # Clears the dark region list.
*/
//=============================================================================
//=============================================================================
// Parameter Variables
//=============================================================================
(function() {
var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
_Game_Interpreter_pluginCommand.call(this, command, args);
if (command === 'DarkenRegion') {
if(args[0] === 'add') {
for(var i = 1; i < args.length; i++) {
$gameSystem.addToDarkList(args[i]);
}
} else if(args[0] === 'remove') {
for(var i = 1; i < args.length; i++) {
$gameSystem.removeFromDarkList(args[i]);
}
} else if(args[0] === 'toggle') {
for(var i = 1; i < args.length; i++) {
if($gameSystem.isDarkRegion(args[i])) {
$gameSystem.removeFromDarkList(args[i]);
} else {
$gameSystem.addToDarkList(args[i]);
}
}
} else if(args[0] === 'clear') {
$gameSystem.clearDarkList();
}
}
};
Game_System.prototype.isDarkRegion = function(regionId) {
if(this._darkList) {
return !!this._darkList[regionId];
}
}
Game_System.prototype.addToDarkList = function(regionId) {
if(!this._darkList) {
this.clearDarkList();
}
this._darkList[Number(regionId)] = true;
}
Game_System.prototype.removeFromDarkList = function(regionId) {
if(this._darkList) {
this._darkList[Number(regionId)] = false;
}
}
Game_System.prototype.clearDarkList = function() {
this._darkList = [];
}
Tilemap.prototype._paintTiles = function(startX, startY, x, y) {
var tableEdgeVirtualId = 10000;
var darkRegionVirtualId = 10000;
var mx = startX + x;
var my = startY + y;
var dx = (mx * this._tileWidth).mod(this._layerWidth);
var dy = (my * this._tileHeight).mod(this._layerHeight);
var lx = dx / this._tileWidth;
var ly = dy / this._tileHeight;
var tileId0 = this._readMapData(mx, my, 0);
var tileId1 = this._readMapData(mx, my, 1);
var tileId2 = this._readMapData(mx, my, 2);
var tileId3 = this._readMapData(mx, my, 3);
var tileId5 = this._readMapData(mx, my, 5);
var shadowBits = this._readMapData(mx, my, 4);
var upperTileId1 = this._readMapData(mx, my - 1, 1);
var lowerTiles = [];
var upperTiles = [];
if (this._isHigherTile(tileId0)) {
upperTiles.push(tileId0);
} else {
lowerTiles.push(tileId0);
}
if (this._isHigherTile(tileId1)) {
upperTiles.push(tileId1);
} else {
lowerTiles.push(tileId1);
}
lowerTiles.push(-shadowBits);
if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) {
if (!Tilemap.isShadowingTile(tileId0)) {
lowerTiles.push(tableEdgeVirtualId + upperTileId1);
}
}
if (this._isOverpassPosition(mx, my)) {
upperTiles.push(tileId2);
upperTiles.push(tileId3);
} else {
if (this._isHigherTile(tileId2)) {
upperTiles.push(tileId2);
} else {
lowerTiles.push(tileId2);
}
if (this._isHigherTile(tileId3)) {
upperTiles.push(tileId3);
} else {
lowerTiles.push(tileId3);
}
if($gameSystem.isDarkRegion(tileId5)){
upperTiles.push(darkRegionVirtualId + tileId5);
}
}
var lastLowerTiles = this._readLastTiles(0, lx, ly);
if (!lowerTiles.equals(lastLowerTiles) ||
(Tilemap.isTileA1(tileId0) && this._frameUpdated)) {
this._lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
for (var i = 0; i < lowerTiles.length; i++) {
var lowerTileId = lowerTiles[i];
if (lowerTileId < 0) {
this._drawShadow(this._lowerBitmap, shadowBits, dx, dy);
} else if (lowerTileId >= tableEdgeVirtualId) {
this._drawTableEdge(this._lowerBitmap, upperTileId1, dx, dy);
} else {
this._drawTile(this._lowerBitmap, lowerTileId, dx, dy);
}
}
this._writeLastTiles(0, lx, ly, lowerTiles);
}
var lastUpperTiles = this._readLastTiles(1, lx, ly);
if (!upperTiles.equals(lastUpperTiles)) {
this._upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
for (var j = 0; j < upperTiles.length; j++) {
if(upperTiles[j] >= darkRegionVirtualId) {
this._drawDarkness(this._upperBitmap, dx, dy);
} else {
this._drawTile(this._upperBitmap, upperTiles[j], dx, dy);
}
}
this._writeLastTiles(1, lx, ly, upperTiles);
}
};
Tilemap.prototype._drawDarkness = function(bitmap, dx, dy) {
var w = this._tileWidth;
var h = this._tileHeight;
var color = 'rgba(0,0,0,1)';
bitmap.fillRect(dx, dy, w, h, color);
};
})();
| Java |
#include "minunit.h"
#include <lcthw/darray_algos.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
static inline int intcmp(int **a, int **b) {
return **a - **b;
}
static inline int sintcmp(int *a, int *b) {
return *a - *b;
}
int make_random(DArray *array, size_t n) {
srand(time(NULL));
size_t i = 0;
for(i = 0; i < n; i++) {
int *random = DArray_new(array);
*random = rand();
check(DArray_push(array, random) == 0, "Inserting random values failed.");
}
return 0;
error:
return -1;
}
int is_sorted(DArray *array, DArray_compare cmp) {
int i = 0;
for(i = 0; i < DArray_count(array) - 1; i++) {
if(cmp(DArray_get(array, i), DArray_get(array, i+1)) > 0) {
return 0;
}
}
return 1;
}
char *run_sort_test(int (*func)(DArray *, DArray_compare), const char *name) {
DArray *nums = DArray_create(sizeof(int *), 20);
int rc = make_random(nums, 20);
mu_assert(rc == 0, "Randomization failed.");
mu_assert(!is_sorted(nums, (DArray_compare)sintcmp), "Numbers should start not sorted.");
debug("--- Testing %s sorting algorithm", name);
rc = func(nums, (DArray_compare)intcmp);
mu_assert(rc == 0, "Sort failed.");
mu_assert(is_sorted(nums, (DArray_compare)sintcmp), "Sort didn't sort properly.");
DArray_clear_destroy(nums);
return NULL;
}
char *test_qsort() {
return run_sort_test(DArray_qsort, "qsort");
}
char *test_heapsort() {
return run_sort_test(DArray_heapsort, "heapsort");
}
char *test_mergesort() {
return run_sort_test(DArray_mergesort, "mergesort");
}
char *speed_sort_test(int (*func)(DArray *, DArray_compare), const char *name) {
size_t N = 10000;
debug("--- Testing the speed of %s", name);
DArray *source = DArray_create(sizeof(void *), N+1);
clock_t fastest = LONG_MAX;
int rc = make_random(source, N);
mu_assert(rc == 0, "Randomizing the source DArray failed.");
int i = 0;
for(i = 0; i < 25; i++) {
DArray *test = DArray_create(sizeof(int *), N+1);
rc = DArray_copy(source, test);
mu_assert(rc == 0, "Copy failed.");
clock_t elapsed = -clock();
rc = func(test, (DArray_compare)intcmp);
elapsed += clock();
mu_assert(rc == 0, "Sort failed.");
mu_assert(is_sorted(test, (DArray_compare)sintcmp), "Sort didn't sort properly.");
if(elapsed < fastest) fastest = elapsed;
DArray_destroy(test);
}
debug("Fastest time for sort: %s, size %zu: %f", name, N, ((float)fastest)/CLOCKS_PER_SEC);
DArray_clear_destroy(source);
return NULL;
}
char *test_speed_qsort() {
return speed_sort_test(DArray_qsort, "quicksort");
}
char *test_speed_mergesort() {
return speed_sort_test(DArray_mergesort, "mergesort");
}
char *test_speed_heapsort() {
return speed_sort_test(DArray_heapsort, "heapsort");
}
char *test_cmp() {
DArray *fake = DArray_create(sizeof(int), 10);
int *num1 = DArray_new(fake);
int *num2 = DArray_new(fake);
*num1 = 100;
*num2 = 20;
mu_assert(sintcmp(num1, num2) > 0, "Comparison fails on 100, 20.");
*num1 = 50;
*num2 = 50;
mu_assert(sintcmp(num1, num2) == 0, "Comparison fails on 50, 50.");
*num1 = 30;
*num2 = 60;
mu_assert(sintcmp(num1, num2) < 0, "Comparison fails on 30, 60.");
DArray_clear_destroy(fake);
return NULL;
}
char *all_tests() {
mu_suite_start();
mu_run_test(test_cmp);
mu_run_test(test_qsort);
mu_run_test(test_heapsort);
mu_run_test(test_mergesort);
mu_run_test(test_speed_qsort);
mu_run_test(test_speed_mergesort);
mu_run_test(test_speed_heapsort);
return NULL;
}
RUN_TESTS(all_tests);
| Java |
<!DOCTYPE html>
<html>
<h1>Sensor Data</h1>
</center>
<table>
<tr>
<td>Temperature</td>
<td>
<input id="temperature" type="text" value="">
</td>
</tr>
<tr>
<td>Precipitation</td>
<td>
<input id="precipitation" type="text" value="">
</td>
</tr>
<tr>
<td>Humidity</td>
<td>
<input id="humidity" type="text" value="">
</td>
</tr>
<tr>
<td>Wind</td>
<td>
<input id="wind" type="text" value="">
</td>
</tr>
<tr>
<td></td>
<td>
<button id="save" onclick="saveWeather()">Save</button>
<button id="clear" onclick="clearForm()">Clear</button>
<button id="read" onclick="readWeather()">Read</button>
</td>
</tr>
</table>
</center>
<script>
var saveWeather = function(){
};
var readWeather = function(){
};
var clearForm = function(){
};
</script>
</html> | Java |
"use strict";
(function() {
function get_promise(endpoint) {
return function($http) {
return $http.get(endpoint);
};
}
angular.module('pagerbot-admin', ['ngRoute', 'ngTable', 'angular-loading-bar'])
.config(function ($routeProvider) {
$routeProvider
.when('/intro', {
templateUrl: 'views/intro.html',
controller: 'PagerdutyCtrl',
resolve: {
pd: function(pagerduty_promise) {
return pagerduty_promise;
}
}
})
.when('/chatbot-settings', {
templateUrl: 'views/bot.html',
controller: 'BotSetupCtrl',
resolve: {
bot_info: get_promise('/api/bot')
}
})
.when('/plugin-setup', {
templateUrl: 'views/plugins.html',
controller: 'PluginSetupCtrl',
resolve: {
plugin_info: get_promise('/api/plugins')
}
})
.when('/user-aliases', {
templateUrl: 'views/users.html',
controller: 'UserAliasCtrl',
resolve: {
users: get_promise('/api/users')
}
})
.when('/schedule-aliases', {
templateUrl: 'views/schedules.html',
controller: 'ScheduleAliasCtrl',
resolve: {
schedules: get_promise('/api/schedules')
}
})
.when('/deploy', {
templateUrl: 'views/deploy.html',
controller: 'DeployCtrl'
})
.otherwise({
redirectTo: '/intro'
});
});
})();
| Java |
<?php
/**
* AAddress filter form.
*
* @package alumni
* @subpackage filter
* @author E.R. Nurwijayadi
* @version 1.0
*/
class AAddressFormFilter extends BaseAAddressFormFilter
{
/**
* @see AddressFormFilter
*/
static protected $order_by_choices = array(
null => '',
6 => 'ID',
21 => 'Name (Alumna/us)',
'' => '----------',
60 => 'Address',
61 => 'Region',
63 => 'Code: Country',
64 => 'Code: Province',
65 => 'Code: District',
66 => 'Postal Code',
67 => 'Street',
68 => 'Area',
69 => 'Building'
);
public function configure()
{
$this->widgetSchema->setFormFormatterName('list');
$this->disableCSRFProtection();
$this->addAllCommunityFields($this);
$this->widgetSchema['order_by'] = new sfWidgetFormChoice(array(
'choices' => self::$order_by_choices));
$this->validatorSchema['order_by'] = new sfValidatorPass();
$this->widgetSchema['department_id'] = new sfWidgetFormChoice(array(
'choices' => array(null => '')
));
$this->useFields(array(
'department_id', 'faculty_id', 'program_id',
'class_year', 'decade', 'order_by'
));
$query = Doctrine_Core::getTable('AAddress')
->createQuery('r')
->leftJoin('r.Country n')
->leftJoin('r.Province p')
->leftJoin('r.District w')
->leftJoin('r.Alumni a')
->leftJoin('a.ACommunities ac');
$this->setQuery($query);
}
public function addOrderByColumnQuery(Doctrine_Query $query, $field, $values)
{
$order_by_choices = array(
6 => 'r.lid',
21 => 'a.name',
60 => 'r.address',
61 => 'r.region',
63 => 'r.country_id',
64 => 'r.province_id',
65 => 'r.district_id',
66 => 'r.postal_code',
67 => 'r.street',
68 => 'r.area',
69 => 'r.building'
);
if ( array_key_exists($values, $order_by_choices) )
$query->orderBy( $order_by_choices[$values] );
}
/* This parts needs Trait in PHP 5.4 */
public function addDepartmentIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.department_id = ?', $values); }
public function addFacultyIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.faculty_id = ?', $values); }
public function addProgramIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.program_id = ?', $values); }
public function addClassYearColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values['text']) ) $query->andWhere('ac.class_year = ?', $values['text']); }
public function addDecadeColumnQuery(Doctrine_Query $query, $field, $values)
{
$decades = array(1960, 1970, 1980, 1990, 2000, 2010);
if ( in_array( $values, $decades ) )
{
$query->andWhere('ac.class_year >= ?', $values);
$query->andWhere('ac.class_year <= ?', $values+9);
}
}
}
| Java |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DailySeedAndCleanup extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('featured_games', function (Blueprint $table) {
$table->increments('id');
$table->date('day')->unique();
$table->integer('seed_id');
$table->string('description')->default('');
$table->timestamps();
});
Schema::table('seeds', function (Blueprint $table) {
$table->dropColumn(['patch']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('seeds', function (Blueprint $table) {
$table->json('patch');
});
Schema::dropIfExists('featured_games');
}
}
| Java |
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
/**
* Default theme for reveal.js.
*
* Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
*/
@font-face {
font-family: 'League Gothic';
src: url("../../lib/font/league_gothic-webfont.eot");
src: url("../../lib/font/league_gothic-webfont.eot?#iefix") format("embedded-opentype"), url("../../lib/font/league_gothic-webfont.woff") format("woff"), url("../../lib/font/league_gothic-webfont.ttf") format("truetype"), url("../../lib/font/league_gothic-webfont.svg#LeagueGothicRegular") format("svg");
font-weight: normal;
font-style: normal; }
/*********************************************
* GLOBAL STYLES
*********************************************/
body {
background: #1c1e20;
background: -moz-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, #555a5f), color-stop(100%, #1c1e20));
background: -webkit-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -o-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -ms-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background-color: #2b2b2b; }
.reveal {
font-family: "Lato", sans-serif;
font-size: 36px;
font-weight: normal;
letter-spacing: -0.02em;
color: #eeeeee; }
::selection {
color: white;
background: #ff5e99;
text-shadow: none; }
/*********************************************
* HEADERS
*********************************************/
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
color: #eeeeee;
font-family: "Lato", Helvetica, sans-serif;
line-height: 0.9em;
letter-spacing: 0.02em;
font-weight: 700;
text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); }
.reveal h1 {
text-shadow: 0 1px 0 #cccccc, 0 2px 0 #c9c9c9, 0 3px 0 #bbbbbb, 0 4px 0 #b9b9b9, 0 5px 0 #aaaaaa, 0 6px 1px rgba(0, 0, 0, 0.1), 0 0 5px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.3), 0 3px 5px rgba(0, 0, 0, 0.2), 0 5px 10px rgba(0, 0, 0, 0.25), 0 20px 20px rgba(0, 0, 0, 0.15); }
/*********************************************
* LINKS
*********************************************/
.reveal a:not(.image) {
color: #13daec;
text-decoration: none;
-webkit-transition: color .15s ease;
-moz-transition: color .15s ease;
-ms-transition: color .15s ease;
-o-transition: color .15s ease;
transition: color .15s ease; }
.reveal a:not(.image):hover {
color: #71e9f4;
text-shadow: none;
border: none; }
.reveal .roll span:after {
color: #fff;
background: #0d99a5; }
/*********************************************
* IMAGES
*********************************************/
.reveal section img {
margin: 15px 0px;
background: rgba(255, 255, 255, 0.12);
border: 4px solid #eeeeee;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
-ms-transition: all .2s linear;
-o-transition: all .2s linear;
transition: all .2s linear; }
.reveal a:hover img {
background: rgba(255, 255, 255, 0.2);
border-color: #13daec;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }
/*********************************************
* NAVIGATION CONTROLS
*********************************************/
.reveal .controls div.navigate-left,
.reveal .controls div.navigate-left.enabled {
border-right-color: #13daec; }
.reveal .controls div.navigate-right,
.reveal .controls div.navigate-right.enabled {
border-left-color: #13daec; }
.reveal .controls div.navigate-up,
.reveal .controls div.navigate-up.enabled {
border-bottom-color: #13daec; }
.reveal .controls div.navigate-down,
.reveal .controls div.navigate-down.enabled {
border-top-color: #13daec; }
.reveal .controls div.navigate-left.enabled:hover {
border-right-color: #71e9f4; }
.reveal .controls div.navigate-right.enabled:hover {
border-left-color: #71e9f4; }
.reveal .controls div.navigate-up.enabled:hover {
border-bottom-color: #71e9f4; }
.reveal .controls div.navigate-down.enabled:hover {
border-top-color: #71e9f4; }
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
background: rgba(0, 0, 0, 0.2); }
.reveal .progress span {
background: #13daec;
-webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-ms-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-o-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }
/*********************************************
* SLIDE NUMBER
*********************************************/
.reveal .slide-number {
color: #13daec; }
| Java |
<?php
namespace GEPedag\EntidadesBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use GEPedag\EntidadesBundle\Entity\Asignatura;
use GEPedag\EntidadesBundle\Form\AsignaturaType;
class AsignaturaController extends Controller {
/**
* @Method("GET")
* @Template()
*/
public function indexAction() {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('GEPedagEntidadesBundle:Asignatura')->findAll();
return [
'entities' => $entities
];
}
/**
* @Method("POST")
*/
public function createAction(Request $request) {
$asignatura = new Asignatura();
$form = $this->createForm(new AsignaturaType(), $asignatura);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'La asignatura <i>' . $asignatura . '</i> se ha creado con éxito!');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
// print_r($form->getErrors());die;
// foreach ($form->getErrors() as $error) {
// }
$this->get('session')->getFlashBag()->add('error', 'Error al registrar la asignatura.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
/**
* @Method("GET")
* @Template("GEPedagEntidadesBundle:Asignatura:new_edit.html.twig")
*/
public function newAction() {
$asignatura = new Asignatura();
$titulo = 'Crear';
$form = $this->createForm(new AsignaturaType(), $asignatura);
$form->add('submit', 'submit', array('label' => $titulo));
return [
'action' => $this->generateUrl('ge_asign_create'),
'entity' => $asignatura,
'form' => $form->createView(),
'titulo' => $titulo,
];
}
/**
* @Method("GET")
*/
public function editAction($id) {
$titulo = 'Actualizar';
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('GEPedagEntidadesBundle:Asignatura')->find($id);
if (!$asignatura) {
throw $this->createNotFoundException('No existe la Asignatura con id: ' . $id);
}
$editForm = $this->createForm(new AsignaturaType(), $asignatura);
$editForm->add('submit', 'submit', array('label' => $titulo));
return $this->render('GEPedagEntidadesBundle:Asignatura:new_edit.html.twig', [
'action' => $this->generateUrl('ge_asign_update', array('id' => $asignatura->getId())),
'entity' => $asignatura,
'titulo' => $titulo,
'form' => $editForm->createView()
]);
}
/**
* @Method("POST")
*/
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('GEPedagEntidadesBundle:Asignatura')->find($id);
if (!$asignatura) {
$this->get('session')->getFlashBag()->add(
'error', 'No existe la asignatura con id: ' . $id);
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$editForm = $this->createForm(new AsignaturaType(), $asignatura);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->persist($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'Muy Bien! La asignatura <i>' . $asignatura . '</i> se ha actualizado con éxito!');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$this->get('session')->getFlashBag()->add(
'success', 'Error al crear la asignatura.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
/**
* @Method("GET")
*/
public function deleteAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('GEPedagEntidadesBundle:Asignatura')->find($id);
if (!$asignatura) {
$this->get('session')->getFlashBag()->add(
'error', 'No existe la asignatura con id: ' . $id);
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$em->remove($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'La asignatura <i>' . $asignatura . '</i> se ha eliminado.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
}
| Java |
QMathematics
============
Dependence:
1. QT (QTSQL QTSVG QTSCRIPT QTPLUGIN)
2. MySql (qsqlmysql4.dll libmysql.dll)
3. QWT
4. GSL
| Java |
""" Tests for Dynamo3 """
import sys
import unittest
from decimal import Decimal
from pickle import dumps, loads
from urllib.parse import urlparse
from botocore.exceptions import ClientError
from mock import ANY, MagicMock, patch
from dynamo3 import (
Binary,
Dynamizer,
DynamoDBConnection,
DynamoDBError,
DynamoKey,
GlobalIndex,
Limit,
Table,
ThroughputException,
)
from dynamo3.constants import STRING
from dynamo3.result import Capacity, ConsumedCapacity, Count, ResultSet, add_dicts
class BaseSystemTest(unittest.TestCase):
"""Base class for system tests"""
dynamo: DynamoDBConnection = None # type: ignore
def setUp(self):
super(BaseSystemTest, self).setUp()
# Clear out any pre-existing tables
for tablename in self.dynamo.list_tables():
self.dynamo.delete_table(tablename)
def tearDown(self):
super(BaseSystemTest, self).tearDown()
for tablename in self.dynamo.list_tables():
self.dynamo.delete_table(tablename)
self.dynamo.clear_hooks()
class TestMisc(BaseSystemTest):
"""Tests that don't fit anywhere else"""
def tearDown(self):
super(TestMisc, self).tearDown()
self.dynamo.default_return_capacity = False
def test_connection_host(self):
"""Connection can access host of endpoint"""
urlparse(self.dynamo.host)
def test_connection_region(self):
"""Connection can access name of connected region"""
self.assertTrue(isinstance(self.dynamo.region, str))
def test_connect_to_region(self):
"""Can connect to a dynamo region"""
conn = DynamoDBConnection.connect("us-west-1")
self.assertIsNotNone(conn.host)
def test_connect_to_region_creds(self):
"""Can connect to a dynamo region with credentials"""
conn = DynamoDBConnection.connect(
"us-west-1", access_key="abc", secret_key="12345"
)
self.assertIsNotNone(conn.host)
def test_connect_to_host_without_session(self):
"""Can connect to a dynamo host without passing in a session"""
conn = DynamoDBConnection.connect("us-west-1", host="localhost")
self.assertIsNotNone(conn.host)
@patch("dynamo3.connection.time")
def test_retry_on_throughput_error(self, time):
"""Throughput exceptions trigger a retry of the request"""
def call(*_, **__):
"""Dummy service call"""
response = {
"ResponseMetadata": {
"HTTPStatusCode": 400,
},
"Error": {
"Code": "ProvisionedThroughputExceededException",
"Message": "Does not matter",
},
}
raise ClientError(response, "list_tables")
with patch.object(self.dynamo, "client") as client:
client.list_tables.side_effect = call
with self.assertRaises(ThroughputException):
self.dynamo.call("list_tables")
self.assertEqual(len(time.sleep.mock_calls), self.dynamo.request_retries - 1)
self.assertTrue(time.sleep.called)
def test_describe_missing(self):
"""Describing a missing table returns None"""
ret = self.dynamo.describe_table("foobar")
self.assertIsNone(ret)
def test_magic_table_props(self):
"""Table can look up properties on response object"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
ret = self.dynamo.describe_table("foobar")
assert ret is not None
self.assertEqual(ret.item_count, ret["ItemCount"])
with self.assertRaises(KeyError):
self.assertIsNotNone(ret["Missing"])
def test_magic_index_props(self):
"""Index can look up properties on response object"""
index = GlobalIndex.all("idx-name", DynamoKey("id"))
index.response = {"FooBar": 2}
self.assertEqual(index["FooBar"], 2)
with self.assertRaises(KeyError):
self.assertIsNotNone(index["Missing"])
def test_describe_during_delete(self):
"""Describing a table during a delete operation should not crash"""
response = {
"ItemCount": 0,
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5,
},
"TableName": "myTableName",
"TableSizeBytes": 0,
"TableStatus": "DELETING",
}
table = Table.from_response(response)
self.assertEqual(table.status, "DELETING")
def test_delete_missing(self):
"""Deleting a missing table returns False"""
ret = self.dynamo.delete_table("foobar")
self.assertTrue(not ret)
def test_re_raise_passthrough(self):
"""DynamoDBError can re-raise itself if missing original exception"""
err = DynamoDBError(400, Code="ErrCode", Message="Ouch", args={})
caught = False
try:
err.re_raise()
except DynamoDBError as e:
caught = True
self.assertEqual(err, e)
self.assertTrue(caught)
def test_re_raise(self):
"""DynamoDBError can re-raise itself with stacktrace of original exc"""
caught = False
try:
try:
raise Exception("Hello")
except Exception as e1:
err = DynamoDBError(
400,
Code="ErrCode",
Message="Ouch",
args={},
exc_info=sys.exc_info(),
)
err.re_raise()
except DynamoDBError as e:
caught = True
import traceback
tb = traceback.format_tb(e.__traceback__)
self.assertIn("Hello", tb[-1])
self.assertEqual(e.status_code, 400)
self.assertTrue(caught)
def test_default_return_capacity(self):
"""When default_return_capacity=True, always return capacity"""
self.dynamo.default_return_capacity = True
with patch.object(self.dynamo, "call") as call:
call().get.return_value = None
rs = self.dynamo.scan("foobar")
list(rs)
call.assert_called_with(
"scan",
TableName="foobar",
ReturnConsumedCapacity="INDEXES",
ConsistentRead=False,
)
def test_list_tables_page(self):
"""Call to ListTables should page results"""
hash_key = DynamoKey("id")
for i in range(120):
self.dynamo.create_table("table%d" % i, hash_key=hash_key)
tables = list(self.dynamo.list_tables(110))
self.assertEqual(len(tables), 110)
def test_limit_complete(self):
"""A limit with item_capacity = 0 is 'complete'"""
limit = Limit(item_limit=0)
self.assertTrue(limit.complete)
def test_wait_create_table(self):
"""Create table shall wait for the table to come online."""
tablename = "foobar_wait"
hash_key = DynamoKey("id")
self.dynamo.create_table(tablename, hash_key=hash_key, wait=True)
self.assertIsNotNone(self.dynamo.describe_table(tablename))
def test_wait_delete_table(self):
"""Delete table shall wait for the table to go offline."""
tablename = "foobar_wait"
hash_key = DynamoKey("id")
self.dynamo.create_table(tablename, hash_key=hash_key, wait=True)
result = self.dynamo.delete_table(tablename, wait=True)
self.assertTrue(result)
class TestDataTypes(BaseSystemTest):
"""Tests for Dynamo data types"""
def make_table(self):
"""Convenience method for making a table"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
def test_string(self):
"""Store and retrieve a string"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc"})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["id"], "abc")
self.assertTrue(isinstance(item["id"], str))
def test_int(self):
"""Store and retrieve an int"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": 1})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["num"], 1)
def test_float(self):
"""Store and retrieve a float"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": 1.1})
item = list(self.dynamo.scan("foobar"))[0]
self.assertAlmostEqual(float(item["num"]), 1.1)
def test_decimal(self):
"""Store and retrieve a Decimal"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": Decimal("1.1")})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["num"], Decimal("1.1"))
def test_binary(self):
"""Store and retrieve a binary"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "data": Binary("abc")})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["data"].value, b"abc")
def test_binary_bytes(self):
"""Store and retrieve bytes as a binary"""
self.make_table()
data = {"a": 1, "b": 2}
self.dynamo.put_item("foobar", {"id": "a", "data": Binary(dumps(data))})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(loads(item["data"].value), data)
def test_string_set(self):
"""Store and retrieve a string set"""
self.make_table()
item = {
"id": "a",
"datas": set(["a", "b"]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_number_set(self):
"""Store and retrieve a number set"""
self.make_table()
item = {
"id": "a",
"datas": set([1, 2, 3]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_binary_set(self):
"""Store and retrieve a binary set"""
self.make_table()
item = {
"id": "a",
"datas": set([Binary("a"), Binary("b")]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_binary_equal(self):
"""Binary should eq other Binaries and also raw bytestrings"""
self.assertEqual(Binary("a"), Binary("a"))
self.assertEqual(Binary("a"), b"a")
self.assertFalse(Binary("a") != Binary("a"))
def test_binary_repr(self):
"""Binary repr should wrap the contained value"""
self.assertEqual(repr(Binary("a")), "Binary(%r)" % b"a")
def test_binary_converts_unicode(self):
"""Binary will convert unicode to bytes"""
b = Binary("a")
self.assertTrue(isinstance(b.value, bytes))
def test_binary_force_string(self):
"""Binary must wrap a string type"""
with self.assertRaises(TypeError):
Binary(2) # type: ignore
def test_bool(self):
"""Store and retrieve a boolean"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc", "b": True})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["b"], True)
self.assertTrue(isinstance(item["b"], bool))
def test_list(self):
"""Store and retrieve a list"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc", "l": ["a", 1, False]})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["l"], ["a", 1, False])
def test_dict(self):
"""Store and retrieve a dict"""
self.make_table()
data = {
"i": 1,
"s": "abc",
"n": None,
"l": ["a", 1, True],
"b": False,
}
self.dynamo.put_item("foobar", {"id": "abc", "d": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["d"], data)
def test_nested_dict(self):
"""Store and retrieve a nested dict"""
self.make_table()
data = {
"s": "abc",
"d": {
"i": 42,
},
}
self.dynamo.put_item("foobar", {"id": "abc", "d": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["d"], data)
def test_nested_list(self):
"""Store and retrieve a nested list"""
self.make_table()
data = [
1,
[
True,
None,
"abc",
],
]
self.dynamo.put_item("foobar", {"id": "abc", "l": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["l"], data)
def test_unrecognized_type(self):
"""Dynamizer throws error on unrecognized type"""
value = {
"ASDF": "abc",
}
with self.assertRaises(TypeError):
self.dynamo.dynamizer.decode(value)
class TestDynamizer(unittest.TestCase):
"""Tests for the Dynamizer"""
def test_register_encoder(self):
"""Can register a custom encoder"""
from datetime import datetime
dynamizer = Dynamizer()
dynamizer.register_encoder(datetime, lambda d, v: (STRING, v.isoformat()))
now = datetime.utcnow()
self.assertEqual(dynamizer.raw_encode(now), (STRING, now.isoformat()))
def test_encoder_missing(self):
"""If no encoder is found, raise ValueError"""
from datetime import datetime
dynamizer = Dynamizer()
with self.assertRaises(ValueError):
dynamizer.encode(datetime.utcnow())
class TestResultModels(unittest.TestCase):
"""Tests for the model classes in results.py"""
def test_add_dicts_base_case(self):
"""add_dict where one argument is None returns the other"""
f = object()
self.assertEqual(add_dicts(f, None), f)
self.assertEqual(add_dicts(None, f), f)
def test_add_dicts(self):
"""Merge two dicts of values together"""
a = {
"a": 1,
"b": 2,
}
b = {
"a": 3,
"c": 4,
}
ret = add_dicts(a, b)
self.assertEqual(
ret,
{
"a": 4,
"b": 2,
"c": 4,
},
)
def test_count_repr(self):
"""Count repr"""
count = Count(0, 0)
self.assertEqual(repr(count), "Count(0)")
def test_count_addition(self):
"""Count addition"""
count = Count(4, 2)
self.assertEqual(count + 5, 9)
def test_count_subtraction(self):
"""Count subtraction"""
count = Count(4, 2)
self.assertEqual(count - 2, 2)
def test_count_multiplication(self):
"""Count multiplication"""
count = Count(4, 2)
self.assertEqual(2 * count, 8)
def test_count_division(self):
"""Count division"""
count = Count(4, 2)
self.assertEqual(count / 2, 2)
def test_count_add_none_capacity(self):
"""Count addition with one None consumed_capacity"""
cap = Capacity(3, 0)
count = Count(4, 2)
count2 = Count(5, 3, cap)
ret = count + count2
self.assertEqual(ret, 9)
self.assertEqual(ret.scanned_count, 5)
self.assertEqual(ret.consumed_capacity, cap)
def test_count_add_capacity(self):
"""Count addition with consumed_capacity"""
count = Count(4, 2, Capacity(3, 0))
count2 = Count(5, 3, Capacity(2, 0))
ret = count + count2
self.assertEqual(ret, 9)
self.assertEqual(ret.scanned_count, 5)
self.assertEqual(ret.consumed_capacity.read, 5)
def test_capacity_math(self):
"""Capacity addition and equality"""
cap = Capacity(2, 4)
s = set([cap])
self.assertIn(Capacity(2, 4), s)
self.assertNotEqual(Capacity(1, 4), cap)
self.assertEqual(Capacity(1, 1) + Capacity(2, 2), Capacity(3, 3))
def test_capacity_format(self):
"""String formatting for Capacity"""
c = Capacity(1, 3)
self.assertEqual(str(c), "R:1.0 W:3.0")
c = Capacity(0, 0)
self.assertEqual(str(c), "0")
def test_total_consumed_capacity(self):
"""ConsumedCapacity can parse results with only Total"""
response = {
"TableName": "foobar",
"ReadCapacityUnits": 4,
"WriteCapacityUnits": 5,
}
cap = ConsumedCapacity.from_response(response)
self.assertEqual(cap.total, (4, 5))
self.assertIsNone(cap.table_capacity)
def test_consumed_capacity_equality(self):
"""ConsumedCapacity addition and equality"""
cap = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
},
{
"g-index": Capacity(0, 3),
},
)
c2 = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
"l-index2": Capacity(0, 7),
},
)
self.assertNotEqual(cap, c2)
c3 = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
},
{
"g-index": Capacity(0, 3),
},
)
self.assertIn(cap, set([c3]))
combined = cap + c2
self.assertEqual(
cap + c2,
ConsumedCapacity(
"foobar",
Capacity(0, 20),
Capacity(0, 4),
{
"l-index": Capacity(0, 8),
"l-index2": Capacity(0, 7),
},
{
"g-index": Capacity(0, 3),
},
),
)
self.assertIn(str(Capacity(0, 3)), str(combined))
def test_add_different_tables(self):
"""Cannot add ConsumedCapacity of two different tables"""
c1 = ConsumedCapacity("foobar", Capacity(1, 28))
c2 = ConsumedCapacity("boofar", Capacity(3, 0))
with self.assertRaises(TypeError):
c1 += c2
def test_always_continue_query(self):
"""Regression test.
If result has no items but does have LastEvaluatedKey, keep querying.
"""
conn = MagicMock()
conn.dynamizer.decode_keys.side_effect = lambda x: x
items = ["a", "b"]
results = [
{"Items": [], "LastEvaluatedKey": {"foo": 1, "bar": 2}},
{"Items": [], "LastEvaluatedKey": {"foo": 1, "bar": 2}},
{"Items": items},
]
conn.call.side_effect = lambda *_, **__: results.pop(0)
rs = ResultSet(conn, Limit())
results = list(rs)
self.assertEqual(results, items)
class TestHooks(BaseSystemTest):
"""Tests for connection callback hooks"""
def tearDown(self):
super(TestHooks, self).tearDown()
for hooks in self.dynamo._hooks.values():
while hooks:
hooks.pop()
def test_precall(self):
"""precall hooks are called before an API call"""
hook = MagicMock()
self.dynamo.subscribe("precall", hook)
def throw(**_):
"""Throw an exception to terminate the request"""
raise Exception()
with patch.object(self.dynamo, "client") as client:
client.describe_table.side_effect = throw
with self.assertRaises(Exception):
self.dynamo.describe_table("foobar")
hook.assert_called_with(self.dynamo, "describe_table", {"TableName": "foobar"})
def test_postcall(self):
"""postcall hooks are called after API call"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
calls = []
def hook(*args):
"""Log the call into a list"""
calls.append(args)
self.dynamo.subscribe("postcall", hook)
self.dynamo.describe_table("foobar")
self.assertEqual(len(calls), 1)
args = calls[0]
self.assertEqual(len(args), 4)
conn, command, kwargs, response = args
self.assertEqual(conn, self.dynamo)
self.assertEqual(command, "describe_table")
self.assertEqual(kwargs["TableName"], "foobar")
self.assertEqual(response["Table"]["TableName"], "foobar")
def test_capacity(self):
"""capacity hooks are called whenever response has ConsumedCapacity"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
hook = MagicMock()
self.dynamo.subscribe("capacity", hook)
with patch.object(self.dynamo, "client") as client:
client.scan.return_value = {
"Items": [],
"ConsumedCapacity": {
"TableName": "foobar",
"ReadCapacityUnits": 4,
},
}
rs = self.dynamo.scan("foobar")
list(rs)
cap = ConsumedCapacity("foobar", Capacity(4, 0))
hook.assert_called_with(self.dynamo, "scan", ANY, ANY, cap)
def test_subscribe(self):
"""Can subscribe and unsubscribe from hooks"""
hook = lambda: None
self.dynamo.subscribe("precall", hook)
self.assertEqual(len(self.dynamo._hooks["precall"]), 1)
self.dynamo.unsubscribe("precall", hook)
self.assertEqual(len(self.dynamo._hooks["precall"]), 0)
| Java |
---
layout: post
title: (转)为何大量中国精英纷纷选择移民海外
category: 生活
description: (转)为何大量中国精英纷纷选择移民海外
---
微信上一篇文章,觉得说的很有道理,转载以示赞同。文章链接[在此](http://mp.weixin.qq.com/s?__biz=MzA4Mzk3OTkxOQ==&mid=402690985&idx=1&sn=bc5c030b5b8018feeb3eacdb3ecf332b)。
原文声明:文章来源:同舟共进,尊重原创,版权归原作者所有,由移民家园网综合整理。
大约在最近10年,国内越来越多社会精英移居海外,成为媒体、政府和公众关注与讨论的话题。
初看起来,这是中国在卷入全球化浪潮之后产生的人员流动的自然现象。在中华人民共和国历史的前期,人员流出与流入水平接近于零;上世纪70年代末改革开放后,人员的流动(主要是外流)开始产生并且规模越来越大,但与世界上许多国家和地区相比并不引人注目。
只是在最近,这个问题才引起注意和谈论,事实上,主要原因还不在于流出的绝对数量,而在于增长的势头及其特殊含义。
与精英外流现象相映成趣的是,也有大量的海外精英流入内地寻求发展机会。最主要的有两部分人,一是早年留学国外,取得学位并在国外的大学、科研机构、公司或政府部门得到职位的中国公民,他们感到在自己工作的领域中,国内的发展机会似乎更多,或者,他们更喜欢自己熟悉的文化环境。二是台湾、香港的企业家,他们看中了在大陆的获利机会或地方的优惠政策。据此,应该认识到,人员流动决不是单向,而是双向的。但一进一出,动机和目标却迥然不同。
上述两类人到大陆工作的动机是寻求机会和发展空间,无意变换自己的国籍或身份,而国内精英移居海外,大多是以取得外国国籍为目的。移居海外的精英中,不少人只是追求拿到一个外国身份,他们挣钱和交友仍旧在国内,这种现象非常值得玩味。
同样值得注意的是,与上世纪80年代移居海外的潮流不同,那时一些人千方百计想去外国,是因为那里生活条件比国内好,工作条件、发展机会优于国内。
而这次移民潮中,大量精英是国内的成功人士,早已享受优越的生活和较高的社会地位,他们去到国外,要么是甘居平淡、低调,要么是准备从头再来,重新开始一轮艰辛的打拼。
也就是说,国内精英移民海外,多半是有所牺牲,有的甚至作出了较大的牺牲。那么,他们到底图什么?原因何在?
据笔者的了解,精英们移民的主要动因是获得安全感,他们凭经验和遭遇认为,在自己生活的社会,不稳定的因素太多,未来是不确定的,自己的前途不是可以根据自己的行动和决断作出合理预期的。除了安全感以外,精英们移民还追求好的自然环境、对子女更好的教育,等等。
精英们为了安全感而想方设法规避风险无可厚非,英国哲学家霍布斯在其名著《利维坦》中说过,人们生活的主要目的是自我保全,所以,安全感对于人来说是第一位的。
其实,精英移民不是孤立现象,而是一种更普遍现象的一部分。有人认为,中国的精英层属于广义的中产阶级,他们和欧洲资产阶级革命时期兴起的中产阶级一样,代表了一种新兴力量,在建构市民社会的过程中可起巨大的积极作用,对于建立法治、实行对于权力的制约、形成公平的自由竞争机制等方面可起正面作用。
但30年的历史进程表明,中国的所谓中产阶级或精英层与当下市场经济一样,带有较强的国情特色和扭曲性,他们与其说是制衡独断、垄断的权力的力量,不如说是更多地巴结、迎合权力,当然,他们这样做是为了自己的生存与获利。
如果说他们还有一些进步性的话,那就是他们对于法治的向往,因为他们毕竟希望在一套明晰的规则之下活动和生活。他们要求的不多——稳定性、可预见性而已。
精英移民的关键之处在于,他们希望具有另一种身份,将自己置于另一套法律系统之下,这套法律系统是否非常完美和公正暂且可以不管,但大致可以放心的是,这套法律系统是严格、清晰的,被任意解释和施行的可能性较小;是独立的,有权威的,不易受到当权者的干涉和侵害;出发点是保障个人的自由与权利,不是官员用来对付“刁民”的工具。
今日中国的移民精英相当务实,他们多半不会浅薄地崇洋媚外,以自己当了美国人、法国人或拿了绿卡在同胞面前炫耀,他们的底气在于随着身份转换而得到的保障。
这就相当于在一大群探险者中,虽然看起来大家的情况都差不多,但其中有的人是买了高额保险的,每个人的抗风险能力和自信心是不一样的。
正义是信心最根本的源泉,只有正义的社会才值得生活于其中的人们热爱和留恋,对精英是如此,对任何人也是如此。 | Java |
{% include header.html %}
{% include about.html %}
{% include work.html %}
{% include contact.html %}
{% include footer.html %} | Java |
@import url('https://fonts.googleapis.com/css?family=Inconsolata|Jim+Nightshade');
body {
overflow: hidden;
font-family: 'Inconsolata', monospace;
color: #333333;
}
#start, .main, #gameTime, #endBoard {
margin: 0 auto;
padding: 30px;
text-align: center;
width: 100%;
height: auto;
}
#gameTime, #endBoard {
display: none;
}
h1, h2 {
display: inline-block;
}
.choose {
font-family: 'Jim Nightshade', cursive;
cursor: pointer;
}
.active {
color: #7ACA99;
}
.board {
width: 300px;
height: 300px;
margin: 0 auto;
}
.table {
font-family: 'Jim Nightshade', cursive;
width: 100px;
height: 100px;
border: 2px solid #7ACA99;
text-align: center;
float: left;
box-sizing: border-box;
cursor: pointer;
font-size: 50px;
font-weight: bold;
line-height: 100px;
}
.disabled {
pointer-events: none;
opacity: 0.7;
background-color: #f4f4f4;
}
#gameStart, #resetGame {
color: #333333;
border: 2px solid #7ACA99;
border-radius: 10px;
font-size: 16px;
text-decoration: none;
padding: 15px 32px;
cursor: pointer;
background-color: white;
-webkit-transition: all .3s; /* Safari */
transition: all .3s;
}
#gameStart:hover, #resetGame:hover {
background-color: #7ACA99;
color: white;
font-weight: bolder;
}
#gameStart:visited, #gameStart:active, #gameStart:focus,
#resetGame:visited, #resetGame:active, #resetGame:focus {
outline: none;
}
footer {
position: absolute;
bottom: 10px;
left: 0;
width: 100%;
background-color: #7ACA99;
font-size: 0.7em;
text-align: center;
}
footer > p {
margin: 0;
}
a {
text-decoration: none;
}
a:hover {
color: white;
}
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.StaticReadOnlyField")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.StaticReadOnlyField")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a881564f-3790-4077-a240-9edd76806251")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pg_prttn_tools" to load this file. \quit
-- Function: prttn_tools.create_child_table(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.create_child_table(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_child_schema CHARACTER VARYING,
p_child_table CHARACTER VARYING,
p_check_condition CHARACTER VARYING,
p_with_rule BOOLEAN)
RETURNS TEXT AS
$body$
DECLARE
/*
Создание дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_child_schema Схема дочерней таблицы
p_child_table Имя дочерней таблицы
p_check_condition Условие для создания constraint на дочерней таблице
p_with_rule Создание rule для родительской таблицы с условием,
заданным в p_check_condition
*/
v_ddl_text CHARACTER VARYING;
BEGIN
-- Создание дочерней таблицы
v_ddl_text := 'CREATE TABLE ' || p_child_schema || '.' || p_child_table ||
' ( LIKE ' || p_schema || '.' || p_table || ' INCLUDING ALL )';
EXECUTE v_ddl_text;
v_ddl_text := 'ALTER TABLE ' || p_child_schema || '.' || p_child_table ||
' INHERIT ' || p_schema || '.' || p_table;
EXECUTE v_ddl_text;
-- Создание CONSTRAINT для дочерней таблицы
IF p_check_condition IS NOT NULL THEN
v_ddl_text := 'ALTER TABLE ' ||
p_child_schema || '.' || p_child_table ||
' ADD CONSTRAINT ' || p_child_table || '_check CHECK ' ||
p_check_condition;
EXECUTE v_ddl_text;
-- Создание правила для родительской таблицы
IF p_with_rule THEN
v_ddl_text := 'CREATE RULE route_' ||
p_child_schema || '_' || p_child_table || ' AS ' ||
' ON INSERT TO ' || p_schema ||'.'|| p_table ||
' WHERE ' || p_check_condition || ' DO INSTEAD INSERT INTO ' ||
p_child_schema || '.' || p_child_table || ' VALUES (new.*)';
EXECUTE v_ddl_text;
END IF;
END IF;
RETURN 'created';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.create_child_table(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.drop_ins_trigger(
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.drop_ins_trigger(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING)
RETURNS TEXT AS
$body$
DECLARE
/*
Удаление триггера на вставку записей и триггерной функции, созданных
функцией part_%_create_trigger()
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
*/
v_ddl_text CHARACTER VARYING;
BEGIN
-- Удаление триггера
v_ddl_text := 'DROP TRIGGER ' || p_table || '_part_ins_tr ON ' ||
p_schema || '.' || p_table;
EXECUTE v_ddl_text;
-- Удаление триггерной функции
v_ddl_text := 'DROP FUNCTION IF EXISTS ' || p_schema || '.' || p_table ||
'_part_ins_tr()';
EXECUTE v_ddl_text;
v_ddl_text := 'DROP FUNCTION IF EXISTS ' || p_schema || '.' || p_table ||
'_part_ins_tr_ac()';
EXECUTE v_ddl_text;
RETURN 'ok';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.drop_ins_trigger(CHARACTER VARYING,
CHARACTER VARYING) OWNER TO postgres;
-- Function: prttn_tools.part_list_check(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_check(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING)
RETURNS table(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING
) AS
$body$
DECLARE
/*
Проверка существования дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_list_value Значение для вставки в поле p_list_column
*/
v_count INTEGER;
BEGIN
-- Формирование имени и параметров дочерней таблицы
child_table := p_table || '_' || p_list_value;
child_list := p_list_value;
-- Проверка существования дочерней таблицы
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table p_table_p_list_value
-- child_table_status exist/noexist
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_check(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING) OWNER TO postgres;
-- Function: prttn_tools.part_list_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_with_rule BOOLEAN)
RETURNS table(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING
) AS
$body$
DECLARE
/*
Создание дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_list_value Значение для вставки в поле p_list_column
p_with_rule Создание rule для родительской таблицы с условием,
заданным в v_check_condition
*/
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
-- Проверка существования поля p_schemaname.p_tablename.p_list_column
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
c.column_name = p_list_column;
-- Выход c ошибкой если данные о поле или таблице не верны
IF v_count != 1 THEN
raise 'incorrect master table %', p_schema || '.' || p_table;
END IF;
-- Формирование имени и параметров дочерней таблицы
SELECT r.child_table, r.child_table_status, r.child_list
INTO child_table, child_table_status, child_list
FROM prttn_tools.part_list_check(p_schema, p_table, p_list_column,
p_list_value) r;
v_check_condition := '(' ||
p_list_column || ' = ' || quote_literal(p_list_value) || ')';
-- Создание таблицы если дочерняя таблица не существует
IF child_table_status = 'noexist' THEN
-- Создание дочерней таблицы
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table p_table_p_list_value
-- child_table_status exist/created
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_add(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_list_create_trigger(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_create_trigger(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
/*
Создание триггера для включения секционирования
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_autocreate Автоматическое/ручное создание секций
*/
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
IF p_autocreate THEN
trigger_function := trigger_function || '_ac';
END IF;
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.part_list_create_trigger
-- ' || now() || '
v_child_table CHARACTER VARYING;
v_child_table_status CHARACTER VARYING;
BEGIN
-- Проверка существования дочерней таблицы
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_list_check(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING);';
IF p_autocreate THEN
v_sql := v_sql || '
-- Создание новой дочерней таблицы, если не существует
IF v_child_table_status = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_list_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
-- Вставка записи в дочернюю таблицу
IF v_child_table_status = ''exist'' OR v_child_table_status = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_create_trigger(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_time_check(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE)
CREATE OR REPLACE FUNCTION prttn_tools.part_time_check(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
/*
Проверка существования дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_time_value Значение для вставки в поле p_time_column
*/
v_count INTEGER;
BEGIN
-- Формирование имени и параметров дочерней таблицы
child_table := p_table || '_';
CASE lower(p_time_range)
WHEN 'year' THEN
child_table := child_table || to_char(p_time_value, 'yyyy');
child_time_from := date_trunc('year', p_time_value);
child_time_to := date_trunc('year',
p_time_value + interval '1 year');
WHEN 'month' THEN
child_table := child_table || to_char(p_time_value, 'yyyymm');
child_time_from := date_trunc('month', p_time_value);
child_time_to := date_trunc('month',
p_time_value + interval '1 month');
WHEN 'day' THEN
child_table := child_table || to_char(p_time_value, 'yyyymmdd');
child_time_from := date_trunc('day', p_time_value);
child_time_to := date_trunc('day',
p_time_value + interval '1 day');
WHEN 'hour' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24');
child_time_from := date_trunc('hour', p_time_value);
child_time_to := date_trunc('hour',
p_time_value + interval '1 hour');
WHEN 'minute' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24mi');
child_time_from := date_trunc('minute', p_time_value);
child_time_to := date_trunc('minute',
p_time_value + interval '1 minute');
ELSE
RAISE 'incorrect variable p_time_range %s', p_time_range;
END CASE;
-- Проверка существования дочерней таблицы
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table | p_table_p_time_value
-- child_table_status | exist/noexist
-- child_time_from | Дата/время начала интервала
-- child_time_to | Дата/время конца интервала
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_time_check(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE)
OWNER TO postgres;
-- Function: prttn_tools.part_time_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_time_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE,
p_with_rule BOOLEAN)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
/*
Создание дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_time_value Значение для вставки в поле p_time_column
p_with_rule Создание rule для родительской таблицы с условием,
заданным в v_check_condition
*/
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
-- Проверка существования поля
-- p_schemaname.p_tablename.p_time_column(timestamp without time zone)
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
c.column_name = p_time_column AND
c.data_type = 'timestamp without time zone';
-- Выход c ошибкой если данные о поле или таблице не верны
IF v_count != 1 THEN
RAISE 'incorrect master table %', p_schema || '.' || p_table;
END IF;
-- Формирование имени и параметров дочерней таблицы
SELECT r.child_table, r.child_table_status, r.child_time_from,
r.child_time_to
INTO child_table, child_table_status, child_time_from, child_time_to
FROM prttn_tools.part_time_check(p_schema, p_table, p_time_column,
p_time_range, p_time_value) r;
v_check_condition := '(' ||
p_time_column || ' >= ' || quote_literal(child_time_from) || ' AND ' ||
p_time_column || ' < ' || quote_literal(child_time_to) || ')';
-- Создание таблицы если дочерняя таблица не существует
IF child_table_status = 'noexist' THEN
-- Создание дочерней таблицы
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table p_table_p_time_value
-- child_table_status exist/created
-- child_time_from Дата/время начала интервала
-- child_time_to Дата/время конца интервала
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_time_add(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE, BOOLEAN)
OWNER TO postgres;
-- Function: prttn_tools.part_time_create_trigger(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_time_create_trigger(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
/*
Создание триггера для включения секционирования
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_autocreate Автоматическое/ручное создание секций
*/
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
IF p_autocreate THEN
trigger_function := trigger_function || '_ac';
END IF;
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.part_time_create_trigger
-- ' || now() || '
v_child_table CHARACTER VARYING;
v_child_table_status CHARACTER VARYING;
BEGIN
-- Проверка существования дочерней таблицы
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_time_check(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE);';
IF p_autocreate THEN
v_sql := v_sql || '
-- Создание новой дочерней таблицы, если не существует
IF v_child_table_status = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_time_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
-- Вставка записи в дочернюю таблицу
IF v_child_table_status = ''exist'' OR v_child_table_status = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_time_create_trigger(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, BOOLEAN)
OWNER TO postgres;
-- Function: prttn_tools.part_list_time_check(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_time_check(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
/*
Проверка существования дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_list_value Значение для вставки в поле p_list_column
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_time_value Значение для вставки в поле p_time_column
*/
v_count INTEGER;
BEGIN
-- Формирование имени и параметров дочерней таблицы
child_table := p_table || '_' || p_list_value || '_';
child_list := p_list_value;
CASE lower(p_time_range)
WHEN 'year' THEN
child_table := child_table || to_char(p_time_value, 'yyyy');
child_time_from := date_trunc('year', p_time_value);
child_time_to := date_trunc('year',
p_time_value + interval '1 year');
WHEN 'month' THEN
child_table := child_table || to_char(p_time_value, 'yyyymm');
child_time_from := date_trunc('month', p_time_value);
child_time_to := date_trunc('month',
p_time_value + interval '1 month');
WHEN 'day' THEN
child_table := child_table || to_char(p_time_value, 'yyyymmdd');
child_time_from := date_trunc('day', p_time_value);
child_time_to := date_trunc('day',
p_time_value + interval '1 day');
WHEN 'hour' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24');
child_time_from := date_trunc('hour', p_time_value);
child_time_to := date_trunc('hour',
p_time_value + interval '1 hour');
WHEN 'minute' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24mi');
child_time_from := date_trunc('minute', p_time_value);
child_time_to := date_trunc('minute',
p_time_value + interval '1 minute');
ELSE
RAISE 'incorrect variable p_time_range %s', p_time_range;
END CASE;
-- Проверка существования дочерней таблицы
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table p_table_p_list_value_p_time_value
-- child_table_status exist/noexist
-- child_list p_list_value
-- child_time_from Дата/время начала интервала
-- child_time_to Дата/время конца интервала
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_time_check(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE) OWNER TO postgres;
-- Function: prttn_tools.part_list_time_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_time_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE,
p_with_rule BOOLEAN)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
/*
Создание дочерней таблицы
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_list_value Значение для вставки в поле p_list_column
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_time_value Значение для вставки в поле p_time_column
p_with_rule Создание rule для родительской таблицы с условием,
заданным в v_check_condition
*/
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
-- Проверка существования полей:
-- p_schemaname.p_tablename.p_list_column
-- p_schemaname.p_tablename.p_time_column(timestamp without time zone)
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
(c.column_name = p_list_column OR
(c.column_name = p_time_column AND
c.data_type = 'timestamp without time zone'
)
);
-- Выход c ошибкой если данные о поле или таблице не верны
IF v_count != 2 THEN
RAISE 'incorrect master table %', p_schema || '.' || p_table;
END IF;
-- Формирование имени и параметров дочерней таблицы
SELECT r.child_table, r.child_table_status, r.child_list, r.child_time_from,
r.child_time_to INTO child_table, child_table_status, child_list,
child_time_from, child_time_to
FROM prttn_tools.part_list_time_check(p_schema, p_table, p_list_column,
p_list_value, p_time_column, p_time_range, p_time_value) r;
v_check_condition := '(' ||
p_list_column || ' = ' || quote_literal(p_list_value) || ' AND ' ||
p_time_column || ' >= ' || quote_literal(child_time_from) || ' AND ' ||
p_time_column || ' < ' || quote_literal(child_time_to) || ')';
-- Создание таблицы если дочерняя таблица не существует
IF child_table_status = 'noexist' THEN
-- Создание child-таблицы
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table p_table_p_list_value_p_time_value
-- child_table_status exist/created
-- child_list p_list_value
-- child_time_from Дата/время начала интервала
-- child_time_to Дата/время конца интервала
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_time_add(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_list_time_create_trigger(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_time_create_trigger(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
/*
Создание триггера для включения секционирования
p_schema Схема родительской таблицы
p_table Имя родительской таблицы
p_list_column Поле для секционирования по значениям
p_time_column Поле для секционирования по интервалу времени
p_time_range Интервал для секционирования:
year, month, day, hour, minute
p_autocreate Автоматическое/ручное создание секций
*/
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.part_list_time_create_trigger
-- ' || now() || '
v_child_table CHARACTER VARYING;
v_child_table_status CHARACTER VARYING;
BEGIN
-- Проверка существования дочерней таблицы
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_list_time_check(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE);';
IF p_autocreate THEN
v_sql := v_sql || '
-- Создание новой дочерней таблицы, если не существует
IF v_child_table_status = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, v_child_table_status
FROM prttn_tools.part_list_time_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
-- Вставка записи в дочернюю таблицу
IF v_child_table_status = ''exist'' OR v_child_table_status = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_time_create_trigger(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_merge(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.part_merge(
p_parent_schema CHARACTER VARYING,
p_parent_table CHARACTER VARYING,
p_child_schema CHARACTER VARYING,
p_child_table CHARACTER VARYING)
RETURNS TEXT AS
$body$
DECLARE
/*
Слияние дочерней таблицы с родительской
p_parent_schema Схема родительской таблицы
p_parent_table Имя родительской таблицы
p_child_schema Схема дочерней таблицы
p_child_table Имя дочерней таблицы
*/
v_count BIGINT;
v_sql_text CHARACTER VARYING;
BEGIN
-- Проверка существования таблицы p_parent_schema.p_parent_table
SELECT count(*) INTO v_count
FROM information_schema.tables t1
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_parent_schema
AND t1.table_name = p_parent_table;
IF v_count != 1 THEN
RAISE 'parent table not found: %', p_parent_schema || '.' ||
p_parent_table;
END IF;
-- Проверка существования таблицы p_child_schema.p_child_table
SELECT count(*) INTO v_count
FROM information_schema.tables t1
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_child_schema
AND t1.table_name = p_child_table;
IF v_count != 1 THEN
RAISE 'child table not found: %', p_child_schema || '.' ||
p_child_table;
END IF;
-- Проверка совместимости таблиц
SELECT count(*) INTO v_count FROM (
SELECT c1.column_name, c1.data_type
FROM information_schema.tables t1
JOIN information_schema.columns c1
ON t1.table_catalog = c1.table_catalog
AND t1.table_schema = c1.table_schema
AND t1.table_name = c1.table_name
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_parent_schema
AND t1.table_name = p_parent_table
EXCEPT
SELECT c2.column_name, c2.data_type
FROM information_schema.tables t2
JOIN information_schema.columns c2
ON t2.table_catalog = c2.table_catalog
AND t2.table_schema = c2.table_schema
AND t2.table_name = c2.table_name
WHERE t2.table_catalog::name = current_database()
AND t2.table_type = 'BASE TABLE'
AND t2.table_schema = p_child_schema
AND t2.table_name = p_child_table
) tt;
IF v_count != 0 THEN
RAISE 'tables are not compatible: %', p_parent_schema || '.' ||
p_parent_table || ', ' || p_child_schema || '.' || p_child_table;
END IF;
-- Вставка данных в родительскую таблицу
v_sql_text := 'INSERT INTO ' || p_parent_schema || '.' || p_parent_table ||
' SELECT * FROM ' || p_child_schema || '.' || p_child_table;
EXECUTE v_sql_text;
-- Удаление дочерней таблицы
v_sql_text := 'DROP TABLE ' || p_child_schema || '.' || p_child_table;
EXECUTE v_sql_text;
RETURN 'ok';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_merge(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING) OWNER TO postgres;
| Java |
---
layout: post
status: publish
published: true
title: WCF Metadata Publication and Others
author:
display_name: Tomas Restrepo
login: tomasr
email: tomas@winterdom.com
url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 68
wordpress_url: http://winterdom.com/2006/10/wcfmetadatapublicationandothers
date: '2006-10-19 18:11:32 +0000'
date_gmt: '2006-10-19 18:11:32 +0000'
categories:
- WCF
- WinFX
- Web Services
tags: []
comments: []
---
<p><!--start_raw-->
<p><a href="http://blogs.msdn.com/ralph.squillace/">Ralph Squillace</a> posted an <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/19/quick-wcf-metadata-publication-walkthrough.aspx">walkthrough entry</a> of how metadata publication (MEX + WSDL) is enabled in Windows Communication Foundation. Besides discussing the configuration aspects, he also briefly touches on how those aspects affect the runtime behavior. </p>
<p>This came at a perfect time for me because I spent a few hours yesterday going over the System.ServiceModel assemblies with reflector trying to understand how it was that the metadata endpoints get hooked up to a service, so this helps a bit. I still need to look closely at a few issues before I understand what's going on well enough to try at something similar I've been wanting to play with...</p>
<p>Ralph has also been writing some samples about Sessionless Duplex Services <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/10/Sessionless-duplex-services_3F00_-No-problem.-Small-issues_2C00_-yes_3B00_-problems_2C00_-no_2E00_.aspx">here</a> and <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/19/sessionless-duplex-services-part-two-lifetimes-and-contexts.aspx">here</a> which are quite interesting as well.</p>
<div class="wlWriterSmartContent" id="d7bf807d-7bb0-458a-811f-90c51817d5c2:ff287cc0-1809-47be-ac08-9afa2e4e4e06" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p><span class="TagSite">Technorati:</span> <a href="http://technorati.com/tag/Windows+Communication+Foundation" rel="tag" class="tag">Windows Communication Foundation</a>, <a href="http://technorati.com/tag/WCF" rel="tag" class="tag">WCF</a><br /><!-- StartInsertedTags: Windows Communication Foundation, WCF :EndInsertedTags --></p></div><!--end_raw--></p>
| Java |
---
layout: angular
title: "Angularjs $scope"
date: 2016-01-01
author: Hao
category: blog
description: Angularjs $scope 笔记, 深入了解一下, 从angularjs github wiki 以及各种stackflow中搜索到的例子...
---
### JavaScript Prototypal Inheritance
首先你需要了解javascript本身的继承机制,这对你了解angularjs scope有着至关重要的作用,让我们先来复习一下。
假设`parentScope`有aString, aNumber, anArray, anObject, aFunction 5种属性, 而且`childScope`继承自`parentScope`。如果我们想从`childScope`获得`parentScope`中定义的属性,那么JavaScript会先从child scope中找,找不到,再去`parentScope`中找
下面这个例子详细说明了JavaScript Prototypal Inheritance
<iframe src="http://jsfiddle.net/hchen1202/e9257kt1/embedded/" style="width: 100%; height: 300px;"></iframe>
String & Num
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name.
Array & Object & Funciton
childScope.anArray[1] = 22
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created.
### Angular Scope Inheritance
在Angularjs中
* 以下几类会生成新的`Scope`而且`inherit prototypically`: ng-repeat, ng-include, ng-swith, ng-view, ng-controller, directive with scope: true, directive with transclude: true.
* 以下生成新的 `isolate scope`,directive with scope: {...}
* `default directive` 不会生成 `new scope`, 默认`directive` scope: false
#### ng-include
每一个ng-include都会产生一个新的`child scope`, 都会prototypically inherit from `parent scope`.
<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/z5q33kg6/embedded/" ></iframe>
当在第一个input中改变值时,hide/shaddow parent scope. 我们可以改变第一个template,达到我们想要的效果。
<input ng-model="$parent.myPrimitive">
当改变第二值时,没有产生新的`child property`, `prototypal inheritance` 发生了。
#### ng-switch
ng-swith跟ng-include一样, 如果你要`two-way binding`, use $parent, or change the model to be an object and then bind to a property of that object.
#### ng-repeat
ng-repeat有些许不一样,每个item,`ng-repeat`都会生成一个新的scope,都从`parent scope` prototypically inherit, 但同时把item的值赋给`child scope`的新属性。
<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/5ye3amjd/1/embedded/" ></iframe>
#### ng-controller
ng-controller没有什么不同,但如果想要从不同的controller中share data,建议还是用`service`
| Java |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Video Player</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="srt"></div>
<div style="float:right; padding: 10px;">Events: <ol class="events" style="height: 390px; overflow: scroll;"></ol></div>
<div id="video-container"></div>
<div id="youtube-video-container"></div>
<hr />
<div>Current time/ Duration: <span class="time"></span>/<span class="duration"></span></div>
<div>Speed: <span class="speed"></span></div>
<div>Muted: <span class="mute"></span></div>
<div>Volume level: <span class="volume"></span></div>
<div>Quality: <span class="quality"></span></div>
<!--script type="text/javascript" src="../build/VideoPlayer.min.js"></script-->
<script>
var requirejs = {
baseUrl: 'js/',
paths: {
'jquery': '../../lib/1.7.2.jquery.min'
}
}
</script>
<script src="../lib/require.js"></script>
<script type="text/javascript">
// new s2js.Video('HTML5', $('#video-container'), {
// sources: [
// 'https://s3.amazonaws.com/edx-course-videos/edx-intro/edX-FA12-cware-1_100.mp4.mp4',
// 'https://s3.amazonaws.com/edx-course-videos/edx-intro/edX-FA12-cware-1_100.webm'],
// volume: 0.5,
// playbackRate: 2.0,
// autoplay: false,
// controls: true,
// loop: true,
// muted: true,
// });
</script>
<script type="text/javascript">
require([
'utils', 'player', 'controls/vcr', 'controls/play_button',
'controls/mute_button', 'controls/progress_slider', 'controls/transcripts', 'components/menu'
], function (Utils, Video, VCR, PlayButton, MuteButton, ProgressSlider, Transcripts, Menu) {
p = new Video('Youtube', $('#youtube-video-container'), {
videoId: 'M7lc1UVf-VE',
volume: 0.75,
playbackRate: 1.0,
autoplay: 0,
controls: 1,
loop: 1,
muted: true,
plugins: [
VCR,
PlayButton,
MuteButton,
ProgressSlider,
Transcripts,
Menu
]
});
var d = document.getElementById('s2js-player-0');
var updateEvent = function (event) {
$('.events').append('<li>' + event + '</li>')
};
d.addEventListener('timeupdate', function () {
$('.time').html(Utils.Utils.secondsToTimecode(p.currentTime));
});
d.addEventListener('durationchange', function () {
$('.duration').html(Utils.Utils.secondsToTimecode(p.duration));
});
d.addEventListener('volumechange', function () {
$('.volume').html(p.volume);
$('.mute').html(p.muted.toString());
});
d.addEventListener('ratechange', function () {
$('.speed').html(p.playbackRate);
});
d.addEventListener('qualitychange', function () {
$('.quality').html(p.playbackQuality);
});
['canplay', 'ratechange', 'loadedmetadata', 'loadeddata', 'durationchange',
'ended', 'play', 'playing', 'pause', 'progress', 'qualitychange', 'error',
'volumechange'
].forEach(function (eventName) {
d.addEventListener(eventName, function () {
updateEvent(eventName);
}, false);
});
});
</script>
</body>
</html>
| Java |
#ifndef GAME_H
#define GAME_H
#include <array>
class Game
{
public:
//Standard Con/Destructors
Game(); //Initialize the board.
~Game(); //Not sure if I need this, but it's here in case
//Are we playing the game?
bool isRunning = true;
//The easiest way I could implement stalemate
//detection with my limited knowledge.
//Is the board completely full, thereby causing a stalemate?
bool isStalemate = false;
//Board specific variables.
static const int MAX_ROWS = 3; //Bounds for our board array
static const int MAX_COLS = 3;
//Return the bounds of our board.
//Useful for, say, only allowing the player
//to make a move within board boundaries
//when player data is in a different class.
int get_max_rows() { return MAX_ROWS; }
int get_max_cols() { return MAX_COLS; }
//Return our private piece variables for public use.
char get_piece_x() { return pieceX; }
char get_piece_o() { return pieceO; }
//Print the board in its current state
void print_board();
//Print our help board. This board does not change.
void print_help_board();
//Check for an overlap, IE placing an X on top of an O.
//Returns false if there is an overlap. The space is invalid.
//Does NOT check for input sanity or bounds!!! This is done
//in some other class, likely going to be the player class.
bool is_valid_space(int xPosition, int yPosition);
//Check for every possible win using piece as the winning piece.
//For example, check if O is the winning piece.
//Returns true on a win, false otherwise.
bool is_victory(char piece);
//Allow a different function/class/file/whatever to acces the board.
//This is done to allow placement of pieces to the board without
//the risk of accidently trashing it. is_valid_space() should always
//be called first, and it likely will be called in this function.
//Returns false if it cannot place the piece.
bool add_new_piece(int xPosition, int yPosition, char piece);
//Removes all pieces from the board, re-sets the score (if I chose to
//implement scoring) to zero. This is used in preperation for a new game.
void reset();
//Simple random number generator, with bounds.
int get_random_num(int bound = 0);
//Place a piece on the board based on user input.
int make_move(int input, char piece);
private:
//Three win calcualtion functions to make my job easier.
//Check for vertical, horizontal, or diagonal wins independently.
//Used by is_victory() to simplify win checking even more.
bool is_win_vertical(char piece);
bool is_win_horizontal(char piece);
bool is_win_diagonal(char piece);
//char board[MAX_ROWS][MAX_COLS]; //The board itself
std::array<std::array<char, MAX_ROWS>, MAX_COLS> board; //The board itself
//These make setting up the board/player(s)/etc MUCH easier.
char pieceX = 'X'; //The player class assigns these variables to a local var.
char pieceO = 'O'; //for example, something like: player.set_piece(game.pieceX);
char pieceNeutral = '-'; //The blank or empty piece.
//Settings for making a help board. Shows the player which number corresponds
//to the tile he/she wants. Below are variables for that.
int helpBoard[MAX_ROWS][MAX_COLS];
};
#endif
| Java |
//
// HNBFlowLayoutViewController.h
// HNBKitDemo
//
// Created by 开发 on 2017/7/21.
// Copyright © 2017年 开发. All rights reserved.
//
#import "HNBBaseViewController.h"
@interface HNBFlowLayoutViewController : HNBBaseViewController
@end
| Java |
<!--
~ Copyright (c) 2017. MIT-license for Jari Van Melckebeke
~ Note that there was a lot of educational work in this project,
~ this project was (or is) used for an assignment from Realdolmen in Belgium.
~ Please just don't abuse my work
-->
<html>
<head>
<meta charset="utf-8">
<script src="esl.js"></script>
<script src="config.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
}
</style>
<div id="main"></div>
<script>
require([
'echarts',
'echarts/chart/scatter',
'echarts/component/legend',
'echarts/component/polar'
], function (echarts) {
var chart = echarts.init(document.getElementById('main'), null, {
renderer: 'canvas'
});
var data1 = [];
var data2 = [];
var data3 = [];
for (var i = 0; i < 100; i++) {
data1.push([Math.random() * 5, Math.random() * 360]);
data2.push([Math.random() * 5, Math.random() * 360]);
data3.push([Math.random() * 10, Math.random() * 360]);
}
chart.setOption({
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
polar: {
},
angleAxis: {
type: 'value'
},
radiusAxis: {
axisAngle: 0
},
series: [{
coordinateSystem: 'polar',
name: 'scatter',
type: 'scatter',
symbolSize: 10,
data: data1
}, {
coordinateSystem: 'polar',
name: 'scatter2',
type: 'scatter',
symbolSize: 10,
data: data2
}, {
coordinateSystem: 'polar',
name: 'scatter3',
type: 'scatter',
symbolSize: 10,
data: data3
}]
});
})
</script>
</body>
</html> | Java |
# Contributing
I explicitly welcome contributions from people who have never contributed to open-source before: we were all beginners once!
I can help build on a partially working pull request with the aim of getting it merged.
I am also actively seeking to diversify our contributors and especially welcome contributions from women from all backgrounds and people of color. <sup>[1](#References)</sup>
If you're interested in contributing, fork this repo and create a pull request.
Please include a short descriptive link to your code in the readme, and order the link alphpabetically by file name.
Include a description of each data structure or algorithm at the top of the file, and if you feel that your code needs further explanation,
you can include a more detailed summary in the Data Structures or Algorithms subfolder's readme.
Please follow the [Ruby](https://github.com/bbatsov/ruby-style-guide) and [JavaScript](https://github.com/airbnb/javascript) Style Guides.
Tests are recommended, but optional.
If you're looking for inspiration, I'd love to have a:
+ [Priority Queue](https://en.wikipedia.org/wiki/Priority_queue)
+ [Valid Sudoku Board](https://en.wikipedia.org/wiki/Sudoku_solving_algorithms)
+ [Sorting Algorithms](https://en.wikipedia.org/wiki/Sorting_algorithm#Popular_sorting_algorithms)
+ [A* Search Algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm)
+ [Knuth-Morris-Pratt Algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm)
+ [Heap](https://en.wikipedia.org/wiki/Heap_\(data_structure\))
+ [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter)
+ [Or refactor one of these files!](/REFACTOR.md)
## Attribution
1. I used and modified [Homebrew's](https://github.com/Homebrew/brew#contributing) welcoming contributing section.
| Java |
Alchemy sentiment analysis: fb12d2c55fff36e1e268584e261b6b010b37279f
Africa Is Talking: 676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe93e77dc2e
| Java |
module.exports = {
project: {
server: {
basePath: '',
ip: '0.0.0.0',
request: {
sesskey: 'sid',
limit: 5000,
parameters: 60
},
render: 'swig',
path: {
routes: 'app/routes',
views: 'app/views',
public: 'public/',
docs: false
},
views: {
extension: 'swig',
errors: 'errors/'
}
}
},
environment: {
server: {
debug: true,
host: 'localhost',
port: 3000,
request: {
secret: new Date().getTime() + '' + Math.random(),
cors: true,
geolocation: false
},
views: {
cache: false
}
}
}
}; | Java |
<?php
namespace RedMedica\ConsultasBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use RedMedica\ConsultasBundle\Entity\Article;
use FOS\ElasticaBundle\Configuration\Search;
/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity()
* @Search(repositoryClass="RedMedica\ConsultasBundle\Entity\SearchRepository\CategoryRepository")
*/
class Category
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="label", type="string", length=250, nullable=false)
*/
protected $label;
/**
* @var Doctrine\Common\Collections\ArrayCollection
*
* @ORM\OneToMany(targetEntity="RedMedica\ConsultasBundle\Entity\Article", mappedBy="category")
*/
protected $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function __toString()
{
return $this->label;
}
public function getId()
{
return $this->id;
}
public function setLabel($label)
{
$this->label = $label;
return $this;
}
public function getLabel()
{
return $this->label;
}
public function addArticle(Article $article)
{
$this->articles->add($article);
return $this;
}
public function setArticles($articles)
{
$this->articles = $articles;
return $this;
}
public function getArticles()
{
return $this->articles;
}
} | Java |
import React from "react";
import styled from 'styled-components'
import Link from './link';
const nextArrow = "/icons/next-arrow.png";
const prevArrow = "/icons/prev-arrow.png";
const PatternLink = styled.span`
width: 100%;
display: flex;
flex-direction: column;
padding: 1em;
float: ${props => props.previous ? 'left' : 'right'}
@media(min-width: $width-tablet) {
width: auto;
}
`;
const ImageContainer = styled.span`
height: 50px;
`;
const Image = styled.img`
height: 100%;
background-color: white;
float: ${props => props.previous ? 'right' : 'left'}
`;
const ArrowContainer = styled.div`
display: flex;
flex-direction: ${props => props.previous ? 'row-reverse' : 'row'};
align-items: center;
`;
const Name = styled.p`
padding: 10px 0;
`;
const Arrow = styled.img`
height: 10px;
flex-direction: row-reverse;
padding: ${props => props.previous ? '0 10px 0 0' : '0 0 0 10px'};
`;
const NextPrevPattern = ({pattern, direction}) => {
const previous = direction === "previous"
return (
<Link href={pattern.url}>
<PatternLink previous={previous}>
<ImageContainer>
<Image previous={previous} src={pattern.painted || pattern.lineDrawing} />
</ImageContainer>
<ArrowContainer previous={previous}>
<Name>{pattern.name}</Name>
{
(direction === "next") &&
<Arrow src={nextArrow}/>
}
{
(direction === "previous") &&
<Arrow previous src={prevArrow} />
}
</ArrowContainer>
</PatternLink>
</Link>
)
};
export default NextPrevPattern;
| Java |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DIGIBYTE_NET_PROCESSING_H
#define DIGIBYTE_NET_PROCESSING_H
#include "net.h"
#include "validationinterface.h"
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
/** Expiration time for orphan transactions in seconds */
static const int64_t ORPHAN_TX_EXPIRE_TIME = 20 * 60;
/** Minimum time between orphan transactions expire time checks in seconds */
static const int64_t ORPHAN_TX_EXPIRE_INTERVAL = 5 * 60;
/** Default number of orphan+recently-replaced txn to keep around for block reconstruction */
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN = 100;
/** Register with a network node to receive its signals */
void RegisterNodeSignals(CNodeSignals& nodeSignals);
/** Unregister a network node */
void UnregisterNodeSignals(CNodeSignals& nodeSignals);
class PeerLogicValidation : public CValidationInterface {
private:
CConnman* connman;
public:
PeerLogicValidation(CConnman* connmanIn);
virtual void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int nPosInBlock);
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload);
virtual void BlockChecked(const CBlock& block, const CValidationState& state);
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock);
};
struct CNodeStateStats {
int nMisbehavior;
int nSyncHeight;
int nCommonHeight;
std::vector<int> vHeightInFlight;
};
/** Get statistics from node state */
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
/** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom, CConnman& connman, std::atomic<bool>& interrupt);
/**
* Send queued protocol messages to be sent to a give node.
*
* @param[in] pto The node which we are sending messages to.
* @param[in] connman The connection manager for that node.
* @param[in] interrupt Interrupt condition for processing threads
* @return True if there is more work to be done
*/
bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interrupt);
#endif // DIGIBYTE_NET_PROCESSING_H
| Java |
#
# $Header: svn://svn/SWM/trunk/web/Reports/ReportAdvanced_TXSold.pm 8251 2013-04-08 09:00:53Z rlee $
#
package Reports::ReportAdvanced_TXSold;
use strict;
use lib ".";
use ReportAdvanced_Common;
use Reports::ReportAdvanced;
our @ISA =qw(Reports::ReportAdvanced);
use strict;
sub _getConfiguration {
my $self = shift;
my $currentLevel = $self->{'EntityTypeID'} || 0;
my $Data = $self->{'Data'};
my $SystemConfig = $self->{'SystemConfig'};
my $clientValues = $Data->{'clientValues'};
my $CommonVals = getCommonValues(
$Data,
{
MYOB => 1,
},
);
my $txt_Clr = $Data->{'SystemConfig'}{'txtCLR'} || 'Clearance';
my %config = (
Name => 'Transactions Sold Report',
StatsReport => 0,
MemberTeam => 0,
ReportEntity => 3,
ReportLevel => 0,
Template => 'default_adv',
TemplateEmail => 'default_adv_CSV',
DistinctValues => 1,
SQLBuilder => \&SQLBuilder,
DefaultPermType => 'NONE',
Fields => {
intPaymentType=> [
'Payment Type',
{
active=>1,
displaytype=>'lookup',
fieldtype=>'dropdown',
dropdownoptions => \%Defs::paymentTypes,
allowsort=>1,
dbfield=>'TL.intPaymentType'
}
],
strTXN=> [
'PayPal Reference Number',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'TL.strTXN',
active=>1
}
],
intLogID=> [
'Payment Log ID',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'TL.intLogID',
allowgrouping=>1,
active=>1
}
],
dtSettlement=> [
'Settlement Date',
{
active=>1,
displaytype=>'date',
fieldtype=>'datetime',
allowsort=>1,
dbformat=>' DATE_FORMAT(dtSettlement,"%d/%m/%Y %H:%i")'
}
],
intAmount => [
'Total Amount Paid',
{
displaytype=>'currency',
fieldtype=>'text',
allowsort=>1,
dbfield=>'TL.intAmount',
active=>1
}
],
SplitAmount=> [
'Split Amount',
{
displaytype=>'currency',
fieldtype=>'text',
allowsort=>1,
total=>1,
active=>1
}
],
SplitLevel=> [
'Split Level',
{
displaytype=>'text',
fieldtype=>'text',
allowsort=>1,
active=>1
}
],
PaymentFor=> [
'Payment For',
{
active=>1,
displaytype=>'text',
fieldtype=>'text',
allowsort => 1
}
],
intExportBankFileID=> [
'PayPal Distribution ID',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'intExportAssocBankFileID'
}
],
intMyobExportID=> [
'SP Invoice Run',
{
displaytype=>'lookup',
fieldtype=>'dropdown',
dropdownoptions => $CommonVals->{'MYOB'}{'Values'},
active=>1,
dbfield=>'intMyobExportID'
}
],
dtRun=> [
'Date Funds Received',
{
displaytype=>'date',
fieldtype=>'date',
allowsort=>1,
dbformat=>' DATE_FORMAT(dtRun,"%d/%m/%Y")',
allowgrouping=>1,
sortfield=>'TL.dtSettlement'
}
],
},
Order => [qw(
intLogID
intPaymentType
strTXN
intAmount
dtSettlement
PaymentFor
SplitLevel
SplitAmount
intMyobExportID
)],
OptionGroups => {
default => ['Details',{}],
},
Config => {
FormFieldPrefix => 'c',
FormName => 'txnform_',
EmailExport => 1,
limitView => 5000,
EmailSenderAddress => $Defs::admin_email,
SecondarySort => 1,
RunButtonLabel => 'Run Report',
},
);
$self->{'Config'} = \%config;
}
sub SQLBuilder {
my($self, $OptVals, $ActiveFields) =@_ ;
my $currentLevel = $self->{'EntityTypeID'} || 0;
my $intID = $self->{'EntityID'} || 0;
my $Data = $self->{'Data'};
my $clientValues = $Data->{'clientValues'};
my $SystemConfig = $Data->{'SystemConfig'};
my $from_levels = $OptVals->{'FROM_LEVELS'};
my $from_list = $OptVals->{'FROM_LIST'};
my $where_levels = $OptVals->{'WHERE_LEVELS'};
my $where_list = $OptVals->{'WHERE_LIST'};
my $current_from = $OptVals->{'CURRENT_FROM'};
my $current_where = $OptVals->{'CURRENT_WHERE'};
my $select_levels = $OptVals->{'SELECT_LEVELS'};
my $sql = '';
{ #Work out SQL
my $clubWHERE = $currentLevel == $Defs::LEVEL_CLUB
? qq[ AND ML.intClubID = $intID ]
: '';
$sql = qq[
SELECT DISTINCT
TL.intLogID,
TL.intAmount,
TL.strTXN,
TL.intPaymentType,
ML.intLogType,
ML.intEntityType,
ML.intMyobExportID,
dtSettlement,
IF(T.intTableType=$Defs::LEVEL_PERSON, CONCAT(M.strLocalSurname, ", ", M.strLocalFirstname), Entity.strLocalName) as PaymentFor,
SUM(ML.curMoney) as SplitAmount,
IF(ML.intEntityType = $Defs::LEVEL_NATIONAL, 'National Split',
IF(ML.intEntityType = $Defs::LEVEL_STATE, 'State Split',
IF(ML.intEntityType = $Defs::LEVEL_REGION, 'Region Split',
IF(ML.intEntityType = $Defs::LEVEL_ZONE, 'Zone Split',
IF(ML.intEntityType = $Defs::LEVEL_CLUB, 'Club Split',
IF((ML.intEntityType = 0 AND intLogType IN (2,3)), 'Fees', '')
)
)
)
)
) as SplitLevel
FROM
tblTransLog as TL
INNER JOIN tblMoneyLog as ML ON (
ML.intTransLogID = TL.intLogID
AND ML.intLogType IN ($Defs::ML_TYPE_SPMAX, $Defs::ML_TYPE_LPF, $Defs::ML_TYPE_SPLIT)
)
LEFT JOIN tblTransactions as T ON (
T.intTransactionID = ML.intTransactionID
)
LEFT JOIN tblPerson as M ON (
M.intPersonID = T.intID
AND T.intTableType = $Defs::LEVEL_PERSON
)
LEFT JOIN tblEntity as Entity ON (
Entity.intEntityID = T.intID
AND T.intTableType = $Defs::LEVEL_PERSON
)
LEFT JOIN tblRegoForm as RF ON (
RF.intRegoFormID= TL.intRegoFormID
)
WHERE TL.intRealmID = $Data->{'Realm'}
$clubWHERE
$where_list
GROUP BY TL.intLogID
];
return ($sql,'');
}
}
1;
| Java |
#!/usr/bin/node --harmony
'use strict'
const noble = require('noble'),
program = require('commander')
program
.version('0.0.1')
.option('-p, --prefix <integer>', 'Manufacturer identifier prefixed to all fan commands', parseInt)
.option('-t, --target [mac]', 'MAC address of devices to target', function(val){ return val.toLowerCase() })
.option('-s, --service <uuid>', 'UUID of fan controller BLE service')
.option('-w, --write <uuid>', 'UUID of fan controller BLE write characteristic')
.option('-n, --notify <uuid>', 'UUID of fan controller BLE notify characteristic')
class FanRequest {
writeInto(buffer) {
throw new TypeError('Must override method')
}
toBuffer() {
var buffer
if (program.prefix > 0) {
buffer = new Buffer(13)
buffer.writeUInt8(program.prefix)
this.writeInto(buffer.slice(1))
} else {
buffer = new Buffer(12)
this.writeInto(buffer)
}
const checksum = buffer.slice(0, buffer.length - 1).reduce(function(a, b){
return a + b
}, 0) & 255
buffer.writeUInt8(checksum, buffer.length - 1)
return buffer
}
}
class FanGetStateRequest extends FanRequest {
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(160)
}
}
Math.clamp = function(number, min, max) {
return Math.max(min, Math.min(number, max))
}
class FanUpdateLightRequest extends FanRequest {
constructor(isOn, level) {
super()
this.on = isOn ? 1 : 0
this.level = Math.clamp(level, 0, 100)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(255, 4)
buffer.writeUInt8(100, 5)
buffer.writeUInt8((this.on << 7) | this.level, 6)
buffer.fill(255, 7, 10)
}
}
class FanUpdateLevelRequest extends FanRequest {
constructor(level) {
super()
this.level = Math.clamp(level, 0, 3)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(this.level, 4)
buffer.fill(255, 5, 10)
}
}
class FanResponse {
static fromBuffer(buffer) {
if (program.prefix > 0) {
buffer = buffer.slice(1)
}
if (buffer.readUInt8(0) != 176) { return null }
const response = new FanResponse()
const windVelocity = buffer.readUInt8(2)
response.supportsFanReversal = (windVelocity & 0b00100000) != 0
response.maximumFanLevel = windVelocity & 0b00011111
const currentWindVelocity = buffer.readUInt8(4)
response.isFanReversed = (currentWindVelocity & 0b10000000) != 0
response.fanLevel = currentWindVelocity & 0b00011111
const currentBrightness = buffer.readUInt8(6)
response.lightIsOn = (currentBrightness & 0b10000000) != 0
response.lightBrightness = (currentBrightness & 0b01111111)
return response
}
}
// MARK: -
var command
program
.command('current')
.description('print current state')
.action(function(env, options) {
command = new FanGetStateRequest()
})
program
.command('fan')
.description('adjusts the fan')
.option('-l --level <size>', 'Fan speed', /^(off|low|medium|high)$/i, 'high')
.action(function(env, options) {
var level
switch (env.level) {
case 'low':
level = 1
break
case 'medium':
level = 2
break
case 'high':
level = 3
break
default:
level = 0
break
}
command = new FanUpdateLevelRequest(level)
})
program
.command('light <on|off>')
.description('adjusts the light')
.option('-l, --level <percent>', 'Light brightness', parseInt, 100)
.action(function(env, options) {
command = new FanUpdateLightRequest(env !== 'off', options.level)
})
program.parse(process.argv);
if (!command) {
program.help();
}
if (!program.target) {
throw new Error('MAC address required')
}
const serviceUUID = program.service || '539c681361a021374f79bf1a11984790'
const writeUUID = program.write || '539c681361a121374f79bf1a11984790'
const notifyUUID = program.notify || '539c681361a221374f79bf1a11984790'
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
console.log('scanning.')
noble.startScanning([ serviceUUID ], false)
} else {
noble.stopScanning()
}
})
noble.on('discover', function(peripheral) {
console.log('found ' + peripheral.address)
if (peripheral.address !== program.target) { return }
noble.stopScanning()
explore(peripheral)
});
function bail(error) {
console.log('failed: ' + error);
process.exit(1)
}
function explore(peripheral) {
console.log('connecting.')
peripheral.once('disconnect', function() {
peripheral.removeAllListeners()
explore(peripheral)
})
peripheral.connect(function(error) {
if (error) { bail(error); }
peripheral.discoverSomeServicesAndCharacteristics([ serviceUUID ], [ writeUUID, notifyUUID ], function(error, services, characteristics) {
if (error) { bail(error); }
var service = services[0]
var write = characteristics[0], notify = characteristics[1]
notify.on('data', function(data, isNotification) {
const response = FanResponse.fromBuffer(data)
if (response) {
console.log(response)
} else {
console.log('sent')
}
process.exit()
})
notify.subscribe(function(error) {
if (error) { bail(error); }
console.log('sending')
const buffer = command.toBuffer()
write.write(buffer, false, function(error){
if (error) { bail(error); }
})
})
})
})
}
| Java |
---
layout: post
category: "工具"
tags: [zsh,fish,linux]
---
[TOC]
### zsh 与yosemite 的bug? ###
在更新了Mac Yosemite 后,发现各种问题,首先是php,macport等问题
接着就是zsh了,不知道为什么,`zsh`总是几乎占了100%的cpu,这让我的macbook电池
暴跌,非常郁闷. 开始怀疑是插件的问题,但是即使把插件全部关了,也还是那样.
之前也用过fish,发现还是不错的一个shell,从设计上面说,非常方便.功能也不错.
于是就准备换到fish算了.

> 发了封邮件给zsh后,
>reply: Any chance that it's this issue with zsh-autosuggestions?
[问题解决](https://github.com/tarruda/zsh-autosuggestions/issues/24 )
发现原来是因为zsh-autosuggestions 的问题.
### fish优点 ###
- Autosuggestions 自动提示history,命令补全等很方便
- 命令的completions 甚至包括man的提示
- 一些`zsh`我喜欢的插件fish也有 例如`autojump` 通过[oh-my-fish](https://github.com/bpinto/oh-my-fishURL ) 可以很方便安装
- `fish-config`命令 可以在线的编辑fish的配置
其实以上一些功能其实`zsh`也可以做到,不过个人觉得补全做的没有`fish`好,只是一直以来`zsh`的社区比较强大
而`fish` 插件会少点,但是一般使用其实用不上很多插件,而且`zsh`用多几个插件就变得很慢.
一直使用 [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh ) ,但是发现了[oh-my-fish](https://github.com/bpinto/oh-my-fishURL ) 后
就想转过去了,因为以前一直以为fish没有插件支持.
### 安装[oh-my-fish](https://github.com/bpinto/oh-my-fishURL )###
brew install fish
sudo vi /etc/shells 将/usr/local/bin/fish加上,否则下面的命令会报错
chsh -s /usr/local/bin/fish
git clone git://github.com/bpinto/oh-my-fish.git ~/.oh-my-fish
copy配置文件
cp ~/.oh-my-fish/templates/config.fish ~/.config/fish/config.fish
### 设置fish ###
- 编辑~/config/fish/config.fish
```
set fish_plugins autojump bundler brew
set -xu PATH /usr/local/bin:$PATH
比较不爽的就是export 在这里不能用要使用`set -x`代替:
`set -x PATH /usr/local/bin $PATH`
-x : -export
-u : 意思是对所有fish session都使用
```
### 编写fish插件 ###
fish 的插件看起来非常好懂,是基于函数的
```ruby
function rg
rails generate $argv
end
```
| Java |
const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
return hasProp(obj, "r") && hasProp(obj, "g") && hasProp(obj, "b");
}
export default class Color {
static normalizeHex(hex) {
if (HEX.test(hex)) {
return hex;
} else if (HEX_SHORT.test(hex)) {
const r = hex.slice(1, 2);
const g = hex.slice(2, 3);
const b = hex.slice(3, 4);
return `#${r + r}${g + g}${b + b}`;
}
return null;
}
static hexToRgb(hex) {
const normalizedHex = this.normalizeHex(hex);
if (normalizedHex == null) {
return null;
}
const m = normalizedHex.match(HEX);
const i = parseInt(m[1], 16);
const r = (i >> 16) & 0xFF;
const g = (i >> 8) & 0xFF;
const b = i & 0xFF;
return { r, g, b };
}
static rgbToHex(rgb) {
const { r, g, b} = rgb;
const i = ((Math.round(r) & 0xFF) << 16) + ((Math.round(g) & 0xFF) << 8) + (Math.round(b) & 0xFF);
const s = i.toString(16).toLowerCase();
return `#${"000000".substring(s.length) + s}`;
}
static rgbToHsv(rgb, round = true) {
const { r, g, b } = rgb;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
const hsv = {};
if (max === 0) {
hsv.s = 0;
} else {
hsv.s = (delta / max * 1000) / 10;
}
if (max === min) {
hsv.h = 0;
} else if (r === max) {
hsv.h = (g - b) / delta;
} else if (g === max) {
hsv.h = 2 + (b - r) / delta;
} else {
hsv.h = 4 + (r - g) / delta;
}
hsv.h = Math.min(hsv.h * 60, 360);
hsv.h = hsv.h < 0 ? hsv.h + 360 : hsv.h;
hsv.v = ((max / 255) * 1000) / 10;
return roundColors(hsv, round);
}
static rgbToXyz(rgb, round = true) {
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const rr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : r / 12.92;
const gg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : g / 12.92;
const bb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : b / 12.92;
const x = (rr * 0.4124 + gg * 0.3576 + bb * 0.1805) * 100;
const y = (rr * 0.2126 + gg * 0.7152 + bb * 0.0722) * 100;
const z = (rr * 0.0193 + gg * 0.1192 + bb * 0.9505) * 100;
return roundColors({ x, y, z }, round);
}
static rgbToLab(rgb, round = true) {
const xyz = Color.rgbToXyz(rgb, false);
let { x, y, z } = xyz;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return roundColors({ l, a, b }, round);
}
constructor(value) {
this.original = value;
if (isRgb(value)) {
this.rgb = value;
this.hex = Color.rgbToHex(value);
} else {
this.hex = Color.normalizeHex(value);
this.rgb = Color.hexToRgb(this.hex);
}
this.hsv = Color.rgbToHsv(this.rgb);
}
}
| Java |
export { default } from 'ember-validation/components/ember-validation-error-list';
| Java |
.WeatherStations {
margin: 30px 30px 30px 30px;
}
.clear{
clear: both;
} | Java |
/*global window */
/**
* @license countdown.js v2.5.2 http://countdownjs.org
* Copyright (c)2006-2014 Stephen M. McKamey.
* Licensed under The MIT License.
*/
/*jshint bitwise:false */
/**
* @public
* @type {Object|null}
*/
var module;
/**
* API entry
* @public
* @param {function(Object)|Date|number} start the starting date
* @param {function(Object)|Date|number} end the ending date
* @param {number} units the units to populate
* @return {Object|number}
*/
var countdown = (
/**
* @param {Object} module CommonJS Module
*/
function(module) {
/*jshint smarttabs:true */
'use strict';
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS = 0x001;
/**
* @private
* @const
* @type {number}
*/
var SECONDS = 0x002;
/**
* @private
* @const
* @type {number}
*/
var MINUTES = 0x004;
/**
* @private
* @const
* @type {number}
*/
var HOURS = 0x008;
/**
* @private
* @const
* @type {number}
*/
var DAYS = 0x010;
/**
* @private
* @const
* @type {number}
*/
var WEEKS = 0x020;
/**
* @private
* @const
* @type {number}
*/
var MONTHS = 0x040;
/**
* @private
* @const
* @type {number}
*/
var YEARS = 0x080;
/**
* @private
* @const
* @type {number}
*/
var DECADES = 0x100;
/**
* @private
* @const
* @type {number}
*/
var CENTURIES = 0x200;
/**
* @private
* @const
* @type {number}
*/
var MILLENNIA = 0x400;
/**
* @private
* @const
* @type {number}
*/
var DEFAULTS = YEARS|MONTHS|DAYS|HOURS|MINUTES|SECONDS;
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS_PER_SECOND = 1000;
/**
* @private
* @const
* @type {number}
*/
var SECONDS_PER_MINUTE = 60;
/**
* @private
* @const
* @type {number}
*/
var MINUTES_PER_HOUR = 60;
/**
* @private
* @const
* @type {number}
*/
var HOURS_PER_DAY = 24;
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND;
/**
* @private
* @const
* @type {number}
*/
var DAYS_PER_WEEK = 7;
/**
* @private
* @const
* @type {number}
*/
var MONTHS_PER_YEAR = 12;
/**
* @private
* @const
* @type {number}
*/
var YEARS_PER_DECADE = 10;
/**
* @private
* @const
* @type {number}
*/
var DECADES_PER_CENTURY = 10;
/**
* @private
* @const
* @type {number}
*/
var CENTURIES_PER_MILLENNIUM = 10;
/**
* @private
* @param {number} x number
* @return {number}
*/
var ceil = Math.ceil;
/**
* @private
* @param {number} x number
* @return {number}
*/
var floor = Math.floor;
/**
* @private
* @param {Date} ref reference date
* @param {number} shift number of months to shift
* @return {number} number of days shifted
*/
function borrowMonths(ref, shift) {
var prevTime = ref.getTime();
// increment month by shift
ref.setMonth( ref.getMonth() + shift );
// this is the trickiest since months vary in length
return Math.round( (ref.getTime() - prevTime) / MILLISECONDS_PER_DAY );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerMonth(ref) {
var a = ref.getTime();
// increment month by 1
var b = new Date(a);
b.setMonth( ref.getMonth() + 1 );
// this is the trickiest since months vary in length
return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerYear(ref) {
var a = ref.getTime();
// increment year by 1
var b = new Date(a);
b.setFullYear( ref.getFullYear() + 1 );
// this is the trickiest since years (periodically) vary in length
return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY );
}
/**
* Applies the Timespan to the given date.
*
* @private
* @param {Timespan} ts
* @param {Date=} date
* @return {Date}
*/
function addToDate(ts, date) {
date = (date instanceof Date) || ((date !== null) && isFinite(date)) ? new Date(+date) : new Date();
if (!ts) {
return date;
}
// if there is a value field, use it directly
var value = +ts.value || 0;
if (value) {
date.setTime(date.getTime() + value);
return date;
}
value = +ts.milliseconds || 0;
if (value) {
date.setMilliseconds(date.getMilliseconds() + value);
}
value = +ts.seconds || 0;
// if (value) {
date.setSeconds(date.getSeconds() + value);
// }
value = +ts.minutes || 0;
if (value) {
date.setMinutes(date.getMinutes() + value);
}
value = +ts.hours || 0;
if (value) {
date.setHours(date.getHours() + value);
}
value = +ts.weeks || 0;
if (value) {
value *= DAYS_PER_WEEK;
}
value += +ts.days || 0;
if (value) {
date.setDate(date.getDate() + value);
}
value = +ts.months || 0;
if (value) {
date.setMonth(date.getMonth() + value);
}
value = +ts.millennia || 0;
if (value) {
value *= CENTURIES_PER_MILLENNIUM;
}
value += +ts.centuries || 0;
if (value) {
value *= DECADES_PER_CENTURY;
}
value += +ts.decades || 0;
if (value) {
value *= YEARS_PER_DECADE;
}
value += +ts.years || 0;
if (value) {
date.setFullYear(date.getFullYear() + value);
}
return date;
}
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLISECONDS = 0;
/**
* @private
* @const
* @type {number}
*/
var LABEL_SECONDS = 1;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MINUTES = 2;
/**
* @private
* @const
* @type {number}
*/
var LABEL_HOURS = 3;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DAYS = 4;
/**
* @private
* @const
* @type {number}
*/
var LABEL_WEEKS = 5;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MONTHS = 6;
/**
* @private
* @const
* @type {number}
*/
var LABEL_YEARS = 7;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DECADES = 8;
/**
* @private
* @const
* @type {number}
*/
var LABEL_CENTURIES = 9;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLENNIA = 10;
/**
* @private
* @type {Array}
*/
var LABELS_SINGLUAR;
/**
* @private
* @type {Array}
*/
var LABELS_PLURAL;
/**
* @private
* @type {string}
*/
var LABEL_LAST;
/**
* @private
* @type {string}
*/
var LABEL_DELIM;
/**
* @private
* @type {string}
*/
var LABEL_NOW;
/**
* Formats a number as a string
*
* @private
* @param {number} value
* @return {string}
*/
var formatNumber;
/**
* @private
* @param {number} value
* @param {number} unit unit index into label list
* @return {string}
*/
function plurality(value, unit) {
return formatNumber(value)+((value === 1) ? LABELS_SINGLUAR[unit] : LABELS_PLURAL[unit]);
}
/**
* Formats the entries with singular or plural labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
var formatList;
/**
* Timespan representation of a duration of time
*
* @private
* @this {Timespan}
* @constructor
*/
function Timespan() {}
/**
* Formats the Timespan as a sentence
*
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toString = function(emptyLabel) {
var label = formatList(this);
var count = label.length;
if (!count) {
return emptyLabel ? ''+emptyLabel : LABEL_NOW;
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Formats the Timespan as a sentence in HTML
*
* @param {string=} tag HTML tag name to wrap each value
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toHTML = function(tag, emptyLabel) {
tag = tag || 'span';
var label = formatList(this);
var count = label.length;
if (!count) {
emptyLabel = emptyLabel || LABEL_NOW;
return emptyLabel ? '<'+tag+'>'+emptyLabel+'</'+tag+'>' : emptyLabel;
}
for (var i=0; i<count; i++) {
// wrap each unit in tag
label[i] = '<'+tag+'>'+label[i]+'</'+tag+'>';
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Applies the Timespan to the given date
*
* @param {Date=} date the date to which the timespan is added.
* @return {Date}
*/
Timespan.prototype.addTo = function(date) {
return addToDate(this, date);
};
/**
* Formats the entries as English labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
formatList = function(ts) {
var list = [];
var value = ts.millennia;
if (value) {
list.push(plurality(value, LABEL_MILLENNIA));
}
value = ts.centuries;
if (value) {
list.push(plurality(value, LABEL_CENTURIES));
}
value = ts.decades;
if (value) {
list.push(plurality(value, LABEL_DECADES));
}
value = ts.years;
if (value) {
list.push(plurality(value, LABEL_YEARS));
}
value = ts.months;
if (value) {
list.push(plurality(value, LABEL_MONTHS));
}
value = ts.weeks;
if (value) {
list.push(plurality(value, LABEL_WEEKS));
}
value = ts.days;
if (value) {
list.push(plurality(value, LABEL_DAYS));
}
value = ts.hours;
if (value) {
list.push(plurality(value, LABEL_HOURS));
}
value = ts.minutes;
if (value) {
list.push(plurality(value, LABEL_MINUTES));
}
value = ts.seconds;
// if (value) {
list.push(plurality(value, LABEL_SECONDS));
// }
value = ts.milliseconds;
if (value) {
list.push(plurality(value, LABEL_MILLISECONDS));
}
return list;
};
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
* @param {string} toUnit
*/
function rippleRounded(ts, toUnit) {
switch (toUnit) {
case 'seconds':
if (ts.seconds !== SECONDS_PER_MINUTE || isNaN(ts.minutes)) {
return;
}
// ripple seconds up to minutes
ts.minutes++;
ts.seconds = 0;
/* falls through */
case 'minutes':
if (ts.minutes !== MINUTES_PER_HOUR || isNaN(ts.hours)) {
return;
}
// ripple minutes up to hours
ts.hours++;
ts.minutes = 0;
/* falls through */
case 'hours':
if (ts.hours !== HOURS_PER_DAY || isNaN(ts.days)) {
return;
}
// ripple hours up to days
ts.days++;
ts.hours = 0;
/* falls through */
case 'days':
if (ts.days !== DAYS_PER_WEEK || isNaN(ts.weeks)) {
return;
}
// ripple days up to weeks
ts.weeks++;
ts.days = 0;
/* falls through */
case 'weeks':
if (ts.weeks !== daysPerMonth(ts.refMonth)/DAYS_PER_WEEK || isNaN(ts.months)) {
return;
}
// ripple weeks up to months
ts.months++;
ts.weeks = 0;
/* falls through */
case 'months':
if (ts.months !== MONTHS_PER_YEAR || isNaN(ts.years)) {
return;
}
// ripple months up to years
ts.years++;
ts.months = 0;
/* falls through */
case 'years':
if (ts.years !== YEARS_PER_DECADE || isNaN(ts.decades)) {
return;
}
// ripple years up to decades
ts.decades++;
ts.years = 0;
/* falls through */
case 'decades':
if (ts.decades !== DECADES_PER_CENTURY || isNaN(ts.centuries)) {
return;
}
// ripple decades up to centuries
ts.centuries++;
ts.decades = 0;
/* falls through */
case 'centuries':
if (ts.centuries !== CENTURIES_PER_MILLENNIUM || isNaN(ts.millennia)) {
return;
}
// ripple centuries up to millennia
ts.millennia++;
ts.centuries = 0;
/* falls through */
}
}
/**
* Ripple up partial units one place
*
* @private
* @param {Timespan} ts timespan
* @param {number} frac accumulated fractional value
* @param {string} fromUnit source unit name
* @param {string} toUnit target unit name
* @param {number} conversion multiplier between units
* @param {number} digits max number of decimal digits to output
* @return {number} new fractional value
*/
function fraction(ts, frac, fromUnit, toUnit, conversion, digits) {
if (ts[fromUnit] >= 0) {
frac += ts[fromUnit];
delete ts[fromUnit];
}
frac /= conversion;
if (frac + 1 <= 1) {
// drop if below machine epsilon
return 0;
}
if (ts[toUnit] >= 0) {
// ensure does not have more than specified number of digits
ts[toUnit] = +(ts[toUnit] + frac).toFixed(digits);
rippleRounded(ts, toUnit);
return 0;
}
return frac;
}
/**
* Ripple up partial units to next existing
*
* @private
* @param {Timespan} ts
* @param {number} digits max number of decimal digits to output
*/
function fractional(ts, digits) {
var frac = fraction(ts, 0, 'milliseconds', 'seconds', MILLISECONDS_PER_SECOND, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'seconds', 'minutes', SECONDS_PER_MINUTE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'minutes', 'hours', MINUTES_PER_HOUR, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'hours', 'days', HOURS_PER_DAY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'days', 'weeks', DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'weeks', 'months', daysPerMonth(ts.refMonth)/DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'months', 'years', daysPerYear(ts.refMonth)/daysPerMonth(ts.refMonth), digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'years', 'decades', YEARS_PER_DECADE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'decades', 'centuries', DECADES_PER_CENTURY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'centuries', 'millennia', CENTURIES_PER_MILLENNIUM, digits);
// should never reach this with remaining fractional value
if (frac) { throw new Error('Fractional unit overflow'); }
}
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
*/
function ripple(ts) {
var x;
if (ts.milliseconds < 0) {
// ripple seconds down to milliseconds
x = ceil(-ts.milliseconds / MILLISECONDS_PER_SECOND);
ts.seconds -= x;
ts.milliseconds += x * MILLISECONDS_PER_SECOND;
} else if (ts.milliseconds >= MILLISECONDS_PER_SECOND) {
// ripple milliseconds up to seconds
ts.seconds += floor(ts.milliseconds / MILLISECONDS_PER_SECOND);
ts.milliseconds %= MILLISECONDS_PER_SECOND;
}
if (ts.seconds < 0) {
// ripple minutes down to seconds
x = ceil(-ts.seconds / SECONDS_PER_MINUTE);
ts.minutes -= x;
ts.seconds += x * SECONDS_PER_MINUTE;
} else if (ts.seconds >= SECONDS_PER_MINUTE) {
// ripple seconds up to minutes
ts.minutes += floor(ts.seconds / SECONDS_PER_MINUTE);
ts.seconds %= SECONDS_PER_MINUTE;
}
if (ts.minutes < 0) {
// ripple hours down to minutes
x = ceil(-ts.minutes / MINUTES_PER_HOUR);
ts.hours -= x;
ts.minutes += x * MINUTES_PER_HOUR;
} else if (ts.minutes >= MINUTES_PER_HOUR) {
// ripple minutes up to hours
ts.hours += floor(ts.minutes / MINUTES_PER_HOUR);
ts.minutes %= MINUTES_PER_HOUR;
}
if (ts.hours < 0) {
// ripple days down to hours
x = ceil(-ts.hours / HOURS_PER_DAY);
ts.days -= x;
ts.hours += x * HOURS_PER_DAY;
} else if (ts.hours >= HOURS_PER_DAY) {
// ripple hours up to days
ts.days += floor(ts.hours / HOURS_PER_DAY);
ts.hours %= HOURS_PER_DAY;
}
while (ts.days < 0) {
// NOTE: never actually seen this loop more than once
// ripple months down to days
ts.months--;
ts.days += borrowMonths(ts.refMonth, 1);
}
// weeks is always zero here
if (ts.days >= DAYS_PER_WEEK) {
// ripple days up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
if (ts.months < 0) {
// ripple years down to months
x = ceil(-ts.months / MONTHS_PER_YEAR);
ts.years -= x;
ts.months += x * MONTHS_PER_YEAR;
} else if (ts.months >= MONTHS_PER_YEAR) {
// ripple months up to years
ts.years += floor(ts.months / MONTHS_PER_YEAR);
ts.months %= MONTHS_PER_YEAR;
}
// years is always non-negative here
// decades, centuries and millennia are always zero here
if (ts.years >= YEARS_PER_DECADE) {
// ripple years up to decades
ts.decades += floor(ts.years / YEARS_PER_DECADE);
ts.years %= YEARS_PER_DECADE;
if (ts.decades >= DECADES_PER_CENTURY) {
// ripple decades up to centuries
ts.centuries += floor(ts.decades / DECADES_PER_CENTURY);
ts.decades %= DECADES_PER_CENTURY;
if (ts.centuries >= CENTURIES_PER_MILLENNIUM) {
// ripple centuries up to millennia
ts.millennia += floor(ts.centuries / CENTURIES_PER_MILLENNIUM);
ts.centuries %= CENTURIES_PER_MILLENNIUM;
}
}
}
}
/**
* Remove any units not requested
*
* @private
* @param {Timespan} ts
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function pruneUnits(ts, units, max, digits) {
var count = 0;
// Calc from largest unit to smallest to prevent underflow
if (!(units & MILLENNIA) || (count >= max)) {
// ripple millennia down to centuries
ts.centuries += ts.millennia * CENTURIES_PER_MILLENNIUM;
delete ts.millennia;
} else if (ts.millennia) {
count++;
}
if (!(units & CENTURIES) || (count >= max)) {
// ripple centuries down to decades
ts.decades += ts.centuries * DECADES_PER_CENTURY;
delete ts.centuries;
} else if (ts.centuries) {
count++;
}
if (!(units & DECADES) || (count >= max)) {
// ripple decades down to years
ts.years += ts.decades * YEARS_PER_DECADE;
delete ts.decades;
} else if (ts.decades) {
count++;
}
if (!(units & YEARS) || (count >= max)) {
// ripple years down to months
ts.months += ts.years * MONTHS_PER_YEAR;
delete ts.years;
} else if (ts.years) {
count++;
}
if (!(units & MONTHS) || (count >= max)) {
// ripple months down to days
if (ts.months) {
ts.days += borrowMonths(ts.refMonth, ts.months);
}
delete ts.months;
if (ts.days >= DAYS_PER_WEEK) {
// ripple day overflow back up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
} else if (ts.months) {
count++;
}
if (!(units & WEEKS) || (count >= max)) {
// ripple weeks down to days
ts.days += ts.weeks * DAYS_PER_WEEK;
delete ts.weeks;
} else if (ts.weeks) {
count++;
}
if (!(units & DAYS) || (count >= max)) {
//ripple days down to hours
ts.hours += ts.days * HOURS_PER_DAY;
delete ts.days;
} else if (ts.days) {
count++;
}
if (!(units & HOURS) || (count >= max)) {
// ripple hours down to minutes
ts.minutes += ts.hours * MINUTES_PER_HOUR;
delete ts.hours;
} else if (ts.hours) {
count++;
}
if (!(units & MINUTES) || (count >= max)) {
// ripple minutes down to seconds
ts.seconds += ts.minutes * SECONDS_PER_MINUTE;
delete ts.minutes;
} else if (ts.minutes) {
count++;
}
if (!(units & SECONDS) || (count >= max)) {
// ripple seconds down to milliseconds
ts.milliseconds += ts.seconds * MILLISECONDS_PER_SECOND;
delete ts.seconds;
} else if (ts.seconds) {
count++;
}
// nothing to ripple milliseconds down to
// so ripple back up to smallest existing unit as a fractional value
if (!(units & MILLISECONDS) || (count >= max)) {
fractional(ts, digits);
}
}
/**
* Populates the Timespan object
*
* @private
* @param {Timespan} ts
* @param {?Date} start the starting date
* @param {?Date} end the ending date
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function populate(ts, start, end, units, max, digits) {
var now = new Date();
ts.start = start = start || now;
ts.end = end = end || now;
ts.units = units;
ts.value = end.getTime() - start.getTime();
if (ts.value < 0) {
// swap if reversed
var tmp = end;
end = start;
start = tmp;
}
// reference month for determining days in month
ts.refMonth = new Date(start.getFullYear(), start.getMonth(), 15, 12, 0, 0);
try {
// reset to initial deltas
ts.millennia = 0;
ts.centuries = 0;
ts.decades = 0;
ts.years = end.getFullYear() - start.getFullYear();
ts.months = end.getMonth() - start.getMonth();
ts.weeks = 0;
ts.days = end.getDate() - start.getDate();
ts.hours = end.getHours() - start.getHours();
ts.minutes = end.getMinutes() - start.getMinutes();
ts.seconds = end.getSeconds() - start.getSeconds();
ts.milliseconds = end.getMilliseconds() - start.getMilliseconds();
ripple(ts);
pruneUnits(ts, units, max, digits);
} finally {
delete ts.refMonth;
}
return ts;
}
/**
* Determine an appropriate refresh rate based upon units
*
* @private
* @param {number} units the units to populate
* @return {number} milliseconds to delay
*/
function getDelay(units) {
if (units & MILLISECONDS) {
// refresh very quickly
return MILLISECONDS_PER_SECOND / 30; //30Hz
}
if (units & SECONDS) {
// refresh every second
return MILLISECONDS_PER_SECOND; //1Hz
}
if (units & MINUTES) {
// refresh every minute
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
}
if (units & HOURS) {
// refresh hourly
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
}
if (units & DAYS) {
// refresh daily
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
}
// refresh the rest weekly
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK;
}
/**
* API entry point
*
* @public
* @param {Date|number|Timespan|null|function(Timespan,number)} start the starting date
* @param {Date|number|Timespan|null|function(Timespan,number)} end the ending date
* @param {number=} units the units to populate
* @param {number=} max number of labels to output
* @param {number=} digits max number of decimal digits to output
* @return {Timespan|number}
*/
function countdown(start, end, units, max, digits) {
var callback;
// ensure some units or use defaults
units = +units || DEFAULTS;
// max must be positive
max = (max > 0) ? max : NaN;
// clamp digits to an integer between [0, 20]
digits = (digits > 0) ? (digits < 20) ? Math.round(digits) : 20 : 0;
// ensure start date
var startTS = null;
if ('function' === typeof start) {
callback = start;
start = null;
} else if (!(start instanceof Date)) {
if ((start !== null) && isFinite(start)) {
start = new Date(+start);
} else {
if ('object' === typeof startTS) {
startTS = /** @type{Timespan} */(start);
}
start = null;
}
}
// ensure end date
var endTS = null;
if ('function' === typeof end) {
callback = end;
end = null;
} else if (!(end instanceof Date)) {
if ((end !== null) && isFinite(end)) {
end = new Date(+end);
} else {
if ('object' === typeof end) {
endTS = /** @type{Timespan} */(end);
}
end = null;
}
}
// must wait to interpret timespans until after resolving dates
if (startTS) {
start = addToDate(startTS, end);
}
if (endTS) {
end = addToDate(endTS, start);
}
if (!start && !end) {
// used for unit testing
return new Timespan();
}
if (!callback) {
return populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits));
}
// base delay off units
var delay = getDelay(units),
timerId,
fn = function() {
callback(
populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits)),
timerId
);
};
fn();
return (timerId = setInterval(fn, delay));
}
/**
* @public
* @const
* @type {number}
*/
countdown.MILLISECONDS = MILLISECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.SECONDS = SECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.MINUTES = MINUTES;
/**
* @public
* @const
* @type {number}
*/
countdown.HOURS = HOURS;
/**
* @public
* @const
* @type {number}
*/
countdown.DAYS = DAYS;
/**
* @public
* @const
* @type {number}
*/
countdown.WEEKS = WEEKS;
/**
* @public
* @const
* @type {number}
*/
countdown.MONTHS = MONTHS;
/**
* @public
* @const
* @type {number}
*/
countdown.YEARS = YEARS;
/**
* @public
* @const
* @type {number}
*/
countdown.DECADES = DECADES;
/**
* @public
* @const
* @type {number}
*/
countdown.CENTURIES = CENTURIES;
/**
* @public
* @const
* @type {number}
*/
countdown.MILLENNIA = MILLENNIA;
/**
* @public
* @const
* @type {number}
*/
countdown.DEFAULTS = DEFAULTS;
/**
* @public
* @const
* @type {number}
*/
countdown.ALL = MILLENNIA|CENTURIES|DECADES|YEARS|MONTHS|WEEKS|DAYS|HOURS|MINUTES|SECONDS|MILLISECONDS;
/**
* Override the unit labels
* @public
* @param {string|Array=} singular a pipe ('|') delimited list of singular unit name overrides
* @param {string|Array=} plural a pipe ('|') delimited list of plural unit name overrides
* @param {string=} last a delimiter before the last unit (default: ' and ')
* @param {string=} delim a delimiter to use between all other units (default: ', ')
* @param {string=} empty a label to use when all units are zero (default: '')
* @param {function(number):string=} formatter a function which formats numbers as a string
*/
countdown.setLabels = function(singular, plural, last, delim, empty, formatter) {
singular = singular || [];
if (singular.split) {
singular = singular.split('|');
}
plural = plural || [];
if (plural.split) {
plural = plural.split('|');
}
for (var i=LABEL_MILLISECONDS; i<=LABEL_MILLENNIA; i++) {
// override any specified units
LABELS_SINGLUAR[i] = singular[i] || LABELS_SINGLUAR[i];
LABELS_PLURAL[i] = plural[i] || LABELS_PLURAL[i];
}
LABEL_LAST = ('string' === typeof last) ? last : LABEL_LAST;
LABEL_DELIM = ('string' === typeof delim) ? delim : LABEL_DELIM;
LABEL_NOW = ('string' === typeof empty) ? empty : LABEL_NOW;
formatNumber = ('function' === typeof formatter) ? formatter : formatNumber;
};
/**
* Revert to the default unit labels
* @public
*/
var resetLabels = countdown.resetLabels = function() {
LABELS_SINGLUAR = ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium'.split('|');
LABELS_PLURAL = ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia'.split('|');
LABEL_LAST = ' and ';
LABEL_DELIM = ', ';
LABEL_NOW = '';
formatNumber = function(value) { return '<span class="contest_timedelta">' + value + "</span>"; };
};
resetLabels();
if (module && module.exports) {
module.exports = countdown;
} else if (typeof window.define === 'function' && typeof window.define.amd !== 'undefined') {
window.define('countdown', [], function() {
return countdown;
});
}
return countdown;
})(module);
| Java |
---
layout: page
title: Avila - Wu Wedding
date: 2016-05-24
author: Abigail Heath
tags: weekly links, java
status: published
summary: Vestibulum enim odio, dapibus non turpis.
banner: images/banner/people.jpg
booking:
startDate: 05/10/2016
endDate: 05/13/2016
ctyhocn: HTSBVHX
groupCode: AWW
published: true
---
Nam luctus finibus nisi vel accumsan. Nunc luctus diam orci, sed sodales mi luctus quis. Donec eget aliquet augue. Nunc eleifend, nisi id vulputate vehicula, eros dui iaculis velit, ac feugiat lectus diam quis tortor. Nam vitae elementum nisi. Suspendisse sed blandit diam. Cras id sodales magna. Integer quam neque, feugiat in venenatis eget, convallis id velit. Donec posuere lectus tincidunt, malesuada sapien ac, lacinia ante. Pellentesque ex risus, volutpat id augue ac, scelerisque ullamcorper mauris. Nam ac metus mauris. Etiam leo mauris, auctor eget pellentesque eu, aliquam sit amet neque. Quisque eget eleifend dolor. Aenean venenatis odio a est egestas commodo quis quis nulla. Duis luctus velit vitae pulvinar elementum. Curabitur quis tincidunt ex.
* Nam imperdiet purus at ante efficitur, ut elementum lectus facilisis
* Cras non elit at mauris lacinia eleifend id a orci
* Nulla pretium odio non varius cursus.
Aliquam erat volutpat. Mauris aliquet nisi et metus porta pulvinar. Curabitur ornare eros eu posuere lacinia. Mauris et tortor gravida, ultrices massa ut, auctor ex. Donec non pharetra nisl. Maecenas augue nibh, hendrerit sed lobortis nec, malesuada eu metus. Proin sollicitudin fermentum tortor et tincidunt. Cras quis tristique odio. Aenean molestie iaculis ornare. Quisque ac nunc arcu. Suspendisse quis mollis est. Maecenas feugiat sit amet nulla vitae condimentum.
Vivamus dictum mi sit amet ultrices tristique. Quisque sit amet venenatis est. Donec vulputate malesuada purus sed finibus. Nunc id justo quis odio vulputate pellentesque a nec arcu. Etiam felis eros, placerat eget odio in, lobortis congue massa. Suspendisse elementum fermentum consectetur. Aliquam diam sapien, mattis sit amet volutpat id, gravida ac lorem. Vestibulum dignissim nibh eu porta sagittis. Aliquam facilisis rhoncus egestas. Sed semper vel eros at lobortis. Quisque non mi massa. Vestibulum feugiat diam ex, eu aliquam mi pharetra id. Nam faucibus sollicitudin nibh, et ultricies ligula porttitor ullamcorper.
| Java |
file(REMOVE_RECURSE
"CMakeFiles/coverage_polymorphic.dir/polymorphic.cpp.o"
"../../../coverage/coverage_polymorphic.pdb"
"../../../coverage/coverage_polymorphic"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/coverage_polymorphic.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
| Java |
var formMode="detail"; /*formMode 页面模式 页面有三种模式 detail add modify*/
var panelType="form"; /*panelType 面板类型 form表单 search 查询 child 从表对象*/
var editIndex = undefined; /*datagrid 编辑对象的行号*/
var dg1EditIndex = undefined;
var objName=label.objName; /*页面管理对象名称*/
var lblDetailStr=label.detailStr; /*在不同的语种下应该不同*/
var lblAddStr=label.addStr; /*在不同的语种下应该不同*/
var lblEditStr=label.editStr; /*在不同的语种下应该不同*/
var pageName=null; /*根据pageName能够取得按钮定义*/
var pageHeight=0; /*pageHeight 页面高度*/
var topHeight=366; /*datagrid高度*/
var dgHeadHeight=28; /*datagrid 收缩后高度*/
var downHeight=30; /*底部高度*/
var paddingHeight=11; /*页面内补丁高度 paddingTop+paddingBottom*/
var gridToolbar = null; /*按钮定义 */
var dgConf=null; /*dgConf配置信息*/
var dg1Conf=null;
function initConf(){} /*在此初始化本页面的所有配置信息*/
function initButton(){
for(var i=0;i<gridToolbar.length;i++){
var b=gridToolbar[i];/*首次运行时所有按钮都是disable状态*/
$("#"+b.id).linkbutton({iconCls: b.iconCls,text:b.text,disabled:true,handler:b.handler,plain:1});
}
}
function initBtnDisabled() {
var btnDisabled=[{"id":"btn_refresh"},{"id":"btn_search"}];
for(var i=0;i<btnDisabled.length;i++) {
$('#'+btnDisabled[i].id).linkbutton('enable');
}
}
function component() {
initConf();
if(window.innerHeight) pageHeight=window.innerHeight;
else pageHeight=document.documentElement.clientHeight;
$('#middle').css("height",pageHeight-topHeight-downHeight-paddingHeight);
$('#tab').tabs({
onSelect:tab_select,
fit:true
});
/*这时候可能还没有key 所以不能直接绑定dom对象,只能使用dom id*/
installKey("btn_collapse",Keys.f1,null,null,null);
installKey("btn_edit",Keys.f2,null,null,null);
installKey("btn_search",Keys.f3,null,null,null);
installKey("btn_add",Keys.f4,null,null,null);
installKey("btn_delete",Keys.del,null,null,null);
installKey("btn2_save",Keys.s,true,null,null);
installKey("btn2_search",Keys.q,true,null,null);
installKey("btn2_edit",Keys.e,true,null,null);
document.onhelp=function(){return false}; /*为了屏蔽IE的F1按键*/
window.onhelp=function(){return false}; /*为了屏蔽IE的F1按键*/
$('#btn2_save').linkbutton({iconCls: 'icon-save'}).click(btn2_save);
$('#btn2_edit').linkbutton({iconCls: 'icon-save'}).click(btn2_update),
$('#btn2_search').linkbutton({iconCls: 'icon-search'}).click(btn2_search);
$('#btn2_addItem').linkbutton({iconCls: 'icon-add'}).click(btn2_addItem);
$('#btn2_editItem').linkbutton({iconCls: 'icon-edit'}).click(btn2_editItem);
$('#btn2_rmItem').linkbutton({iconCls: 'icon-remove'}).click(btn2_rmItem);
$('#btn2_ok').linkbutton({iconCls: 'icon-ok'}).click(btn2_ok);
dgConf.toolbar='#tb';
dgConf.onCollapse=dg_collapse;
dgConf.onSelect=dg_select;
dgConf.singleSelect=true;
dgConf.onLoadSuccess=dg_load;
dgConf.onClickRow=dg_click;
dgConf.onDblClickRow=dg_dbl;
dgConf.onExpand=dg_expand;
dgConf.collapsible=true;
dgConf.collapseID="btn_collapse";
dgConf.pagination=true;
dgConf.fit=true;
dgConf.rownumbers=true;
dgConf.singleSelect=true;
dg1Conf.onClickRow=dg1_click;
dg1Conf.onDblClickRow=dg1_dbl;
$("#dg").datagrid(dgConf);
initButton();
initBtnDisabled();
$('#top').css("height","auto");
lov_init();
$(".formChild").height(pageHeight-topHeight-downHeight-paddingHeight-dgHeadHeight-1);
//$("#ff1 input").attr("readonly",1); /*详细表单的输入框只读*/
}
function showChildGrid(param){/*dg 选中事件触发*/
$("#dg1").datagrid(dg1Conf);
}
function showForm(row){/*dg 选中事件触发*/
//$("#ff1").form("load",row);
//$("#ff2").form("load",row);;
}
function dg_collapse(){/*收缩后 总是要修改tabs 会触发tab_select事件 那么前面就需要将panel的selected属性设为true*/
var panel=$("#tab").tabs("getSelected"); /*先获取selected对象*/
if(panel!=null) panel.panel({selected:1});
$('#middle').css("height",pageHeight-dgHeadHeight-downHeight-paddingHeight);
$(".formChild").height(pageHeight-dgHeadHeight-downHeight-paddingHeight-dgHeadHeight-1);
$("#tab").tabs({fit:true,stopSelect:true});/*tab发生变化了 会触发tab_select事件 */
if(panel!=null) panel.panel({selected:0});
}
function dg_expand(){
var panel=$("#tab").tabs("getSelected");
if(panel!=null) panel.panel({selected:1});
$('#middle').css("height",pageHeight-topHeight-downHeight-paddingHeight);
$(".formChild").height(pageHeight-topHeight-downHeight-paddingHeight-dgHeadHeight-1);
$("#tab").tabs({fit:true,stopSelect:true});
if(panel!=null) panel.panel({selected:0});
}
function dg_load(){/*选中第一行*/
$('#mask').css('display', "none");
$('#dg').datagrid('selectRow', 0);
}
function dg_select(rowIndex, rowData){/*选中事件 填充ff1 ff2 dg1*/
showChildGrid(rowData);/*子表模式下,重绘子表列表*/
showForm(rowData,"add");
useDetailMode();
}
function dg_add(){/*列表新增按钮事件*/
useAddMode();
}
function dg_edit(){/*列表编辑按钮触发事件*/
var row=$('#dg').datagrid('getSelected');
if(row){
useEditMode();
}
else $.messager.alert('选择提示', '请选择您编辑的数据!',"info");
}
function dg_delete(){/*列表删除按钮触发事件*/
var confirmBack=function(r){
if(!r) return;
var p=$('#dg').datagrid('getRowIndex',$('#dg').datagrid('getSelected'));
/*执行服务器请求,完成服务端数据的删除 然后完成前端的删除*/
if (p == undefined){return}
$('#dg').datagrid('cancelEdit', p)
.datagrid('deleteRow', p);
/*删除成功后应该刷新页面 并把下一条选中*/
var currRows=$('#dg').datagrid('getRows').length;
if(p>=currRows) p--;
if(p>=0) $('#dg').datagrid('selectRow', p);/*如果已经到末尾则 选中p-1 */
}
var row=$('#dg').datagrid('getSelected');
if(row) $.messager.confirm('确认提示', '您确认要删除这条数据吗?', confirmBack);
else $.messager.alert('选择提示', '请选择您要删除的数据!',"info");
}
function dg_refresh(){/*列表刷新按钮事件*/
}
function dg_search(){/*列表搜索事件 search模式不再禁用其他面板*/
panelType="search";
$('#tab').tabs("select",1);
}
function dg_click(index){
/*切换回详细信息模式 首先判断tab的当前选项*/
if(panelType=="search"){
$('#tab').tabs("select",0);
}
}
function dg_dbl(){/*列表双击事件 双击进入编辑模式*/
document.getElementById("btn_edit").click();/*双击等同于点击编辑按钮*/
}
function tab_select(title,index){/*选项卡的切换 需要更改按钮的显示*/
$('#down a').css("display","none");
if(index==0){/*根据grid的状态来生成按钮 add edit*/
$('#btn2_addItem').css("display","inline-block");/*新增行按钮*/
$('#btn2_editItem').css("display","inline-block");/*删除行按钮*/
$('#btn2_rmItem').css("display","inline-block");/*删除行按钮*/
$('#btn2_ok').css("display","inline-block");/*commit按钮*/
}
else if(index==1){/*查询选项卡 切换到查询页签等同于按钮 search被点击*/
panelType="search";
$('#btn2_search').css("display","inline-block");/*搜索按钮*/
}
}
function useDetailMode(row){
//formMode="detail";
//$('#ff2').css("display","none");
//$('#ff1').css("display","block");
//if(panelType=="search") $('#tab').tabs("select",0);
//else tab_select();
}
function btn2_addItem(){
if(dg1_endEditing()){/*结束编辑状态成功*/
var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected'));
/*执行服务器请求,完成服务端数据的删除 然后完成前端的删除*/
if (p == undefined){return}
$('#dg1').datagrid('unselectAll');
$('#dg1').datagrid('insertRow',{index:p+1,row:{}})
.datagrid('beginEdit', p+1)
.datagrid('selectRow', p+1);
dg1EditIndex=p+1;
}
else{
$('#dg1').datagrid('selectRow', dg1EditIndex);
}
}
function btn2_editItem(){
var index=$('#dg1').datagrid('getRowIndex', $('#dg1').datagrid('getSelected'));
if (dg1EditIndex != index){
if (dg1_endEditing()){
$('#dg1').datagrid('selectRow', index)
.datagrid('beginEdit', index);
dg1EditIndex = index;
} else {
$('#dg1').datagrid('selectRow', dg1EditIndex);
}
}
}
function btn2_rmItem(){
var confirmBack=function(r){
if(!r) return;
var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected'));
if (p == undefined){return}
$('#dg1').datagrid('cancelEdit', p)
.datagrid('deleteRow', p);
var currRows=$('#dg1').datagrid('getRows').length;
if(p>=currRows) p--;
if(p>=0) $('#dg1').datagrid('selectRow', p);/*如果已经到末尾则 选中p-1 */
}
var row=$('#dg1').datagrid('getSelected');
if(row) $.messager.confirm('确认提示', '您确认要删除这条数据吗?', confirmBack);
else $.messager.alert('选择提示', '请选择您要删除的数据!',"info");
}
function dg1_endEditing(){
if (dg1EditIndex == undefined){return true}
var flag=$('#dg1').datagrid('validateRow',dg1EditIndex);
if(flag){/*如果校验通过 允许结束编辑状态*/
$('#dg1').datagrid('endEdit', dg1EditIndex);
dg1EditIndex = undefined;
return true;
}
return false;
}
function dg1_click(index){/*从表单击事件 在编辑模式下打开编辑*/
if (dg1EditIndex != index){
dg1_endEditing();
}
}
function dg1_dbl(index){/*从表双击事件 双击进入编辑模式*/
document.getElementById("btn2_editItem").click();/*双击等同于点击编辑按钮*/
}
function useAddMode(){};
function useEditMode(){};
function form_change(type){}/*type= add|edit*/
function removeValidate(){}/*type= enable|remove*/
function btn2_save(){}
function btn2_update(){}
function btn2_search(){}
function btn2_ok(){}
function lov_init(){}/*绑定值列表*/
| Java |
FROM ruby:2.3.3
RUN apt-get update && apt-get install -y \
#Packages
net-tools \
nodejs
#Install phantomjs
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
bzip2 \
libfontconfig \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
curl \
&& mkdir /tmp/phantomjs \
&& curl -L https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 \
| tar -xj --strip-components=1 -C /tmp/phantomjs \
&& cd /tmp/phantomjs \
&& mv bin/phantomjs /usr/local/bin \
&& cd \
&& apt-get purge --auto-remove -y \
curl \
&& apt-get clean \
&& rm -rf /tmp/* /var/lib/apt/lists/*
#Install gems
RUN mkdir /app
WORKDIR /app
COPY Gemfile* /app/
RUN bundle install
RUN apt-get clean
#Upload source
COPY . /app
RUN useradd ruby
RUN chown -R ruby /app
USER ruby
# Database defaults
ENV DATABASE_NAME bookIT
ENV DATABASE_HOST db
ENV DATABASE_USER bookIT
ENV DATABASE_PASSWORD password
ENV DATABASE_ADAPTER mysql2
ENV ACCOUNT_ADDRESS https://gamma.chalmers.it
#In production, Host is set to naboo.chlamers.it
# Start server
ENV RAILS_ENV production
ENV RACK_ENV production
ENV SECRET_KEY_BASE secret
ENV PORT 3000
EXPOSE 3000
RUN rake assets:precompile
CMD ["sh", "start.sh"]
| Java |
## Capistrano
[](http://travis-ci.org/capistrano/capistrano)[](https://codeclimate.com/github/capistrano/capistrano)
Capistrano is a utility and framework for executing commands in parallel on
multiple remote machines, via SSH. It uses a simple DSL (borrowed in part from
[Rake](http://rake.rubyforge.org/)) that allows you to define _tasks_, which may
be applied to machines in certain roles. It also supports tunneling connections
via some gateway machine to allow operations to be performed behind VPN's and
firewalls.
Capistrano was originally designed to simplify and automate deployment of web
applications to distributed environments, and originally came bundled with a set
of tasks designed for deploying Rails applications.
## Documentation
* [https://github.com/capistrano/capistrano/wiki](https://github.com/capistrano/capistrano/wiki)
## DEPENDENCIES
* [Net::SSH](http://net-ssh.rubyforge.org)
* [Net::SFTP](http://net-ssh.rubyforge.org)
* [Net::SCP](http://net-ssh.rubyforge.org)
* [Net::SSH::Gateway](http://net-ssh.rubyforge.org)
* [HighLine](http://highline.rubyforge.org)
* [Ruby](http://www.ruby-lang.org/en/) ≥ 1.8.7
If you want to run the tests, you'll also need to install the dependencies with
Bundler, see the `Gemfile` within .
## ASSUMPTIONS
Capistrano is "opinionated software", which means it has very firm ideas about
how things ought to be done, and tries to force those ideas on you. Some of the
assumptions behind these opinions are:
* You are using SSH to access the remote servers.
* You either have the same password to all target machines, or you have public
keys in place to allow passwordless access to them.
Do not expect these assumptions to change.
## USAGE
In general, you'll use Capistrano as follows:
* Create a recipe file ("capfile" or "Capfile").
* Use the `cap` script to execute your recipe.
Use the `cap` script as follows:
cap sometask
By default, the script will look for a file called one of `capfile` or
`Capfile`. The `sometask` text indicates which task to execute. You can do
"cap -h" to see all the available options and "cap -T" to see all the available
tasks.
## CONTRIBUTING:
* Fork Capistrano
* Create a topic branch - `git checkout -b my_branch`
* Rebase your branch so that all your changes are reflected in one
commit
* Push to your branch - `git push origin my_branch`
* Create a Pull Request from your branch, include as much documentation
as you can in the commit message/pull request, following these
[guidelines on writing a good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
* That's it!
## LICENSE:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| Java |
/*
* Jermit
*
* The MIT License (MIT)
*
* Copyright (C) 2018 Kevin Lamonte
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* @author Kevin Lamonte [kevin.lamonte@gmail.com]
* @version 1
*/
package jermit.protocol.zmodem;
/**
* ZEofHeader represents the end of a file.
*/
class ZEofHeader extends Header {
// ------------------------------------------------------------------------
// Constructors -----------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Public constructor.
*/
public ZEofHeader() {
this(0);
}
/**
* Public constructor.
*
* @param data the data field for this header
*/
public ZEofHeader(final int data) {
super(Type.ZEOF, (byte) 0x0B, "ZEOF", data);
}
// ------------------------------------------------------------------------
// Header -----------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ZEofHeader -------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Get the file size value.
*
* @return the value
*/
public int getFileSize() {
return data;
}
}
| Java |
# fullstack-course4-submissions | Java |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FormLoader {
public static String connectionString = "jdbc:hsqldb:file:db-data/teamsandplayers";
static Connection con;
public static void main(String[] args) throws Exception {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (ClassNotFoundException e) {
throw e;
}
MainTeamForm form = new MainTeamForm();
form.setVisible(true);
try {
// will create DB if does not exist
// "SA" is default user with hypersql
con = DriverManager.getConnection(connectionString, "SA", "");
} catch (SQLException e) {
throw e;
} finally {
con.close();
System.out.println("Program complete");
}
}
}
| Java |
<?php
namespace Memento\Test;
use Memento;
class SingleTest extends Harness
{
/** @dataProvider provideClients */
public function testStoreMethod(Memento\Client $client)
{
$success = $client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires());
$this->assertTrue($success);
$this->assertEquals($this->getExpires(), $client->getExpires($this->getKey()));
$this->assertEquals($this->getExpires(), $client->getTtl($this->getKey())); // default should be the same as expires
// store with ttl
$success = $client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires(), $this->getTtl());
$this->assertTrue($success);
$this->assertLessThanOrEqual($this->getExpires(), $client->getExpires($this->getKey()));
$this->assertLessThanOrEqual($this->getTtl(), $client->getTtl($this->getKey()));
}
/** @dataProvider provideClients */
public function testExists(Memento\Client $client)
{
$client->store($this->getKey(), true);
$exists = $client->exists($this->getKey());
$this->assertTrue($exists);
}
/** @dataProvider provideClients */
public function testRetrieve(Memento\Client $client)
{
$client->store($this->getKey(), array('foo' => 'bar'));
$data = $client->retrieve($this->getKey());
$this->assertEquals($data, array('foo' => 'bar'));
}
/** @dataProvider provideClients */
public function testInvalidRetrieve(Memento\Client $client)
{
$data = $client->retrieve(new Memento\Key(md5(time() . rand(0, 1000))));
$this->assertEquals($data, null);
}
/** @dataProvider provideClients */
public function testInvalidate(Memento\Client $client)
{
$client->store($this->getKey(), true);
$invalid = $client->invalidate($this->getKey());
$this->assertTrue($invalid);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
}
/** @dataProvider provideClients */
public function testTerminate(Memento\Client $client)
{
$client->store($this->getKey(), true);
$terminated = $client->terminate($this->getKey());
$this->assertTrue($terminated);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
}
/** @dataProvider provideClients */
public function testExpires(Memento\Client $client)
{
$client->store($this->getKey(), array('foo' => 'bar'), 1, $ttl = 5);
sleep(3);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
// check if cache exists but include expired caches
$exists = $client->exists($this->getKey(), true);
$this->assertTrue($exists);
$client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires(), $this->getTtl());
$this->assertTrue($client->exists($this->getKey()));
$client->expire($this->getKey());
sleep(1);
$this->assertFalse($client->exists($this->getKey()));
// check if cache exists but include expired caches
$exists = $client->exists($this->getKey(), true);
$this->assertTrue($exists);
}
}
| Java |
/*
Copyright (c) 2015 Shaps Mohsenin. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Shaps Mohsenin `AS IS' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL Shaps Mohsenin OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@import UIKit;
#import "SPXDataView.h"
/**
* Provides collectionView specific definitions of a dataView
*/
@interface UITableView (SPXDataViewAdditions) <SPXDataView>
/**
* Gets/sets the block to execute when the collectionView requests a cell
*/
@property (nonatomic, copy) UITableViewCell *(^viewForItemAtIndexPathBlock)(UITableView *tableView, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests the cell to be configured
*/
@property (nonatomic, copy) void (^configureViewForItemAtIndexPathBlock)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests a section header
*/
@property (nonatomic, copy) NSString *(^titleForHeaderInSectionBlock)(UITableView *tableView, NSUInteger section);
/**
* Gets/sets the block to execute when the collectionView requests a section footer
*/
@property (nonatomic, copy) NSString *(^titleForFooterInSectionBlock)(UITableView *tableView, NSUInteger section);
/**
* Gets/sets the block to execute when the collectionView requests whether or not a cell can be moved
*/
@property (nonatomic, copy) BOOL (^canMoveItemAtIndexPathBlock)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests whether or not a cell can be edited
*/
@property (nonatomic, copy) BOOL (^canEditItemAtIndexPathBlock)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView commits an editing action for a cell
*/
@property (nonatomic, copy) void (^commitEditingStyleForItemAtIndexPathBlock)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView moves a cell
*/
@property (nonatomic, copy) void (^moveItemAtSourceIndexPathToDestinationIndexPathBlock)(UITableView *tableView, NSIndexPath *sourceIndexPath, NSIndexPath *destinationIndexPath);
@end
| Java |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "CDStructures.h"
@interface _IDEKitPrivateClassForFindingBundle : NSObject
{
}
@end
| Java |
<html lang="en">
<head>
<title>C - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Supported-Languages.html#Supported-Languages" title="Supported Languages">
<link rel="next" href="D.html#D" title="D">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988-2017 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="C"></a>
Next: <a rel="next" accesskey="n" href="D.html#D">D</a>,
Up: <a rel="up" accesskey="u" href="Supported-Languages.html#Supported-Languages">Supported Languages</a>
<hr>
</div>
<h4 class="subsection">15.4.1 C and C<tt>++</tt></h4>
<p><a name="index-C-and-C_0040t_007b_002b_002b_007d-947"></a><a name="index-expressions-in-C-or-C_0040t_007b_002b_002b_007d-948"></a>
Since C and C<tt>++</tt> are so closely related, many features of <span class="sc">gdb</span> apply
to both languages. Whenever this is the case, we discuss those languages
together.
<p><a name="index-C_0040t_007b_002b_002b_007d-949"></a><a name="index-g_t_0040code_007bg_002b_002b_007d_002c-_0040sc_007bgnu_007d-C_0040t_007b_002b_002b_007d-compiler-950"></a><a name="index-g_t_0040sc_007bgnu_007d-C_0040t_007b_002b_002b_007d-951"></a>The C<tt>++</tt> debugging facilities are jointly implemented by the C<tt>++</tt>
compiler and <span class="sc">gdb</span>. Therefore, to debug your C<tt>++</tt> code
effectively, you must compile your C<tt>++</tt> programs with a supported
C<tt>++</tt> compiler, such as <span class="sc">gnu</span> <code>g++</code>, or the HP ANSI C<tt>++</tt>
compiler (<code>aCC</code>).
<ul class="menu">
<li><a accesskey="1" href="C-Operators.html#C-Operators">C Operators</a>: C and C<tt>++</tt> operators
<li><a accesskey="2" href="C-Constants.html#C-Constants">C Constants</a>: C and C<tt>++</tt> constants
<li><a accesskey="3" href="C-Plus-Plus-Expressions.html#C-Plus-Plus-Expressions">C Plus Plus Expressions</a>: C<tt>++</tt> expressions
<li><a accesskey="4" href="C-Defaults.html#C-Defaults">C Defaults</a>: Default settings for C and C<tt>++</tt>
<li><a accesskey="5" href="C-Checks.html#C-Checks">C Checks</a>: C and C<tt>++</tt> type and range checks
<li><a accesskey="6" href="Debugging-C.html#Debugging-C">Debugging C</a>: <span class="sc">gdb</span> and C
<li><a accesskey="7" href="Debugging-C-Plus-Plus.html#Debugging-C-Plus-Plus">Debugging C Plus Plus</a>: <span class="sc">gdb</span> features for C<tt>++</tt>
<li><a accesskey="8" href="Decimal-Floating-Point.html#Decimal-Floating-Point">Decimal Floating Point</a>: Numbers in Decimal Floating Point format
</ul>
</body></html>
| Java |
Answer these questions in your reflection:
What git concepts were you struggling with prior to the GPS session?
- Prior to the GPS session I was having trouble navigating between branches. I also was completely confused on remote and fetch. I thought that you could just use the command git pull which would fetch/merge in one.
What concepts were clarified during the GPS?
- Using git checkout moves between branches.
What questions did you ask your pair and the guide?
- I asked them questions on what was troubling me and that cleared things up. I am still a little fuzzy on fetch / remote but I know that will come with more practice. Git pull is also a compact way to fetch and merge in one.
What still confuses you about git?
- When using the remote I am still not completely sure on what it does. I will need to do more research and practice while I work on the HTML this week.
How was your first experience of pairing in a GPS?
- My first experience was great! I really enjoyed working with my partner and the guide had some great pointers. Once again my feelings toward DBC are getting better and better as the days go on. I am having a great time learning things that interest me. | Java |
#!/usr/bin/env python3
"""
Categorize and analyze user sessions.
Read in ecfs_obfuscated_filtered.gz file, output some fancy results.
"""
from collections import defaultdict
from collections import Counter
import sys
import time
import os
import resource
import json
import fnmatch
from pipes import Pipes
import operator
from operation import Operation
KB = 1024
MB = KB * 1024
GB = MB * 1024
TB = GB * 1024
PB = TB * 1024
MONITOR_LINES = 100000
class UserSession():
def __init__(self, user_id):
self.user_id = user_id
self.from_ts = 0
self.till_ts = 0
self.get_requests = 0
self.reget_requests = 0
self.put_requests = 0
self.get_bytes = 0
self.put_bytes = 0
self.rename_requests = 0
self.del_requests = 0
self.get_dirs = 0
self.put_dirs = 0
self.put_files_per_dir = 0.0
self.get_files_per_dir = 0.0
self.window_seconds = 0
self.file_cnt_gets = Counter()
self.file_cnt_puts = Counter()
self.dir_cnt_gets = Counter()
self.dir_cnt_puts = Counter()
self.num_ops = 0
self.last_ts = 0
def add_op(self, op):
self.num_ops += 1
if op.ts < self.last_ts:
raise Exception("Timestamp too old")
else:
self.last_ts = op.ts
if op.optype == 'g':
self.get_requests += 1
self.get_bytes += op.size
self.file_cnt_gets[op.obj_id] += 1
self.dir_cnt_gets[op.parent_dir_id] += 1
elif op.optype == 'p':
self.put_requests += 1
self.put_bytes += op.size
self.file_cnt_puts[op.obj_id] += 1
self.dir_cnt_puts[op.parent_dir_id] += 1
elif op.optype == 'd':
self.del_requests += 1
elif op.optype == 'r':
self.rename_requests += 1
#update last time stamp in the session
self.till_ts = op.ts + op.execution_time
def finish(self):
self.get_dirs = len(self.dir_cnt_gets)
if self.get_dirs > 0:
self.get_files_per_dir = float(self.get_requests) / self.get_dirs
self.put_dirs = len(self.dir_cnt_puts)
if self.put_dirs > 0:
self.put_files_per_dir = float(self.put_requests) / self.put_dirs
"""
set reget_counter
:param counter: contains [ 1, 1, 5] counts of objects. value > 1 is a re-retrieval.
:return:
"""
for c in self.file_cnt_gets.values():
if c > 1:
self.reget_requests += (c - 1)
# self.announce()
return ";".join([str(x) for x in [
self.user_id,
self.from_ts,
self.till_ts,
self.till_ts - self.from_ts,
self.get_requests,
self.reget_requests,
self.put_requests,
self.get_bytes,
self.put_bytes,
self.rename_requests,
self.del_requests,
self.get_dirs,
self.put_dirs,
self.put_files_per_dir,
self.get_files_per_dir,
self.window_seconds
]]
)
def announce(self):
print("closed session. gets: %r, regets: %r, puts: %r, dels: %r, renames: %r get_dirs: %r, put_dirs: %r, get_bytes: %r put_bytes: %r window_seconds: %d" % \
(self.get_requests, self.reget_requests, self.put_requests, self.del_requests, self.rename_requests, self.get_dirs, self.put_dirs, self.get_bytes, self.put_bytes, self.window_seconds))
def find_clusters(atimes):
foo = Counter()
bar = dict()
for i in xrange(120, 3660, 10):
clusters = get_clusters(atimes, i)
cs = len(clusters)
foo[cs] += 1
# note first occurance of this cluster size.
if cs not in bar:
bar[cs] = i
# print(len(atimes), i, cs)
return bar[foo.most_common()[0][0]]
def get_clusters(data, maxgap):
'''Arrange data into groups where successive elements
differ by no more than *maxgap*
>>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
[[1, 6, 9], [100, 102, 105, 109], [134, 139]]
>>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
[[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]
'''
data.sort()
groups = [[data[0]]]
for x in data[1:]:
if abs(x - groups[-1][-1]) <= maxgap:
groups[-1].append(x)
else:
groups.append([x])
return groups
def analyze_user_session(user_session_file, out_pipeline, target_file_name):
with open(user_session_file, 'r') as sf:
ops = list()
atimes = list()
for line in sf:
op = Operation()
op.init(line.strip())
ops.append(op)
atimes.append(op.ts)
ops.sort(key=operator.attrgetter('ts'))
atimes.sort()
window_seconds = find_clusters(atimes)
session_counter = 1
uf = os.path.basename(user_session_file)
user_id = uf[:uf.find(".user_session.csv")]
session = UserSession(user_id)
session.window_seconds = window_seconds
for op in ops:
if session.from_ts == 0:
session.from_ts = op.ts
session.till_ts = op.ts + op.execution_time
if (session.till_ts + window_seconds) < op.ts:
# this session is over, so archive it.
out_pipeline.write_to(target_file_name, session.finish())
del session
session = UserSession(user_id)
session.window_seconds = window_seconds
session_counter += 1
session.add_op(op)
if session.num_ops > 0:
out_pipeline.write_to(target_file_name, session.finish())
print("sessions: %d with window_seconds: %d" %(session_counter, window_seconds))
if __name__ == "__main__":
source_dir = os.path.abspath(sys.argv[1])
result = os.path.abspath(sys.argv[2])
results_dir = os.path.dirname(result)
target_file_name = os.path.basename(result)
users_session_files = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(source_dir)
for f in fnmatch.filter(files, '*.user_session.csv')]
#remove the old log file, as outpipe is append only.
if os.path.exists(os.path.join(results_dir, target_file_name)):
os.remove(os.path.join(results_dir, target_file_name))
out_pipe = Pipes(results_dir)
csv_header = ";".join(["user_id",
"from_ts",
"till_ts",
"session_lifetime",
"get_requests",
"reget_requests",
"put_requests",
"get_bytes",
"put_bytes",
"rename_requests",
"del_requests",
"get_dirs",
"put_dirs",
"put_files_per_dir",
"get_files_per_dir",
"window_seconds"
])
out_pipe.write_to(target_file_name, csv_header)
cnt = 0
for sf in users_session_files:
cnt += 1
print ("working on %d/%d" % (cnt, len(users_session_files)))
analyze_user_session(sf, out_pipe, target_file_name)
# if cnt >=20:
# break
out_pipe.close()
print("wrote results to %s: " % (os.path.join(results_dir, target_file_name)))
| Java |
package esl
import (
"io"
"errors"
"unicode/utf8"
)
// Buffer ...
type buffer []byte
// MemoryReader ...
type memReader [ ]byte
// MemoryWriter ...
type memWriter [ ]byte
// ErrBufferSize indicates that memory cannot be allocated to store data in a buffer.
var ErrBufferSize = errors.New(`could not allocate memory`)
func newBuffer( size int ) *buffer {
buf := make([ ]byte, 0, size )
return (*buffer)(&buf)
}
func ( buf *buffer ) reader( ) *memReader {
n := len( *buf )
rbuf := ( *buf )[:n:n]
return ( *memReader )( &rbuf )
}
func ( buf *buffer ) writer( ) *memWriter {
return ( *memWriter )( buf )
}
func ( buf *buffer ) grow( n int ) error {
if ( len( *buf )+ n ) > cap( *buf ) {
// Not enough space to store [:+(n)]byte(s)
mbuf, err := makebuf( cap( *buf )+ n )
if ( err != nil ) {
return ( err )
}
copy( mbuf, *buf )
*( buf ) = mbuf
}
return nil
}
// allocates a byte slice of size.
// If the allocation fails, returns error
// indicating that memory cannot be allocated to store data in a buffer.
func makebuf( size int ) ( buf [ ]byte, memerr error ) {
defer func( ) {
// If the make fails, give a known error.
if ( recover( ) != nil ) {
( memerr ) = ErrBufferSize
}
}( )
return make( [ ]byte, 0, size ), nil
}
func ( buf *memReader ) Read( b [ ]byte ) ( n int, err error ) {
if len( *buf ) == 0 {
return ( 0 ), io.EOF
}
n, *buf = copy( b, *buf ), ( *buf )[ n: ]
return // n, nil
}
func ( buf *memReader ) ReadByte( ) ( c byte, err error ) {
if len(*buf) == 0 {
return ( 0 ), io.EOF
}
c, *buf = (*buf)[0], (*buf)[1:]
return // c, nil
}
func ( buf *memReader ) ReadRune( ) ( r rune, size int, err error ) {
if len(*buf) == 0 {
return 0, 0, io.EOF
}
r, size = utf8.DecodeRune(*buf)
*buf = (*buf)[size:]
return // r, size, nil
}
func ( buf *memReader ) WriteTo( w io.Writer ) ( n int64, err error ) {
for len( *buf ) > 0 {
rw, err := w.Write( *buf )
if ( rw > 0 ) {
n, *buf = n + int64( rw ), (*buf)[rw:]
}
if ( err != nil ) {
return n, err
}
}
return ( 0 ), io.EOF
}
func ( buf *memWriter ) Write( b []byte ) ( n int, err error ) {
*buf = append( *buf, b...)
return len( b ), nil
}
func ( buf *memWriter ) WriteByte( c byte ) error {
*buf = append( *buf, c )
return ( nil )
}
func ( buf *memWriter ) WriteRune( r rune ) error {
if ( r < utf8.RuneSelf ) {
return buf.WriteByte( byte( r ))
}
b := *buf
n := len( b )
if ( n + utf8.UTFMax ) > cap( b ) {
b = make( []byte, ( n + utf8.UTFMax ))
copy( b, *buf )
}
w := utf8.EncodeRune( b[ n:( n + utf8.UTFMax )], r )
*buf = b[ :( n + w )]
return nil
}
func ( buf *memWriter ) WriteString( s string ) ( n int, err error ) {
*buf = append( *buf, s...)
return len( s ), nil
}
// func (buf *memWriter) ReadFrom(r io.Reader) (n int64, err error) {
// // NOTE: indefinite allocation! Try to use io.WriterTo interface!
// } | Java |
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double Pods_WZYUnlimitedScrollViewDemoVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_WZYUnlimitedScrollViewDemoVersionString[];
| Java |
package com.zimbra.cs.versioncheck;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.ServerBy;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.soap.SoapTransport;
import com.zimbra.common.util.CliUtil;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.client.LmcSession;
import com.zimbra.cs.client.soap.LmcSoapClientException;
import com.zimbra.cs.client.soap.LmcVersionCheckRequest;
import com.zimbra.cs.client.soap.LmcVersionCheckResponse;
import com.zimbra.cs.util.BuildInfo;
import com.zimbra.cs.util.SoapCLI;
import com.zimbra.common.util.DateUtil;
/**
* @author Greg Solovyev
*/
public class VersionCheckUtil extends SoapCLI {
private static final String OPT_CHECK_VERSION = "c";
private static final String OPT_MANUAL_CHECK_VERSION = "m";
private static final String SHOW_LAST_STATUS = "r";
protected VersionCheckUtil() throws ServiceException {
super();
}
public static void main(String[] args) {
CliUtil.toolSetup();
SoapTransport.setDefaultUserAgent("zmcheckversion", BuildInfo.VERSION);
VersionCheckUtil util = null;
try {
util = new VersionCheckUtil();
} catch (ServiceException e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
util.setupCommandLineOptions();
CommandLine cl = null;
try {
cl = util.getCommandLine(args);
} catch (ParseException e) {
System.out.println(e.getMessage());
util.usage();
System.exit(1);
}
if (cl == null) {
System.exit(1);
}
if (cl.hasOption(OPT_CHECK_VERSION)) {
//check schedule
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
String updaterServerId = config.getAttr(Provisioning.A_zimbraVersionCheckServer);
if (updaterServerId != null) {
Server server = prov.get(Key.ServerBy.id, updaterServerId);
if (server != null) {
Server localServer = prov.getLocalServer();
if (localServer!=null) {
if(!localServer.getId().equalsIgnoreCase(server.getId())) {
System.out.println("Wrong server");
System.exit(0);
}
}
}
}
String versionInterval = config.getAttr(Provisioning.A_zimbraVersionCheckInterval);
if(versionInterval == null || versionInterval.length()==0 || versionInterval.equalsIgnoreCase("0")) {
System.out.println("Automatic updates are disabled");
System.exit(0);
} else {
long checkInterval = DateUtil.getTimeIntervalSecs(versionInterval,0);
String lastAttempt = config.getAttr(Provisioning.A_zimbraVersionCheckLastAttempt);
if(lastAttempt != null) {
Date lastChecked = DateUtil.parseGeneralizedTime(config.getAttr(Provisioning.A_zimbraVersionCheckLastAttempt));
Date now = new Date();
if (now.getTime()/1000- lastChecked.getTime()/1000 >= checkInterval) {
util.doVersionCheck();
} else {
System.out.println("Too early");
System.exit(0);
}
} else {
util.doVersionCheck();
}
}
} else if (cl.hasOption(OPT_MANUAL_CHECK_VERSION)) {
util.doVersionCheck();
} else if (cl.hasOption(SHOW_LAST_STATUS)) {
util.doResult();
System.exit(0);
} else {
util.usage();
System.exit(1);
}
} catch (Exception e) {
System.err.println(e.getMessage());
ZimbraLog.extensions.error("Error in versioncheck util", e);
util.usage(null);
System.exit(1);
}
}
private void doVersionCheck() throws SoapFaultException, IOException, ServiceException, LmcSoapClientException {
LmcSession session = auth();
LmcVersionCheckRequest req = new LmcVersionCheckRequest();
req.setAction(AdminConstants.VERSION_CHECK_CHECK);
req.setSession(session);
req.invoke(getServerUrl());
}
private void doResult() throws SoapFaultException, IOException, ServiceException, LmcSoapClientException {
try {
LmcSession session = auth();
LmcVersionCheckRequest req = new LmcVersionCheckRequest();
req.setAction(AdminConstants.VERSION_CHECK_STATUS);
req.setSession(session);
LmcVersionCheckResponse res = (LmcVersionCheckResponse) req.invoke(getServerUrl());
List <VersionUpdate> updates = res.getUpdates();
for(Iterator <VersionUpdate> iter = updates.iterator();iter.hasNext();){
VersionUpdate update = iter.next();
String critical;
if(update.isCritical()) {
critical = "critical";
} else {
critical = "not critical";
}
System.out.println(
String.format("Found a %s update. Update is %s . Update version: %s. For more info visit: %s",
update.getType(),critical,update.getVersion(),update.getUpdateURL())
);
}
} catch (SoapFaultException soape) {
System.out.println("Cought SoapFaultException");
System.out.println(soape.getStackTrace().toString());
throw (soape);
} catch (LmcSoapClientException lmce) {
System.out.println("Cought LmcSoapClientException");
System.out.println(lmce.getStackTrace().toString());
throw (lmce);
} catch (ServiceException se) {
System.out.println("Cought ServiceException");
System.out.println(se.getStackTrace().toString());
throw (se);
} catch (IOException ioe) {
System.out.println("Cought IOException");
System.out.println(ioe.getStackTrace().toString());
throw (ioe);
}
}
protected void setupCommandLineOptions() {
// super.setupCommandLineOptions();
Options options = getOptions();
Options hiddenOptions = getHiddenOptions();
hiddenOptions.addOption(OPT_CHECK_VERSION, "autocheck", false, "Initiate version check request (exits if zimbraVersionCheckInterval==0)");
options.addOption(SHOW_LAST_STATUS, "result", false, "Show results of last version check.");
options.addOption(OPT_MANUAL_CHECK_VERSION, "manual", false, "Initiate version check request.");
}
protected String getCommandUsage() {
return "zmcheckversion <options>";
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeFinder.Models
{
public enum Position
{
Bartender,
Waiter,
Bellboy,
Receptionist,
Manager,
Housekeeper,
Chef,
Manintanace
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain
{
public class Meeting
{
public int ConsultantId { get; set; }
public Consultant Consultant { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public DateTime BeginTime { get; set; }
public DateTime EndTime { get; set; }
public override string ToString()
{
return $"{BeginTime} -> {EndTime}";
}
}
}
| Java |
module PiwikAnalytics
module Helpers
def piwik_tracking_tag
config = PiwikAnalytics.configuration
return if config.disabled?
if config.use_async?
file = "piwik_analytics/piwik_tracking_tag_async"
else
file = "piwik_analytics/piwik_tracking_tag"
end
render({
:file => file,
:locals => {:url => config.url, :id_site => config.id_site}
})
end
end
end
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author Stephan Reith
@date 31.08.2016
This is a simple example to demonstrate how the ROS Spinnaker Interface can be used.
You will also need a ROS Listener and a ROS Talker to send and receive data.
Make sure they communicate over the same ROS topics and std_msgs.Int64 ROS Messages used in here.
"""
import spynnaker.pyNN as pynn
from ros_spinnaker_interface import ROS_Spinnaker_Interface
# import transfer_functions as tf
from ros_spinnaker_interface import SpikeSourcePoisson
from ros_spinnaker_interface import SpikeSinkSmoothing
ts = 0.1
n_neurons = 1
simulation_time = 10000 # ms
pynn.setup(timestep=ts, min_delay=ts, max_delay=2.0*ts)
pop = pynn.Population(size=n_neurons, cellclass=pynn.IF_curr_exp, cellparams={}, label='pop')
# The ROS_Spinnaker_Interface just needs to be initialised. The following parameters are possible:
ros_interface = ROS_Spinnaker_Interface(
n_neurons_source=n_neurons, # number of neurons of the injector population
Spike_Source_Class=SpikeSourcePoisson, # the transfer function ROS Input -> Spikes you want to use.
Spike_Sink_Class=SpikeSinkSmoothing, # the transfer function Spikes -> ROS Output you want to use.
# You can choose from the transfer_functions module
# or write one yourself.
output_population=pop, # the pynn population you wish to receive the
# live spikes from.
ros_topic_send='to_spinnaker', # the ROS topic used for the incoming ROS values.
ros_topic_recv='from_spinnaker', # the ROS topic used for the outgoing ROS values.
clk_rate=1000, # mainloop clock (update) rate in Hz.
ros_output_rate=10) # number of ROS messages send out per second.
# Build your network, run the simulation and optionally record the spikes and voltages.
pynn.Projection(ros_interface, pop, pynn.OneToOneConnector(weights=5, delays=1))
pop.record()
pop.record_v()
pynn.run(simulation_time)
spikes = pop.getSpikes()
pynn.end()
# Plot
import pylab
spike_times = [spike[1] for spike in spikes]
spike_ids = [spike[0] for spike in spikes]
pylab.plot(spike_times, spike_ids, ".")
pylab.xlabel('Time (ms)')
pylab.ylabel('Neuron ID')
pylab.title('Spike Plot')
pylab.xlim(xmin=0)
pylab.show()
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>area-method: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / area-method - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
area-method
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-04 18:52:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-04 18:52:19 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/area-method"
license: "Proprietary"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/AreaMethod"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:geometry" "keyword:chou gao zhang area method" "keyword:decision procedure" "category:Mathematics/Geometry/AutomatedDeduction" "date:2004-2010" ]
authors: [ "Julien Narboux <>" ]
bug-reports: "https://github.com/coq-contribs/area-method/issues"
dev-repo: "git+https://github.com/coq-contribs/area-method.git"
synopsis: "The Chou, Gao and Zhang area method"
description: """
This contribution is the implementation of the Chou, Gao and Zhang's area method decision procedure for euclidean plane geometry.
This development contains a partial formalization of the book "Machine Proofs in Geometry, Automated Production of Readable Proofs for Geometry Theorems" by Chou, Gao and Zhang.
The examples shown automatically (there are more than 100 examples) includes the Ceva, Desargues, Menelaus, Pascal, Centroïd, Pappus, Gauss line, Euler line, Napoleon theorems.
Changelog
2.1 : remove some not needed assumptions in some elimination lemmas (2010)
2.0 : extension implementation to Euclidean geometry (2009-2010)
1.0 : first implementation for affine geometry (2004)"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/area-method/archive/v8.5.0.tar.gz"
checksum: "md5=ba9772aa2056aa4bc9ccc051a9a76a7f"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-area-method.8.5.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-area-method -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-area-method.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ieee754: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.1 / ieee754 - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
ieee754
<small>
8.7.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-24 17:47:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-24 17:47:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.9.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/ieee754"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/IEEE754"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: floating-point arithmetic" "keyword: floats" "keyword: IEEE" "category: Computer Science/Data Types and Data Structures" "category: Computer Science/Semantics and Compilation/Semantics" "date: 1997" ]
authors: [ "Patrick Loiseleur" ]
bug-reports: "https://github.com/coq-contribs/ieee754/issues"
dev-repo: "git+https://github.com/coq-contribs/ieee754.git"
synopsis: "A formalisation of the IEEE754 norm on floating-point arithmetic"
description: """
This library contains a non-verified implementation of
binary floating-point addition and multiplication operators inspired
by the IEEE-754 standard. It is today outdated.
See the attached 1997 report rapport-stage-dea.ps.gz for a discussion
(in French) of this work.
For the state of the art at the time of updating this notice, see
e.g. "Flocq: A Unified Library for Proving Floating-point Algorithms
in Coq" by S. Boldo and G. Melquiond, 2011."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/ieee754/archive/v8.7.0.tar.gz"
checksum: "md5=c79fabb9831e0231bc5ce75f3be6aad7"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-ieee754.8.7.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1).
The following dependencies couldn't be met:
- coq-ieee754 -> coq < 8.8~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ieee754.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| Java |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, templateSourceUrl} from './compile_metadata';
import {CompilerConfig, preserveWhitespacesDefault} from './config';
import {ViewEncapsulation} from './core';
import * as html from './ml_parser/ast';
import {HtmlParser} from './ml_parser/html_parser';
import {InterpolationConfig} from './ml_parser/interpolation_config';
import {ParseTreeResult as HtmlParseTreeResult} from './ml_parser/parser';
import {ResourceLoader} from './resource_loader';
import {extractStyleUrls, isStyleUrlResolvable} from './style_url_resolver';
import {PreparsedElementType, preparseElement} from './template_parser/template_preparser';
import {UrlResolver} from './url_resolver';
import {isDefined, stringify, SyncAsync, syntaxError} from './util';
export interface PrenormalizedTemplateMetadata {
ngModuleType: any;
componentType: any;
moduleUrl: string;
template: string|null;
templateUrl: string|null;
styles: string[];
styleUrls: string[];
interpolation: [string, string]|null;
encapsulation: ViewEncapsulation|null;
animations: any[];
preserveWhitespaces: boolean|null;
}
export class DirectiveNormalizer {
private _resourceLoaderCache = new Map<string, SyncAsync<string>>();
constructor(
private _resourceLoader: ResourceLoader, private _urlResolver: UrlResolver,
private _htmlParser: HtmlParser, private _config: CompilerConfig) {}
clearCache(): void {
this._resourceLoaderCache.clear();
}
clearCacheFor(normalizedDirective: CompileDirectiveMetadata): void {
if (!normalizedDirective.isComponent) {
return;
}
const template = normalizedDirective.template !;
this._resourceLoaderCache.delete(template.templateUrl!);
template.externalStylesheets.forEach((stylesheet) => {
this._resourceLoaderCache.delete(stylesheet.moduleUrl!);
});
}
private _fetch(url: string): SyncAsync<string> {
let result = this._resourceLoaderCache.get(url);
if (!result) {
result = this._resourceLoader.get(url);
this._resourceLoaderCache.set(url, result);
}
return result;
}
normalizeTemplate(prenormData: PrenormalizedTemplateMetadata):
SyncAsync<CompileTemplateMetadata> {
if (isDefined(prenormData.template)) {
if (isDefined(prenormData.templateUrl)) {
throw syntaxError(`'${
stringify(prenormData
.componentType)}' component cannot define both template and templateUrl`);
}
if (typeof prenormData.template !== 'string') {
throw syntaxError(`The template specified for component ${
stringify(prenormData.componentType)} is not a string`);
}
} else if (isDefined(prenormData.templateUrl)) {
if (typeof prenormData.templateUrl !== 'string') {
throw syntaxError(`The templateUrl specified for component ${
stringify(prenormData.componentType)} is not a string`);
}
} else {
throw syntaxError(
`No template specified for component ${stringify(prenormData.componentType)}`);
}
if (isDefined(prenormData.preserveWhitespaces) &&
typeof prenormData.preserveWhitespaces !== 'boolean') {
throw syntaxError(`The preserveWhitespaces option for component ${
stringify(prenormData.componentType)} must be a boolean`);
}
return SyncAsync.then(
this._preParseTemplate(prenormData),
(preparsedTemplate) => this._normalizeTemplateMetadata(prenormData, preparsedTemplate));
}
private _preParseTemplate(prenomData: PrenormalizedTemplateMetadata):
SyncAsync<PreparsedTemplate> {
let template: SyncAsync<string>;
let templateUrl: string;
if (prenomData.template != null) {
template = prenomData.template;
templateUrl = prenomData.moduleUrl;
} else {
templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl!);
template = this._fetch(templateUrl);
}
return SyncAsync.then(
template, (template) => this._preparseLoadedTemplate(prenomData, template, templateUrl));
}
private _preparseLoadedTemplate(
prenormData: PrenormalizedTemplateMetadata, template: string,
templateAbsUrl: string): PreparsedTemplate {
const isInline = !!prenormData.template;
const interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation!);
const templateUrl = templateSourceUrl(
{reference: prenormData.ngModuleType}, {type: {reference: prenormData.componentType}},
{isInline, templateUrl: templateAbsUrl});
const rootNodesAndErrors = this._htmlParser.parse(
template, templateUrl, {tokenizeExpansionForms: true, interpolationConfig});
if (rootNodesAndErrors.errors.length > 0) {
const errorString = rootNodesAndErrors.errors.join('\n');
throw syntaxError(`Template parse errors:\n${errorString}`);
}
const templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata(
{styles: prenormData.styles, moduleUrl: prenormData.moduleUrl}));
const visitor = new TemplatePreparseVisitor();
html.visitAll(visitor, rootNodesAndErrors.rootNodes);
const templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata(
{styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl}));
const styles = templateMetadataStyles.styles.concat(templateStyles.styles);
const inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
const styleUrls = this
._normalizeStylesheet(new CompileStylesheetMetadata(
{styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl}))
.styleUrls;
return {
template,
templateUrl: templateAbsUrl,
isInline,
htmlAst: rootNodesAndErrors,
styles,
inlineStyleUrls,
styleUrls,
ngContentSelectors: visitor.ngContentSelectors,
};
}
private _normalizeTemplateMetadata(
prenormData: PrenormalizedTemplateMetadata,
preparsedTemplate: PreparsedTemplate): SyncAsync<CompileTemplateMetadata> {
return SyncAsync.then(
this._loadMissingExternalStylesheets(
preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)),
(externalStylesheets) => this._normalizeLoadedTemplateMetadata(
prenormData, preparsedTemplate, externalStylesheets));
}
private _normalizeLoadedTemplateMetadata(
prenormData: PrenormalizedTemplateMetadata, preparsedTemplate: PreparsedTemplate,
stylesheets: Map<string, CompileStylesheetMetadata>): CompileTemplateMetadata {
// Algorithm:
// - produce exactly 1 entry per original styleUrl in
// CompileTemplateMetadata.externalStylesheets with all styles inlined
// - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
// Reason: be able to determine how many stylesheets there are even without loading
// the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
// (as resource loading may be async)
const styles = [...preparsedTemplate.styles];
this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
const styleUrls = preparsedTemplate.styleUrls;
const externalStylesheets = styleUrls.map(styleUrl => {
const stylesheet = stylesheets.get(styleUrl)!;
const styles = [...stylesheet.styles];
this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
return new CompileStylesheetMetadata({moduleUrl: styleUrl, styles: styles});
});
let encapsulation = prenormData.encapsulation;
if (encapsulation == null) {
encapsulation = this._config.defaultEncapsulation;
}
if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
styleUrls.length === 0) {
encapsulation = ViewEncapsulation.None;
}
return new CompileTemplateMetadata({
encapsulation,
template: preparsedTemplate.template,
templateUrl: preparsedTemplate.templateUrl,
htmlAst: preparsedTemplate.htmlAst,
styles,
styleUrls,
ngContentSelectors: preparsedTemplate.ngContentSelectors,
animations: prenormData.animations,
interpolation: prenormData.interpolation,
isInline: preparsedTemplate.isInline,
externalStylesheets,
preserveWhitespaces: preserveWhitespacesDefault(
prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
});
}
private _inlineStyles(
styleUrls: string[], stylesheets: Map<string, CompileStylesheetMetadata>,
targetStyles: string[]) {
styleUrls.forEach(styleUrl => {
const stylesheet = stylesheets.get(styleUrl)!;
stylesheet.styles.forEach(style => targetStyles.push(style));
this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
});
}
private _loadMissingExternalStylesheets(
styleUrls: string[],
loadedStylesheets:
Map<string, CompileStylesheetMetadata> = new Map<string, CompileStylesheetMetadata>()):
SyncAsync<Map<string, CompileStylesheetMetadata>> {
return SyncAsync.then(
SyncAsync.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
.map(
styleUrl => SyncAsync.then(
this._fetch(styleUrl),
(loadedStyle) => {
const stylesheet =
this._normalizeStylesheet(new CompileStylesheetMetadata(
{styles: [loadedStyle], moduleUrl: styleUrl}));
loadedStylesheets.set(styleUrl, stylesheet);
return this._loadMissingExternalStylesheets(
stylesheet.styleUrls, loadedStylesheets);
}))),
(_) => loadedStylesheets);
}
private _normalizeStylesheet(stylesheet: CompileStylesheetMetadata): CompileStylesheetMetadata {
const moduleUrl = stylesheet.moduleUrl!;
const allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
.map(url => this._urlResolver.resolve(moduleUrl, url));
const allStyles = stylesheet.styles.map(style => {
const styleWithImports = extractStyleUrls(this._urlResolver, moduleUrl, style);
allStyleUrls.push(...styleWithImports.styleUrls);
return styleWithImports.style;
});
return new CompileStylesheetMetadata(
{styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl});
}
}
interface PreparsedTemplate {
template: string;
templateUrl: string;
isInline: boolean;
htmlAst: HtmlParseTreeResult;
styles: string[];
inlineStyleUrls: string[];
styleUrls: string[];
ngContentSelectors: string[];
}
class TemplatePreparseVisitor implements html.Visitor {
ngContentSelectors: string[] = [];
styles: string[] = [];
styleUrls: string[] = [];
ngNonBindableStackCount: number = 0;
visitElement(ast: html.Element, context: any): any {
const preparsedElement = preparseElement(ast);
switch (preparsedElement.type) {
case PreparsedElementType.NG_CONTENT:
if (this.ngNonBindableStackCount === 0) {
this.ngContentSelectors.push(preparsedElement.selectAttr);
}
break;
case PreparsedElementType.STYLE:
let textContent = '';
ast.children.forEach(child => {
if (child instanceof html.Text) {
textContent += child.value;
}
});
this.styles.push(textContent);
break;
case PreparsedElementType.STYLESHEET:
this.styleUrls.push(preparsedElement.hrefAttr);
break;
default:
break;
}
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount++;
}
html.visitAll(this, ast.children);
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount--;
}
return null;
}
visitExpansion(ast: html.Expansion, context: any): any {
html.visitAll(this, ast.cases);
}
visitExpansionCase(ast: html.ExpansionCase, context: any): any {
html.visitAll(this, ast.expression);
}
visitComment(ast: html.Comment, context: any): any {
return null;
}
visitAttribute(ast: html.Attribute, context: any): any {
return null;
}
visitText(ast: html.Text, context: any): any {
return null;
}
}
| Java |
<?php
/* TwigBundle:Exception:error.atom.twig */
class __TwigTemplate_405349459f7f2e8922747537b1c12aa2323bb61b0265aaf549db7e51eafd66f4 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->env->loadTemplate("TwigBundle:Exception:error.xml.twig")->display(array_merge($context, array("exception" => (isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")))));
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.atom.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 19 => 1, 79 => 21, 72 => 13, 69 => 12, 47 => 18, 40 => 11, 37 => 10, 22 => 1, 246 => 32, 157 => 56, 145 => 46, 139 => 45, 131 => 42, 123 => 41, 120 => 40, 115 => 39, 111 => 38, 108 => 37, 101 => 33, 98 => 32, 96 => 31, 83 => 25, 74 => 14, 66 => 11, 55 => 16, 52 => 21, 50 => 14, 43 => 9, 41 => 8, 35 => 9, 32 => 4, 29 => 6, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 70, 182 => 68, 176 => 64, 173 => 63, 168 => 62, 164 => 58, 162 => 57, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 42, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 35, 109 => 34, 106 => 36, 103 => 32, 99 => 30, 95 => 28, 92 => 29, 86 => 24, 82 => 22, 80 => 24, 73 => 19, 64 => 19, 60 => 6, 57 => 12, 54 => 22, 51 => 10, 48 => 9, 45 => 17, 42 => 16, 39 => 6, 36 => 5, 33 => 4, 30 => 3,);
}
}
| Java |
<HTML>
<!-- Created by HTTrack Website Copier/3.49-2 [XR&CO'2014] -->
<!-- Mirrored from thevillagedanang.com/?p=62 by HTTrack Website Copier/3.x [XR&CO'2014], Thu, 02 Nov 2017 14:46:03 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack -->
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=about-us/index.html"><TITLE>Page has moved</TITLE>
</HEAD>
<BODY>
<A HREF="about-us/index.html"><h3>Click here...</h3></A>
</BODY>
<!-- Created by HTTrack Website Copier/3.49-2 [XR&CO'2014] -->
<!-- Mirrored from thevillagedanang.com/?p=62 by HTTrack Website Copier/3.x [XR&CO'2014], Thu, 02 Nov 2017 14:46:03 GMT -->
</HTML>
| Java |
/**
* HTTP.test
*/
"use strict";
/* Node modules */
/* Third-party modules */
var steeplejack = require("steeplejack");
/* Files */
describe("HTTPError test", function () {
var HTTPError;
beforeEach(function () {
injector(function (_HTTPError_) {
HTTPError = _HTTPError_;
});
});
describe("Instantation tests", function () {
it("should extend the steeplejack Fatal exception", function () {
var obj = new HTTPError("text");
expect(obj).to.be.instanceof(HTTPError)
.to.be.instanceof(steeplejack.Exceptions.Fatal);
expect(obj.type).to.be.equal("HTTPError");
expect(obj.message).to.be.equal("text");
expect(obj.httpCode).to.be.equal(500);
expect(obj.getHttpCode()).to.be.equal(500);
});
it("should set the HTTP code in the first input", function () {
var obj = new HTTPError(401);
expect(obj.httpCode).to.be.equal(401);
expect(obj.getHttpCode()).to.be.equal(401);
});
});
});
| Java |
require File.join(File.dirname(__FILE__), './scribd-carrierwave/version')
require File.join(File.dirname(__FILE__), './scribd-carrierwave/config')
require 'carrierwave'
require 'rscribd'
require 'configatron'
module ScribdCarrierWave
class << self
def included(base)
base.extend ClassMethods
end
def upload uploader
file_path = full_path(uploader)
args = { file: file_path, access: ( uploader.class.public? ? 'public' : 'private' )}
type = File.extname(file_path)
if type
type = type.gsub(/^\./, '').gsub(/\?.*$/, '')
args.merge!(type: type) if type != ''
end
scribd_user.upload(args)
end
def destroy uploader
document = scribd_user.find_document(uploader.ipaper_id) rescue nil
document.destroy if !document.nil?
end
def load_ipaper_document(id)
scribd_user.find_document(id) rescue nil
end
def full_path uploader
if uploader.url =~ /^http(s?):\/\//
uploader.url
else
uploader.root + uploader.url
end
end
module ClassMethods
def public?
@public
end
def has_ipaper(public = false)
include InstanceMethods
after :store, :upload_to_scribd
before :remove, :delete_from_scribd
@public = !!public
end
end
module InstanceMethods
def self.included(base)
base.extend ClassMethods
end
def upload_to_scribd files
res = ScribdCarrierWave::upload(self)
set_params res
end
def delete_from_scribd
ScribdCarrierWave::destroy(self)
end
def display_ipaper(options = {})
id = options.delete(:id)
<<-END
<script type="text/javascript" src="//www.scribd.com/javascripts/scribd_api.js"></script>
<div id="embedded_doc#{id}">#{options.delete(:alt)}</div>
<script type="text/javascript">
var scribd_doc = scribd.Document.getDoc(#{ipaper_id}, '#{ipaper_access_key}');
scribd_doc.addParam( 'jsapi_version', 2 );
#{options.map do |k,v|
" scribd_doc.addParam('#{k.to_s}', #{v.is_a?(String) ? "'#{v.to_s}'" : v.to_s});"
end.join("\n")}
scribd_doc.write("embedded_doc#{id}");
</script>
END
end
def fullscreen_url
"http://www.scribd.com/fullscreen/#{ipaper_id}?access_key=#{ipaper_access_key}"
end
def ipaper_id
self.model.send("#{self.mounted_as.to_s}_ipaper_id")
end
def ipaper_access_key
self.model.send("#{self.mounted_as.to_s}_ipaper_access_key")
end
# Responds the Scribd::Document associated with this model, or nil if it does not exist.
def ipaper_document
@document ||= ScribdCarrierWave::load_ipaper_document(ipaper_id)
end
private
def set_params res
self.model.update_attributes({"#{self.mounted_as}_ipaper_id" => res.doc_id,
"#{self.mounted_as}_ipaper_access_key" => res.access_key})
end
end
private
def scribd_user
Scribd::API.instance.key = ScribdCarrierWave.config.key
Scribd::API.instance.secret = ScribdCarrierWave.config.secret
@scribd_user = Scribd::User.login(ScribdCarrierWave.config.username, ScribdCarrierWave.config.password)
end
end
end
CarrierWave::Uploader::Base.send(:include, ScribdCarrierWave) if Object.const_defined?("CarrierWave")
| Java |
var gulp = require('gulp');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var merge = require('merge-stream');
var stylus = require('gulp-stylus');
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var cssmin = require("gulp-cssmin");
var ngAnnotate = require('gulp-ng-annotate');
var nib = require("nib");
var watch = require('gulp-watch');
function compileJs(devOnly) {
var othersUmd = gulp.src(['src/**/*.js', '!src/main.js'])
.pipe(babel({
modules: 'umdStrict',
moduleRoot: 'angular-chatbar',
moduleIds: true
})),
mainUmd = gulp.src('src/main.js')
.pipe(babel({
modules: 'umdStrict',
moduleIds: true,
moduleId: 'angular-chatbar'
})),
stream = merge(othersUmd, mainUmd)
.pipe(concat('angular-chatbar.umd.js'))
.pipe(gulp.dest('dist'))
;
if (!devOnly) {
stream = stream
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(rename('angular-chatbar.umd.min.js'))
.pipe(gulp.dest('dist'));
}
return stream;
}
function compileCss(name, devOnly) {
var stream = gulp.src('styles/' + name + '.styl')
.pipe(stylus({use: nib()}))
.pipe(rename('angular-' + name + '.css'))
.pipe(gulp.dest('dist'))
;
if (!devOnly) {
stream = stream.pipe(cssmin())
.pipe(rename('angular-' + name + '.min.css'))
.pipe(gulp.dest('dist'));
}
return stream;
}
function compileAllCss(devOnly) {
var streams = [];
['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) {
streams.push(compileCss(name, devOnly));
});
return merge.apply(null, streams);
}
gulp.task('default', function() {
return merge.apply(compileJs(), compileAllCss());
});
gulp.task('_watch', function() {
watch('styles/**/*.styl', function () {
compileAllCss(true);
});
watch('src/**/*.js', function () {
compileJs(true);
});
});
gulp.task('watch', ['default', '_watch']);
| Java |
# -*- coding: utf-8 -*-
""" Resource Import Tools
@copyright: 2011-12 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
# @todo: remove all interactive error reporting out of the _private methods, and raise exceptions instead.
__all__ = ["S3Importer", "S3ImportJob", "S3ImportItem"]
import os
import sys
import cPickle
import tempfile
from datetime import datetime
from copy import deepcopy
try:
from cStringIO import StringIO # Faster, where available
except:
from StringIO import StringIO
try:
from lxml import etree
except ImportError:
print >> sys.stderr, "ERROR: lxml module needed for XML handling"
raise
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json # try external module
except:
import gluon.contrib.simplejson as json # fallback to pure-Python module
from gluon import *
from gluon.serializers import json as jsons
from gluon.storage import Storage, Messages
from gluon.tools import callback
from s3utils import SQLTABLES3
from s3crud import S3CRUD
from s3xml import S3XML
from s3utils import s3_mark_required, s3_has_foreign_key, s3_get_foreign_key
DEBUG = False
if DEBUG:
print >> sys.stderr, "S3IMPORTER: DEBUG MODE"
def _debug(m):
print >> sys.stderr, m
else:
_debug = lambda m: None
# =============================================================================
class S3Importer(S3CRUD):
"""
Transformable formats (XML, JSON, CSV) import handler
"""
UPLOAD_TABLE_NAME = "s3_import_upload"
# -------------------------------------------------------------------------
def apply_method(self, r, **attr):
"""
Apply CRUD methods
@param r: the S3Request
@param attr: dictionary of parameters for the method handler
@returns: output object to send to the view
Known means of communicating with this module:
It expects a URL of the form: /prefix/name/import
It will interpret the http requests as follows:
GET will trigger the upload
POST will trigger either commits or display the import details
DELETE will trigger deletes
It will accept one of the following control vars:
item: to specify a single item in the import job
job: to specify a job
It should not receive both so job takes precedent over item
For CSV imports, the calling controller can add extra fields
to the upload form to add columns to each row in the CSV. To add
the extra fields, pass a named parameter "csv_extra_fields" to the
s3_rest_controller call (or the S3Request call, respectively):
s3_rest_controller(module, resourcename,
csv_extra_fields=[
dict(label="ColumnLabelInTheCSV",
field=field_instance)
])
The Field instance "field" will be added to the upload form, and
the user input will be added to each row of the CSV under the
label as specified. If the "field" validator has options, the
input value will be translated into the option representation,
otherwise the value will be used as-is.
Note that the "label" in the dict is the column label in the CSV,
whereas the field label for the form is to be set in the Field
instance passed as "field".
You can add any arbitrary number of csv_extra_fields to the list.
Additionally, you may want to allow the user to choose whether
the import shall first remove all existing data in the target
table. To do so, pass a label for the "replace_option" to the
request:
s3_rest_controller(module, resourcename,
replace_option=T("Remove existing data before import"))
This will add the respective checkbox to the upload form.
You may also want to provide a link to download a CSV template from
the upload form. To do that, add the resource name to the request
attributes:
s3_rest_controller(module, resourcename,
csv_template="<resourcename>")
This will provide a link to:
- static/formats/s3csv/<controller>/<resourcename>.csv
at the top of the upload form.
"""
_debug("S3Importer.apply_method(%s)" % r)
# Messages
T = current.T
messages = self.messages = Messages(T)
messages.download_template = "Download Template"
messages.invalid_file_format = "Invalid File Format"
messages.unsupported_file_type = "Unsupported file type of %s"
messages.stylesheet_not_found = "No Stylesheet %s could be found to manage the import file."
messages.no_file = "No file submitted"
messages.file_open_error = "Unable to open the file %s"
messages.file_not_found = "The file to upload is missing"
messages.no_records_to_import = "No records to import"
messages.no_job_to_delete = "No job to delete, maybe it has already been deleted."
messages.title_job_read = "Details of the selected import job"
messages.title_job_list = "List of import items"
messages.file_uploaded = "Import file uploaded"
messages.upload_submit_btn = "Upload Data File"
messages.open_btn = "Open"
messages.view_btn = "View"
messages.delete_btn = "Delete"
messages.item_show_details = "Display Details"
messages.job_total_records = "Total records in the Import Job"
messages.job_records_selected = "Records selected"
messages.job_deleted = "Import job deleted"
messages.job_completed = "Job run on %s. With result of (%s)"
messages.import_file = "Import File"
messages.import_file_comment = "Upload a file formatted according to the Template."
messages.user_name = "User Name"
messages.commit_total_records_imported = "%s records imported"
messages.commit_total_records_ignored = "%s records ignored"
messages.commit_total_errors = "%s records in error"
try:
self.uploadTitle = current.response.s3.crud_strings[self.tablename].title_upload
except:
self.uploadTitle = T("Upload a %s import file" % r.function)
# @todo: correct to switch this off for the whole session?
current.session.s3.ocr_enabled = False
# Reset all errors/warnings
self.error = None
self.warning = None
# CSV upload configuration
if "csv_stylesheet" in attr:
self.csv_stylesheet = attr["csv_stylesheet"]
else:
self.csv_stylesheet = None
self.csv_extra_fields = None
self.csv_extra_data = None
# Environment
self.controller = r.controller
self.function = r.function
# Target table for the data import
self.controller_resource = self.resource
self.controller_table = self.table
self.controller_tablename = self.tablename
# Table for uploads
self.__define_table()
self.upload_resource = None
self.item_resource = None
# XSLT Path
self.xslt_path = os.path.join(r.folder, r.XSLT_PATH)
self.xslt_extension = r.XSLT_EXTENSION
# Check authorization
authorised = self.permit("create", self.upload_tablename) and \
self.permit("create", self.controller_tablename)
if not authorised:
if r.method is not None:
r.unauthorised()
else:
return dict(form=None)
# @todo: clean this up
source = None
transform = None
upload_id = None
items = None
# @todo get the data from either get_vars or post_vars appropriately
# for post -> commit_items would need to add the uploadID
if "transform" in r.get_vars:
transform = r.get_vars["transform"]
if "filename" in r.get_vars:
source = r.get_vars["filename"]
if "job" in r.post_vars:
upload_id = r.post_vars["job"]
elif "job" in r.get_vars:
upload_id = r.get_vars["job"]
items = self._process_item_list(upload_id, r.vars)
if "delete" in r.get_vars:
r.http = "DELETE"
# If we have an upload ID, then get upload and import job
self.upload_id = upload_id
query = (self.upload_table.id == upload_id)
self.upload_job = current.db(query).select(limitby=(0, 1)).first()
if self.upload_job:
self.job_id = self.upload_job.job_id
else:
self.job_id = None
# Now branch off to the appropriate controller function
if r.http == "GET":
if source != None:
self.commit(source, transform)
output = self.upload(r, **attr)
if upload_id != None:
output = self.display_job(upload_id)
else:
output = self.upload(r, **attr)
elif r.http == "POST":
if items != None:
output = self.commit_items(upload_id, items)
else:
output = self.generate_job(r, **attr)
elif r.http == "DELETE":
if upload_id != None:
output = self.delete_job(upload_id)
else:
r.error(405, current.manager.ERROR.BAD_METHOD)
return output
# -------------------------------------------------------------------------
def upload(self, r, **attr):
"""
This will display the upload form
It will ask for a file to be uploaded or for a job to be selected.
If a file is uploaded then it will guess at the file type and
ask for the transform file to be used. The transform files will
be in a dataTable with the module specific files shown first and
after those all other known transform files. Once the transform
file is selected the import process can be started which will
generate an importJob, and a "POST" method will occur
If a job is selected it will have two actions, open and delete.
Open will mean that a "GET" method will occur, with the job details
passed in.
Whilst the delete action will trigger a "DELETE" method.
"""
_debug("S3Importer.upload()")
request = self.request
form = self._upload_form(r, **attr)
output = self._create_upload_dataTable()
if request.representation == "aadata":
return output
output.update(form=form, title=self.uploadTitle)
return output
# -------------------------------------------------------------------------
def generate_job(self, r, **attr):
"""
Generate an ImportJob from the submitted upload form
"""
_debug("S3Importer.display()")
response = current.response
s3 = response.s3
db = current.db
table = self.upload_table
title=self.uploadTitle
form = self._upload_form(r, **attr)
r = self.request
r.read_body()
sfilename = form.vars.file
try:
ofilename = r.post_vars["file"].filename
except:
form.errors.file = self.messages.no_file
if form.errors:
response.flash = ""
output = self._create_upload_dataTable()
output.update(form=form, title=title)
elif not sfilename or \
ofilename not in r.files or r.files[ofilename] is None:
response.flash = ""
response.error = self.messages.file_not_found
output = self._create_upload_dataTable()
output.update(form=form, title=title)
else:
output = dict()
query = (table.file == sfilename)
db(query).update(controller=self.controller,
function=self.function,
filename=ofilename,
user_id=current.session.auth.user.id)
# must commit here to separate this transaction from
# the trial import phase which will be rolled back.
db.commit()
extension = ofilename.rsplit(".", 1).pop()
if extension not in ("csv", "xls"):
response.flash = None
response.error = self.messages.invalid_file_format
return self.upload(r, **attr)
upload_file = r.files[ofilename]
if extension == "xls":
if "xls_parser" in s3:
upload_file.seek(0)
upload_file = s3.xls_parser(upload_file.read())
extension = "csv"
if upload_file is None:
response.flash = None
response.error = self.messages.file_not_found
return self.upload(r, **attr)
else:
upload_file.seek(0)
row = db(query).select(table.id, limitby=(0, 1)).first()
upload_id = row.id
if "single_pass" in r.vars:
single_pass = r.vars["single_pass"]
else:
single_pass = None
self._generate_import_job(upload_id,
upload_file,
extension,
commit_job = single_pass)
if upload_id is None:
row = db(query).update(status = 2) # in error
if self.error != None:
response.error = self.error
if self.warning != None:
response.warning = self.warning
response.flash = ""
return self.upload(r, **attr)
else:
if single_pass:
current.session.flash = self.messages.file_uploaded
# For a single pass retain the vars from the original URL
next_URL = URL(r=self.request,
f=self.function,
args=["import"],
vars=current.request.get_vars
)
redirect(next_URL)
s3.dataTable_vars = {"job" : upload_id}
return self.display_job(upload_id)
return output
# -------------------------------------------------------------------------
def display_job(self, upload_id):
"""
@todo: docstring?
"""
_debug("S3Importer.display_job()")
request = self.request
response = current.response
db = current.db
table = self.upload_table
job_id = self.job_id
output = dict()
if job_id == None:
# redirect to the start page (removes all vars)
query = (table.id == upload_id)
row = db(query).update(status = 2) # in error
current.session.warning = self.messages.no_records_to_import
redirect(URL(r=request, f=self.function, args=["import"]))
# Get the status of the upload job
query = (table.id == upload_id)
row = db(query).select(table.status,
table.modified_on,
table.summary_added,
table.summary_error,
table.summary_ignored,
limitby=(0, 1)).first()
status = row.status
# completed display details
if status == 3: # Completed
# @todo currently this is an unnecessary server call,
# change for completed records to be a display details
# and thus avoid the round trip.
# but keep this code to protect against hand-crafted URLs
# (and the 'go back' syndrome on the browser)
result = (row.summary_added,
row.summary_error,
row.summary_ignored,
)
self._display_completed_job(result, row.modified_on)
redirect(URL(r=request, f=self.function, args=["import"]))
# otherwise display import items
response.view = self._view(request, "list.html")
output = self._create_import_item_dataTable(upload_id, job_id)
if request.representation == "aadata":
return output
if response.s3.error_report:
error_report = "Errors|" + "|".join(response.s3.error_report)
error_tip = A("All Errors",
_class="errortip",
_title=error_report)
else:
# @todo: restore the error tree from all items?
error_tip = ""
rowcount = len(self._get_all_items(upload_id))
rheader = DIV(TABLE(
TR(
TH("%s: " % self.messages.job_total_records),
TD(rowcount, _id="totalAvaliable"),
TH("%s: " % self.messages.job_records_selected),
TD(0, _id="totalSelected"),
TH(error_tip)
),
))
output["title"] = self.messages.title_job_read
output["rheader"] = rheader
output["subtitle"] = self.messages.title_job_list
return output
# -------------------------------------------------------------------------
def commit(self, source, transform):
"""
@todo: docstring?
"""
_debug("S3Importer.commit(%s, %s)" % (source, transform))
db = current.db
session = current.session
request = self.request
try:
openFile = open(source, "r")
except:
session.error = self.messages.file_open_error % source
redirect(URL(r=request, f=self.function))
# @todo: manage different file formats
# @todo: find file format from request.extension
fileFormat = "csv"
# insert data in the table and get the ID
try:
user = session.auth.user.id
except:
user = None
upload_id = self.upload_table.insert(controller=self.controller,
function=self.function,
filename = source,
user_id = user,
status = 1)
db.commit()
# create the import job
result = self._generate_import_job(upload_id,
openFile,
fileFormat,
stylesheet=transform
)
if result == None:
if self.error != None:
if session.error == None:
session.error = self.error
else:
session.error += self.error
if self.warning != None:
if session.warning == None:
session.warning = self.warning
else:
session.warning += self.warning
else:
items = self._get_all_items(upload_id, True)
# commit the import job
self._commit_import_job(upload_id, items)
result = self._update_upload_job(upload_id)
# get the results and display
msg = "%s : %s %s %s" % (source,
self.messages.commit_total_records_imported,
self.messages.commit_total_errors,
self.messages.commit_total_records_ignored)
msg = msg % result
if session.flash == None:
session.flash = msg
else:
session.flash += msg
# @todo: return the upload_id?
# -------------------------------------------------------------------------
def commit_items(self, upload_id, items):
"""
@todo: docstring?
"""
_debug("S3Importer.commit_items(%s, %s)" % (upload_id, items))
# Save the import items
self._commit_import_job(upload_id, items)
# Update the upload table
# change the status to completed
# record the summary details
# delete the upload file
result = self._update_upload_job(upload_id)
# redirect to the start page (removes all vars)
self._display_completed_job(result)
redirect(URL(r=self.request, f=self.function, args=["import"]))
# -------------------------------------------------------------------------
def delete_job(self, upload_id):
"""
Delete an uploaded file and the corresponding import job
@param upload_id: the upload ID
"""
_debug("S3Importer.delete_job(%s)" % (upload_id))
db = current.db
request = self.request
resource = request.resource # use self.resource?
response = current.response
# Get the import job ID
job_id = self.job_id
# Delete the import job (if any)
if job_id:
result = resource.import_xml(None,
id = None,
tree = None,
job_id = job_id,
delete_job = True)
# @todo: check result
# now delete the upload entry
query = (self.upload_table.id == upload_id)
count = db(query).delete()
# @todo: check that the record has been deleted
# Now commit the changes
db.commit()
result = count
# return to the main import screen
# @todo: check result properly
if result == False:
response.warning = self.messages.no_job_to_delete
else:
response.flash = self.messages.job_deleted
# redirect to the start page (remove all vars)
self.next = self.request.url(vars=dict())
return
# ========================================================================
# Utility methods
# ========================================================================
def _upload_form(self, r, **attr):
"""
Create and process the upload form, including csv_extra_fields
"""
EXTRA_FIELDS = "csv_extra_fields"
TEMPLATE = "csv_template"
REPLACE_OPTION = "replace_option"
session = current.session
response = current.response
s3 = response.s3
request = self.request
table = self.upload_table
formstyle = s3.crud.formstyle
response.view = self._view(request, "list_create.html")
if REPLACE_OPTION in attr:
replace_option = attr[REPLACE_OPTION]
if replace_option is not None:
table.replace_option.readable = True
table.replace_option.writable = True
table.replace_option.label = replace_option
fields = [f for f in table if f.readable or f.writable and not f.compute]
if EXTRA_FIELDS in attr:
extra_fields = attr[EXTRA_FIELDS]
if extra_fields is not None:
fields.extend([f["field"] for f in extra_fields if "field" in f])
self.csv_extra_fields = extra_fields
labels, required = s3_mark_required(fields)
if required:
s3.has_required = True
form = SQLFORM.factory(table_name=self.UPLOAD_TABLE_NAME,
labels=labels,
formstyle=formstyle,
upload = os.path.join(request.folder, "uploads", "imports"),
separator = "",
message=self.messages.file_uploaded,
*fields)
args = ["s3csv"]
template = attr.get(TEMPLATE, True)
if template is True:
args.extend([self.controller, "%s.csv" % self.function])
elif isinstance(template, basestring):
args.extend([self.controller, "%s.csv" % template])
elif isinstance(template, (tuple, list)):
args.extend(template[:-1])
args.append("%s.csv" % template[-1])
else:
template = None
if template is not None:
url = URL(r=request, c="static", f="formats", args=args)
try:
# only add the download link if the template can be opened
open("%s/../%s" % (r.folder, url))
form[0][0].insert(0, TR(TD(A(self.messages.download_template,
_href=url)),
_id="template__row"))
except:
pass
if form.accepts(r.post_vars, session,
formname="upload_form"):
upload_id = table.insert(**table._filter_fields(form.vars))
if self.csv_extra_fields:
self.csv_extra_data = Storage()
for f in self.csv_extra_fields:
label = f.get("label", None)
if not label:
continue
field = f.get("field", None)
value = f.get("value", None)
if field:
if field.name in form.vars:
data = form.vars[field.name]
else:
data = field.default
value = data
requires = field.requires
if not isinstance(requires, (list, tuple)):
requires = [requires]
if requires:
requires = requires[0]
if isinstance(requires, IS_EMPTY_OR):
requires = requires.other
try:
options = requires.options()
except:
pass
else:
for k, v in options:
if k == str(data):
value = v
elif value is None:
continue
self.csv_extra_data[label] = value
s3.no_formats = True
return form
# -------------------------------------------------------------------------
def _create_upload_dataTable(self):
"""
List of previous Import jobs
"""
db = current.db
request = self.request
controller = self.controller
function = self.function
s3 = current.response.s3
table = self.upload_table
s3.filter = (table.controller == controller) & \
(table.function == function)
fields = ["id",
"filename",
"created_on",
"user_id",
"replace_option",
"status"]
self._use_upload_table()
# Hide the list of prior uploads for now
#output = self._dataTable(fields, sort_by = [[2,"desc"]])
output = dict()
self._use_controller_table()
if request.representation == "aadata":
return output
query = (table.status != 3) # Status of Pending or in-Error
rows = db(query).select(table.id)
restrictOpen = [str(row.id) for row in rows]
query = (table.status == 3) # Status of Completed
rows = db(query).select(table.id)
restrictView = [str(row.id) for row in rows]
s3.actions = [
dict(label=str(self.messages.open_btn),
_class="action-btn",
url=URL(r=request,
c=controller,
f=function,
args=["import"],
vars={"job":"[id]"}),
restrict = restrictOpen
),
dict(label=str(self.messages.view_btn),
_class="action-btn",
url=URL(r=request,
c=controller,
f=function,
args=["import"],
vars={"job":"[id]"}),
restrict = restrictView
),
dict(label=str(self.messages.delete_btn),
_class="delete-btn",
url=URL(r=request,
c=controller,
f=function,
args=["import"],
vars={"job":"[id]",
"delete":"True"
}
)
),
]
# Display an Error if no job is attached with this record
query = (table.status == 1) # Pending
rows = db(query).select(table.id)
s3.dataTableStyleAlert = [str(row.id) for row in rows]
query = (table.status == 2) # in error
rows = db(query).select(table.id)
s3.dataTableStyleWarning = [str(row.id) for row in rows]
return output
# -------------------------------------------------------------------------
def _create_import_item_dataTable(self, upload_id, job_id):
"""
@todo: docstring?
"""
s3 = current.response.s3
represent = {"element" : self._item_element_represent}
self._use_import_item_table(job_id)
# Add a filter to the dataTable query
s3.filter = (self.table.job_id == job_id) & \
(self.table.tablename == self.controller_tablename)
# Get a list of the records that have an error of None
query = (self.table.job_id == job_id) & \
(self.table.tablename == self.controller_tablename)
rows = current.db(query).select(self.table.id, self.table.error)
select_list = []
error_list = []
for row in rows:
if row.error:
error_list.append(str(row.id))
else:
select_list.append("%s" % row.id)
select_id = ",".join(select_list)
output = self._dataTable(["id", "element", "error"],
sort_by = [[1, "asc"]],
represent=represent)
self._use_controller_table()
if self.request.representation == "aadata":
return output
# Highlight rows in error in red
s3.dataTableStyleWarning = error_list
s3.dataTableSelectable = True
s3.dataTablePostMethod = True
table = output["items"]
job = INPUT(_type="hidden", _id="importUploadID", _name="job",
_value="%s" % upload_id)
mode = INPUT(_type="hidden", _id="importMode", _name="mode",
_value="Inclusive")
# only select the rows with no errors
selected = INPUT(_type="hidden", _id="importSelected",
_name="selected", _value="[%s]" % select_id)
form = FORM(table, job, mode, selected)
output["items"] = form
s3.dataTableSelectSubmitURL = "import?job=%s&" % upload_id
s3.actions = [
dict(label= str(self.messages.item_show_details),
_class="action-btn",
_jqclick="$('.importItem.'+id).toggle();",
),
]
return output
# -------------------------------------------------------------------------
def _generate_import_job(self,
upload_id,
openFile,
fileFormat,
stylesheet=None,
commit_job=False):
"""
This will take a s3_import_upload record and
generate the importJob
@param uploadFilename: The name of the uploaded file
@todo: complete parameter descriptions
"""
_debug("S3Importer._generate_import_job(%s, %s, %s, %s)" % (upload_id,
openFile,
fileFormat,
stylesheet
)
)
db = current.db
request = self.request
resource = request.resource
# ---------------------------------------------------------------------
# CSV
if fileFormat == "csv" or fileFormat == "comma-separated-values":
fmt = "csv"
src = openFile
# ---------------------------------------------------------------------
# XML
# @todo: implement
#elif fileFormat == "xml":
# ---------------------------------------------------------------------
# S3JSON
# @todo: implement
#elif fileFormat == "s3json":
# ---------------------------------------------------------------------
# PDF
# @todo: implement
#elif fileFormat == "pdf":
# ---------------------------------------------------------------------
# Unsupported Format
else:
msg = self.messages.unsupported_file_type % fileFormat
self.error = msg
_debug(msg)
return None
# Get the stylesheet
if stylesheet == None:
stylesheet = self._get_stylesheet()
if stylesheet == None:
return None
# before calling import tree ensure the db.table is the controller_table
self.table = self.controller_table
self.tablename = self.controller_tablename
# Pass stylesheet arguments
args = Storage()
mode = request.get_vars.get("xsltmode", None)
if mode is not None:
args.update(mode=mode)
# Generate the import job
resource.import_xml(src,
format=fmt,
extra_data=self.csv_extra_data,
stylesheet=stylesheet,
ignore_errors = True,
commit_job = commit_job,
**args)
job = resource.job
if job is None:
if resource.error:
# Error
self.error = resource.error
return None
else:
# Nothing to import
self.warning = self.messages.no_records_to_import
return None
else:
# Job created
job_id = job.job_id
errors = current.xml.collect_errors(job)
if errors:
current.response.s3.error_report = errors
query = (self.upload_table.id == upload_id)
result = db(query).update(job_id=job_id)
# @todo: add check that result == 1, if not we are in error
# Now commit the changes
db.commit()
self.job_id = job_id
return True
# -------------------------------------------------------------------------
def _get_stylesheet(self, file_format="csv"):
"""
Get the stylesheet for transformation of the import
@param file_format: the import source file format
"""
if file_format == "csv":
xslt_path = os.path.join(self.xslt_path, "s3csv")
else:
xslt_path = os.path.join(self.xslt_path, file_format, "import.xsl")
return xslt_path
# Use the "csv_stylesheet" parameter to override the CSV stylesheet subpath
# and filename, e.g.
# s3_rest_controller(module, resourcename,
# csv_stylesheet=("inv", "inv_item.xsl"))
if self.csv_stylesheet:
if isinstance(self.csv_stylesheet, (tuple, list)):
stylesheet = os.path.join(xslt_path,
*self.csv_stylesheet)
else:
stylesheet = os.path.join(xslt_path,
self.controller,
self.csv_stylesheet)
else:
xslt_filename = "%s.%s" % (self.function, self.xslt_extension)
stylesheet = os.path.join(xslt_path,
self.controller,
xslt_filename)
if os.path.exists(stylesheet) is False:
msg = self.messages.stylesheet_not_found % stylesheet
self.error = msg
_debug(msg)
return None
return stylesheet
# -------------------------------------------------------------------------
def _commit_import_job(self, upload_id, items):
"""
This will save all of the selected import items
@todo: parameter descriptions?
"""
_debug("S3Importer._commit_import_job(%s, %s)" % (upload_id, items))
db = current.db
resource = self.request.resource
# Load the items from the s3_import_item table
self.importDetails = dict()
table = self.upload_table
query = (table.id == upload_id)
row = db(query).select(table.job_id,
table.replace_option,
limitby=(0, 1)).first()
if row is None:
return False
else:
job_id = row.job_id
current.response.s3.import_replace = row.replace_option
itemTable = S3ImportJob.define_item_table()
if itemTable != None:
#****************************************************************
# EXPERIMENTAL
# This doesn't delete related items
# but import_tree will tidy it up later
#****************************************************************
# get all the items selected for import
rows = self._get_all_items(upload_id, as_string=True)
# loop through each row and delete the items not required
self._store_import_details(job_id, "preDelete")
for id in rows:
if str(id) not in items:
# @todo: replace with a helper method from the API
_debug("Deleting item.id = %s" % id)
query = (itemTable.id == id)
db(query).delete()
#****************************************************************
# EXPERIMENTAL
#****************************************************************
# set up the table we will import data into
self.table = self.controller_table
self.tablename = self.controller_tablename
self._store_import_details(job_id, "preImportTree")
# Now commit the remaining items
msg = resource.import_xml(None,
job_id = job_id,
ignore_errors = True)
return resource.error is None
# -------------------------------------------------------------------------
def _store_import_details(self, job_id, key):
"""
This will store the details from an importJob
@todo: parameter descriptions?
"""
_debug("S3Importer._store_import_details(%s, %s)" % (job_id, key))
itemTable = S3ImportJob.define_item_table()
query = (itemTable.job_id == job_id) & \
(itemTable.tablename == self.controller_tablename)
rows = current.db(query).select(itemTable.data, itemTable.error)
items = [dict(data=row.data, error=row.error) for row in rows]
self.importDetails[key] = items
# -------------------------------------------------------------------------
def _update_upload_job(self, upload_id):
"""
This will record the results from the import, and change the
status of the upload job
@todo: parameter descriptions?
@todo: report errors in referenced records, too
"""
_debug("S3Importer._update_upload_job(%s)" % (upload_id))
request = self.request
resource = request.resource
db = current.db
totalPreDelete = len(self.importDetails["preDelete"])
totalPreImport = len(self.importDetails["preImportTree"])
totalIgnored = totalPreDelete - totalPreImport
if resource.error_tree is None:
totalErrors = 0
else:
totalErrors = len(resource.error_tree.findall(
"resource[@name='%s']" % resource.tablename))
totalRecords = totalPreImport - totalErrors
if totalRecords < 0:
totalRecords = 0
query = (self.upload_table.id == upload_id)
result = db(query).update(summary_added=totalRecords,
summary_error=totalErrors,
summary_ignored = totalIgnored,
status = 3)
# Now commit the changes
db.commit()
return (totalRecords, totalErrors, totalIgnored)
# -------------------------------------------------------------------------
def _display_completed_job(self, totals, timestmp=None):
"""
Generate a summary flash message for a completed import job
@param totals: the job totals as tuple
(total imported, total errors, total ignored)
@param timestmp: the timestamp of the completion
"""
session = current.session
msg = "%s - %s - %s" % \
(self.messages.commit_total_records_imported,
self.messages.commit_total_errors,
self.messages.commit_total_records_ignored)
msg = msg % totals
if timestmp != None:
session.flash = self.messages.job_completed % \
(self.date_represent(timestmp), msg)
elif totals[1] is not 0:
session.error = msg
elif totals[2] is not 0:
session.warning = msg
else:
session.flash = msg
# -------------------------------------------------------------------------
def _dataTable(self,
list_fields = [],
sort_by = [[1, "asc"]],
represent={},
):
"""
Method to get the data for the dataTable
This can be either a raw html representation or
and ajax call update
Additional data will be cached to limit calls back to the server
@param list_fields: list of field names
@param sort_by: list of sort by columns
@param represent: a dict of field callback functions used
to change how the data will be displayed
@return: a dict()
In html representations this will be a table of the data
plus the sortby instructions
In ajax this will be a json response
In addition the following values will be made available:
totalRecords Number of records in the filtered data set
totalDisplayRecords Number of records to display
start Start point in the ordered data set
limit Number of records in the ordered set
NOTE: limit - totalDisplayRecords = total cached
"""
# ********************************************************************
# Common tasks
# ********************************************************************
db = current.db
session = current.session
request = self.request
response = current.response
resource = self.resource
s3 = response.s3
representation = request.representation
table = self.table
tablename = self.tablename
vars = request.get_vars
output = dict()
# Check permission to read this table
authorised = self.permit("read", tablename)
if not authorised:
request.unauthorised()
# List of fields to select from
# fields is a list of Field objects
# list_field is a string list of field names
if list_fields == []:
fields = resource.readable_fields()
else:
fields = [table[f] for f in list_fields if f in table.fields]
if not fields:
fields = []
# attach any represent callbacks
for f in fields:
if f.name in represent:
f.represent = represent[f.name]
# Make sure that we have the table id as the first column
if fields[0].name != table.fields[0]:
fields.insert(0, table[table.fields[0]])
list_fields = [f.name for f in fields]
# Filter
if s3.filter is not None:
self.resource.add_filter(s3.filter)
# ********************************************************************
# ajax call
# ********************************************************************
if representation == "aadata":
start = vars.get("iDisplayStart", None)
limit = vars.get("iDisplayLength", None)
if limit is not None:
try:
start = int(start)
limit = int(limit)
except ValueError:
start = None
limit = None # use default
else:
start = None # use default
# Using the sort variables sent from dataTables
if vars.iSortingCols:
orderby = self.ssp_orderby(resource, list_fields)
# Echo
sEcho = int(vars.sEcho or 0)
# Get the list
items = resource.sqltable(fields=list_fields,
start=start,
limit=limit,
orderby=orderby,
download_url=self.download_url,
as_page=True) or []
# Ugly hack to change any occurrence of [id] with the true id
# Needed because the represent doesn't know the id
for i in range(len(items)):
id = items[i][0]
for j in range(len(items[i])):
new = items[i][j].replace("[id]",id)
items[i][j] = new
totalrows = self.resource.count()
result = dict(sEcho = sEcho,
iTotalRecords = totalrows,
iTotalDisplayRecords = totalrows,
aaData = items)
output = jsons(result)
# ********************************************************************
# html 'initial' call
# ********************************************************************
else: # catch all
start = 0
limit = 1
# Sort by
vars["iSortingCols"] = len(sort_by)
# generate the dataTables.js variables for sorting
index = 0
for col in sort_by:
colName = "iSortCol_%s" % str(index)
colValue = col[0]
dirnName = "sSortDir_%s" % str(index)
if len(col) > 1:
dirnValue = col[1]
else:
dirnValue = "asc"
vars[colName] = colValue
vars[dirnName] = dirnValue
# Now using these sort variables generate the order by statement
orderby = self.ssp_orderby(resource, list_fields)
del vars["iSortingCols"]
for col in sort_by:
del vars["iSortCol_%s" % str(index)]
del vars["sSortDir_%s" % str(index)]
# Get the first row for a quick up load
items = resource.sqltable(fields=list_fields,
start=start,
limit=1,
orderby=orderby,
download_url=self.download_url)
totalrows = resource.count()
if items:
if totalrows:
if s3.dataTable_iDisplayLength:
limit = 2 * s3.dataTable_iDisplayLength
else:
limit = 50
# Add a test on the first call here:
# Now get the limit rows for ajax style update of table
sqltable = resource.sqltable(fields=list_fields,
start=start,
limit=limit,
orderby=orderby,
download_url=self.download_url,
as_page=True)
aadata = dict(aaData = sqltable or [])
# Ugly hack to change any occurrence of [id] with the true id
# Needed because the represent doesn't know the id
for i in range(len(aadata["aaData"])):
id = aadata["aaData"][i][0]
for j in range(len(aadata["aaData"][i])):
new = aadata["aaData"][i][j].replace("[id]",id)
aadata["aaData"][i][j] = new
aadata.update(iTotalRecords=totalrows,
iTotalDisplayRecords=totalrows)
response.aadata = jsons(aadata)
s3.start = 0
s3.limit = limit
else: # No items in database
# s3import tables don't have a delete field but kept for the record
if "deleted" in table:
available_records = db(table.deleted == False)
else:
available_records = db(table.id > 0)
# check for any records on an unfiltered table
if available_records.select(table.id,
limitby=(0, 1)).first():
items = self.crud_string(tablename, "msg_no_match")
else:
items = self.crud_string(tablename, "msg_list_empty")
output.update(items=items, sortby=sort_by)
# Value to be added to the dataTable ajax call
s3.dataTable_Method = "import"
return output
# -------------------------------------------------------------------------
def _item_element_represent(self, value):
"""
Represent the element in an import item for dataTable display
@param value: the string containing the element
"""
T = current.T
db = current.db
value = S3XML.xml_decode(value)
try:
element = etree.fromstring(value)
except:
# XMLSyntaxError: return the element as-is
return DIV(value)
tablename = element.get("name")
table = current.db[tablename]
output = DIV()
details = TABLE(_class="importItem [id]")
header, rows = self._add_item_details(element.findall("data"), table)
if header is not None:
output.append(header)
# Add components, if present
components = element.findall("resource")
for component in components:
ctablename = component.get("name")
ctable = db[ctablename]
self._add_item_details(component.findall("data"), ctable,
details=rows, prefix=True)
if rows:
details.append(TBODY(rows))
# Add error messages, if present
errors = current.xml.collect_errors(element)
if errors:
details.append(TFOOT(TR(TH("%s:" % T("Errors")),
TD(UL([LI(e) for e in errors])))))
if rows == [] and components == []:
# At this stage we don't have anything to display to see if we can
# find something to show. This could be the case when a table being
# imported is a resolver for a many to many relationship
refdetail = TABLE(_class="importItem [id]")
references = element.findall("reference")
for reference in references:
tuid = reference.get("tuid")
resource = reference.get("resource")
refdetail.append(TR(TD(resource), TD(tuid)))
output.append(refdetail)
else:
output.append(details)
return str(output)
# -------------------------------------------------------------------------
@staticmethod
def _add_item_details(data, table, details=None, prefix=False):
"""
Add details of the item element
@param data: the list of data elements in the item element
@param table: the table for the data
@param details: the existing details rows list (to append to)
"""
tablename = table._tablename
if details is None:
details = []
first = None
firstString = None
header = None
for child in data:
f = child.get("field", None)
if f not in table.fields:
continue
elif f == "wkt":
# Skip bulky WKT fields
continue
field = table[f]
ftype = str(field.type)
value = child.get("value", None)
if not value:
value = child.text
try:
value = S3Importer._decode_data(field, value)
except:
pass
if value:
value = S3XML.xml_encode(unicode(value))
else:
value = ""
if f != None and value != None:
headerText = P(B("%s: " % f), value)
if not first:
first = headerText
if ftype == "string" and not firstString:
firstString = headerText
if f == "name":
header = headerText
if prefix:
details.append(TR(TH("%s.%s:" % (tablename, f)), TD(value)))
else:
details.append(TR(TH("%s:" % f), TD(value)))
if not header:
if firstString:
header = firstString
else:
header = first
return (header, details)
# -------------------------------------------------------------------------
@staticmethod
def _decode_data(field, value):
"""
Try to decode string data into their original type
@param field: the Field instance
@param value: the stringified value
@todo: replace this by ordinary decoder
"""
if field.type == "string" or \
field.type == "string" or \
field.type == "password" or \
field.type == "upload" or \
field.type == "text":
return value
elif field.type == "integer" or field.type == "id":
return int(value)
elif field.type == "double" or field.type == "decimal":
return double(value)
elif field.type == 'boolean':
if value and not str(value)[:1].upper() in ["F", "0"]:
return "T"
else:
return "F"
elif field.type == "date":
return value # @todo fix this to get a date
elif field.type == "time":
return value # @todo fix this to get a time
elif field.type == "datetime":
return value # @todo fix this to get a datetime
else:
return value
# -------------------------------------------------------------------------
@staticmethod
def date_represent(date_obj):
"""
Represent a datetime object as string
@param date_obj: the datetime object
@todo: replace by S3DateTime method?
"""
return date_obj.strftime("%d %B %Y, %I:%M%p")
# -------------------------------------------------------------------------
def _process_item_list(self, upload_id, vars):
"""
Get the list of IDs for the selected items from the "mode"
and "selected" request variables
@param upload_id: the upload_id
@param vars: the request variables
"""
items = None
if "mode" in vars:
mode = vars["mode"]
if "selected" in vars:
selected = vars["selected"].split(",")
else:
selected = []
if mode == "Inclusive":
items = selected
elif mode == "Exclusive":
all_items = self._get_all_items(upload_id, as_string=True)
items = [i for i in all_items if i not in selected]
return items
# -------------------------------------------------------------------------
def _get_all_items(self, upload_id, as_string=False):
""" Get a list of the record IDs of all import items for
the the given upload ID
@param upload_id: the upload ID
@param as_string: represent each ID as string
"""
item_table = S3ImportJob.define_item_table()
upload_table = self.upload_table
query = (upload_table.id == upload_id) & \
(item_table.job_id == upload_table.job_id) & \
(item_table.tablename == self.controller_tablename)
rows = current.db(query).select(item_table.id)
if as_string:
items = [str(row.id) for row in rows]
else:
items = [row.id for row in rows]
return items
# -------------------------------------------------------------------------
def _use_upload_table(self):
"""
Set the resource and the table to being s3_import_upload
"""
if self.upload_resource == None:
from s3resource import S3Resource
(prefix, name) = self.UPLOAD_TABLE_NAME.split("_",1)
self.upload_resource = S3Resource(prefix, name)
self.resource = self.upload_resource
self.table = self.upload_table
self.tablename = self.upload_tablename
# -------------------------------------------------------------------------
def _use_controller_table(self):
"""
Set the resource and the table to be the imported resource
"""
self.resource = self.controller_resource
self.table = self.controller_table
self.tablename = self.controller_tablename
# -------------------------------------------------------------------------
def _use_import_item_table(self, job_id):
"""
Set the resource and the table to being s3_import_item
"""
if self.item_resource == None:
from s3resource import S3Resource
(prefix, name) = S3ImportJob.ITEM_TABLE_NAME.split("_",1)
self.item_resource = S3Resource(prefix, name)
self.resource = self.item_resource
self.tablename = S3ImportJob.ITEM_TABLE_NAME
self.table = S3ImportJob.define_item_table()
# -------------------------------------------------------------------------
def __define_table(self):
""" Configures the upload table """
_debug("S3Importer.__define_table()")
T = current.T
db = current.db
request = current.request
self.upload_tablename = self.UPLOAD_TABLE_NAME
import_upload_status = {
1: T("Pending"),
2: T("In error"),
3: T("Completed"),
}
def user_name_represent(id):
# @todo: use s3_present_user?
rep_str = "-"
table = db.auth_user
query = (table.id == id)
row = db(query).select(table.first_name,
table.last_name,
limitby=(0, 1)).first()
if row:
rep_str = "%s %s" % (row.first_name, row.last_name)
return rep_str
def status_represent(index):
if index == None:
return "Unknown" # @todo: use messages (internationalize)
else:
return import_upload_status[index]
now = request.utcnow
table = self.define_upload_table()
table.file.upload_folder = os.path.join(request.folder,
"uploads",
#"imports"
)
table.file.comment = DIV(_class="tooltip",
_title="%s|%s" %
(self.messages.import_file,
self.messages.import_file_comment))
table.file.label = self.messages.import_file
table.status.requires = IS_IN_SET(import_upload_status, zero=None)
table.status.represent = status_represent
table.user_id.label = self.messages.user_name
table.user_id.represent = user_name_represent
table.created_on.default = now
table.created_on.represent = self.date_represent
table.modified_on.default = now
table.modified_on.update = now
table.modified_on.represent = self.date_represent
table.replace_option.label = T("Replace")
self.upload_table = db[self.UPLOAD_TABLE_NAME]
# -------------------------------------------------------------------------
@classmethod
def define_upload_table(cls):
""" Defines the upload table """
db = current.db
uploadfolder = os.path.join(current.request.folder,
"uploads",
)
if cls.UPLOAD_TABLE_NAME not in db:
upload_table = db.define_table(cls.UPLOAD_TABLE_NAME,
Field("controller",
readable=False,
writable=False),
Field("function",
readable=False,
writable=False),
Field("file", "upload",
uploadfolder=os.path.join(current.request.folder, "uploads", "imports"),
autodelete=True),
Field("filename",
readable=False,
writable=False),
Field("status", "integer",
default=1,
readable=False,
writable=False),
Field("extra_data",
readable=False,
writable=False),
Field("replace_option", "boolean",
default=False,
readable=False,
writable=False),
Field("job_id",
length=128,
readable=False,
writable=False),
Field("user_id", "integer",
readable=False,
writable=False),
Field("created_on", "datetime",
readable=False,
writable=False),
Field("modified_on", "datetime",
readable=False,
writable=False),
Field("summary_added", "integer",
readable=False,
writable=False),
Field("summary_error", "integer",
readable=False,
writable=False),
Field("summary_ignored", "integer",
readable=False,
writable=False),
Field("completed_details", "text",
readable=False,
writable=False))
else:
upload_table = db[cls.UPLOAD_TABLE_NAME]
return upload_table
# =============================================================================
class S3ImportItem(object):
""" Class representing an import item (=a single record) """
METHOD = Storage(
CREATE="create",
UPDATE="update",
DELETE="delete"
)
POLICY = Storage(
THIS="THIS", # keep local instance
OTHER="OTHER", # update unconditionally
NEWER="NEWER", # update if import is newer
MASTER="MASTER" # update if import is master
)
# -------------------------------------------------------------------------
def __init__(self, job):
"""
Constructor
@param job: the import job this item belongs to
"""
self.job = job
self.ERROR = current.manager.ERROR
# Locking and error handling
self.lock = False
self.error = None
# Identification
import uuid
self.item_id = uuid.uuid4() # unique ID for this item
self.id = None
self.uid = None
# Data elements
self.table = None
self.tablename = None
self.element = None
self.data = None
self.original = None
self.components = []
self.references = []
self.load_components = []
self.load_references = []
self.parent = None
self.skip = False
# Conflict handling
self.mci = 2
self.mtime = datetime.utcnow()
self.modified = True
self.conflict = False
# Allowed import methods
self.strategy = job.strategy
# Update and conflict resolution policies
self.update_policy = job.update_policy
self.conflict_policy = job.conflict_policy
# Actual import method
self.method = None
self.onvalidation = None
self.onaccept = None
# Item import status flags
self.accepted = None
self.permitted = False
self.committed = False
# Writeback hook for circular references:
# Items which need a second write to update references
self.update = []
# -------------------------------------------------------------------------
def __repr__(self):
""" Helper method for debugging """
_str = "<S3ImportItem %s {item_id=%s uid=%s id=%s error=%s data=%s}>" % \
(self.table, self.item_id, self.uid, self.id, self.error, self.data)
return _str
# -------------------------------------------------------------------------
def parse(self,
element,
original=None,
table=None,
tree=None,
files=None):
"""
Read data from a <resource> element
@param element: the element
@param table: the DB table
@param tree: the import tree
@param files: uploaded files
@returns: True if successful, False if not (sets self.error)
"""
db = current.db
xml = current.xml
manager = current.manager
validate = manager.validate
s3db = current.s3db
self.element = element
if table is None:
tablename = element.get(xml.ATTRIBUTE.name, None)
try:
table = s3db[tablename]
except:
self.error = self.ERROR.BAD_RESOURCE
element.set(xml.ATTRIBUTE.error, self.error)
return False
self.table = table
self.tablename = table._tablename
if original is None:
original = manager.original(table, element)
data = xml.record(table, element,
files=files,
original=original,
validate=validate)
if data is None:
self.error = self.ERROR.VALIDATION_ERROR
self.accepted = False
if not element.get(xml.ATTRIBUTE.error, False):
element.set(xml.ATTRIBUTE.error, str(self.error))
return False
self.data = data
if original is not None:
self.original = original
self.id = original[table._id.name]
if xml.UID in original:
self.uid = original[xml.UID]
self.data.update({xml.UID:self.uid})
elif xml.UID in data:
self.uid = data[xml.UID]
if xml.MTIME in data:
self.mtime = data[xml.MTIME]
if xml.MCI in data:
self.mci = data[xml.MCI]
_debug("New item: %s" % self)
return True
# -------------------------------------------------------------------------
def deduplicate(self):
RESOLVER = "deduplicate"
if self.id:
return
table = self.table
if table is None:
return
if self.original is not None:
original = self.original
else:
original = current.manager.original(table, self.data)
if original is not None:
self.original = original
self.id = original[table._id.name]
UID = current.xml.UID
if UID in original:
self.uid = original[UID]
self.data.update({UID:self.uid})
self.method = self.METHOD.UPDATE
else:
resolve = current.s3db.get_config(self.tablename, RESOLVER)
if self.data and resolve:
resolve(self)
return
# -------------------------------------------------------------------------
def authorize(self):
"""
Authorize the import of this item, sets self.permitted
"""
db = current.db
manager = current.manager
authorize = manager.permit
self.permitted = False
if not self.table:
return False
prefix = self.tablename.split("_", 1)[0]
if prefix in manager.PROTECTED:
return False
if not authorize:
self.permitted = True
self.method = self.METHOD.CREATE
if self.id:
if self.data.deleted is True:
self.method = self.METHOD.DELETE
self.accepted = True
else:
if not self.original:
query = (self.table.id == self.id)
self.original = db(query).select(limitby=(0, 1)).first()
if self.original:
self.method = self.METHOD.UPDATE
if self.method == self.METHOD.CREATE:
self.id = 0
if authorize:
self.permitted = authorize(self.method,
self.tablename,
record_id=self.id)
return self.permitted
# -------------------------------------------------------------------------
def validate(self):
"""
Validate this item (=record onvalidation), sets self.accepted
"""
if self.accepted is not None:
return self.accepted
if self.data is None or not self.table:
self.accepted = False
return False
form = Storage()
form.method = self.method
form.vars = self.data
if self.id:
form.vars.id = self.id
form.errors = Storage()
tablename = self.tablename
key = "%s_onvalidation" % self.method
s3db = current.s3db
onvalidation = s3db.get_config(tablename, key,
s3db.get_config(tablename, "onvalidation"))
if onvalidation:
try:
callback(onvalidation, form, tablename=tablename)
except:
pass # @todo need a better handler here.
self.accepted = True
if form.errors:
error = current.xml.ATTRIBUTE.error
for k in form.errors:
e = self.element.findall("data[@field='%s']" % k)
if not e:
e = self.element.findall("reference[@field='%s']" % k)
if not e:
e = self.element
form.errors[k] = "[%s] %s" % (k, form.errors[k])
else:
e = e[0]
e.set(error,
str(form.errors[k]).decode("utf-8"))
self.error = self.ERROR.VALIDATION_ERROR
self.accepted = False
return self.accepted
# -------------------------------------------------------------------------
def commit(self, ignore_errors=False):
"""
Commit this item to the database
@param ignore_errors: skip invalid components
(still reports errors)
"""
db = current.db
s3db = current.s3db
xml = current.xml
manager = current.manager
table = self.table
# Check if already committed
if self.committed:
# already committed
return True
# If the parent item gets skipped, then skip this item as well
if self.parent is not None and self.parent.skip:
return True
_debug("Committing item %s" % self)
# Resolve references
self._resolve_references()
# Validate
if not self.validate():
_debug("Validation error: %s (%s)" % (self.error, xml.tostring(self.element, pretty_print=True)))
self.skip = True
return ignore_errors
elif self.components:
for component in self.components:
if not component.validate():
if hasattr(component, "tablename"):
tn = component.tablename
else:
tn = None
_debug("Validation error, component=%s" % tn)
component.skip = True
# Skip this item on any component validation errors
# unless ignore_errors is True
if ignore_errors:
continue
else:
self.skip = True
return False
# De-duplicate
self.deduplicate()
# Log this item
if manager.log is not None:
manager.log(self)
# Authorize item
if not self.authorize():
_debug("Not authorized - skip")
self.error = manager.ERROR.NOT_PERMITTED
self.skip = True
return ignore_errors
_debug("Method: %s" % self.method)
# Check if import method is allowed in strategy
if not isinstance(self.strategy, (list, tuple)):
self.strategy = [self.strategy]
if self.method not in self.strategy:
_debug("Method not in strategy - skip")
self.error = manager.ERROR.NOT_PERMITTED
self.skip = True
return True
this = self.original
if not this and self.id and \
self.method in (self.METHOD.UPDATE, self.METHOD.DELETE):
query = (table.id == self.id)
this = db(query).select(limitby=(0, 1)).first()
this_mtime = None
this_mci = 0
if this:
if xml.MTIME in table.fields:
this_mtime = xml.as_utc(this[xml.MTIME])
if xml.MCI in table.fields:
this_mci = this[xml.MCI]
self.mtime = xml.as_utc(self.mtime)
# Conflict detection
this_modified = True
self.modified = True
self.conflict = False
last_sync = xml.as_utc(self.job.last_sync)
if last_sync:
if this_mtime and this_mtime < last_sync:
this_modified = False
if self.mtime and self.mtime < last_sync:
self.modified = False
if self.modified and this_modified:
self.conflict = True
if self.conflict and \
self.method in (self.METHOD.UPDATE, self.METHOD.DELETE):
_debug("Conflict: %s" % self)
if self.job.onconflict:
self.job.onconflict(self)
if self.data is not None:
data = Storage(self.data)
else:
data = Storage()
# Update existing record
if self.method == self.METHOD.UPDATE:
if this:
if "deleted" in this and this.deleted:
policy = self._get_update_policy(None)
if policy == self.POLICY.NEWER and \
this_mtime and this_mtime > self.mtime or \
policy == self.POLICY.MASTER and \
(this_mci == 0 or self.mci != 1):
self.skip = True
return True
fields = data.keys()
for f in fields:
if f not in this:
continue
if isinstance(this[f], datetime):
if xml.as_utc(data[f]) == xml.as_utc(this[f]):
del data[f]
continue
else:
if data[f] == this[f]:
del data[f]
continue
remove = False
policy = self._get_update_policy(f)
if policy == self.POLICY.THIS:
remove = True
elif policy == self.POLICY.NEWER:
if this_mtime and this_mtime > self.mtime:
remove = True
elif policy == self.POLICY.MASTER:
if this_mci == 0 or self.mci != 1:
remove = True
if remove:
del data[f]
self.data.update({f:this[f]})
if "deleted" in this and this.deleted:
# Undelete re-imported records:
data.update(deleted=False)
if "deleted_fk" in table:
data.update(deleted_fk="")
if "created_by" in table:
data.update(created_by=table.created_by.default)
if "modified_by" in table:
data.update(modified_by=table.modified_by.default)
if not self.skip and not self.conflict and \
(len(data) or self.components or self.references):
if self.uid and xml.UID in table:
data.update({xml.UID:self.uid})
if xml.MTIME in table:
data.update({xml.MTIME: self.mtime})
if xml.MCI in data:
# retain local MCI on updates
del data[xml.MCI]
query = (table._id == self.id)
try:
success = db(query).update(**dict(data))
except:
self.error = sys.exc_info()[1]
self.skip = True
return False
if success:
self.committed = True
else:
# Nothing to update
self.committed = True
# Create new record
elif self.method == self.METHOD.CREATE:
# Do not apply field policy to UID and MCI
UID = xml.UID
if UID in data:
del data[UID]
MCI = xml.MCI
if MCI in data:
del data[MCI]
for f in data:
policy = self._get_update_policy(f)
if policy == self.POLICY.MASTER and self.mci != 1:
del data[f]
if len(data) or self.components or self.references:
# Restore UID and MCI
if self.uid and UID in table.fields:
data.update({UID:self.uid})
if MCI in table.fields:
data.update({MCI:self.mci})
# Insert the new record
try:
success = table.insert(**dict(data))
except:
self.error = sys.exc_info()[1]
self.skip = True
return False
if success:
self.id = success
self.committed = True
else:
# Nothing to create
self.skip = True
return True
# Delete local record
elif self.method == self.METHOD.DELETE:
if this:
if this.deleted:
self.skip = True
policy = self._get_update_policy(None)
if policy == self.POLICY.THIS:
self.skip = True
elif policy == self.POLICY.NEWER and \
(this_mtime and this_mtime > self.mtime):
self.skip = True
elif policy == self.POLICY.MASTER and \
(this_mci == 0 or self.mci != 1):
self.skip = True
else:
self.skip = True
if not self.skip and not self.conflict:
prefix, name = self.tablename.split("_", 1)
resource = manager.define_resource(prefix, name, id=self.id)
ondelete = s3db.get_config(self.tablename, "ondelete")
success = resource.delete(ondelete=ondelete,
cascade=True)
if resource.error:
self.error = resource.error
self.skip = True
return ignore_errors
_debug("Success: %s, id=%s %sd" % (self.tablename, self.id,
self.skip and "skippe" or \
self.method))
return True
# Audit + onaccept on successful commits
if self.committed:
form = Storage()
form.method = self.method
form.vars = self.data
tablename = self.tablename
prefix, name = tablename.split("_", 1)
if self.id:
form.vars.id = self.id
if manager.audit is not None:
manager.audit(self.method, prefix, name,
form=form,
record=self.id,
representation="xml")
s3db.update_super(table, form.vars)
if self.method == self.METHOD.CREATE:
current.auth.s3_set_record_owner(table, self.id)
key = "%s_onaccept" % self.method
onaccept = s3db.get_config(tablename, key,
s3db.get_config(tablename, "onaccept"))
if onaccept:
callback(onaccept, form, tablename=self.tablename)
# Update referencing items
if self.update and self.id:
for u in self.update:
item = u.get("item", None)
if not item:
continue
field = u.get("field", None)
if isinstance(field, (list, tuple)):
pkey, fkey = field
query = table.id == self.id
row = db(query).select(table[pkey],
limitby=(0, 1)).first()
if row:
item._update_reference(fkey, row[pkey])
else:
item._update_reference(field, self.id)
_debug("Success: %s, id=%s %sd" % (self.tablename, self.id,
self.skip and "skippe" or \
self.method))
return True
# -------------------------------------------------------------------------
def _get_update_policy(self, field):
"""
Get the update policy for a field (if the item will
update an existing record)
@param field: the name of the field
"""
if isinstance(self.update_policy, dict):
r = self.update_policy.get(field,
self.update_policy.get("__default__", self.POLICY.THIS))
else:
r = self.update_policy
if not r in self.POLICY.values():
r = self.POLICY.THIS
return r
# -------------------------------------------------------------------------
def _resolve_references(self):
"""
Resolve the references of this item (=look up all foreign
keys from other items of the same job). If a foreign key
is not yet available, it will be scheduled for later update.
"""
if not self.table:
return
items = self.job.items
for reference in self.references:
item = None
field = reference.field
entry = reference.entry
if not entry:
continue
# Resolve key tuples
if isinstance(field, (list,tuple)):
pkey, fkey = field
else:
pkey, fkey = ("id", field)
# Resolve the key table name
ktablename, key, multiple = s3_get_foreign_key(self.table[fkey])
if not ktablename:
if self.tablename == "auth_user" and \
fkey == "organisation_id":
ktablename = "org_organisation"
else:
continue
if entry.tablename:
ktablename = entry.tablename
try:
ktable = current.s3db[ktablename]
except:
continue
# Resolve the foreign key (value)
fk = entry.id
if entry.item_id:
item = items[entry.item_id]
if item:
fk = item.id
if fk and pkey != "id":
row = current.db(ktable._id == fk).select(ktable[pkey],
limitby=(0, 1)).first()
if not row:
fk = None
continue
else:
fk = row[pkey]
# Update record data
if fk:
if multiple:
val = self.data.get(fkey, [])
if fk not in val:
val.append(fk)
self.data[fkey] = val
else:
self.data[fkey] = fk
else:
if fkey in self.data and not multiple:
del self.data[fkey]
if item:
item.update.append(dict(item=self, field=fkey))
# -------------------------------------------------------------------------
def _update_reference(self, field, value):
"""
Helper method to update a foreign key in an already written
record. Will be called by the referenced item after (and only
if) it has been committed. This is only needed if the reference
could not be resolved before commit due to circular references.
@param field: the field name of the foreign key
@param value: the value of the foreign key
"""
if not value or not self.table:
return
db = current.db
if self.id and self.permitted:
fieldtype = str(self.table[field].type)
if fieldtype.startswith("list:reference"):
query = (self.table.id == self.id)
record = db(query).select(self.table[field],
limitby=(0,1)).first()
if record:
values = record[field]
if value not in values:
values.append(value)
db(self.table.id == self.id).update(**{field:values})
else:
db(self.table.id == self.id).update(**{field:value})
# -------------------------------------------------------------------------
def store(self, item_table=None):
"""
Store this item in the DB
"""
_debug("Storing item %s" % self)
if item_table is None:
return None
db = current.db
query = item_table.item_id == self.item_id
row = db(query).select(item_table.id, limitby=(0, 1)).first()
if row:
record_id = row.id
else:
record_id = None
record = Storage(job_id = self.job.job_id,
item_id = self.item_id,
tablename = self.tablename,
record_uid = self.uid,
error = self.error)
if self.element is not None:
element_str = current.xml.tostring(self.element,
xml_declaration=False)
record.update(element=element_str)
if self.data is not None:
data = Storage()
for f in self.data.keys():
table = self.table
if f not in table.fields:
continue
fieldtype = str(self.table[f].type)
if fieldtype == "id" or s3_has_foreign_key(self.table[f]):
continue
data.update({f:self.data[f]})
data_str = cPickle.dumps(data)
record.update(data=data_str)
ritems = []
for reference in self.references:
field = reference.field
entry = reference.entry
store_entry = None
if entry:
if entry.item_id is not None:
store_entry = dict(field=field,
item_id=str(entry.item_id))
elif entry.uid is not None:
store_entry = dict(field=field,
tablename=entry.tablename,
uid=str(entry.uid))
if store_entry is not None:
ritems.append(json.dumps(store_entry))
if ritems:
record.update(ritems=ritems)
citems = [c.item_id for c in self.components]
if citems:
record.update(citems=citems)
if self.parent:
record.update(parent=self.parent.item_id)
if record_id:
db(item_table.id == record_id).update(**record)
else:
record_id = item_table.insert(**record)
_debug("Record ID=%s" % record_id)
return record_id
# -------------------------------------------------------------------------
def restore(self, row):
"""
Restore an item from a item table row. This does not restore
the references (since this can not be done before all items
are restored), must call job.restore_references() to do that
@param row: the item table row
"""
xml = current.xml
self.item_id = row.item_id
self.accepted = None
self.permitted = False
self.committed = False
tablename = row.tablename
self.id = None
self.uid = row.record_uid
if row.data is not None:
self.data = cPickle.loads(row.data)
else:
self.data = Storage()
data = self.data
if xml.MTIME in data:
self.mtime = data[xml.MTIME]
if xml.MCI in data:
self.mci = data[xml.MCI]
UID = xml.UID
if UID in data:
self.uid = data[UID]
self.element = etree.fromstring(row.element)
if row.citems:
self.load_components = row.citems
if row.ritems:
self.load_references = [json.loads(ritem) for ritem in row.ritems]
self.load_parent = row.parent
try:
table = current.s3db[tablename]
except:
self.error = self.ERROR.BAD_RESOURCE
return False
else:
self.table = table
self.tablename = tablename
original = current.manager.original(table, self.data)
if original is not None:
self.original = original
self.id = original[table._id.name]
if UID in original:
self.uid = original[UID]
self.data.update({UID:self.uid})
self.error = row.error
if self.error and not self.data:
# Validation error
return False
return True
# =============================================================================
class S3ImportJob():
"""
Class to import an element tree into the database
"""
JOB_TABLE_NAME = "s3_import_job"
ITEM_TABLE_NAME = "s3_import_item"
# -------------------------------------------------------------------------
def __init__(self, manager, table,
tree=None,
files=None,
job_id=None,
strategy=None,
update_policy=None,
conflict_policy=None,
last_sync=None,
onconflict=None):
"""
Constructor
@param manager: the S3RequestManager instance performing this job
@param tree: the element tree to import
@param files: files attached to the import (for upload fields)
@param job_id: restore job from database (record ID or job_id)
@param strategy: the import strategy
@param update_policy: the update policy
@param conflict_policy: the conflict resolution policy
@param last_sync: the last synchronization time stamp (datetime)
@param onconflict: custom conflict resolver function
"""
self.error = None # the last error
self.error_tree = etree.Element(current.xml.TAG.root)
self.table = table
self.tree = tree
self.files = files
self.directory = Storage()
self.elements = Storage()
self.items = Storage()
self.references = []
self.job_table = None
self.item_table = None
self.count = 0 # total number of records imported
self.created = [] # IDs of created records
self.updated = [] # IDs of updated records
self.deleted = [] # IDs of deleted records
# Import strategy
self.strategy = strategy
if self.strategy is None:
self.strategy = [S3ImportItem.METHOD.CREATE,
S3ImportItem.METHOD.UPDATE,
S3ImportItem.METHOD.DELETE]
if not isinstance(self.strategy, (tuple, list)):
self.strategy = [self.strategy]
# Update policy (default=always update)
self.update_policy = update_policy
if not self.update_policy:
self.update_policy = S3ImportItem.POLICY.OTHER
# Conflict resolution policy (default=always update)
self.conflict_policy = conflict_policy
if not self.conflict_policy:
self.conflict_policy = S3ImportItem.POLICY.OTHER
# Synchronization settings
self.mtime = None
self.last_sync = last_sync
self.onconflict = onconflict
if job_id:
self.__define_tables()
jobtable = self.job_table
if str(job_id).isdigit():
query = jobtable.id == job_id
else:
query = jobtable.job_id == job_id
row = current.db(query).select(limitby=(0, 1)).first()
if not row:
raise SyntaxError("Job record not found")
self.job_id = row.job_id
if not self.table:
tablename = row.tablename
try:
table = current.s3db[tablename]
except:
pass
else:
import uuid
self.job_id = uuid.uuid4() # unique ID for this job
# -------------------------------------------------------------------------
def add_item(self,
element=None,
original=None,
components=None,
parent=None,
joinby=None):
"""
Parse and validate an XML element and add it as new item
to the job.
@param element: the element
@param original: the original DB record (if already available,
will otherwise be looked-up by this function)
@param components: a dictionary of components (as in S3Resource)
to include in the job (defaults to all
defined components)
@param parent: the parent item (if this is a component)
@param joinby: the component join key(s) (if this is a component)
@returns: a unique identifier for the new item, or None if there
was an error. self.error contains the last error, and
self.error_tree an element tree with all failing elements
including error attributes.
"""
if element in self.elements:
# element has already been added to this job
return self.elements[element]
# Parse the main element
item = S3ImportItem(self)
# Update lookup lists
item_id = item.item_id
self.items[item_id] = item
if element is not None:
self.elements[element] = item_id
if not item.parse(element,
original=original,
files=self.files):
self.error = item.error
item.accepted = False
if parent is None:
self.error_tree.append(deepcopy(item.element))
else:
# Now parse the components
table = item.table
components = current.s3db.get_components(table, names=components)
cnames = Storage()
cinfos = Storage()
for alias in components:
component = components[alias]
pkey = component.pkey
if component.linktable:
ctable = component.linktable
fkey = component.lkey
else:
ctable = component.table
fkey = component.fkey
ctablename = ctable._tablename
if ctablename in cnames:
cnames[ctablename].append(alias)
else:
cnames[ctablename] = [alias]
cinfos[(ctablename, alias)] = Storage(component = component,
ctable = ctable,
pkey = pkey,
fkey = fkey,
original = None,
uid = None)
add_item = self.add_item
xml = current.xml
for celement in xml.components(element, names=cnames.keys()):
# Get the component tablename
ctablename = celement.get(xml.ATTRIBUTE.name, None)
if not ctablename:
continue
# Get the component alias (for disambiguation)
calias = celement.get(xml.ATTRIBUTE.alias, None)
if calias is None:
if ctablename not in cnames:
continue
aliases = cnames[ctablename]
if len(aliases) == 1:
calias = aliases[0]
else:
# ambiguous components *must* use alias
continue
if (ctablename, calias) not in cinfos:
continue
else:
cinfo = cinfos[(ctablename, calias)]
component = cinfo.component
original = cinfo.original
ctable = cinfo.ctable
pkey = cinfo.pkey
fkey = cinfo.fkey
if not component.multiple:
if cinfo.uid is not None:
continue
if original is None and item.id:
query = (table.id == item.id) & \
(table[pkey] == ctable[fkey])
original = current.db(query).select(ctable.ALL,
limitby=(0, 1)).first()
if original:
cinfo.uid = uid = original.get(xml.UID, None)
celement.set(xml.UID, uid)
cinfo.original = original
item_id = add_item(element=celement,
original=original,
parent=item,
joinby=(pkey, fkey))
if item_id is None:
item.error = self.error
self.error_tree.append(deepcopy(item.element))
else:
citem = self.items[item_id]
citem.parent = item
item.components.append(citem)
# Handle references
table = item.table
tree = self.tree
if tree is not None:
fields = [table[f] for f in table.fields]
rfields = filter(s3_has_foreign_key, fields)
item.references = self.lookahead(element,
table=table,
fields=rfields,
tree=tree,
directory=self.directory)
for reference in item.references:
entry = reference.entry
if entry and entry.element is not None:
item_id = add_item(element=entry.element)
if item_id:
entry.update(item_id=item_id)
# Parent reference
if parent is not None:
entry = Storage(item_id=parent.item_id,
element=parent.element,
tablename=parent.tablename)
item.references.append(Storage(field=joinby,
entry=entry))
return item.item_id
# -------------------------------------------------------------------------
def lookahead(self,
element,
table=None,
fields=None,
tree=None,
directory=None):
"""
Find referenced elements in the tree
@param element: the element
@param table: the DB table
@param fields: the FK fields in the table
@param tree: the import tree
@param directory: a dictionary to lookup elements in the tree
(will be filled in by this function)
"""
db = current.db
s3db = current.s3db
xml = current.xml
import_uid = xml.import_uid
ATTRIBUTE = xml.ATTRIBUTE
TAG = xml.TAG
UID = xml.UID
reference_list = []
root = None
if tree is not None:
if isinstance(tree, etree._Element):
root = tree
else:
root = tree.getroot()
references = element.findall("reference")
for reference in references:
field = reference.get(ATTRIBUTE.field, None)
# Ignore references without valid field-attribute
if not field or field not in fields:
continue
# Find the key table
multiple = False
fieldtype = str(table[field].type)
if fieldtype.startswith("reference"):
ktablename = fieldtype[10:]
elif fieldtype.startswith("list:reference"):
ktablename = fieldtype[15:]
multiple = True
else:
# ignore if the field is not a reference type
continue
try:
ktable = s3db[ktablename]
except:
# Invalid tablename - skip
continue
tablename = reference.get(ATTRIBUTE.resource, None)
# Ignore references to tables without UID field:
if UID not in ktable.fields:
continue
# Fall back to key table name if tablename is not specified:
if not tablename:
tablename = ktablename
# Super-entity references must use the super-key:
if tablename != ktablename:
field = (ktable._id.name, field)
# Ignore direct references to super-entities:
if tablename == ktablename and ktable._id.name != "id":
continue
# Get the foreign key
uids = reference.get(UID, None)
attr = UID
if not uids:
uids = reference.get(ATTRIBUTE.tuid, None)
attr = ATTRIBUTE.tuid
if uids and multiple:
uids = json.loads(uids)
elif uids:
uids = [uids]
# Find the elements and map to DB records
relements = []
# Create a UID<->ID map
id_map = Storage()
if attr == UID and uids:
_uids = map(import_uid, uids)
query = ktable[UID].belongs(_uids)
records = db(query).select(ktable.id,
ktable[UID])
id_map = dict([(r[UID], r.id) for r in records])
if not uids:
# Anonymous reference: <resource> inside the element
expr = './/%s[@%s="%s"]' % (TAG.resource,
ATTRIBUTE.name,
tablename)
relements = reference.xpath(expr)
if relements and not multiple:
relements = [relements[0]]
elif root is not None:
for uid in uids:
entry = None
# Entry already in directory?
if directory is not None:
entry = directory.get((tablename, attr, uid), None)
if not entry:
expr = ".//%s[@%s='%s' and @%s='%s']" % (
TAG.resource,
ATTRIBUTE.name,
tablename,
attr,
uid)
e = root.xpath(expr)
if e:
# Element in the source => append to relements
relements.append(e[0])
else:
# No element found, see if original record exists
_uid = import_uid(uid)
if _uid and _uid in id_map:
_id = id_map[_uid]
entry = Storage(tablename=tablename,
element=None,
uid=uid,
id=_id,
item_id=None)
reference_list.append(Storage(field=field,
entry=entry))
else:
continue
else:
reference_list.append(Storage(field=field,
entry=entry))
# Create entries for all newly found elements
for relement in relements:
uid = relement.get(attr, None)
if attr == UID:
_uid = import_uid(uid)
id = _uid and id_map and id_map.get(_uid, None) or None
else:
_uid = None
id = None
entry = Storage(tablename=tablename,
element=relement,
uid=uid,
id=id,
item_id=None)
# Add entry to directory
if uid and directory is not None:
directory[(tablename, attr, uid)] = entry
# Append the entry to the reference list
reference_list.append(Storage(field=field, entry=entry))
return reference_list
# -------------------------------------------------------------------------
def load_item(self, row):
"""
Load an item from the item table (counterpart to add_item
when restoring a job from the database)
"""
item = S3ImportItem(self)
if not item.restore(row):
self.error = item.error
if item.load_parent is None:
self.error_tree.append(deepcopy(item.element))
# Update lookup lists
item_id = item.item_id
self.items[item_id] = item
return item_id
# -------------------------------------------------------------------------
def resolve(self, item_id, import_list):
"""
Resolve the reference list of an item
@param item_id: the import item UID
@param import_list: the ordered list of items (UIDs) to import
"""
item = self.items[item_id]
if item.lock or item.accepted is False:
return False
references = []
for reference in item.references:
ritem_id = reference.entry.item_id
if ritem_id and ritem_id not in import_list:
references.append(ritem_id)
for ritem_id in references:
item.lock = True
if self.resolve(ritem_id, import_list):
import_list.append(ritem_id)
item.lock = False
return True
# -------------------------------------------------------------------------
def commit(self, ignore_errors=False):
"""
Commit the import job to the DB
@param ignore_errors: skip any items with errors
(does still report the errors)
"""
ATTRIBUTE = current.xml.ATTRIBUTE
# Resolve references
import_list = []
for item_id in self.items:
self.resolve(item_id, import_list)
if item_id not in import_list:
import_list.append(item_id)
# Commit the items
items = self.items
count = 0
mtime = None
created = []
cappend = created.append
updated = []
deleted = []
tablename = self.table._tablename
for item_id in import_list:
item = items[item_id]
error = None
success = item.commit(ignore_errors=ignore_errors)
error = item.error
if error:
self.error = error
element = item.element
if element is not None:
if not element.get(ATTRIBUTE.error, False):
element.set(ATTRIBUTE.error, str(self.error))
self.error_tree.append(deepcopy(element))
if not ignore_errors:
return False
elif item.tablename == tablename:
count += 1
if mtime is None or item.mtime > mtime:
mtime = item.mtime
if item.id:
if item.method == item.METHOD.CREATE:
cappend(item.id)
elif item.method == item.METHOD.UPDATE:
updated.append(item.id)
elif item.method == item.METHOD.DELETE:
deleted.append(item.id)
self.count = count
self.mtime = mtime
self.created = created
self.updated = updated
self.deleted = deleted
return True
# -------------------------------------------------------------------------
def __define_tables(self):
"""
Define the database tables for jobs and items
"""
self.job_table = self.define_job_table()
self.item_table = self.define_item_table()
# -------------------------------------------------------------------------
@classmethod
def define_job_table(cls):
db = current.db
if cls.JOB_TABLE_NAME not in db:
job_table = db.define_table(cls.JOB_TABLE_NAME,
Field("job_id", length=128,
unique=True,
notnull=True),
Field("tablename"),
Field("timestmp", "datetime",
default=datetime.utcnow()))
else:
job_table = db[cls.JOB_TABLE_NAME]
return job_table
# -------------------------------------------------------------------------
@classmethod
def define_item_table(cls):
db = current.db
if cls.ITEM_TABLE_NAME not in db:
item_table = db.define_table(cls.ITEM_TABLE_NAME,
Field("item_id", length=128,
unique=True,
notnull=True),
Field("job_id", length=128),
Field("tablename", length=128),
#Field("record_id", "integer"),
Field("record_uid"),
Field("error", "text"),
Field("data", "text"),
Field("element", "text"),
Field("ritems", "list:string"),
Field("citems", "list:string"),
Field("parent", length=128))
else:
item_table = db[cls.ITEM_TABLE_NAME]
return item_table
# -------------------------------------------------------------------------
def store(self):
"""
Store this job and all its items in the job table
"""
db = current.db
_debug("Storing Job ID=%s" % self.job_id)
self.__define_tables()
jobtable = self.job_table
query = jobtable.job_id == self.job_id
row = db(query).select(jobtable.id, limitby=(0, 1)).first()
if row:
record_id = row.id
else:
record_id = None
record = Storage(job_id=self.job_id)
try:
tablename = self.table._tablename
except:
pass
else:
record.update(tablename=tablename)
for item in self.items.values():
item.store(item_table=self.item_table)
if record_id:
db(jobtable.id == record_id).update(**record)
else:
record_id = jobtable.insert(**record)
_debug("Job record ID=%s" % record_id)
return record_id
# -------------------------------------------------------------------------
def get_tree(self):
"""
Reconstruct the element tree of this job
"""
if self.tree is not None:
return tree
else:
xml = current.xml
root = etree.Element(xml.TAG.root)
for item in self.items.values():
if item.element is not None and not item.parent:
if item.tablename == self.table._tablename or \
item.element.get(xml.UID, None) or \
item.element.get(xml.ATTRIBUTE.tuid, None):
root.append(deepcopy(item.element))
return etree.ElementTree(root)
# -------------------------------------------------------------------------
def delete(self):
"""
Delete this job and all its items from the job table
"""
db = current.db
_debug("Deleting job ID=%s" % self.job_id)
self.__define_tables()
item_table = self.item_table
query = item_table.job_id == self.job_id
db(query).delete()
job_table = self.job_table
query = job_table.job_id == self.job_id
db(query).delete()
# -------------------------------------------------------------------------
def restore_references(self):
"""
Restore the job's reference structure after loading items
from the item table
"""
db = current.db
UID = current.xml.UID
for item in self.items.values():
for citem_id in item.load_components:
if citem_id in self.items:
item.components.append(self.items[citem_id])
item.load_components = []
for ritem in item.load_references:
field = ritem["field"]
if "item_id" in ritem:
item_id = ritem["item_id"]
if item_id in self.items:
_item = self.items[item_id]
entry = Storage(tablename=_item.tablename,
element=_item.element,
uid=_item.uid,
id=_item.id,
item_id=item_id)
item.references.append(Storage(field=field,
entry=entry))
else:
_id = None
uid = ritem.get("uid", None)
tablename = ritem.get("tablename", None)
if tablename and uid:
try:
table = current.s3db[tablename]
except:
continue
if UID not in table.fields:
continue
query = table[UID] == uid
row = db(query).select(table._id,
limitby=(0, 1)).first()
if row:
_id = row[table._id.name]
else:
continue
entry = Storage(tablename = ritem["tablename"],
element=None,
uid = ritem["uid"],
id = _id,
item_id = None)
item.references.append(Storage(field=field,
entry=entry))
item.load_references = []
if item.load_parent is not None:
item.parent = self.items[item.load_parent]
item.load_parent = None
# END =========================================================================
| Java |
package br.ufrj.g2matricula.domain;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import br.ufrj.g2matricula.domain.enumeration.MatriculaStatus;
/**
* A Matricula.
*/
@Entity
@Table(name = "matricula")
@Document(indexName = "matricula")
public class Matricula implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private MatriculaStatus status;
@ManyToOne
private Aluno dreAluno;
@ManyToOne
private Curso curso;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MatriculaStatus getStatus() {
return status;
}
public Matricula status(MatriculaStatus status) {
this.status = status;
return this;
}
public void setStatus(MatriculaStatus status) {
this.status = status;
}
public Aluno getDreAluno() {
return dreAluno;
}
public Matricula dreAluno(Aluno aluno) {
this.dreAluno = aluno;
return this;
}
public void setDreAluno(Aluno aluno) {
this.dreAluno = aluno;
}
public Curso getCurso() {
return curso;
}
public Matricula curso(Curso curso) {
this.curso = curso;
return this;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Matricula matricula = (Matricula) o;
if (matricula.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), matricula.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Matricula{" +
"id=" + getId() +
", status='" + getStatus() + "'" +
"}";
}
}
| Java |
# rhodecode-ce-dockerized
Docker container for RhodeCode Community Edition repository management platform
# WIP
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.