repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
the-t-in-rtf/gpii-handlebars | src/js/server/lib/resolver.js | 1883 | /* eslint-env node */
"use strict";
var fluid = require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.handlebars");
/**
*
* @typedef PrioritisedPathDef
* @property {String} [priority] - The priority for this entry in the final array, relative to other path definitions.
* @property {String} [namespace] - The namespace that other entries can use to express their priority.
* @property {String} path - A package-relative path to be resolved.
*
*/
/**
*
* A static function that uses `fluid.module.resolvePath` to resolve all paths, and return them ordered by priority.
*
* (See https://docs.fluidproject.org/infusion/development/Priorities.html)
*
* Used to consistently resolve the path to template and message bundle directories in the `handlebars`, `inline`, and
* `dispatcher` modules.
*
* Takes a string describing a single path, or an array of strings describing multiple paths. Returns an array of
* resolved paths.
*
* @param {Object<PrioritisedPathDef>|Object<String>} pathsToResolve - A map of paths to resolve.
* @return {Array<String>} - An array of resolved paths.
*
*/
gpii.handlebars.resolvePrioritisedPaths = function (pathsToResolve) {
// Make sure that any short form (string) paths are resolved to structured path defs.
var longFormPathDefs = fluid.transform(pathsToResolve, function (pathDef) {
if (fluid.get(pathDef, "path")) {
return pathDef;
}
else {
return { path: pathDef };
}
});
var prioritisedPathDefs = fluid.parsePriorityRecords(longFormPathDefs, "resource directory");
var resolvedPaths = fluid.transform(prioritisedPathDefs, function (pathDef) {
var pathToResolve = fluid.get(pathDef, "path") || pathDef;
return fluid.module.resolvePath(pathToResolve);
});
return resolvedPaths;
};
| bsd-3-clause |
evelinad/eigen | build/test/CMakeFiles/array_replicate_1.dir/DependInfo.cmake | 1015 | # The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/home/evelina/Downloads/eigen-eigen-b30b87236a1b/test/array_replicate.cpp" "/home/evelina/Downloads/eigen-eigen-b30b87236a1b/build/test/CMakeFiles/array_replicate_1.dir/array_replicate.cpp.o"
)
set(CMAKE_CXX_COMPILER_ID "GNU")
# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS
"QT_CORE_LIB"
"QT_GUI_LIB"
"QT_NO_DEBUG"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
"test"
"../test"
".."
"."
"/usr/include/qt4"
"/usr/include/qt4/QtGui"
"/usr/include/qt4/QtCore"
)
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
| bsd-3-clause |
leonfoks/coretran | src/arrays/sm_array_d1D.f90 | 16258 | submodule (m_array1D) m_Array_d1D
!! Routines for double precision arrays
implicit none
contains
!====================================================================!
module procedure arange_d1D
!! Interfaced with [[arange]]
!====================================================================!
!module function arange_d1D(start,stp,_step) result(this)
!real(r64) :: start !! Start from here
!real(r64) :: stp !! Stop here
!real(r64) :: step !! Step size
!real(r64), allocatable :: res(:)
integer(i32) :: i
integer(i32) :: N
real(r64) :: step_
step_=1.d0
if (present(step)) step_ = step
N=int((stp-start)/step_)+1
if (size(res) /= N) call eMsg('arange_d1D:1D Array must be size '//str(N))
if (step_ == 1.d0) then
do i = 1, N
res(i) = start + real(i-1, kind=r64)
enddo
else
do i = 1, N
res(i) = start + real(i-1, kind=r64)*step_
enddo
endif
end procedure
!====================================================================!
!====================================================================!
module procedure diff_d1D
!! Interfaced [[diff]]
!====================================================================!
! real(r64), intent(in) :: this(:) !! 1D array
! real(r64) :: res(size(this)-1) !! Difference along array
integer(i32) :: i
integer(i32) :: N
N=size(this)
if (size(res) /= N-1) call eMsg('diff_d1D:Result must be size '//str(N-1))
do i=1,N-1
res(i) = this(i+1) - this(i)
end do
end procedure
!====================================================================!
!====================================================================!
module procedure isSorted_d1D
!! Interfaced with [[isSorted]]
!====================================================================!
!module function isSorted_d1D(this) result(yes)
!real(r64):: this(:) !! 1D array
!logical :: yes !! isSorted
integer :: i,N
N=size(this)
yes=.true.
do i=2,N
if (this(i) < this(i-1)) then
yes=.false.
return
end if
end do
end procedure
!====================================================================!
!====================================================================!
module procedure isSorted_d1Di1D
!! Interfaced with [[isSorted]]
!====================================================================!
!module function isSorted_d1D(this) result(yes)
!real(r64):: this(:) !! 1D array
!integer(i32) :: indx(:)
!logical :: yes !! isSorted
integer :: i,N
N=size(this)
yes=.true.
do i=2,N
if (this(indx(i)) < this(indx(i-1))) then
yes=.false.
return
end if
end do
end procedure
!====================================================================!
!====================================================================!
module procedure repeat_d1D
!! Interfaced with [[repeat]]
!====================================================================!
! real(r64) :: this(:) !! 1D array
! integer(i32) :: nRepeats !! Number of times each element should be repeated
! real(r64) :: res(size(this)*nRepeats)
integer(i32) :: i,k,N,nTmp
N = size(this)
nTmp = N * nRepeats
call allocate(res, nTmp)
!if (size(res) /= nTmp) call eMsg('repeat_d1D:Result must be size '//str(nTmp))
k = 1
do i = 1, N
res(k:k + nRepeats - 1) = this(i) ! Repeat the element
k = k + nRepeats
end do
end procedure
!====================================================================!
!====================================================================!
module procedure shuffle_d1D
!! Interfaced with [[shuffle]]
!====================================================================!
!module subroutine shuffle_d1D(this)
!real(r64) :: this(:)
integer(i32) :: i
integer(i32) :: N
integer(i32) :: r
N=size(this)
do i = 2, N
call rngInteger(r, 1, i)
call swap(this(i), this(r))
end do
end procedure
!====================================================================!
! !====================================================================!
! function calcInternalAngle_Vector(this,that) result(theta)
! !====================================================================!
! real(r64) :: this(:),that(:)
! real(r64) :: theta
! theta=dacos(dot_product(this,that)/(magnitude_Vector(this)*magnitude_Vector(that)))
! end function
! !====================================================================!
! !====================================================================!
! function outerproduct(a,b) result(c)
! !====================================================================!
! real(r64) :: a(:),b(:)
! integer :: nB
! real(r64) :: c(size(a),size(b))
! integer :: i
! nB=size(b)
! do i=1,nB
! c(:,i)=a*b(i)
! enddo
! end function
! !====================================================================!
! !====================================================================!
! function normalize_Vector(this) result(that)
! !====================================================================!
! real(r64) :: this(:)
! real(r64) :: that(size(this))
! real(r64) :: magnitude
!
! that=this
! magnitude=magnitude_Vector(this)
! if (magnitude /= 0.d0) that=that/magnitude
!
! end function
! !====================================================================!
! !====================================================================!
! function ContraharmonicMean(this,order) result(that)
! !====================================================================!
! ! Input
! real(r64) :: this(:)
! real(r64) :: order
! ! Output
! real(r64) :: that
! ! Specific
! real(r64) :: tmp
! !====================================================================!
! ! Compute the Contraharmonic mean of a vector
! ! Digital Image Processing|Gonzalez and Woods|2011|3rd Edition
! !====================================================================!
! tmp=sum(this)
! that=tmp**(order+1.d0)
! that=that/(tmp**order)
! return
! end function
! !====================================================================!
! !====================================================================!
! function HarmonicMean(this) result(that)
! !====================================================================!
! real(r64) :: this(:)
! real(r64) :: that
! real(r64) :: N
! !====================================================================!
! ! Compute the Harmonic mean of a vector
! ! Digital Image Processing|Gonzalez and Woods|2011|3rd Edition
! !====================================================================!
! N=dble(size(this))
! that=N/(sum(1.d0/this))
! return
! end function
! !====================================================================!
! !====================================================================!
! function isConstant_DV(this) result(yes)
! !====================================================================!
! ! Checks whether a vector contains the same value throughout
! real(r64) :: this(:)
! logical :: yes
! real(r64) :: tmp
! yes=.true.
! tmp=this(1)
! if (any(this/=tmp)) yes=.false.
! end function
! !====================================================================!
! !====================================================================!
! function isConstantIncrement_DV(this,val) result(yes)
! !====================================================================!
! ! Checks whether a vector contains the same value throughout
! real(r64) :: this(:)
! real(r64) :: val
! logical :: yes
! integer :: i,N
! N=size(this)
! yes=.true.
! do i=2,N
! if ((this(i)-this(i-1))/=val) then
! yes=.false.
! return
! endif
! enddo
! end function
! !====================================================================!
! !====================================================================!
! function isInside1D_I1(this,x0,sortme) result(yes)
! !====================================================================!
! integer :: this(:)
! integer :: x0
! integer :: n
! logical :: sortme
! logical :: yes
! !====================================================================!
! ! Determine if x0 is within this
! !====================================================================!
! n=size(this)
! if (sortme) call sort(this)
!
! yes=.true.
! if (x0 < this(1)) yes=.false.
! if (x0 > this(n)) yes=.false.
!
! end function
! !====================================================================!
! !====================================================================!
! function isFactor2Vector(this) result(yes)
! !====================================================================!
! real(r64) :: this(:)
! logical :: yes
! integer :: ii,N
! real(r64) :: tmp1,tmp2
! N=size(this)
! yes=.true.
! tmp1=dabs(this(2)-this(1))
! do ii=3,N
! tmp2=dabs(this(ii)-this(ii-1))
! if (tmp2==tmp1) cycle
! if (tmp2 /= 2.d0*tmp1 .and. tmp2/=0.5d0*tmp1) then
! yes=.false.
! return
! endif
! tmp1=tmp2
! enddo
! end function
! !====================================================================!
! !====================================================================!
! function getBin1D_I1(this,x0,sortme) result(i)
! !====================================================================!
! integer :: this(:)
! integer :: x0
! integer :: x1,x2,x3
! logical :: sortme
! integer :: i
! integer :: i1,i2,i3,n
! !====================================================================!
! ! Determine the bin in this containing x0 using bisection
! ! Forces the return index to lie within the vector "this"
! !====================================================================!
! n=size(this)
! if (sortme) call sort(this)
!
! if (x0.le.this(2) ) then
! i=1
! return
! endif
! if (x0.gt.this(n-1)) then
! i=n-1
! return
! endif
!
! i1=2;
! x1=this(i1) ! Left value
! i3=n-2;
! x3=this(i3) ! Right value
! i2=(i3+i1)/2;
! x2=this(i2) ! Central value
!
! do while ( (i3-i1) /= 1)
! if (x0 <= x2) then;
! i3=i2;
! x3=x2
! elseif (x0 > x2) then;
! i1=i2;
! x1=x2;
! endif
! i2=(i3+i1)/2;
! x2=this(i2) ! Central value
! enddo
! i=i1
! end function
! !====================================================================!
! !====================================================================!
! function isInside1D_D1(this,x0,sortme) result(yes)
! !====================================================================!
! real(r64) :: this(:)
! real(r64) :: x0
! integer :: n
! logical :: sortme
! logical :: yes
! !====================================================================!
! ! Determine if x0 is within this
! !====================================================================!
! n=size(this)
! if (sortme) call sort(this)
!
! yes=.true.
! if (x0 < this(1)) yes=.false.
! if (x0 > this(n)) yes=.false.
!
! end function
! !====================================================================!
! !====================================================================!
! function getBin1D_D1(this,x0,sortme) result(i)
! !====================================================================!
! real(r64) :: this(:)
! real(r64) :: x0
! real(r64) :: x1,x2,x3
! logical :: sortme
! integer :: i
! integer :: i1,i2,i3,n
! !====================================================================!
! ! Determine the bin in this containing x0 using bisection
! ! Forces the return index to lie within the vector "this"
! ! Do NOT use an unsorted vector!
! !====================================================================!
! n=size(this)
! if (sortme) call sort(this)
!
! if (x0 <= this(2)) then
! i=1
! return
! endif
! if (x0 > this(n-1)) then
! i=n-1;
! return;
! endif
!
! i1=2;
! x1=this(i1) ! Left value
! i3=n-2;
! x3=this(i3) ! Right value
! i2=(i3+i1)/2;
! x2=this(i2) ! Central value
! ! Bisection Method to obtain the bin
! do while ( (i3-i1) /= 1)
! if (x0 <= x2) then;
! i3=i2;
! x3=x2
! elseif (x0 > x2) then;
! i1=i2;
! x1=x2;
! endif
! i2=(i3+i1)/2;
! x2=this(i2) ! Central value
! enddo
! i=i1
! end function
! !====================================================================!
! !====================================================================!
! function getSmallestIncrement(this) result(inc)
! !====================================================================!
! real(r64) :: this(:)
! real(r64) :: inc
! integer :: ii,N
! real(r64) :: tmp1
! N=size(this)
! tmp1=dabs(this(2)-this(1))
! inc=tmp1
! do ii=2,N
! tmp1=dabs(this(ii+1)-this(ii))
! if (tmp1 < inc) inc=tmp1
! enddo
! end function
! !====================================================================!
! !====================================================================!
! subroutine unitize_1D(this)
! !====================================================================!
! real(r64) :: this(:)
! ! Normalize the input vector
! this=this-minval(this)
! this=this/maxval(this)
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine scaleVector(this,xmin,xmax)
! !====================================================================!
! ! Scales a vector to [xmin xmax]
! real(r64) :: this(:),xmin,xmax
! ! Normalize the input vector
! call unitize(this)
! ! Map to new limits
! this=(this*(xmax-xmin))+xmin
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine integerizeVector(this,x0,inc)
! !====================================================================!
! ! Takes a vector and maps it to integer increments for easy nearest neighbour
! ! operations for grids, e.g. if x0=10, inc=5 then
! ! (-50,-12.5,5,24.3) = (-11,-3.5,0,3.86) Only the 4th point is inside a grid.
! real(r64) :: this(:),inc,x0
! this=((this-x0)/inc)+1.d0
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine deintegerizeVector(this,x0,inc)
! !====================================================================!
! ! Takes an integerized vector and maps it to non-integerized format.
! real(r64) :: this(:),inc,x0
! this=((this-1.d0)*inc)+x0
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine removeItem(this,i)
! !====================================================================!
! real(r64) :: this(:)
! integer :: i,j
! integer :: N
! N=size(this)
! if (i < 1 .or. i > N) call Emsg('removeItem','index is outside the array')
! do j=i,N-1
! this(j)=this(j+1)
! enddo
! this(N)=tiny(0.d0)
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine insertItem(this,i,val)
! !====================================================================!
! real(r64) :: this(:)
! integer :: i,j
! real(r64) :: val
! integer :: N
! N=size(this)
! if (i < 1 .or. i > N) call Emsg('insertItem','index is outside the array')
! do j=N,i+1,-1
! this(j)=this(j-1)
! enddo
! this(i)=val
! end subroutine
! !====================================================================!
! !====================================================================!
! subroutine writeToFile_D1D(this,fname)
! !====================================================================!
! real(r64) :: this(:)
! character(len=*) :: fname
! integer :: i,istat,iunit,N
! N=size(this)
! call openFile(fname,iunit,'unknown',istat)
! do i=1,N
! write(iunit,'(a)') str(this(i),7)
! enddo
! call closeFile(fname,iunit,'unknown',istat)
! end subroutine
! !====================================================================!
end submodule
| bsd-3-clause |
louiscryan/grpc-java | interop-testing/src/test/java/io/grpc/testing/integration/TransportCompressionTest.java | 8398 | /*
* Copyright 2015, Google 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* OWNER 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.
*/
package io.grpc.testing.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.google.protobuf.ByteString;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.Codec;
import io.grpc.CompressorRegistry;
import io.grpc.DecompressorRegistry;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.internal.GrpcUtil;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.testing.integration.Messages.CompressionType;
import io.grpc.testing.integration.Messages.Payload;
import io.grpc.testing.integration.Messages.PayloadType;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Tests that compression is turned on.
*/
@RunWith(JUnit4.class)
public class TransportCompressionTest extends AbstractInteropTest {
// Masquerade as identity.
private static final Fzip FZIPPER = new Fzip("gzip", new Codec.Gzip());
private volatile boolean expectFzip;
private static final DecompressorRegistry decompressors = DecompressorRegistry.emptyInstance()
.with(Codec.Identity.NONE, false)
.with(FZIPPER, true);
private static final CompressorRegistry compressors = CompressorRegistry.newEmptyInstance();
@Before
public void beforeTests() {
FZIPPER.anyRead = false;
FZIPPER.anyWritten = false;
}
/** Start server. */
@BeforeClass
public static void startServer() {
compressors.register(FZIPPER);
compressors.register(Codec.Identity.NONE);
startStaticServer(
NettyServerBuilder.forPort(0)
.maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.compressorRegistry(compressors)
.decompressorRegistry(decompressors),
new ServerInterceptor() {
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata headers, ServerCallHandler<ReqT, RespT> next) {
Listener<ReqT> listener = next.startCall(call, headers);
// TODO(carl-mastrangelo): check that encoding was set.
call.setMessageCompression(true);
return listener;
}
});
}
/** Stop server. */
@AfterClass
public static void stopServer() {
stopStaticServer();
}
@Test
public void compresses() {
expectFzip = true;
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(314159)
.setResponseCompression(CompressionType.GZIP)
.setResponseType(PayloadType.COMPRESSABLE)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setType(PayloadType.COMPRESSABLE)
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertEquals(goldenResponse, blockingStub.unaryCall(request));
// Assert that compression took place
assertTrue(FZIPPER.anyRead);
assertTrue(FZIPPER.anyWritten);
}
@Override
protected ManagedChannel createChannel() {
return NettyChannelBuilder.forAddress("localhost", getPort())
.maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.decompressorRegistry(decompressors)
.compressorRegistry(compressors)
.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
return new ForwardingClientCall<ReqT, RespT>() {
@Override
protected ClientCall<ReqT, RespT> delegate() {
return call;
}
@Override
public void start(
final ClientCall.Listener<RespT> responseListener, Metadata headers) {
ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {
@Override
protected io.grpc.ClientCall.Listener<RespT> delegate() {
return responseListener;
}
@Override
public void onHeaders(Metadata headers) {
super.onHeaders(headers);
if (expectFzip) {
String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
assertEquals(encoding, FZIPPER.getMessageEncoding());
}
}
};
super.start(listener, headers);
setMessageCompression(true);
}
};
}
})
.usePlaintext(true)
.build();
}
/**
* Fzip is a custom compressor.
*/
static class Fzip implements Codec {
volatile boolean anyRead;
volatile boolean anyWritten;
volatile Codec delegate;
private final String actualName;
public Fzip(String actualName, Codec delegate) {
this.actualName = actualName;
this.delegate = delegate;
}
@Override
public String getMessageEncoding() {
return actualName;
}
@Override
public OutputStream compress(OutputStream os) throws IOException {
return new FilterOutputStream(delegate.compress(os)) {
@Override
public void write(int b) throws IOException {
super.write(b);
anyWritten = true;
}
};
}
@Override
public InputStream decompress(InputStream is) throws IOException {
return new FilterInputStream(delegate.decompress(is)) {
@Override
public int read() throws IOException {
int val = super.read();
anyRead = true;
return val;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int total = super.read(b, off, len);
anyRead = true;
return total;
}
};
}
}
}
| bsd-3-clause |
GaloisInc/hacrypto | src/Java/BouncyCastle/BouncyCastle-1.54/bcpkix-jdk15on-154/javadoc/org/bouncycastle/cms/OriginatorInfoGenerator.html | 11063 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_91) on Tue Dec 29 12:44:24 AEDT 2015 -->
<title>OriginatorInfoGenerator (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="OriginatorInfoGenerator (Bouncy Castle Library 1.54 API Specification)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/bouncycastle/cms/KeyTransRecipientInformation.html" title="class in org.bouncycastle.cms"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/bouncycastle/cms/OriginatorInformation.html" title="class in org.bouncycastle.cms"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/bouncycastle/cms/OriginatorInfoGenerator.html" target="_top">Frames</a></li>
<li><a href="OriginatorInfoGenerator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.bouncycastle.cms</div>
<h2 title="Class OriginatorInfoGenerator" class="title">Class OriginatorInfoGenerator</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.bouncycastle.cms.OriginatorInfoGenerator</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">OriginatorInfoGenerator</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/bouncycastle/cms/OriginatorInfoGenerator.html#OriginatorInfoGenerator(org.bouncycastle.util.Store)">OriginatorInfoGenerator</a></strong>(org.bouncycastle.util.Store origCerts)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/bouncycastle/cms/OriginatorInfoGenerator.html#OriginatorInfoGenerator(org.bouncycastle.util.Store,%20org.bouncycastle.util.Store)">OriginatorInfoGenerator</a></strong>(org.bouncycastle.util.Store origCerts,
org.bouncycastle.util.Store origCRLs)</code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/bouncycastle/cms/OriginatorInfoGenerator.html#OriginatorInfoGenerator(org.bouncycastle.cert.X509CertificateHolder)">OriginatorInfoGenerator</a></strong>(<a href="../../../org/bouncycastle/cert/X509CertificateHolder.html" title="class in org.bouncycastle.cert">X509CertificateHolder</a> origCert)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../org/bouncycastle/cms/OriginatorInformation.html" title="class in org.bouncycastle.cms">OriginatorInformation</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/bouncycastle/cms/OriginatorInfoGenerator.html#generate()">generate</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="OriginatorInfoGenerator(org.bouncycastle.cert.X509CertificateHolder)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OriginatorInfoGenerator</h4>
<pre>public OriginatorInfoGenerator(<a href="../../../org/bouncycastle/cert/X509CertificateHolder.html" title="class in org.bouncycastle.cert">X509CertificateHolder</a> origCert)</pre>
</li>
</ul>
<a name="OriginatorInfoGenerator(org.bouncycastle.util.Store)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>OriginatorInfoGenerator</h4>
<pre>public OriginatorInfoGenerator(org.bouncycastle.util.Store origCerts)
throws <a href="../../../org/bouncycastle/cms/CMSException.html" title="class in org.bouncycastle.cms">CMSException</a></pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../org/bouncycastle/cms/CMSException.html" title="class in org.bouncycastle.cms">CMSException</a></code></dd></dl>
</li>
</ul>
<a name="OriginatorInfoGenerator(org.bouncycastle.util.Store, org.bouncycastle.util.Store)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>OriginatorInfoGenerator</h4>
<pre>public OriginatorInfoGenerator(org.bouncycastle.util.Store origCerts,
org.bouncycastle.util.Store origCRLs)
throws <a href="../../../org/bouncycastle/cms/CMSException.html" title="class in org.bouncycastle.cms">CMSException</a></pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../org/bouncycastle/cms/CMSException.html" title="class in org.bouncycastle.cms">CMSException</a></code></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="generate()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>generate</h4>
<pre>public <a href="../../../org/bouncycastle/cms/OriginatorInformation.html" title="class in org.bouncycastle.cms">OriginatorInformation</a> generate()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/bouncycastle/cms/KeyTransRecipientInformation.html" title="class in org.bouncycastle.cms"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/bouncycastle/cms/OriginatorInformation.html" title="class in org.bouncycastle.cms"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/bouncycastle/cms/OriginatorInfoGenerator.html" target="_top">Frames</a></li>
<li><a href="OriginatorInfoGenerator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-3-clause |
akaidrive2014/persseleb | protected/views/adminosu/news/admin.php | 4360 | <?php
/* @var $this NewsController */
/* @var $model SBNews */
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#".$this->IDname."-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<?php echo $title;?>
<?php echo CHtml::ajaxLink(
' <i class="glyphicon glyphicon-plus"></i> Add New ',
array($this->id.'/create'),
array('update' => ".view-x",//".content-data-x",
'beforeSend' => 'function(){
loading("show");
}',
'complete' => 'function(){
/*$(".loading-x").fadeOut("slow",function(){
$(".modal-dialog").css({"width":"90%"});
});*/
//loading("hide");
$(".loading-x").fadeOut("slow",function(){
$(".modal-dialog").css({"width":"90%"});
});
return false;
}',
),
array('class'=>'btn btn-success btn-x pull-right')
);?>
<div class="clearfix"></div>
</div>
<div class="table-responsive">
<br>
<?php echo CHtml::link('<i class="glyphicon glyphicon-search"></i> Search','#',array('class'=>'search-button btn btn-default')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'pagerCssClass'=>'text-center',
'pager' => array(
'class' => 'CLinkPager',
'header' => '',
'selectedPageCssClass'=>'active',
'nextPageLabel'=>'<i class="fa fa-angle-right"></i>',
'prevPageLabel'=>'<i class="fa fa-angle-left"></i>',
'lastPageLabel'=>'<i class="fa fa-angle-double-right"></i>',
'firstPageLabel'=>'<i class="fa fa-angle-double-left"></i>',
'htmlOptions'=>array(
'class'=>'pagination pagination-sm',
'id'=>FALSE,
),
),
'id'=>$this->IDname.'-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'itemsCssClass'=>'table table-bordered',
'afterAjaxUpdate'=>'modal',
'columns'=>array(
'news_id',
array(
'name'=>'news_title',
'value'=>function($data){
return "<a href=\"{$data->url_link}\">{$data->news_title}</a>";
},
'type'=>'HTML',
),
array(
'name'=>'source',
'value'=>function($data){
return "<a target='_blank' href=\"{$data->url}\">{$data->source}</a>";
},
'type'=>'HTML',
),
array(
'name'=>'news_date',
'value'=>'$data->display_date_admin'
),
/*
'original_url',
*/
array(
'class'=>'CButtonColumn',
'template'=>'{update} {delete}',
'buttons'=>array(
'update' => array(
'options' => array('data-toggle'=>'tooltip','title' => 'Edit', 'class' => 'btn btn-x btn-default btn-xs'),
'label' => "<i class='fa fa-pencil-square-o'></i>",
'imageUrl' => false,
'click'=>"function(){
loading('show');
$('.view-x').load($(this).attr('href'),function(){
//loading('hide')
$('.modal-dialog').css({'width':'90%'});
});
return false;
}",
),
'delete' => array(
'options' => array('data-toggle'=>'tooltip','title' => 'Delete', 'class' => 'btn btn-danger btn-xs'),
'label' => '<i class="glyphicon glyphicon-remove"></i>',
'imageUrl' => false,
),
),
),
),
)); ?>
</div>
</div>
</div>
</div>
</div>
<script>
$(function(){
$('.datepicker23').datepicker({
format:'dd/mm/yyyy',
todayHighlight: true
});
})
</script> | bsd-3-clause |
Gimalca/piderapido | module/Admin/src/Admin/Controller/IndexController.php | 1586 | <?php
namespace Admin\Controller;
use Sale\Model\Dao\CustomerDao;
use Sale\Model\Dao\OrderDao;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController {
private $_user;
public function indexAction() {
$auth = $this->getService('Admin\Model\LoginAdmin');
if ($auth->isLoggedIn()) {
$this->_user = $auth->getIdentity();
// var_dump($this->_user);die;
$this->layout()->first_name = $this->_user->firstname;
$this->layout()->last_name = $this->_user->lastname;
// $this->layout()->user_id = $this->_user->user_id;
$orderTableGateway = $this->getService('OrderHydratingTableGateway');
$orderDao = new OrderDao($orderTableGateway);
$order = $orderDao->getLatest();
$order = $order->fetchAll();
$view['order'] = $order;
// var_dump($view['order']);die;
$customerTableGateway = $this->getService('CustomerTableGateway');
$customerDao = new CustomerDao($customerTableGateway);
$customer = $customerDao->getLatest();
$view['customer'] = $customer;
return new ViewModel($view);
} else {
return $this->forward()->dispatch('Admin\Controller\Login', array('action' => 'index'));
}
}
public function getService($serviceName) {
$sm = $this->getServiceLocator();
$service = $sm->get($serviceName);
return $service;
}
}
| bsd-3-clause |
timvdm/ComputerGraphics | run_engine.py | 151 | #!/usr/bin/env python
import glob
import os
for f in sorted(glob.glob('*.ini')):
print 'Running ' + f + '...'
os.system('./src/engine ' + f)
| bsd-3-clause |
GilaCMS/gila | tests/phpunit/RequestTest.php | 467 | <?php
include __DIR__.'/includes.php';
include __DIR__.'/../../src/core/classes/Controller.php';
use PHPUnit\Framework\TestCase;
use Gila\Router;
use Gila\Request;
class RequestTest extends TestCase
{
public function test_validate()
{
$_POST = [
'one'=>1,
'two'=>'two',
];
$data = Request::validate([
'one'=>'',
'two'=>'required',
]);
$this->assertEquals([
'one'=>1,
'two'=>'two',
], $data);
}
}
| bsd-3-clause |
beeftornado/sentry | src/sentry/static/sentry/app/utils/discover/discoverQuery.tsx | 656 | import React from 'react';
import {MetaType} from 'app/utils/discover/eventView';
import withApi from 'app/utils/withApi';
import GenericDiscoverQuery, {DiscoverQueryProps} from './genericDiscoverQuery';
/**
* An individual row in a DiscoverQuery result
*/
export type TableDataRow = {
id: string;
[key: string]: React.ReactText;
};
/**
* A DiscoverQuery result including rows and metadata.
*/
export type TableData = {
data: Array<TableDataRow>;
meta?: MetaType;
};
function DiscoverQuery(props: DiscoverQueryProps) {
return <GenericDiscoverQuery<TableData, {}> route="eventsv2" {...props} />;
}
export default withApi(DiscoverQuery);
| bsd-3-clause |
kordless/zoto-server | www/static_pages/site_down/index.php | 2162 | <?
preg_match('@^(?:http://)?([^/]+)@i', $_SERVER['HTTP_HOST'], $matches);
$host = $matches[1];
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
$zoto_domain = $matches[0];
if(strstr(getenv('HTTP_REFERER'), "site_down")) {
$referer = $_COOKIE["zoto_down_referer"];
} else {
if (getenv('HTTP_REFERER')) {
$referer = getenv('HTTP_REFERER');
} else {
$referer = "http://www.".$zoto_domain;
}
setcookie("zoto_down_referer", $referer, time()+86400, "/", "".$zoto_domain); /* expire in a day */
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Zoto 3.0 - Zoto is Down for Maintenance</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"/>
<META http-equiv="refresh" content="60;URL=<?=$referer?>"/>
<link media="screen" title="" rel="stylesheet" href="site_down.css" type="text/css"/>
</head>
<body>
<div id="main_page_container">
<div>
<a href="http://www.<?=$zoto_domain?>"><img src="big_logo.png" align="left"/></a>
<br clear=all />
</div>
<div id="main_photo_container">
<div id="main_photo">
<div id="caption"></div>
</div>
<div id="well_be_back">
<img src="well_be_back.jpg"/>
</div>
</div>
<div id="main_happy_talk">
<br>
<h3>Oh No! Zoto is down.</h3>
<br>
<h3>ETA updated to at earliest late Sunday. Here's the senario - might as well be transparent. We have lost a drive in our NAS, which houses all the photos. The NAS is currently in a degraded state, but that means it's fixable at least, but it's fragile and I don't want to poke it. We need to install a new drive and recover the RAID array tomorrow. Clint is going up Saturday AM to assist us. We'll keep you posted on progress.</h3>
<br><br>
<i>Have questions? Please visit our</i> <a href="http://forum.<?=$zoto_domain?>">support forum</a>.
<br><br>
This page will attempt to access zoto every 60 seconds, or you can <a href="<?=$referer?>">manually refresh</a>.
</div>
</div>
<div id="copyright">
<br clear=all />
<br /><br />
Copyright © 2007, Zoto Inc. All rights reserved.
</div>
</div>
</body>
</html>
| bsd-3-clause |
HaikuArchives/IMKit | docs/usage/infopopper/team.html | 1820 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" type="text/css" href="../meta/default.css" media="all">
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>InfoPopper - Team</title>
</head>
<body>
<div id="nav">
<a href="index.html">Introduction</a><br>
<a href="applications.html">Applications</a><br>
<a href="configuration.html">Configuration</a><br>
<a href="developers.html">Developers</a><br>
<cur>Team</cur><br>
<a href="license.html">License</a><br>
</div>
<div id="content">
<h1>InfoPopper</h1>
<br>
<h2>Team</h2>
<div class="quotbox">
<p>The developer team is constantly looking for new members. If you want to
contribute, please don't hesitate to contact us or simply just join us on
our IRC channel #beosimkit on irc.freenode.org</p>
<p>As we are all using ZETA, we hope that there are someone that can help
us out compiling a BeOS version of InfoPopper.</p>
</div>
<p>Mikael Eiman (m_eiman) - Project Leader</p>
<p>Michael Davidson (slaad) - Developer</p>
<p>Andrea Anzani (xeD) - Developer</p>
<p>Nathan Whitehorn (NathanW) - Developer, BeOS R5 version</p>
<p>Jörn Weigend (Das_Jott) - Developer, InfoPopper Settings</p>
<p>Frank Paul Silye (frankps) - Documentation</p>
<p> </p>
<h2>Thanks to ...</h2>
<p>We would like to thank David Reid and <a href="http://www.beclan.org/">BeClan</a>
for hosting this project. </p>
<p>As InfoPopper Settings is developed with YAB, a special thanks also goes
to <a href="http://www.team-maui.de/">Team-Maui</a> for their YAB Interpreter.</p>
</div>
</body>
</html>
| bsd-3-clause |
grimmerm/sulong | projects/com.oracle.truffle.llvm.test/src/com/oracle/truffle/llvm/test/TestSuiteBase.java | 13256 | /*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE
* COPYRIGHT HOLDER 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.
*/
package com.oracle.truffle.llvm.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.oracle.truffle.llvm.runtime.LLVMLogger;
import com.oracle.truffle.llvm.runtime.LLVMOptions;
import com.oracle.truffle.llvm.runtime.LLVMParserException;
import com.oracle.truffle.llvm.runtime.LLVMUnsupportedException;
import com.oracle.truffle.llvm.runtime.LLVMUnsupportedException.UnsupportedReason;
import com.oracle.truffle.llvm.test.spec.SpecificationEntry;
import com.oracle.truffle.llvm.test.spec.SpecificationFileReader;
import com.oracle.truffle.llvm.test.spec.TestSpecification;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions.OptimizationLevel;
import com.oracle.truffle.llvm.tools.GCC;
import com.oracle.truffle.llvm.tools.Opt;
import com.oracle.truffle.llvm.tools.Opt.OptOptions;
import com.oracle.truffle.llvm.tools.Opt.OptOptions.Pass;
import com.oracle.truffle.llvm.tools.ProgrammingLanguage;
public abstract class TestSuiteBase {
private static List<File> failingTests;
private static List<File> succeedingTests;
private static List<File> parserErrorTests;
private static Map<UnsupportedReason, List<File>> unsupportedErrorTests;
protected void recordTestCase(TestCaseFiles tuple, boolean pass) {
if (pass) {
if (!succeedingTests.contains(tuple.getOriginalFile()) && !failingTests.contains(tuple.getOriginalFile())) {
succeedingTests.add(tuple.getOriginalFile());
}
} else {
if (!failingTests.contains(tuple.getOriginalFile())) {
failingTests.add(tuple.getOriginalFile());
}
}
}
protected void recordError(TestCaseFiles tuple, Throwable error) {
Throwable currentError = error;
if (!failingTests.contains(tuple.getOriginalFile())) {
failingTests.add(tuple.getOriginalFile());
}
while (currentError != null) {
if (currentError instanceof LLVMParserException) {
if (!parserErrorTests.contains(tuple.getOriginalFile())) {
parserErrorTests.add(tuple.getOriginalFile());
}
break;
} else if (currentError instanceof LLVMUnsupportedException) {
List<File> list = unsupportedErrorTests.get(((LLVMUnsupportedException) currentError).getReason());
if (!list.contains(tuple.getOriginalFile())) {
list.add(tuple.getOriginalFile());
}
break;
}
currentError = currentError.getCause();
}
}
private static final int LIST_MIN_SIZE = 1000;
@BeforeClass
public static void beforeClass() {
succeedingTests = new ArrayList<>(LIST_MIN_SIZE);
failingTests = new ArrayList<>(LIST_MIN_SIZE);
parserErrorTests = new ArrayList<>(LIST_MIN_SIZE);
unsupportedErrorTests = new HashMap<>(LIST_MIN_SIZE);
for (UnsupportedReason reason : UnsupportedReason.values()) {
unsupportedErrorTests.put(reason, new ArrayList<>(LIST_MIN_SIZE));
}
}
protected static void printList(String header, List<File> files) {
if (files.size() != 0) {
LLVMLogger.info(header + " (" + files.size() + "):");
files.stream().forEach(t -> LLVMLogger.info(t.toString()));
}
}
@After
public void displaySummary() {
if (LLVMOptions.debugEnabled()) {
if (LLVMOptions.discoveryTestModeEnabled()) {
printList("succeeding tests:", succeedingTests);
} else {
printList("failing tests:", failingTests);
}
printList("parser error tests", parserErrorTests);
for (UnsupportedReason reason : UnsupportedReason.values()) {
printList("unsupported test " + reason, unsupportedErrorTests.get(reason));
}
}
}
@AfterClass
public static void displayEndSummary() {
if (!LLVMOptions.discoveryTestModeEnabled()) {
printList("failing tests:", failingTests);
}
}
protected interface TestCaseGenerator {
ProgrammingLanguage[] getSupportedLanguages();
TestCaseFiles getBitCodeTestCaseFiles(SpecificationEntry bitCodeFile);
List<TestCaseFiles> getCompiledTestCaseFiles(SpecificationEntry toBeCompiled);
}
public static class TestCaseGeneratorImpl implements TestCaseGenerator {
@Override
public TestCaseFiles getBitCodeTestCaseFiles(SpecificationEntry bitCodeFile) {
return TestCaseFiles.createFromBitCodeFile(bitCodeFile.getFile(), bitCodeFile.getFlags());
}
@Override
public List<TestCaseFiles> getCompiledTestCaseFiles(SpecificationEntry toBeCompiled) {
List<TestCaseFiles> files = new ArrayList<>();
File toBeCompiledFile = toBeCompiled.getFile();
File dest = TestHelper.getTempLLFile(toBeCompiledFile, "_main");
try {
if (ProgrammingLanguage.FORTRAN.isFile(toBeCompiledFile)) {
TestCaseFiles gccCompiledTestCase = TestHelper.compileToLLVMIRWithGCC(toBeCompiledFile, dest, toBeCompiled.getFlags());
files.add(gccCompiledTestCase);
} else if (ProgrammingLanguage.C_PLUS_PLUS.isFile(toBeCompiledFile)) {
ClangOptions builder = ClangOptions.builder().optimizationLevel(OptimizationLevel.NONE);
OptOptions options = OptOptions.builder().pass(Pass.LOWER_INVOKE).pass(Pass.PRUNE_EH).pass(Pass.SIMPLIFY_CFG);
TestCaseFiles compiledFiles = TestHelper.compileToLLVMIRWithClang(toBeCompiledFile, dest, toBeCompiled.getFlags(), builder);
files.add(optimize(compiledFiles, options, "opt"));
} else {
ClangOptions builder = ClangOptions.builder().optimizationLevel(OptimizationLevel.NONE);
try {
TestCaseFiles compiledFiles = TestHelper.compileToLLVMIRWithClang(toBeCompiledFile, dest, toBeCompiled.getFlags(), builder);
files.add(compiledFiles);
TestCaseFiles optimized = getOptimizedTestCase(compiledFiles);
files.add(optimized);
} catch (Exception e) {
return Collections.emptyList();
}
}
} catch (Exception e) {
return Collections.emptyList();
}
return files;
}
private static TestCaseFiles getOptimizedTestCase(TestCaseFiles compiledFiles) {
OptOptions options = OptOptions.builder().pass(Pass.MEM_TO_REG).pass(Pass.ALWAYS_INLINE).pass(Pass.JUMP_THREADING).pass(Pass.SIMPLIFY_CFG);
TestCaseFiles optimize = optimize(compiledFiles, options, "opt");
return optimize;
}
@Override
public ProgrammingLanguage[] getSupportedLanguages() {
return GCC.getSupportedLanguages();
}
}
protected static List<TestCaseFiles[]> getTestCasesFromConfigFile(File configFile, File testSuite, TestCaseGenerator gen) throws IOException, AssertionError {
TestSpecification testSpecification = SpecificationFileReader.readSpecificationFolder(configFile, testSuite);
List<SpecificationEntry> includedFiles = testSpecification.getIncludedFiles();
if (LLVMOptions.discoveryTestModeEnabled()) {
List<SpecificationEntry> excludedFiles = testSpecification.getExcludedFiles();
File absoluteDiscoveryPath = new File(testSuite.getAbsolutePath(), LLVMOptions.getTestDiscoveryPath());
assert absoluteDiscoveryPath.exists() : absoluteDiscoveryPath.toString();
LLVMLogger.info("\tcollect files");
List<File> filesToRun = getFilesRecursively(absoluteDiscoveryPath, gen);
for (SpecificationEntry alreadyCanExecute : includedFiles) {
filesToRun.remove(alreadyCanExecute.getFile());
}
for (SpecificationEntry excludedFile : excludedFiles) {
filesToRun.remove(excludedFile.getFile());
}
List<TestCaseFiles[]> discoveryTestCases = new ArrayList<>();
for (File f : filesToRun) {
if (ProgrammingLanguage.LLVM.isFile(f)) {
TestCaseFiles testCase = gen.getBitCodeTestCaseFiles(new SpecificationEntry(f));
discoveryTestCases.add(new TestCaseFiles[]{testCase});
} else {
List<TestCaseFiles> testCases = gen.getCompiledTestCaseFiles(new SpecificationEntry(f));
for (TestCaseFiles testCase : testCases) {
discoveryTestCases.add(new TestCaseFiles[]{testCase});
}
}
}
LLVMLogger.info("\tfinished collecting files");
return discoveryTestCases;
} else {
List<TestCaseFiles[]> includedFileTestCases = collectIncludedFiles(includedFiles, gen);
return includedFileTestCases;
}
}
private static List<TestCaseFiles[]> collectIncludedFiles(List<SpecificationEntry> specificationEntries, TestCaseGenerator gen) throws AssertionError {
List<TestCaseFiles[]> files = new ArrayList<>();
for (SpecificationEntry e : specificationEntries) {
File f = e.getFile();
if (f.isFile()) {
if (ProgrammingLanguage.LLVM.isFile(f)) {
files.add(new TestCaseFiles[]{gen.getBitCodeTestCaseFiles(e)});
} else {
for (TestCaseFiles testCaseFile : gen.getCompiledTestCaseFiles(e)) {
files.add(new TestCaseFiles[]{testCaseFile});
}
}
} else {
throw new AssertionError("could not find specified test file " + f);
}
}
return files;
}
public static List<File> getFilesRecursively(File currentFolder, TestCaseGenerator gen) {
List<File> allBitcodeFiles = new ArrayList<>(1000);
List<File> cFiles = TestHelper.collectFilesWithExtension(currentFolder, gen.getSupportedLanguages());
allBitcodeFiles.addAll(cFiles);
return allBitcodeFiles;
}
protected static List<TestCaseFiles> applyOpt(List<TestCaseFiles> allBitcodeFiles, OptOptions pass, String name) {
return getFilteredOptStream(allBitcodeFiles).map(f -> optimize(f, pass, name)).collect(Collectors.toList());
}
protected static Stream<TestCaseFiles> getFilteredOptStream(List<TestCaseFiles> allBitcodeFiles) {
return allBitcodeFiles.parallelStream().filter(f -> !f.getOriginalFile().getParent().endsWith(LLVMPaths.NO_OPTIMIZATIONS_FOLDER_NAME));
}
protected static TestCaseFiles optimize(TestCaseFiles toBeOptimized, OptOptions optOptions, String name) {
File destinationFile = TestHelper.getTempLLFile(toBeOptimized.getOriginalFile(), "_" + name);
Opt.optimizeBitcodeFile(toBeOptimized.getBitCodeFile(), destinationFile, optOptions);
return TestCaseFiles.createFromCompiledFile(toBeOptimized.getOriginalFile(), destinationFile, toBeOptimized.getFlags());
}
}
| bsd-3-clause |
straight-street/straight-street | scratchpad/translate/index5.php | 4540 | <?
//----------------------
//require("GTranslate.php");
//----------------------
?>
<html>
<head>
<title>This is the test page</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<style>
body {
font-family:arial;
}
div.container
{
border:4px solid green;
}
div.container div.row
{
border:0px solid green;
width:400px;
}
div.container div.row div
{
border:1px solid blue;
width:150px;
float:left;
text-align:center;
margin:2px;
height:26px;
vertical-align:middle;
}
div.container div.row div.word_en
{
background-color:#fff;
}
div.container div.row div.word_en_sel
{
background-color:#afa;
}
div.container div.row div.word_tr
{
background-color:#ddd;
}
div.container div.row div.word_tr_changed
{
background-color:#ff7;
}
div.container div.row div.title_en,
div.container div.row div.title_tr
{
font-weight:bold;
font-size:16px;
background-color:#555;
color:#fff;
}
div.container div.row div input
{
width:100px;
}
div#previewWindow
{
display:none;
position:absolute;
top:100px;
left:300px;
border:4px solid #afa;
}
div#previewWindow img
{
width:150px;
border:1px solid green;
}
</style>
<script>
function translateTable()
{
if (confirm('Do you wish to RE-TRANSLATE the whole table?')) {
var now = new Date();
//get value of hidden field, which contains the number of words in the table
$wordCount = $('#wordcount').val();
//loop thru objects
for ($x=0;$x<$wordCount;$x++)
{
//get word on this row
$thisWord = $('#en_'+$x).html();
//alert($thisWord);
//translate each word
$.ajax({
type: "POST",
url: "misc_gtranslate.php",
data: "x="+$x+"&w=" +$thisWord+ "&ms=" + now.getTime(),
success: function(sResult){
//on completion, put result (translation) into new cell editbox
//*** NOTE ***
//Due to the asynchronous nature of ajax, the results
//for each word request will come back out of order.
//So each requested word is paired with an ID (1,2,3,etc)
//and then the returned translated word also contains the same id.
//This means that the translated word can be inserted into the
//correct table cell.
// req "3 Green" ---->
// <---- rec'v "3 Vert"
//split into ID and TEXT
$aryValues=sResult.split(' ');
// [0] is ID, [1] is TEXT
$('#tr_'+$aryValues[0]).val($aryValues[1]);
//set class of newly translated cell to default
//(incase a user has manually changed the value, which changes the div class)
$('#div_tr_'+$aryValues[0]).attr('class','word_tr');
}
});
}
}
}
function showPreview($id)
{
//set image on preview window
$sEnWord = $('#en_'+$id).html().toLowerCase();
$('#previewImg').attr('src',$sEnWord+'.wmf');
//set class of english word cell, to "sel" to simulate highlighting a row
$('#en_'+$id).attr('class','word_en_sel');
//show preview window
$('#previewWindow').show();
}
function hidePreview($id)
{
//set class of english word cell back to normal
$('#en_'+$id).attr('class','word_en');
//hide window when textbox loses focus
$('#previewWindow').hide();
}
function valueChanged($id)
{
//set class of a translated cell to indicate that it's been changed manually
$('#div_tr_'+$id).attr('class','word_tr_changed');
}
</script>
</head>
<body>
<div id="previewWindow">
<img id="previewImg">
</div>
<input type="button" value="Translate Table" onClick="translateTable();">
<br/><br/>
<div class="container" onClick="james(this);">
<div class="row">
<div class="title_en">English</div><div class="title_tr">Translation</div>
<br style="clear:both;">
</div>
<?
//----------
//Simulating a PHP fetch of data (DB) for words to be translated
//----------
//simulated list of words (in an array here)
$aryWordsEn = array ("Fruit","Apple","Hello","Pear","Banana","Car","Bag","Train","Pencil","Shoe");
$x=-1;
while ($x<count($aryWordsEn)-1) {
$x++;
//----------
?>
<div class="row">
<div id="en_<?=$x;?>" class="word_en"><?=$aryWordsEn[$x]?></div><div id="div_tr_<?=$x;?>" class="word_tr"><input type="text" id="tr_<?=$x;?>" onFocus="showPreview('<?=$x;?>')" onBlur="hidePreview('<?=$x;?>')" onChange="valueChanged('<?=$x;?>')"></div>
<br style="clear:both;">
</div>
<?
//----------
}
//----------
?>
<input type="hidden" id="wordcount" value="<?=$x+1;?>">
<br style="clear:both;">
</div>
</body>
</html> | bsd-3-clause |
pulsar-chem/Pulsar-Core | pulsar/math/PowerSetItr.hpp | 6364 | /*
* File: PowerSetItr.hpp
*
* Created on March 17, 2016, 6:07 PM
*/
#pragma once
#include <memory>
#include "pulsar/math/CombItr.hpp"
namespace pulsar{
/** \brief Class to facilitate iterating over the power set of a set
*
* Let's start with what a power set is. Given a set \f$S\f$, the
* power set of \f$S\f$, usually denoted \f$\mathbb{P}(S)\f$ is the
* set of all subsets of \f$S\f$. In particular this means the
* empty set and \f$S\f$ itself are in \f$\mathbb{P}(S)\f$. In
* terms of combinatorics, there is a deep symmetry between the
* power set of \f$S\f$ and a row of Pascal's triangle, hence
* iterating over (at least part of) a power set typically arises
* when one is iterating over say all ways of picking one, two ,
* and three objects from a set.
*
* Note for posterity, I had coded this iterator up in terms of counting in
* binary, which is based on the realization that the binary
* representation of \f$2^N-1\f$ contains \f$N\f$ 1's. So counting
* from 0 to \f$2^N-1\f$, in binary will generate all of the
* \f$2^N\f$ subsets of \f$S\f$ if we associate a 1 in the \f$i\f$-th
* place with \f$S_i\f$ being in the current subset and a 0 with its
* absence. Unfortunately this generates the subsets in a weird
* order, something akin to (assuming \f$S=\{1,2,3,\cdots,N\}\f$):
* \verbatim
(empty set)
1
2
1 2
3
1 3
2 3
1 2 3
...
1 2 3...N
\endverbatim
*
* It's more natural to instead iterate in the order:
* \verbatim
* (empty set)
* 1
* 2
* 3
* ...
* N
* 1 2
* 1 3
* ...
* 1 2 3
* ...
* 1 2 ...N
* \endverbatim
* this is the order the current generation loops in.
*
* The implementation for this is straightforward, either by
* examining the intended order, or again by analogy to Pascal's
* triangle, one sees that we simply want to iterate over all
* combinations of our current set. Hence we call CombItr \f$N\f$
* times. I suspect this is not as effecient as the counting in binary, but
* I haven't timed it.
*
* Usage of this class is similar to its cousin class CombItr:
* \code
///Typedef of container
typedef std::set<size_t> Set_t;
///Declare and fill a set of integers
Set_t TestSet;
for(size_t i=0;i<5;i++)TestSet.insert(i);
///Declare a power set iterator that runs over the whole set
PowerSetItr<Set_t> MyItr(TestSet);
///Iterate until done
for(;!MyItr.done();++MyItr){
Set_t::const_iterator elem=MyItr->begin(),elemEnd=MyItr->end();
for(;elem!=elemEnd;++elem)
std::cout<<*elem<<" ";
std::cout<<std::endl;
}
\endcode
The output should be:
\verbatim
0
1
2
3
4
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
0 1 2 3
0 1 2 4
0 1 3 4
0 2 3 4
1 2 3 4
0 1 2 3 4
\endverbatim
*
*
* \param T The type of the set we are iterating over, will also be
* the type of susbsets returned by the iterator.
*
* \note This class is not exported to Python and itertools does not provide a
* direct equivalent, but one can easily use chain()
*/
template<typename T>
class PowerSetItr{
private:
///The set we are generating the power set of
const T& Set_;
///The maximum order this iterator is going up to
size_t MaxOrder_;
///The first order we are considering
size_t MinOrder_;
///The current order
size_t Order_;
typedef typename pulsar::CombItr<T> CombItr_t;
typedef typename std::shared_ptr<CombItr_t> SharedItr_t;
SharedItr_t CurrentIt_;
///Have we iterated over the entire range yet?
bool Done_;
///Implementation for getting the next element
void next();
public:
/** \brief Given a set, iterates over all subsets containing Min
* number of elements to Max number of elements
*
* Often one only wants to iterate over part of the power set, which
* is what this function does. Specifically it iterates from sets
* containing \p Min elements to those containing \p Max elements
* inclusively. Note that this is not usual C++ counting (Min=1 really
* gives you sets with 1 element and not 2).
*/
PowerSetItr(const T& Set, size_t Min, size_t Max);
///Iterates over the entire power set
PowerSetItr(const T& Set):PowerSetItr(Set,0,Set.size()){}
///Deep copies other iterator
PowerSetItr(const PowerSetItr&);
///Returns true if we have iterated over the whole range
bool done()const{return Done_;}
///Returns true if there are combinations left
operator bool()const{return !Done_;}
///Moves on to the next subset and returns it
PowerSetItr<T>& operator++(){next();return *this;}
///Moves to next, returns current
PowerSetItr<T> operator++(int);
///Returns the current subset
const T& operator*()const{return CurrentIt_->operator*();}
///Allows access of the subset's container's members
const T* operator->()const{return CurrentIt_->operator->();}
};
/******************** Implementations ******************/
template<typename T>
PowerSetItr<T>::PowerSetItr(const PowerSetItr<T>& other)
: Set_(other.Set_),MaxOrder_(other.MaxOrder_),MinOrder_(other.MinOrder_),
Order_(other.Order_),
CurrentIt_(other.CurrentIt_?std::make_shared<CombItr_t>(*other.CurrentIt_):nullptr),
Done_(other.Done_)
{
}
template<typename T>
PowerSetItr<T> PowerSetItr<T>::operator++(int)
{
PowerSetItr<T> temp(*this);
next();
return temp;
}
template<typename T>
PowerSetItr<T>::PowerSetItr(const T& Set, size_t Min,size_t Max):
Set_(Set),
MaxOrder_(Max),
MinOrder_(Min),
Order_(MinOrder_),
CurrentIt_(std::make_shared<CombItr_t>(Set_,Order_++)),
//Can't iterate under this condition (it occurs quite naturally in
//recursion)
Done_(MaxOrder_<MinOrder_||Max==0){}
template<typename T>
void PowerSetItr<T>::next(){
++(*CurrentIt_);
if(!CurrentIt_->done())return;
else if(Order_<=MaxOrder_)
CurrentIt_=std::make_shared<CombItr_t>(Set_,Order_++);
else Done_=true;
}
}//End namespace
| bsd-3-clause |
NCIP/i-spy | src/gov/nih/nci/ispy/service/common/TimepointType.java | 568 | /*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/i-spy/LICENSE.txt for details.
*/
package gov.nih.nci.ispy.service.common;
import java.awt.Color;
import java.io.Serializable;
public enum TimepointType implements Serializable {
T1 { public Color getColor() { return Color.GREEN; }},
T2 { public Color getColor() { return Color.YELLOW; }},
T3 { public Color getColor() { return Color.RED; }},
T4 { public Color getColor() { return Color.BLUE; }};
public abstract Color getColor();
}
| bsd-3-clause |
mural/spm | db4oj/src/main/java/com/db4o/internal/activation/ModifiedObjectQuery.java | 795 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2010 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.internal.activation;
public interface ModifiedObjectQuery {
boolean isModified(Object obj);
}
| bsd-3-clause |
nacl-webkit/chrome_deps | content/renderer/pepper/content_renderer_pepper_host_factory.h | 1402 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_PEPPER_CONTENT_RENDERER_PEPPER_HOST_FACTORY_H_
#define CONTENT_RENDERER_PEPPER_CONTENT_RENDERER_PEPPER_HOST_FACTORY_H_
#if ENABLE(PEPPER_PLUGIN_API)
#include "base/compiler_specific.h"
#include "ppapi/host/host_factory.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
namespace ppapi {
class PpapiPermissions;
}
namespace content {
class PepperInstanceStateAccessor;
class RendererPpapiHostImpl;
class RenderViewImpl;
class ContentRendererPepperHostFactory : public ppapi::host::HostFactory {
public:
explicit ContentRendererPepperHostFactory(
RendererPpapiHostImpl* host);
virtual ~ContentRendererPepperHostFactory();
virtual scoped_ptr<ppapi::host::ResourceHost> CreateResourceHost(
ppapi::host::PpapiHost* host,
const ppapi::proxy::ResourceMessageCallParams& params,
PP_Instance instance,
const IPC::Message& message) OVERRIDE;
private:
const ppapi::PpapiPermissions& GetPermissions() const;
// Non-owning pointer.
RendererPpapiHostImpl* host_;
DISALLOW_COPY_AND_ASSIGN(ContentRendererPepperHostFactory);
};
} // namespace content
#endif // ENABLE(PEPPER_PLUGIN_API)
#endif // CONTENT_RENDERER_PEPPER_CONTENT_RENDERER_PEPPER_HOST_FACTORY_H_
| bsd-3-clause |
wpjesus/codematch | ietf/secr/drafts/urls.py | 1671 | from django.conf.urls import patterns, url
urlpatterns = patterns('ietf.secr.drafts.views',
url(r'^$', 'search', name='drafts'),
url(r'^add/$', 'add', name='drafts_add'),
url(r'^approvals/$', 'approvals', name='drafts_approvals'),
url(r'^dates/$', 'dates', name='drafts_dates'),
url(r'^nudge-report/$', 'nudge_report', name='drafts_nudge_report'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/$', 'view', name='drafts_view'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/abstract/$', 'abstract', name='drafts_abstract'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/announce/$', 'announce', name='drafts_announce'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/authors/$', 'authors', name='drafts_authors'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/author_delete/(?P<oid>\d{1,6})$',
'author_delete', name='drafts_author_delete'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/confirm/$', 'confirm', name='drafts_confirm'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/edit/$', 'edit', name='drafts_edit'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/extend/$', 'extend', name='drafts_extend'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/email/$', 'email', name='drafts_email'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/makerfc/$', 'makerfc', name='drafts_makerfc'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/replace/$', 'replace', name='drafts_replace'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/resurrect/$', 'resurrect', name='drafts_resurrect'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/revision/$', 'revision', name='drafts_revision'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/update/$', 'update', name='drafts_update'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/withdraw/$', 'withdraw', name='drafts_withdraw'),
)
| bsd-3-clause |
mick-d/nipype | nipype/pipeline/plugins/tests/test_somaflow.py | 1509 | # -*- coding: utf-8 -*-
import os
from time import sleep
import nipype.interfaces.base as nib
import pytest
import nipype.pipeline.engine as pe
from nipype.pipeline.plugins.somaflow import soma_not_loaded
class InputSpec(nib.TraitedSpec):
input1 = nib.traits.Int(desc='a random int')
input2 = nib.traits.Int(desc='a random int')
class OutputSpec(nib.TraitedSpec):
output1 = nib.traits.List(nib.traits.Int, desc='outputs')
class SomaTestInterface(nib.BaseInterface):
input_spec = InputSpec
output_spec = OutputSpec
def _run_interface(self, runtime):
runtime.returncode = 0
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs['output1'] = [1, self.inputs.input1]
return outputs
@pytest.mark.skipif(soma_not_loaded, reason="soma not loaded")
def test_run_somaflow(tmpdir):
os.chdir(str(tmpdir))
pipe = pe.Workflow(name='pipe')
mod1 = pe.Node(interface=SomaTestInterface(), name='mod1')
mod2 = pe.MapNode(interface=SomaTestInterface(),
iterfield=['input1'],
name='mod2')
pipe.connect([(mod1, mod2, [('output1', 'input1')])])
pipe.base_dir = os.getcwd()
mod1.inputs.input1 = 1
execgraph = pipe.run(plugin="SomaFlow")
names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()]
node = list(execgraph.nodes())[names.index('pipe.mod1')]
result = node.get_output('output1')
assert result == [1, 1]
| bsd-3-clause |
inkasjasonk/rs | research/base/static/js/plugins.js | 3480 | // usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};
// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());
// place any jQuery/helper plugins in here, instead of separate, slower script files.
// Bootstrap Dropdown
/* ============================================================
* bootstrap-dropdown.js v2.0.0
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle="dropdown"]'
, Dropdown = function ( element ) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function ( e ) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
, isActive
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
isActive = $parent.hasClass('open')
clearMenus()
!isActive && $parent.toggleClass('open')
return false
}
}
function clearMenus() {
$(toggle).parent().removeClass('open')
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
$.fn.dropdown = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(function () {
$('html').on('click.dropdown.data-api', clearMenus)
$('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle)
})
}( window.jQuery )
| bsd-3-clause |
antgonza/qiita | qiita_db/support_files/patches/82.sql | 1648 | -- May 25, 2021
-- Adding max samples in a single preparation
-- we need to do it via a DO because IF NOT EXISTS in ALTER TABLE only exists
-- in PostgreSQL 9.6 or higher and we use 9.5
DO $do$
BEGIN
IF NOT EXISTS (
SELECT DISTINCT table_name FROM information_schema.columns
WHERE table_name = 'settings' AND column_name = 'max_preparation_samples'
) THEN
ALTER TABLE settings ADD COLUMN max_preparation_samples INT DEFAULT 800;
END IF;
END $do$;
ALTER TABLE qiita.analysis
DROP CONSTRAINT fk_analysis_user,
ADD CONSTRAINT fk_analysis_user
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
ALTER TABLE qiita.study_users
DROP CONSTRAINT fk_study_users_user,
ADD CONSTRAINT fk_study_users_user
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
ALTER TABLE qiita.message_user
DROP CONSTRAINT fk_message_user_0,
ADD CONSTRAINT fk_message_user_0
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
ALTER TABLE qiita.processing_job
DROP CONSTRAINT fk_processing_job_qiita_user,
ADD CONSTRAINT fk_processing_job_qiita_user
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
ALTER TABLE qiita.processing_job_workflow
DROP CONSTRAINT fk_processing_job_workflow,
ADD CONSTRAINT fk_processing_job_workflow
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
ALTER TABLE qiita.study
DROP CONSTRAINT fk_study_user,
ADD CONSTRAINT fk_study_user
FOREIGN KEY (email)
REFERENCES qiita.qiita_user(email)
ON UPDATE CASCADE;
| bsd-3-clause |
Team319/RecyleRush | src/org/usfirst/frc319/RecyleRush/commands/ScoreTotes.java | 1036 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc319.RecyleRush.commands;
import org.usfirst.frc319.RecyleRush.Robot;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class ScoreTotes extends CommandGroup {
public ScoreTotes() {
addSequential(new ActiveCollectorOpen());
addSequential(new ElevatorFloorPickup()); //lower stack to floor position
addSequential(new ToteClawOpen()); //release stack
addSequential(new ContainerClawOpen());
//addSequential(new SetToteCount(0)); //Sets totecounter to = 0;
}
}
| bsd-3-clause |
imrehg/rust-freegeoip | README.md | 647 | # rust-freegeoip
[](https://travis-ci.org/imrehg/rust-freegeoip)
[](https://crates.io/crates/freegeoip/)
[](./LICENSE)
A wrapper to the [freegeoip](https://freegeoip.net) IP geolocation HTTP API.
Work in progress....
## To Do
+ [ ] proper error checking
+ [ ] set http/https query type
+ [ ] make struct values into [options](https://doc.rust-lang.org/std/option/)
+ [ ] add documentation
+ [ ] check for API quota limit errors (403)
| bsd-3-clause |
clime/pimcore-custom | static/js/pimcore/object/tags/checkbox.js | 2339 | /**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.object.tags.checkbox");
pimcore.object.tags.checkbox = Class.create(pimcore.object.tags.abstract, {
type: "checkbox",
initialize: function (data, fieldConfig) {
this.data = "";
if (data) {
this.data = data;
}
this.fieldConfig = fieldConfig;
},
getGridColumnConfig: function(field) {
return new Ext.grid.CheckColumn({
header: ts(field.label),
dataIndex: field.key,
renderer: function (key, value, metaData, record, rowIndex, colIndex, store) {
if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
metaData.css += " grid_value_inherited";
}
metaData.css += ' x-grid3-check-col-td';
return String.format('<div class="x-grid3-check-col{0}"> </div>', value ? '-on' : '');
}.bind(this, field.key)
});
},
getGridColumnFilter: function(field) {
return {type: 'boolean', dataIndex: field.key};
},
getLayoutEdit: function () {
var checkbox = {
fieldLabel: this.fieldConfig.title,
name: this.fieldConfig.name,
itemCls: "object_field"
};
if (this.fieldConfig.width) {
checkbox.width = this.fieldConfig.width;
}
this.component = new Ext.form.Checkbox(checkbox);
this.component.setValue(this.data);
return this.component;
},
getLayoutShow: function () {
this.component = this.getLayoutEdit();
this.component.disable();
return this.component;
},
getValue: function () {
return this.component.getValue();
},
getName: function () {
return this.fieldConfig.name;
},
isInvalidMandatory: function () {
return false;
}
}); | bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE401_Memory_Leak/s03/CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18.c | 3333 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18.c
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-18.tmpl.c
*/
/*
* @description
* CWE: 401 Memory Leak
* BadSource: calloc Allocate data using calloc()
* GoodSource: Allocate data on the stack
* Sinks:
* GoodSink: call free() on data
* BadSink : no deallocation of data
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
void CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18_bad()
{
struct _twoIntsStruct * data;
data = NULL;
goto source;
source:
/* POTENTIAL FLAW: Allocate memory on the heap */
data = (struct _twoIntsStruct *)calloc(100, sizeof(struct _twoIntsStruct));
if (data == NULL) {exit(-1);}
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
goto sink;
sink:
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G() - use badsource and goodsink by reversing the blocks on the second goto statement */
static void goodB2G()
{
struct _twoIntsStruct * data;
data = NULL;
goto source;
source:
/* POTENTIAL FLAW: Allocate memory on the heap */
data = (struct _twoIntsStruct *)calloc(100, sizeof(struct _twoIntsStruct));
if (data == NULL) {exit(-1);}
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
goto sink;
sink:
/* FIX: Deallocate memory */
free(data);
}
/* goodG2B() - use goodsource and badsink by reversing the blocks on the first goto statement */
static void goodG2B()
{
struct _twoIntsStruct * data;
data = NULL;
goto source;
source:
/* FIX: Use memory allocated on the stack with ALLOCA */
data = (struct _twoIntsStruct *)ALLOCA(100*sizeof(struct _twoIntsStruct));
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
goto sink;
sink:
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
void CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18_good()
{
goodB2G();
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE401_Memory_Leak__struct_twoIntsStruct_calloc_18_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
zmicier/WbBase | src/WbBase/WbTrait/ServiceManager/ServiceManagerAwareTrait.php | 808 | <?php
namespace WbBase\WbTrait\ServiceManager;
use \Zend\ServiceManager\ServiceManager;
/**
* ServiceManagerAwareTrait
*
* @package WbBase\WbTrait\ServiceManager
* @author Źmicier Hryškieivič <[email protected]>
*/
trait ServiceManagerAwareTrait
{
/**
* @var ServiceManager
*/
protected $serviceManager;
/**
* ServiceManager setter
*
* @param ServiceManager $serviceManager Service manager.
*
* @return void
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
/**
* ServiceManager getter
*
* @return ServiceManager
*/
public function getServiceManager()
{
return $this->serviceManager;
}
}
| bsd-3-clause |
tommus/XNAGameWrapper | Implementation/WPMusic.cs | 2056 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Media;
namespace GameFramework.Implementation
{
public class WPMusic : Music
{
#region Fields
private Song song;
#endregion
#region Properties
public Boolean IsPlaying
{
get
{
return (MediaPlayer.State == MediaState.Playing);
}
}
public Boolean IsStopped
{
get
{
return (MediaPlayer.State == MediaState.Stopped);
}
}
public bool IsLooping
{
get
{
return MediaPlayer.IsRepeating;
}
}
#endregion
#region Constructors
public WPMusic(Song song)
{
this.song = song;
}
#endregion
#region Methods
public void Play()
{
if (MediaPlayer.State == MediaState.Playing)
return;
MediaPlayer.Play(song);
}
public void Pause()
{
if (MediaPlayer.State == MediaState.Playing)
MediaPlayer.Pause();
}
public void Resume()
{
if (MediaPlayer.State == MediaState.Paused)
MediaPlayer.Resume();
if (MediaPlayer.State == MediaState.Stopped)
Play();
}
public void Stop()
{
if (MediaPlayer.State == MediaState.Playing)
MediaPlayer.Stop();
}
public void SetLooping(bool looping)
{
MediaPlayer.IsRepeating = looping;
}
public void SetVolume(float volume)
{
MediaPlayer.Volume = volume;
}
public void Dispose()
{
song.Dispose();
}
#endregion
}
} | bsd-3-clause |
rudimeier/dateutils | lib/nifty.h | 2316 | /*** nifty.h -- generally handy macroes
*
* Copyright (C) 2009-2016 Sebastian Freundt
*
* Author: Sebastian Freundt <[email protected]>
*
* This file is part of dateutils.
*
* 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.
*
* 3. Neither the name of the author nor the names of any contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 THE REGENTS 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.
*
***/
#if !defined INCLUDED_nifty_h_
#define INCLUDED_nifty_h_
#if !defined LIKELY
# define LIKELY(_x) __builtin_expect((_x), 1)
#endif /* !LIKELY */
#if !defined UNLIKELY
# define UNLIKELY(_x) __builtin_expect((_x), 0)
#endif /* UNLIKELY */
#if !defined UNUSED
# define UNUSED(_x) _x __attribute__((unused))
#endif /* !UNUSED */
#if !defined ALGN
# define ALGN(_x, to) _x __attribute__((aligned(to)))
#endif /* !ALGN */
#if !defined countof
# define countof(x) (sizeof(x) / sizeof(*x))
#endif /* !countof */
#if !defined with
# define with(args...) for (args, *__ep__ = (void*)1; __ep__; __ep__ = 0)
#endif /* !with */
#endif /* INCLUDED_nifty_h_ */
| bsd-3-clause |
johnjbarton/Purple | ui/flexor.js | 2344 | // Box sizing in JavaScript
// Copyright 2011 Google Inc.
// see Purple/license.txt for BSD license
// [email protected]
define(['lib/nodelist/nodelist'], function (nodelist){
var Flexor = {};
Flexor.getChildernByClassName = function(parentBox, classname) {
var hboxes = [];
parentBox.childNodes.forEach(function (child) {
if (child.classList && child.classList.contains(classname)) {
hboxes.push(child);
}
});
return hboxes;
};
Flexor.sizeHBoxes = function(boxes) {
if (!boxes.length) {
return;
}
var flexibles = this.flexibleBoxes(boxes);
var remainingHeight = this.remainingHeight(boxes);
if (remainingHeight <= 0) {
console.error("Purple.Flexor: no remaining height");
return;
}
var remainder = 0;
flexibles.forEach(function convertToHeight(box) {
var flexible = parseInt(box.dataset.flexible);
var floatingHeight = remainingHeight * (flexible / flexibles.totalFlexible) + remainder;
var height = Math.floor(floatingHeight);
remainder = floatingHeight - height;
box.style.height = height+"px";
});
};
// return an array of boxes all having valid, non-zero data-flexible attributes
Flexor.flexibleBoxes = function(boxes) {
var flexibles = [];
flexibles.totalFlexible = 0;
boxes.forEach(function gatherFlexible(box) {
var flexibleString = box.dataset.flexible;
if (flexibleString) {
var flexible = parseInt(flexibleString);
if (!flexible) {
console.error("Purple.Flexor: invalid flexible value "+flexibleString, box);
box.removeAttribute('data-flexible');
return;
}
flexibles.push(box);
flexibles.totalFlexible += flexible;
}
});
if (flexibles.length) {
if (!flexibles.totalFlexible) {
console.error("Purple.Flexor: no valid flexible values", flexibles);
return [];
}
}
return flexibles;
};
// return the parent height minus all of the inflexible box heights
Flexor.remainingHeight = function(boxes) {
var remainingHeight = boxes[0].parentNode.getBoundingClientRect().height;
boxes.forEach(function decrement(box) {
if (!box.dataset.flexible) {
remainingHeight -= box.getBoundingClientRect().height;
}
});
return remainingHeight;
};
return Flexor;
}); | bsd-3-clause |
jonathanihm/freeCodeCamp | curriculum/challenges/chinese/03-front-end-libraries/jquery/delete-your-jquery-functions.chinese.md | 2641 | ---
id: bad87fee1348bd9aeda08726
title: Delete Your jQuery Functions
required:
- link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css'
challengeType: 6
videoUrl: ''
localeTitle: 删除您的jQuery函数
---
## Description
<section id="description">这些动画起初很酷,但现在它们让人分心。从<code>document ready function</code>删除所有这三个jQuery函数,但保留<code>document ready function</code>本身。 </section>
## Instructions
<section id="instructions">
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 从<code>document ready function</code>删除所有三个jQuery <code>document ready function</code> 。
testString: assert(code.match(/\{\s*\}\);/g));
- text: 保持<code>script</code>元素不变。
testString: assert(code.match(/<script>/g));
- text: '将<code>$(document).ready(function() {</code>保留到<code>script</code>元素的开头。'
testString: assert(code.match(/\$\(document\)\.ready\(function\(\)\s?\{/g));
- text: '保持“文档就绪功能”关闭<code>})</code>完好无损。'
testString: assert(code.match(/.*\s*\}\);/g));
- text: 保持<code>script</code>元素结束标记不变。
testString: assert(code.match(/<\/script>/g) && code.match(/<script/g) && code.match(/<\/script>/g).length === code.match(/<script/g).length);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='html-seed'>
```html
<script>
$(document).ready(function() {
$("button").addClass("animated bounce");
$(".well").addClass("animated shake");
$("#target3").addClass("animated fadeOut");
});
</script>
<!-- Only change code above this line. -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
| bsd-3-clause |
lordqwerty/ltsmin | src/pins-lib/prob-pins.h | 650 | #ifndef PROB_GREYBOX_H
#define PROB_GREYBOX_H
#include <popt.h>
#include <pins-lib/pins.h>
#include "../../prob_link_library/src/pins.h"
// ProB Link Prototypes
extern void start_prob(void);
extern void stop_prob(void);
extern State *prob_get_init_state(void);
extern State **prob_get_next_state(State*, char*, int*);
extern int prob_get_variable_count(void);
extern int prob_get_transition_group_count(void);
extern int prob_get_state_label_count(void);
extern char **prob_get_variable_names(void);
extern char **prob_get_transition_names(void);
extern char **prob_get_state_label_names(void);
extern struct poptOption prob_options[];
#endif | bsd-3-clause |
openthread/ot-rtos | third_party/freertos/repo/FreeRTOS/Demo/ARM7_AT91FR40008_GCC/serial/serial.c | 7520 | /*
* FreeRTOS Kernel V10.1.1
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/*
BASIC INTERRUPT DRIVEN SERIAL PORT DRIVER FOR USART0.
This file contains all the serial port components that can be compiled to
either ARM or THUMB mode. Components that must be compiled to ARM mode are
contained in serialISR.c.
*/
/* Standard includes. */
#include <stdlib.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "queue.h"
#include "task.h"
/* Demo application includes. */
#include "serial.h"
#include "AT91R40008.h"
#include "usart.h"
#include "pio.h"
#include "aic.h"
/*-----------------------------------------------------------*/
/* Constants to setup and access the UART. */
#define portUSART0_AIC_CHANNEL ( ( unsigned long ) 2 )
#define serINVALID_QUEUE ( ( QueueHandle_t ) 0 )
#define serHANDLE ( ( xComPortHandle ) 1 )
#define serNO_BLOCK ( ( TickType_t ) 0 )
/*-----------------------------------------------------------*/
/* Queues used to hold received characters, and characters waiting to be
transmitted. */
static QueueHandle_t xRxedChars;
static QueueHandle_t xCharsForTx;
/*-----------------------------------------------------------*/
/*
* The queues are created in serialISR.c as they are used from the ISR.
* Obtain references to the queues and THRE Empty flag.
*/
extern void vSerialISRCreateQueues( unsigned portBASE_TYPE uxQueueLength, QueueHandle_t *pxRxedChars, QueueHandle_t *pxCharsForTx );
/*-----------------------------------------------------------*/
xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength )
{
unsigned long ulSpeed;
unsigned long ulCD;
xComPortHandle xReturn = serHANDLE;
extern void ( vUART_ISR_Wrapper )( void );
/* The queues are used in the serial ISR routine, so are created from
serialISR.c (which is always compiled to ARM mode. */
vSerialISRCreateQueues( uxQueueLength, &xRxedChars, &xCharsForTx );
if(
( xRxedChars != serINVALID_QUEUE ) &&
( xCharsForTx != serINVALID_QUEUE ) &&
( ulWantedBaud != ( unsigned long ) 0 )
)
{
portENTER_CRITICAL();
{
/* Enable clock to USART0... */
AT91C_BASE_PS->PS_PCER = AT91C_PS_US0;
/* Disable all USART0 interrupt sources to begin... */
AT91C_BASE_US0->US_IDR = 0xFFFFFFFF;
/* Reset various status bits (just in case)... */
AT91C_BASE_US0->US_CR = US_RSTSTA;
AT91C_BASE_PIO->PIO_PDR = TXD0 | RXD0; /* Enable RXD and TXD pins */
AT91C_BASE_US0->US_CR = US_RSTRX | US_RSTTX | US_RXDIS | US_TXDIS;
/* Clear Transmit and Receive Counters */
AT91C_BASE_US0->US_RCR = 0;
AT91C_BASE_US0->US_TCR = 0;
/* Input clock to baud rate generator is MCK */
ulSpeed = configCPU_CLOCK_HZ * 10;
ulSpeed = ulSpeed / 16;
ulSpeed = ulSpeed / ulWantedBaud;
/* compute the error */
ulCD = ulSpeed / 10;
if ((ulSpeed - (ulCD * 10)) >= 5)
ulCD++;
/* Define the baud rate divisor register */
AT91C_BASE_US0->US_BRGR = ulCD;
/* Define the USART mode */
AT91C_BASE_US0->US_MR = US_CLKS_MCK | US_CHRL_8 | US_PAR_NO | US_NBSTOP_1 | US_CHMODE_NORMAL;
/* Write the Timeguard Register */
AT91C_BASE_US0->US_TTGR = 0;
/* Setup the interrupt for USART0.
Store interrupt handler function address in USART0 vector register... */
AT91C_BASE_AIC->AIC_SVR[ portUSART0_AIC_CHANNEL ] = (unsigned long)vUART_ISR_Wrapper;
/* USART0 interrupt level-sensitive, priority 1... */
AT91C_BASE_AIC->AIC_SMR[ portUSART0_AIC_CHANNEL ] = AIC_SRCTYPE_INT_LEVEL_SENSITIVE | 1;
/* Clear some pending USART0 interrupts (just in case)... */
AT91C_BASE_US0->US_CR = US_RSTSTA;
/* Enable USART0 interrupt sources (but not Tx for now)... */
AT91C_BASE_US0->US_IER = US_RXRDY;
/* Enable USART0 interrupts in the AIC... */
AT91C_BASE_AIC->AIC_IECR = ( 1 << portUSART0_AIC_CHANNEL );
/* Enable receiver and transmitter... */
AT91C_BASE_US0->US_CR = US_RXEN | US_TXEN;
}
portEXIT_CRITICAL();
}
else
{
xReturn = ( xComPortHandle ) 0;
}
return xReturn;
}
/*-----------------------------------------------------------*/
signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed char *pcRxedChar, TickType_t xBlockTime )
{
/* The port handle is not required as this driver only supports UART0. */
( void ) pxPort;
/* Get the next character from the buffer. Return false if no characters
are available, or arrive before xBlockTime expires. */
if( xQueueReceive( xRxedChars, pcRxedChar, xBlockTime ) )
{
return pdTRUE;
}
else
{
return pdFALSE;
}
}
/*-----------------------------------------------------------*/
void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength )
{
signed char *pxNext;
/* NOTE: This implementation does not handle the queue being full as no
block time is used! */
/* The port handle is not required as this driver only supports UART0. */
( void ) pxPort;
( void ) usStringLength;
/* Send each character in the string, one at a time. */
pxNext = ( signed char * ) pcString;
while( *pxNext )
{
xSerialPutChar( pxPort, *pxNext, serNO_BLOCK );
pxNext++;
}
}
/*-----------------------------------------------------------*/
signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, TickType_t xBlockTime )
{
( void ) pxPort;
/* Place the character in the queue of characters to be transmitted. */
if( xQueueSend( xCharsForTx, &cOutChar, xBlockTime ) != pdPASS )
{
return pdFAIL;
}
/* Turn on the Tx interrupt so the ISR will remove the character from the
queue and send it. This does not need to be in a critical section as
if the interrupt has already removed the character the next interrupt
will simply turn off the Tx interrupt again. */
AT91C_BASE_US0->US_IER = US_TXRDY;
return pdPASS;
}
/*-----------------------------------------------------------*/
void vSerialClose( xComPortHandle xPort )
{
/* Not supported as not required by the demo application. */
( void ) xPort;
}
/*-----------------------------------------------------------*/
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66a.c | 5902 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-66a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sinks: w32_execv
* BadSink : execute command with execv
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#include <process.h>
#define EXECV _execv
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66b_badSink(char * dataArray[]);
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66_bad()
{
char * data;
char * dataArray[5];
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* put data in array */
dataArray[2] = data;
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66b_badSink(dataArray);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66b_goodG2BSink(char * dataArray[]);
static void goodG2B()
{
char * data;
char * dataArray[5];
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
dataArray[2] = data;
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66b_goodG2BSink(dataArray);
}
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_66_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
aurelian/medick2 | lib/action/view/AbstractTemplateEngine.php | 497 | <?php
// $Id: AbstractTemplateEngine.php 477 2008-05-19 08:10:31Z aurelian $
abstract class AbstractTemplateEngine extends Object implements ITemplateEngine {
protected $vars;
protected $context;
protected $controller;
public function __construct(ContextManager $context, ActionController $controller) {
$this->context= $context;
$this->controller= $controller;
$this->vars= array();
}
public function assign($name, $value) {
$this->vars[$name]= $value;
}
}
| bsd-3-clause |
PolymerLabs/arcs-live | concrete-storage/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts | 1601 | /**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class ensures the packets from the server arrive in order
* This class takes data from the server and ensures it gets passed into the callbacks in order.
* @constructor
*/
export declare class PacketReceiver {
private onMessage_;
pendingResponses: any[];
currentResponseNum: number;
closeAfterResponse: number;
onClose: (() => void) | null;
/**
* @param onMessage_
*/
constructor(onMessage_: (a: Object) => void);
closeAfter(responseNum: number, callback: () => void): void;
/**
* Each message from the server comes with a response number, and an array of data. The responseNumber
* allows us to ensure that we process them in the right order, since we can't be guaranteed that all
* browsers will respond in the same order as the requests we sent
* @param {number} requestNum
* @param {Array} data
*/
handleResponse(requestNum: number, data: any[]): void;
}
| bsd-3-clause |
cernvm/ci-scripts | cvmfs/cloud_testing/remote_gcov_run.sh | 2463 | #!/bin/bash
#
# This script is designed to be as platform independent as possible. It does
# final preparations to run the platform specific test cases of CernVM-FS and
# invokes a platform dependent script to steer the actual test session
#
usage() {
local error_msg=$1
echo "$error_msg"
echo
echo "Mandatory options:"
echo "-r <test script> platform specific script (inside the cvmfs sources)"
echo
echo "Optional parameters:"
echo "-p <platform path> custom search path for platform specific script"
echo "-u <user name> user name to use for test run"
exit 1
}
export LC_ALL=C
# static information (check also remote_setup.sh and run.sh)
cvmfs_workspace="/tmp/cvmfs-test-gcov-workspace"
cvmfs_source_directory="${cvmfs_workspace}/cvmfs-source"
cvmfs_log_directory="${cvmfs_workspace}/logs"
# parameterized variables
platform_script=""
platform_script_path=""
test_username="sftnight"
# from now on everything is logged to the logfile
# Note: the only output of this script is the absolute path to the generated
# log files
RUN_LOGFILE="${cvmfs_log_directory}/run.log"
sudo touch $RUN_LOGFILE
sudo chmod a+w $RUN_LOGFILE
sudo chown $test_username:$test_username $RUN_LOGFILE
exec &> $RUN_LOGFILE
# switch to working directory
cd $cvmfs_workspace
# read parameters
while getopts "r:p:u:" option; do
case $option in
r)
platform_script=$OPTARG
;;
p)
platform_script_path=$OPTARG
;;
u)
test_username=$OPTARG
;;
?)
shift $(($OPTIND-2))
usage "Unrecognized option: $1"
;;
esac
done
# check if we have all bits and pieces
if [ x"$platform_script" = "x" ]; then
usage "Missing parameter(s)"
fi
# find the platform specific script
if [ x$platform_script_path = "x" ]; then
platform_script_path=${cvmfs_source_directory}/test/cloud_testing/platforms
fi
platform_script_abs=${platform_script_path}/${platform_script}
if [ ! -f $platform_script_abs ]; then
echo "platform specific script $platform_script not found here:"
echo $platform_script_abs
exit 2
fi
# run the platform specific script to perform CernVM-FS tests
echo "running platform specific script $platform_script ..."
sudo -H -E -u $test_username bash $platform_script_abs -t $cvmfs_source_directory \
-l $cvmfs_log_directory
| bsd-3-clause |
annushara/diplom | views/refill/_form.php | 673 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Refill */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="refill-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'id_printer')->textInput() ?>
<?= $form->field($model, 'comment')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'date')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
ajzuse/PHPOrientadoAObjetos | module/Application/src/Application/Model/Autor.php | 1429 | <?php
class Autor
{
private $nome;
private $data_nascimento;
private $email;
private $id;
/**
*
* @return the $nome
*/
public function getNome()
{
return $this->nome;
}
/**
*
* @return the $data_nascimento
*/
public function getData_nascimento()
{
return $this->data_nascimento;
}
/**
*
* @return the $email
*/
public function getEmail()
{
return $this->email;
}
/**
*
* @return the $id
*/
public function getId()
{
return $this->id;
}
/**
*
* @param field_type $nome
*/
public function setNome($nome)
{
$this->nome = $nome;
}
/**
*
* @param field_type $data_nascimento
*/
public function setData_nascimento($data_nascimento)
{
$this->data_nascimento = $data_nascimento;
}
/**
*
* @param field_type $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
*
* @param field_type $id
*/
public function setId($id)
{
$this->id = $id;
}
public function toArray()
{
return array('nome' => $this->nome,
'data_nascimento' => $this->data_nascimento,
'email' => $this->email
);
}
}
| bsd-3-clause |
danielknorr/MITK | Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleXWriter.h | 2393 | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __mitkFiberBundleXWriter_h
#define __mitkFiberBundleXWriter_h
#include <mitkAbstractFileWriter.h>
#include "mitkFiberBundleX.h"
#include <vtkPolyDataWriter.h>
namespace mitk
{
/**
* Writes fiber bundles to a file
* @ingroup Process
*/
class FiberBundleXWriter : public mitk::AbstractFileWriter
{
public:
FiberBundleXWriter();
FiberBundleXWriter(const FiberBundleXWriter & other);
virtual FiberBundleXWriter * Clone() const;
virtual ~FiberBundleXWriter();
using mitk::AbstractFileWriter::Write;
virtual void Write();
static const char* XML_GEOMETRY;
static const char* XML_MATRIX_XX;
static const char* XML_MATRIX_XY;
static const char* XML_MATRIX_XZ;
static const char* XML_MATRIX_YX;
static const char* XML_MATRIX_YY;
static const char* XML_MATRIX_YZ;
static const char* XML_MATRIX_ZX;
static const char* XML_MATRIX_ZY;
static const char* XML_MATRIX_ZZ;
static const char* XML_ORIGIN_X;
static const char* XML_ORIGIN_Y;
static const char* XML_ORIGIN_Z;
static const char* XML_SPACING_X;
static const char* XML_SPACING_Y;
static const char* XML_SPACING_Z;
static const char* XML_SIZE_X;
static const char* XML_SIZE_Y;
static const char* XML_SIZE_Z;
static const char* XML_FIBER_BUNDLE;
static const char* XML_FIBER;
static const char* XML_PARTICLE;
static const char* XML_ID;
static const char* XML_POS_X;
static const char* XML_POS_Y;
static const char* XML_POS_Z;
static const char* VERSION_STRING;
static const char* XML_FIBER_BUNDLE_FILE;
static const char* XML_FILE_VERSION;
static const char* XML_NUM_FIBERS;
static const char* XML_NUM_PARTICLES;
static const char* ASCII_FILE;
static const char* FILE_NAME;
};
} // end of namespace mitk
#endif //__mitkFiberBundleXWriter_h
| bsd-3-clause |
rubysl/rubysl-matrix | spec/conj_spec.rb | 168 | require File.expand_path('../shared/conjugate', __FILE__)
ruby_version_is "1.9" do
describe "Matrix#conj" do
it_behaves_like(:matrix_conjugate, :conj)
end
end
| bsd-3-clause |
haya-hammoud/advanced | backend/models/Fields.php | 1895 | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "fields".
*
* @property integer $field_id
* @property string $arabic_name
* @property string $english_name
* @property string $field_type
* @property integer $is_required
* @property integer $field_order
* @property integer $list_page
* @property integer $filter_page
*
* @property CategoriesFields[] $categoriesFields
* @property FieldListData[] $fieldListDatas
*/
class Fields extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'fields';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['arabic_name', 'english_name', 'field_type', 'is_required', 'field_order', 'list_page', 'filter_page'], 'required'],
[['field_type'], 'string'],
[['is_required', 'field_order', 'list_page', 'filter_page'], 'integer'],
[['arabic_name', 'english_name'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'field_id' => 'Field ID',
'arabic_name' => 'Arabic Name',
'english_name' => 'English Name',
'field_type' => 'Field Type',
'is_required' => 'Is Required',
'field_order' => 'Field Order',
'list_page' => 'List Page',
'filter_page' => 'Filter Page',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCategoriesFields()
{
return $this->hasMany(CategoriesFields::className(), ['field_id' => 'field_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFieldListDatas()
{
return $this->hasMany(FieldListData::className(), ['field_id' => 'field_id']);
}
}
| bsd-3-clause |
Workday/OpenFrame | components/error_page/renderer/net_error_helper_core.cc | 42701 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/error_page/renderer/net_error_helper_core.h"
#include <set>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/debug/alias.h"
#include "base/debug/dump_without_crashing.h"
#include "base/i18n/rtl.h"
#include "base/json/json_reader.h"
#include "base/json/json_value_converter.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "components/error_page/common/error_page_params.h"
#include "components/url_formatter/url_formatter.h"
#include "content/public/common/url_constants.h"
#include "grit/components_strings.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
#include "url/url_constants.h"
namespace error_page {
namespace {
#define MAX_DEBUG_HISTORY_EVENTS 50
struct CorrectionTypeToResourceTable {
int resource_id;
const char* correction_type;
};
const CorrectionTypeToResourceTable kCorrectionResourceTable[] = {
{IDS_ERRORPAGES_SUGGESTION_VISIT_GOOGLE_CACHE, "cachedPage"},
// "reloadPage" is has special handling.
{IDS_ERRORPAGES_SUGGESTION_CORRECTED_URL, "urlCorrection"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "siteDomain"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "host"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "sitemap"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "pathParentFolder"},
// "siteSearchQuery" is not yet supported.
// TODO(mmenke): Figure out what format "siteSearchQuery" uses for its
// suggestions.
// "webSearchQuery" has special handling.
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "contentOverlap"},
{IDS_ERRORPAGES_SUGGESTION_CORRECTED_URL, "emphasizedUrlCorrection"},
};
struct NavigationCorrection {
NavigationCorrection() : is_porn(false), is_soft_porn(false) {
}
static void RegisterJSONConverter(
base::JSONValueConverter<NavigationCorrection>* converter) {
converter->RegisterStringField("correctionType",
&NavigationCorrection::correction_type);
converter->RegisterStringField("urlCorrection",
&NavigationCorrection::url_correction);
converter->RegisterStringField("clickType",
&NavigationCorrection::click_type);
converter->RegisterStringField("clickData",
&NavigationCorrection::click_data);
converter->RegisterBoolField("isPorn", &NavigationCorrection::is_porn);
converter->RegisterBoolField("isSoftPorn",
&NavigationCorrection::is_soft_porn);
}
std::string correction_type;
std::string url_correction;
std::string click_type;
std::string click_data;
bool is_porn;
bool is_soft_porn;
};
struct NavigationCorrectionResponse {
std::string event_id;
std::string fingerprint;
ScopedVector<NavigationCorrection> corrections;
static void RegisterJSONConverter(
base::JSONValueConverter<NavigationCorrectionResponse>* converter) {
converter->RegisterStringField("result.eventId",
&NavigationCorrectionResponse::event_id);
converter->RegisterStringField("result.fingerprint",
&NavigationCorrectionResponse::fingerprint);
converter->RegisterRepeatedMessage(
"result.UrlCorrections",
&NavigationCorrectionResponse::corrections);
}
};
base::TimeDelta GetAutoReloadTime(size_t reload_count) {
static const int kDelaysMs[] = {
0, 5000, 30000, 60000, 300000, 600000, 1800000
};
if (reload_count >= arraysize(kDelaysMs))
reload_count = arraysize(kDelaysMs) - 1;
return base::TimeDelta::FromMilliseconds(kDelaysMs[reload_count]);
}
// Returns whether |net_error| is a DNS-related error (and therefore whether
// the tab helper should start a DNS probe after receiving it.)
bool IsDnsError(const blink::WebURLError& error) {
return error.domain.utf8() == net::kErrorDomain &&
(error.reason == net::ERR_NAME_NOT_RESOLVED ||
error.reason == net::ERR_NAME_RESOLUTION_FAILED);
}
GURL SanitizeURL(const GURL& url) {
GURL::Replacements remove_params;
remove_params.ClearUsername();
remove_params.ClearPassword();
remove_params.ClearQuery();
remove_params.ClearRef();
return url.ReplaceComponents(remove_params);
}
// Sanitizes and formats a URL for upload to the error correction service.
std::string PrepareUrlForUpload(const GURL& url) {
// TODO(yuusuke): Change to url_formatter::FormatUrl when Link Doctor becomes
// unicode-capable.
std::string spec_to_send = SanitizeURL(url).spec();
// Notify navigation correction service of the url truncation by sending of
// "?" at the end.
if (url.has_query())
spec_to_send.append("?");
return spec_to_send;
}
// Given a WebURLError, returns true if the FixURL service should be used
// for that error. Also sets |error_param| to the string that should be sent to
// the FixURL service to identify the error type.
bool ShouldUseFixUrlServiceForError(const blink::WebURLError& error,
std::string* error_param) {
error_param->clear();
// Don't use the correction service for HTTPS (for privacy reasons).
GURL unreachable_url(error.unreachableURL);
if (GURL(unreachable_url).SchemeIsCryptographic())
return false;
std::string domain = error.domain.utf8();
if (domain == url::kHttpScheme && error.reason == 404) {
*error_param = "http404";
return true;
}
if (IsDnsError(error)) {
*error_param = "dnserror";
return true;
}
if (domain == net::kErrorDomain &&
(error.reason == net::ERR_CONNECTION_FAILED ||
error.reason == net::ERR_CONNECTION_REFUSED ||
error.reason == net::ERR_ADDRESS_UNREACHABLE ||
error.reason == net::ERR_CONNECTION_TIMED_OUT)) {
*error_param = "connectionFailure";
return true;
}
return false;
}
// Creates a request body for use with the fixurl service. Sets parameters
// shared by all types of requests to the service. |correction_params| must
// contain the parameters specific to the actual request type.
std::string CreateRequestBody(
const std::string& method,
const std::string& error_param,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
scoped_ptr<base::DictionaryValue> params_dict) {
// Set params common to all request types.
params_dict->SetString("key", correction_params.api_key);
params_dict->SetString("clientName", "chrome");
params_dict->SetString("error", error_param);
if (!correction_params.language.empty())
params_dict->SetString("language", correction_params.language);
if (!correction_params.country_code.empty())
params_dict->SetString("originCountry", correction_params.country_code);
base::DictionaryValue request_dict;
request_dict.SetString("method", method);
request_dict.SetString("apiVersion", "v1");
request_dict.Set("params", params_dict.release());
std::string request_body;
bool success = base::JSONWriter::Write(request_dict, &request_body);
DCHECK(success);
return request_body;
}
// If URL correction information should be retrieved remotely for a main frame
// load that failed with |error|, returns true and sets
// |correction_request_body| to be the body for the correction request.
std::string CreateFixUrlRequestBody(
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params) {
std::string error_param;
bool result = ShouldUseFixUrlServiceForError(error, &error_param);
DCHECK(result);
// TODO(mmenke): Investigate open sourcing the relevant protocol buffers and
// using those directly instead.
scoped_ptr<base::DictionaryValue> params(new base::DictionaryValue());
params->SetString("urlQuery", PrepareUrlForUpload(error.unreachableURL));
return CreateRequestBody("linkdoctor.fixurl.fixurl", error_param,
correction_params, params.Pass());
}
std::string CreateClickTrackingUrlRequestBody(
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
const NavigationCorrectionResponse& response,
const NavigationCorrection& correction) {
std::string error_param;
bool result = ShouldUseFixUrlServiceForError(error, &error_param);
DCHECK(result);
scoped_ptr<base::DictionaryValue> params(new base::DictionaryValue());
params->SetString("originalUrlQuery",
PrepareUrlForUpload(error.unreachableURL));
params->SetString("clickedUrlCorrection", correction.url_correction);
params->SetString("clickType", correction.click_type);
params->SetString("clickData", correction.click_data);
params->SetString("eventId", response.event_id);
params->SetString("fingerprint", response.fingerprint);
return CreateRequestBody("linkdoctor.fixurl.clicktracking", error_param,
correction_params, params.Pass());
}
base::string16 FormatURLForDisplay(const GURL& url, bool is_rtl,
const std::string accept_languages) {
// Translate punycode into UTF8, unescape UTF8 URLs.
base::string16 url_for_display(url_formatter::FormatUrl(
url, accept_languages, url_formatter::kFormatUrlOmitNothing,
net::UnescapeRule::NORMAL, nullptr, nullptr, nullptr));
// URLs are always LTR.
if (is_rtl)
base::i18n::WrapStringWithLTRFormatting(&url_for_display);
return url_for_display;
}
scoped_ptr<NavigationCorrectionResponse> ParseNavigationCorrectionResponse(
const std::string raw_response) {
// TODO(mmenke): Open source related protocol buffers and use them directly.
scoped_ptr<base::Value> parsed = base::JSONReader::Read(raw_response);
scoped_ptr<NavigationCorrectionResponse> response(
new NavigationCorrectionResponse());
base::JSONValueConverter<NavigationCorrectionResponse> converter;
if (!parsed || !converter.Convert(*parsed, response.get()))
response.reset();
return response.Pass();
}
scoped_ptr<ErrorPageParams> CreateErrorPageParams(
const NavigationCorrectionResponse& response,
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
const std::string& accept_languages,
bool is_rtl) {
// Version of URL for display in suggestions. It has to be sanitized first
// because any received suggestions will be relative to the sanitized URL.
base::string16 original_url_for_display =
FormatURLForDisplay(SanitizeURL(GURL(error.unreachableURL)), is_rtl,
accept_languages);
scoped_ptr<ErrorPageParams> params(new ErrorPageParams());
params->override_suggestions.reset(new base::ListValue());
scoped_ptr<base::ListValue> parsed_corrections(new base::ListValue());
for (ScopedVector<NavigationCorrection>::const_iterator it =
response.corrections.begin();
it != response.corrections.end(); ++it) {
// Doesn't seem like a good idea to show these.
if ((*it)->is_porn || (*it)->is_soft_porn)
continue;
int tracking_id = it - response.corrections.begin();
if ((*it)->correction_type == "reloadPage") {
params->suggest_reload = true;
params->reload_tracking_id = tracking_id;
continue;
}
if ((*it)->correction_type == "webSearchQuery") {
// If there are mutliple searches suggested, use the first suggestion.
if (params->search_terms.empty()) {
params->search_url = correction_params.search_url;
params->search_terms = (*it)->url_correction;
params->search_tracking_id = tracking_id;
}
continue;
}
// Allow reload page and web search query to be empty strings, but not
// links.
if ((*it)->url_correction.empty())
continue;
size_t correction_index;
for (correction_index = 0;
correction_index < arraysize(kCorrectionResourceTable);
++correction_index) {
if ((*it)->correction_type !=
kCorrectionResourceTable[correction_index].correction_type) {
continue;
}
base::DictionaryValue* suggest = new base::DictionaryValue();
suggest->SetString("header",
l10n_util::GetStringUTF16(
kCorrectionResourceTable[correction_index].resource_id));
suggest->SetString("urlCorrection", (*it)->url_correction);
suggest->SetString(
"urlCorrectionForDisplay",
FormatURLForDisplay(GURL((*it)->url_correction), is_rtl,
accept_languages));
suggest->SetString("originalUrlForDisplay", original_url_for_display);
suggest->SetInteger("trackingId", tracking_id);
suggest->SetInteger("type", static_cast<int>(correction_index));
params->override_suggestions->Append(suggest);
break;
}
}
if (params->override_suggestions->empty() && !params->search_url.is_valid())
params.reset();
return params.Pass();
}
void ReportAutoReloadSuccess(const blink::WebURLError& error, size_t count) {
if (error.domain.utf8() != net::kErrorDomain)
return;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtSuccess", -error.reason);
UMA_HISTOGRAM_COUNTS("Net.AutoReload.CountAtSuccess",
static_cast<base::HistogramBase::Sample>(count));
if (count == 1) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtFirstSuccess",
-error.reason);
}
}
void ReportAutoReloadFailure(const blink::WebURLError& error, size_t count) {
if (error.domain.utf8() != net::kErrorDomain)
return;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtStop", -error.reason);
UMA_HISTOGRAM_COUNTS("Net.AutoReload.CountAtStop",
static_cast<base::HistogramBase::Sample>(count));
}
} // namespace
struct NetErrorHelperCore::ErrorPageInfo {
ErrorPageInfo(blink::WebURLError error,
bool was_failed_post,
bool was_ignoring_cache)
: error(error),
was_failed_post(was_failed_post),
was_ignoring_cache(was_ignoring_cache),
needs_dns_updates(false),
needs_load_navigation_corrections(false),
reload_button_in_page(false),
show_saved_copy_button_in_page(false),
show_cached_copy_button_in_page(false),
show_offline_pages_button_in_page(false),
show_offline_copy_button_in_page(false),
is_finished_loading(false),
auto_reload_triggered(false) {}
// Information about the failed page load.
blink::WebURLError error;
bool was_failed_post;
bool was_ignoring_cache;
// Information about the status of the error page.
// True if a page is a DNS error page and has not yet received a final DNS
// probe status.
bool needs_dns_updates;
// True if a blank page was loaded, and navigation corrections need to be
// loaded to generate the real error page.
bool needs_load_navigation_corrections;
// Navigation correction service paramers, which will be used in response to
// certain types of network errors. They are all stored here in case they
// change over the course of displaying the error page.
scoped_ptr<NetErrorHelperCore::NavigationCorrectionParams>
navigation_correction_params;
scoped_ptr<NavigationCorrectionResponse> navigation_correction_response;
// All the navigation corrections that have been clicked, for tracking
// purposes.
std::set<int> clicked_corrections;
// Track if specific buttons are included in an error page, for statistics.
bool reload_button_in_page;
bool show_saved_copy_button_in_page;
bool show_cached_copy_button_in_page;
bool show_offline_pages_button_in_page;
bool show_offline_copy_button_in_page;
// True if a page has completed loading, at which point it can receive
// updates.
bool is_finished_loading;
// True if the auto-reload timer has fired and a reload is or has been in
// flight.
bool auto_reload_triggered;
};
NetErrorHelperCore::NavigationCorrectionParams::NavigationCorrectionParams() {
}
NetErrorHelperCore::NavigationCorrectionParams::~NavigationCorrectionParams() {
}
bool NetErrorHelperCore::IsReloadableError(
const NetErrorHelperCore::ErrorPageInfo& info) {
GURL url = info.error.unreachableURL;
return info.error.domain.utf8() == net::kErrorDomain &&
info.error.reason != net::ERR_ABORTED &&
// For now, net::ERR_UNKNOWN_URL_SCHEME is only being displayed on
// Chrome for Android.
info.error.reason != net::ERR_UNKNOWN_URL_SCHEME &&
// Do not trigger if the server rejects a client certificate.
// https://crbug.com/431387
!net::IsClientCertificateError(info.error.reason) &&
// Some servers reject client certificates with a generic
// handshake_failure alert.
// https://crbug.com/431387
info.error.reason != net::ERR_SSL_PROTOCOL_ERROR &&
!info.was_failed_post &&
// Don't auto-reload non-http/https schemas.
// https://crbug.com/471713
url.SchemeIsHTTPOrHTTPS();
}
NetErrorHelperCore::NetErrorHelperCore(Delegate* delegate,
bool auto_reload_enabled,
bool auto_reload_visible_only,
bool is_visible)
: delegate_(delegate),
last_probe_status_(DNS_PROBE_POSSIBLE),
can_show_network_diagnostics_dialog_(false),
auto_reload_enabled_(auto_reload_enabled),
auto_reload_visible_only_(auto_reload_visible_only),
auto_reload_timer_(new base::Timer(false, false)),
auto_reload_paused_(false),
auto_reload_in_flight_(false),
uncommitted_load_started_(false),
// TODO(ellyjones): Make online_ accurate at object creation.
online_(true),
visible_(is_visible),
auto_reload_count_(0),
#if defined(OS_ANDROID)
offline_page_status_(OfflinePageStatus::NONE),
#endif // defined(OS_ANDROID)
navigation_from_button_(NO_BUTTON) {
}
NetErrorHelperCore::~NetErrorHelperCore() {
if (committed_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
ReportAutoReloadFailure(committed_error_page_info_->error,
auto_reload_count_);
}
}
void NetErrorHelperCore::CancelPendingFetches() {
RecordHistoryDebugEvent(HistoryDebugEvent::CANCEL_PENDING_FETCHES);
// Cancel loading the alternate error page, and prevent any pending error page
// load from starting a new error page load. Swapping in the error page when
// it's finished loading could abort the navigation, otherwise.
if (committed_error_page_info_)
committed_error_page_info_->needs_load_navigation_corrections = false;
if (pending_error_page_info_)
pending_error_page_info_->needs_load_navigation_corrections = false;
delegate_->CancelFetchNavigationCorrections();
auto_reload_timer_->Stop();
auto_reload_paused_ = false;
}
void NetErrorHelperCore::OnStop() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_STOP);
if (committed_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
ReportAutoReloadFailure(committed_error_page_info_->error,
auto_reload_count_);
}
CancelPendingFetches();
uncommitted_load_started_ = false;
auto_reload_count_ = 0;
auto_reload_in_flight_ = false;
}
void NetErrorHelperCore::OnWasShown() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_WAS_SHOWN);
visible_ = true;
if (!auto_reload_visible_only_)
return;
if (auto_reload_paused_)
MaybeStartAutoReloadTimer();
}
void NetErrorHelperCore::OnWasHidden() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_WAS_HIDDEN);
visible_ = false;
if (!auto_reload_visible_only_)
return;
PauseAutoReloadTimer();
}
void NetErrorHelperCore::OnStartLoad(FrameType frame_type, PageType page_type) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_START_LOAD);
uncommitted_load_started_ = true;
// If there's no pending error page information associated with the page load,
// or the new page is not an error page, then reset pending error page state.
if (!pending_error_page_info_ || page_type != ERROR_PAGE)
CancelPendingFetches();
}
void NetErrorHelperCore::OnCommitLoad(FrameType frame_type, const GURL& url) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_COMMIT_LOAD);
// If a page is committing, either it's an error page and autoreload will be
// started again below, or it's a success page and we need to clear autoreload
// state.
auto_reload_in_flight_ = false;
// uncommitted_load_started_ could already be false, since RenderFrameImpl
// calls OnCommitLoad once for each in-page navigation (like a fragment
// change) with no corresponding OnStartLoad.
uncommitted_load_started_ = false;
// Track if an error occurred due to a page button press.
// This isn't perfect; if (for instance), the server is slow responding
// to a request generated from the page reload button, and the user hits
// the browser reload button, this code will still believe the
// result is from the page reload button.
if (committed_error_page_info_ && pending_error_page_info_ &&
navigation_from_button_ != NO_BUTTON &&
committed_error_page_info_->error.unreachableURL ==
pending_error_page_info_->error.unreachableURL) {
DCHECK(navigation_from_button_ == RELOAD_BUTTON ||
navigation_from_button_ == SHOW_SAVED_COPY_BUTTON);
RecordEvent(navigation_from_button_ == RELOAD_BUTTON ?
NETWORK_ERROR_PAGE_RELOAD_BUTTON_ERROR :
NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_ERROR);
}
navigation_from_button_ = NO_BUTTON;
if (committed_error_page_info_ && !pending_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
const blink::WebURLError& error = committed_error_page_info_->error;
const GURL& error_url = error.unreachableURL;
if (url == error_url)
ReportAutoReloadSuccess(error, auto_reload_count_);
else if (url != GURL(content::kUnreachableWebDataURL))
ReportAutoReloadFailure(error, auto_reload_count_);
}
committed_error_page_info_.reset(pending_error_page_info_.release());
RecordHistoryDebugEvent(HistoryDebugEvent::ON_COMMIT_LOAD_END);
}
void NetErrorHelperCore::OnFinishLoad(FrameType frame_type) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD);
if (!committed_error_page_info_) {
auto_reload_count_ = 0;
RecordHistoryDebugEvent(
HistoryDebugEvent::ON_FINISH_LOAD_END_NOT_ERROR_PAGE);
return;
}
committed_error_page_info_->is_finished_loading = true;
RecordEvent(NETWORK_ERROR_PAGE_SHOWN);
if (committed_error_page_info_->reload_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_RELOAD_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_offline_pages_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_PAGES_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_offline_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_COPY_BUTTON_SHOWN);
}
if (committed_error_page_info_->reload_button_in_page &&
committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_SHOWN);
}
if (committed_error_page_info_->show_cached_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_CACHED_COPY_BUTTON_SHOWN);
}
delegate_->EnablePageHelperFunctions();
if (committed_error_page_info_->needs_load_navigation_corrections) {
// If there is another pending error page load, |fix_url| should have been
// cleared.
DCHECK(!pending_error_page_info_);
DCHECK(!committed_error_page_info_->needs_dns_updates);
delegate_->FetchNavigationCorrections(
committed_error_page_info_->navigation_correction_params->url,
CreateFixUrlRequestBody(
committed_error_page_info_->error,
*committed_error_page_info_->navigation_correction_params));
} else if (auto_reload_enabled_ &&
IsReloadableError(*committed_error_page_info_)) {
MaybeStartAutoReloadTimer();
}
if (!committed_error_page_info_->needs_dns_updates ||
last_probe_status_ == DNS_PROBE_POSSIBLE) {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD_END_DNS_PROBE);
return;
}
DVLOG(1) << "Error page finished loading; sending saved status.";
UpdateErrorPage();
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD_END_NO_DNS_PROBE);
}
void NetErrorHelperCore::GetErrorHTML(FrameType frame_type,
const blink::WebURLError& error,
bool is_failed_post,
bool is_ignoring_cache,
std::string* error_html) {
if (frame_type == MAIN_FRAME) {
// If navigation corrections were needed before, that should have been
// cancelled earlier by starting a new page load (Which has now failed).
DCHECK(!committed_error_page_info_ ||
!committed_error_page_info_->needs_load_navigation_corrections);
RecordHistoryDebugEvent(HistoryDebugEvent::GET_ERROR_HTML);
pending_error_page_info_.reset(
new ErrorPageInfo(error, is_failed_post, is_ignoring_cache));
pending_error_page_info_->navigation_correction_params.reset(
new NavigationCorrectionParams(navigation_correction_params_));
GetErrorHtmlForMainFrame(pending_error_page_info_.get(), error_html);
} else {
// These values do not matter, as error pages in iframes hide the buttons.
bool reload_button_in_page;
bool show_saved_copy_button_in_page;
bool show_cached_copy_button_in_page;
bool show_offline_pages_button_in_page;
bool show_offline_copy_button_in_page;
delegate_->GenerateLocalizedErrorPage(
error, is_failed_post,
false /* No diagnostics dialogs allowed for subframes. */,
OfflinePageStatus::NONE /* No offline button provided in subframes */,
scoped_ptr<ErrorPageParams>(), &reload_button_in_page,
&show_saved_copy_button_in_page, &show_cached_copy_button_in_page,
&show_offline_pages_button_in_page,
&show_offline_copy_button_in_page, error_html);
}
}
void NetErrorHelperCore::OnNetErrorInfo(DnsProbeStatus status) {
DCHECK_NE(DNS_PROBE_POSSIBLE, status);
RecordHistoryDebugEvent(HistoryDebugEvent::NET_ERROR_INFO_RECEIVED);
last_probe_status_ = status;
if (!committed_error_page_info_ ||
!committed_error_page_info_->needs_dns_updates ||
!committed_error_page_info_->is_finished_loading) {
return;
}
UpdateErrorPage();
}
void NetErrorHelperCore::OnSetCanShowNetworkDiagnosticsDialog(
bool can_show_network_diagnostics_dialog) {
can_show_network_diagnostics_dialog_ = can_show_network_diagnostics_dialog;
}
void NetErrorHelperCore::OnSetNavigationCorrectionInfo(
const GURL& navigation_correction_url,
const std::string& language,
const std::string& country_code,
const std::string& api_key,
const GURL& search_url) {
navigation_correction_params_.url = navigation_correction_url;
navigation_correction_params_.language = language;
navigation_correction_params_.country_code = country_code;
navigation_correction_params_.api_key = api_key;
navigation_correction_params_.search_url = search_url;
}
void NetErrorHelperCore::OnSetOfflinePageInfo(
OfflinePageStatus offline_page_status) {
#if defined(OS_ANDROID)
offline_page_status_ = offline_page_status;
#endif // defined(OS_ANDROID)
}
void NetErrorHelperCore::GetErrorHtmlForMainFrame(
ErrorPageInfo* pending_error_page_info,
std::string* error_html) {
std::string error_param;
blink::WebURLError error = pending_error_page_info->error;
if (pending_error_page_info->navigation_correction_params &&
pending_error_page_info->navigation_correction_params->url.is_valid() &&
ShouldUseFixUrlServiceForError(error, &error_param)) {
pending_error_page_info->needs_load_navigation_corrections = true;
return;
}
if (IsDnsError(pending_error_page_info->error)) {
// The last probe status needs to be reset if this is a DNS error. This
// means that if a DNS error page is committed but has not yet finished
// loading, a DNS probe status scheduled to be sent to it may be thrown
// out, but since the new error page should trigger a new DNS probe, it
// will just get the results for the next page load.
last_probe_status_ = DNS_PROBE_POSSIBLE;
pending_error_page_info->needs_dns_updates = true;
error = GetUpdatedError(error);
}
delegate_->GenerateLocalizedErrorPage(
error, pending_error_page_info->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus(),
scoped_ptr<ErrorPageParams>(),
&pending_error_page_info->reload_button_in_page,
&pending_error_page_info->show_saved_copy_button_in_page,
&pending_error_page_info->show_cached_copy_button_in_page,
&pending_error_page_info->show_offline_pages_button_in_page,
&pending_error_page_info->show_offline_copy_button_in_page,
error_html);
}
void NetErrorHelperCore::UpdateErrorPage() {
DCHECK(committed_error_page_info_->needs_dns_updates);
DCHECK(committed_error_page_info_->is_finished_loading);
DCHECK_NE(DNS_PROBE_POSSIBLE, last_probe_status_);
RecordHistoryDebugEvent(HistoryDebugEvent::UPDATE_ERROR_PAGE);
UMA_HISTOGRAM_ENUMERATION("DnsProbe.ErrorPageUpdateStatus",
last_probe_status_,
DNS_PROBE_MAX);
// Every status other than DNS_PROBE_POSSIBLE and DNS_PROBE_STARTED is a
// final status code. Once one is reached, the page does not need further
// updates.
if (last_probe_status_ != DNS_PROBE_STARTED)
committed_error_page_info_->needs_dns_updates = false;
// There is no need to worry about the button display statistics here because
// the presentation of the reload and show saved copy buttons can't be changed
// by a DNS error update.
delegate_->UpdateErrorPage(
GetUpdatedError(committed_error_page_info_->error),
committed_error_page_info_->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus());
}
void NetErrorHelperCore::OnNavigationCorrectionsFetched(
const std::string& corrections,
const std::string& accept_languages,
bool is_rtl) {
// Loading suggestions only starts when a blank error page finishes loading,
// and is cancelled with a new load.
DCHECK(!pending_error_page_info_);
DCHECK(committed_error_page_info_->is_finished_loading);
DCHECK(committed_error_page_info_->needs_load_navigation_corrections);
DCHECK(committed_error_page_info_->navigation_correction_params);
RecordHistoryDebugEvent(HistoryDebugEvent::NAVIGATION_CORRECTIONS_FETCHED);
pending_error_page_info_.reset(new ErrorPageInfo(
committed_error_page_info_->error,
committed_error_page_info_->was_failed_post,
committed_error_page_info_->was_ignoring_cache));
pending_error_page_info_->navigation_correction_response =
ParseNavigationCorrectionResponse(corrections);
std::string error_html;
scoped_ptr<ErrorPageParams> params;
if (pending_error_page_info_->navigation_correction_response) {
// Copy navigation correction parameters used for the request, so tracking
// requests can still be sent if the configuration changes.
pending_error_page_info_->navigation_correction_params.reset(
new NavigationCorrectionParams(
*committed_error_page_info_->navigation_correction_params));
params = CreateErrorPageParams(
*pending_error_page_info_->navigation_correction_response,
pending_error_page_info_->error,
*pending_error_page_info_->navigation_correction_params,
accept_languages, is_rtl);
delegate_->GenerateLocalizedErrorPage(
pending_error_page_info_->error,
pending_error_page_info_->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus(),
params.Pass(),
&pending_error_page_info_->reload_button_in_page,
&pending_error_page_info_->show_saved_copy_button_in_page,
&pending_error_page_info_->show_cached_copy_button_in_page,
&pending_error_page_info_->show_offline_pages_button_in_page,
&pending_error_page_info_->show_offline_copy_button_in_page,
&error_html);
} else {
// Since |navigation_correction_params| in |pending_error_page_info_| is
// NULL, this won't trigger another attempt to load corrections.
GetErrorHtmlForMainFrame(pending_error_page_info_.get(), &error_html);
}
// TODO(mmenke): Once the new API is in place, look into replacing this
// double page load by just updating the error page, like DNS
// probes do.
delegate_->LoadErrorPage(error_html,
pending_error_page_info_->error.unreachableURL);
}
blink::WebURLError NetErrorHelperCore::GetUpdatedError(
const blink::WebURLError& error) const {
// If a probe didn't run or wasn't conclusive, restore the original error.
if (last_probe_status_ == DNS_PROBE_NOT_RUN ||
last_probe_status_ == DNS_PROBE_FINISHED_INCONCLUSIVE) {
return error;
}
blink::WebURLError updated_error;
updated_error.domain = blink::WebString::fromUTF8(kDnsProbeErrorDomain);
updated_error.reason = last_probe_status_;
updated_error.unreachableURL = error.unreachableURL;
updated_error.staleCopyInCache = error.staleCopyInCache;
return updated_error;
}
void NetErrorHelperCore::Reload(bool ignore_cache) {
RecordHistoryDebugEvent(HistoryDebugEvent::RELOAD);
if (!committed_error_page_info_) {
return;
}
delegate_->ReloadPage(ignore_cache);
}
bool NetErrorHelperCore::MaybeStartAutoReloadTimer() {
RecordHistoryDebugEvent(HistoryDebugEvent::MAYBE_RELOAD);
if (!committed_error_page_info_ ||
!committed_error_page_info_->is_finished_loading ||
pending_error_page_info_ ||
uncommitted_load_started_) {
return false;
}
StartAutoReloadTimer();
return true;
}
void NetErrorHelperCore::StartAutoReloadTimer() {
DCHECK(committed_error_page_info_);
DCHECK(IsReloadableError(*committed_error_page_info_));
RecordHistoryDebugEvent(HistoryDebugEvent::START_RELOAD_TIMER);
committed_error_page_info_->auto_reload_triggered = true;
if (!online_ || (!visible_ && auto_reload_visible_only_)) {
RecordHistoryDebugEvent(HistoryDebugEvent::START_RELOAD_TIMER_PAUSED);
auto_reload_paused_ = true;
return;
}
auto_reload_paused_ = false;
base::TimeDelta delay = GetAutoReloadTime(auto_reload_count_);
auto_reload_timer_->Stop();
auto_reload_timer_->Start(FROM_HERE, delay,
base::Bind(&NetErrorHelperCore::AutoReloadTimerFired,
base::Unretained(this)));
}
void NetErrorHelperCore::AutoReloadTimerFired() {
// AutoReloadTimerFired only runs if:
// 1. StartAutoReloadTimer was previously called, which requires that
// committed_error_page_info_ is populated;
// 2. No other page load has started since (1), since OnStartLoad stops the
// auto-reload timer.
DCHECK(committed_error_page_info_);
RecordHistoryDebugEvent(HistoryDebugEvent::RELOAD_TIMER_FIRED);
auto_reload_count_++;
auto_reload_in_flight_ = true;
if (!committed_error_page_info_) {
HistoryDebugEvent history_debug_events[MAX_DEBUG_HISTORY_EVENTS];
size_t num_history_debug_events = history_debug_events_.size();
for (size_t i = 0; i < num_history_debug_events; ++i) {
history_debug_events[i] = history_debug_events_[i];
}
base::debug::Alias(history_debug_events);
base::debug::Alias(&num_history_debug_events);
base::debug::DumpWithoutCrashing();
return;
}
Reload(committed_error_page_info_->was_ignoring_cache);
}
void NetErrorHelperCore::PauseAutoReloadTimer() {
RecordHistoryDebugEvent(HistoryDebugEvent::PAUSE_RELOAD_TIMER);
if (!auto_reload_timer_->IsRunning())
return;
DCHECK(committed_error_page_info_);
DCHECK(!auto_reload_paused_);
DCHECK(committed_error_page_info_->auto_reload_triggered);
auto_reload_timer_->Stop();
auto_reload_paused_ = true;
}
void NetErrorHelperCore::NetworkStateChanged(bool online) {
RecordHistoryDebugEvent(HistoryDebugEvent::NETWORK_STATE_CHANGED);
bool was_online = online_;
online_ = online;
if (!was_online && online) {
// Transitioning offline -> online
if (auto_reload_paused_)
MaybeStartAutoReloadTimer();
} else if (was_online && !online) {
// Transitioning online -> offline
if (auto_reload_timer_->IsRunning())
auto_reload_count_ = 0;
PauseAutoReloadTimer();
}
}
bool NetErrorHelperCore::ShouldSuppressErrorPage(FrameType frame_type,
const GURL& url) {
// Don't suppress child frame errors.
if (frame_type != MAIN_FRAME)
return false;
RecordHistoryDebugEvent(HistoryDebugEvent::SHOULD_SUPPRESS_ERROR_PAGE);
// If there's no auto reload attempt in flight, this error page didn't come
// from auto reload, so don't suppress it.
if (!auto_reload_in_flight_)
return false;
uncommitted_load_started_ = false;
// This serves to terminate the auto-reload in flight attempt. If
// ShouldSuppressErrorPage is called, the auto-reload yielded an error, which
// means the request was already sent.
auto_reload_in_flight_ = false;
MaybeStartAutoReloadTimer();
return true;
}
void NetErrorHelperCore::ExecuteButtonPress(Button button) {
// If there's no committed error page, should not be invoked.
DCHECK(committed_error_page_info_);
RecordHistoryDebugEvent(HistoryDebugEvent::EXECUTE_BUTTON_PRESS);
switch (button) {
case RELOAD_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_RELOAD_BUTTON_CLICKED);
if (committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_RELOAD_CLICKED);
}
navigation_from_button_ = RELOAD_BUTTON;
Reload(false);
return;
case SHOW_SAVED_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_CLICKED);
navigation_from_button_ = SHOW_SAVED_COPY_BUTTON;
if (committed_error_page_info_->reload_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_SHOWN_SAVED_COPY_CLICKED);
}
delegate_->LoadPageFromCache(
committed_error_page_info_->error.unreachableURL);
return;
case MORE_BUTTON:
// Visual effects on page are handled in Javascript code.
RecordEvent(NETWORK_ERROR_PAGE_MORE_BUTTON_CLICKED);
return;
case EASTER_EGG:
RecordEvent(NETWORK_ERROR_EASTER_EGG_ACTIVATED);
return;
case SHOW_CACHED_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_CACHED_COPY_BUTTON_CLICKED);
return;
case DIAGNOSE_ERROR:
RecordEvent(NETWORK_ERROR_DIAGNOSE_BUTTON_CLICKED);
delegate_->DiagnoseError(
committed_error_page_info_->error.unreachableURL);
return;
case SHOW_OFFLINE_PAGES_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_PAGES_BUTTON_CLICKED);
delegate_->ShowOfflinePages();
return;
case SHOW_OFFLINE_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_COPY_BUTTON_CLICKED);
delegate_->LoadOfflineCopy(
committed_error_page_info_->error.unreachableURL);
return;
case NO_BUTTON:
NOTREACHED();
return;
}
}
void NetErrorHelperCore::TrackClick(int tracking_id) {
// It's technically possible for |navigation_correction_params| to be NULL but
// for |navigation_correction_response| not to be NULL, if the paramters
// changed between loading the original error page and loading the error page
if (!committed_error_page_info_ ||
!committed_error_page_info_->navigation_correction_response) {
return;
}
NavigationCorrectionResponse* response =
committed_error_page_info_->navigation_correction_response.get();
// |tracking_id| is less than 0 when the error page was not generated by the
// navigation correction service. |tracking_id| should never be greater than
// the array size, but best to be safe, since it contains data from a remote
// site, though none of that data should make it into Javascript callbacks.
if (tracking_id < 0 ||
static_cast<size_t>(tracking_id) >= response->corrections.size()) {
return;
}
// Only report a clicked link once.
if (committed_error_page_info_->clicked_corrections.count(tracking_id))
return;
committed_error_page_info_->clicked_corrections.insert(tracking_id);
std::string request_body = CreateClickTrackingUrlRequestBody(
committed_error_page_info_->error,
*committed_error_page_info_->navigation_correction_params,
*response,
*response->corrections[tracking_id]);
delegate_->SendTrackingRequest(
committed_error_page_info_->navigation_correction_params->url,
request_body);
}
OfflinePageStatus NetErrorHelperCore::GetOfflinePageStatus() const {
#if defined(OS_ANDROID)
return offline_page_status_;
#else
return OfflinePageStatus::NONE;
#endif // defined(OS_ANDROID)
}
void NetErrorHelperCore::RecordHistoryDebugEvent(
HistoryDebugEvent::EventType event_type) {
if (history_debug_events_.size() > MAX_DEBUG_HISTORY_EVENTS)
history_debug_events_.erase(history_debug_events_.begin());
HistoryDebugEvent event;
event.event_type = event_type;
event.pending_error_page_info_exists = !!pending_error_page_info_;
event.committed_error_page_info_exists = !!committed_error_page_info_;
event.timer_running = auto_reload_timer_->IsRunning();
history_debug_events_.push_back(event);
}
} // namespace error_page
| bsd-3-clause |
ryanolson/couchdb-python | couchdb/tests/client.py | 26584 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
from datetime import datetime
import doctest
import os
import os.path
import shutil
from StringIO import StringIO
import time
import tempfile
import threading
import unittest
import urlparse
from couchdb import client, http
from couchdb.tests import testutil
from schematics.validation import validate_instance
class ServerTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_init_with_resource(self):
sess = http.Session()
res = http.Resource(client.DEFAULT_BASE_URL, sess)
serv = client.Server(url=res)
serv.config()
def test_init_with_session(self):
sess = http.Session()
serv = client.Server(client.DEFAULT_BASE_URL, session=sess)
serv.config()
self.assertTrue(serv.resource.session is sess)
def test_exists(self):
self.assertTrue(client.Server(client.DEFAULT_BASE_URL))
self.assertFalse(client.Server('http://localhost:9999'))
def test_repr(self):
repr(self.server)
def test_server_vars(self):
version = self.server.version()
self.assertTrue(isinstance(version, basestring))
config = self.server.config()
self.assertTrue(isinstance(config, dict))
tasks = self.server.tasks()
self.assertTrue(isinstance(tasks, list))
def test_server_stats(self):
stats = self.server.stats()
self.assertTrue(isinstance(stats, dict))
stats = self.server.stats('httpd/requests')
self.assertTrue(isinstance(stats, dict))
self.assertTrue(len(stats) == 1 and len(stats['httpd']) == 1)
def test_get_db_missing(self):
self.assertRaises(http.ResourceNotFound,
lambda: self.server['couchdb-python/missing'])
def test_create_db_conflict(self):
name, db = self.temp_db()
self.assertRaises(http.PreconditionFailed, self.server.create,
name)
def test_delete_db(self):
name, db = self.temp_db()
assert name in self.server
self.del_db(name)
assert name not in self.server
def test_delete_db_missing(self):
self.assertRaises(http.ResourceNotFound, self.server.delete,
'couchdb-python/missing')
def test_replicate(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
id, rev = a.save({'test': 'a'})
result = self.server.replicate(aname, bname)
self.assertEquals(result['ok'], True)
self.assertEquals(b[id]['test'], 'a')
doc = b[id]
doc['test'] = 'b'
b.update([doc],validate=False)
self.server.replicate(bname, aname)
self.assertEquals(a[id]['test'], 'b')
self.assertEquals(b[id]['test'], 'b')
def test_replicate_continuous(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
result = self.server.replicate(aname, bname, continuous=True)
self.assertEquals(result['ok'], True)
version = tuple(int(i) for i in self.server.version().split('.')[:2])
if version >= (0, 10):
self.assertTrue('_local_id' in result)
def test_iter(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
dbs = list(self.server)
self.assertTrue(aname in dbs)
self.assertTrue(bname in dbs)
def test_len(self):
self.temp_db()
self.temp_db()
self.assertTrue(len(self.server) >= 2)
def test_uuids(self):
ls = self.server.uuids()
assert type(ls) == list
ls = self.server.uuids(count=10)
assert type(ls) == list and len(ls) == 10
class DatabaseTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_save_new(self):
doc = {'foo': 'bar'}
id, rev = self.db.save(doc)
self.assertTrue(id is not None)
self.assertTrue(rev is not None)
self.assertEqual((id, rev), (doc['_id'], doc['_rev']))
doc = self.db.get(id)
self.assertEqual(doc['foo'], 'bar')
def test_save_new_with_id(self):
doc = {'_id': 'foo'}
id, rev = self.db.save(doc)
self.assertTrue(doc['_id'] == id == 'foo')
self.assertEqual(doc['_rev'], rev)
def test_save_existing(self):
doc = {}
id_rev_old = self.db.save(doc)
doc['foo'] = True
id_rev_new = self.db.save(doc)
self.assertTrue(doc['_rev'] == id_rev_new[1])
self.assertTrue(id_rev_old[1] != id_rev_new[1])
def test_save_new_batch(self):
doc = {'_id': 'foo'}
id, rev = self.db.save(doc, batch='ok')
self.assertTrue(rev is None)
self.assertTrue('_rev' not in doc)
def test_save_existing_batch(self):
doc = {'_id': 'foo'}
self.db.save(doc)
id_rev_old = self.db.save(doc)
id_rev_new = self.db.save(doc, batch='ok')
self.assertTrue(id_rev_new[1] is None)
self.assertEqual(id_rev_old[1], doc['_rev'])
def test_exists(self):
self.assertTrue(self.db)
self.assertFalse(client.Database('couchdb-python/missing'))
def test_name(self):
# Access name assigned during creation.
name, db = self.temp_db()
self.assertTrue(db.name == name)
# Access lazily loaded name,
self.assertTrue(client.Database(db.resource.url).name == name)
def test_commit(self):
self.assertTrue(self.db.commit()['ok'] == True)
def test_create_large_doc(self):
self.db['foo'] = {'data': '0123456789' * 110 * 1024} # 10 MB
self.assertEqual('foo', self.db['foo']['_id'])
def test_doc_id_quoting(self):
self.db['foo/bar'] = {'foo': 'bar'}
self.assertEqual('bar', self.db['foo/bar']['foo'])
del self.db['foo/bar']
self.assertEqual(None, self.db.get('foo/bar'))
def test_unicode(self):
self.db[u'føø'] = {u'bår': u'Iñtërnâtiônàlizætiøn', 'baz': 'ASCII'}
self.assertEqual(u'Iñtërnâtiônàlizætiøn', self.db[u'føø'][u'bår'])
self.assertEqual(u'ASCII', self.db[u'føø'][u'baz'])
def test_disallow_nan(self):
try:
self.db['foo'] = {u'number': float('nan')}
self.fail('Expected ValueError')
except ValueError:
pass
def test_disallow_none_id(self):
deldoc = lambda: self.db.delete({'_id': None, '_rev': None})
self.assertRaises(ValueError, deldoc)
def test_doc_revs(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
doc['bar'] = 43
self.db['foo'] = doc
new_rev = doc['_rev']
new_doc = self.db.get('foo')
self.assertEqual(new_rev, new_doc['_rev'])
new_doc = self.db.get('foo', rev=new_rev)
self.assertEqual(new_rev, new_doc['_rev'])
old_doc = self.db.get('foo', rev=old_rev)
self.assertEqual(old_rev, old_doc['_rev'])
revs = [i for i in self.db.revisions('foo')]
self.assertEqual(revs[0]['_rev'], new_rev)
self.assertEqual(revs[1]['_rev'], old_rev)
gen = self.db.revisions('crap')
self.assertRaises(StopIteration, lambda: gen.next())
self.assertTrue(self.db.compact())
while self.db.info()['compact_running']:
pass
# 0.10 responds with 404, 0.9 responds with 500, same content
doc = 'fail'
try:
doc = self.db.get('foo', rev=old_rev)
except http.ServerError:
doc = None
assert doc is None
def test_attachment_crud(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
self.db.put_attachment(doc, 'Foo bar', 'foo.txt', 'text/plain')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['foo.txt']
self.assertEqual(len('Foo bar'), attachment['length'])
self.assertEqual('text/plain', attachment['content_type'])
self.assertEqual('Foo bar',
self.db.get_attachment(doc, 'foo.txt').read())
self.assertEqual('Foo bar',
self.db.get_attachment('foo', 'foo.txt').read())
old_rev = doc['_rev']
self.db.delete_attachment(doc, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
self.assertEqual(None, self.db['foo'].get('_attachments'))
def test_attachment_crud_with_files(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
fileobj = StringIO('Foo bar baz')
self.db.put_attachment(doc, fileobj, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['foo.txt']
self.assertEqual(len('Foo bar baz'), attachment['length'])
self.assertEqual('text/plain', attachment['content_type'])
self.assertEqual('Foo bar baz',
self.db.get_attachment(doc, 'foo.txt').read())
self.assertEqual('Foo bar baz',
self.db.get_attachment('foo', 'foo.txt').read())
old_rev = doc['_rev']
self.db.delete_attachment(doc, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
self.assertEqual(None, self.db['foo'].get('_attachments'))
def test_empty_attachment(self):
doc = {}
self.db['foo'] = doc
old_rev = doc['_rev']
self.db.put_attachment(doc, '', 'empty.txt')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['empty.txt']
self.assertEqual(0, attachment['length'])
def test_default_attachment(self):
doc = {}
self.db['foo'] = doc
self.assertTrue(self.db.get_attachment(doc, 'missing.txt') is None)
sentinel = object()
self.assertTrue(self.db.get_attachment(doc, 'missing.txt', sentinel) is sentinel)
def test_attachment_from_fs(self):
tmpdir = tempfile.mkdtemp()
tmpfile = os.path.join(tmpdir, 'test.txt')
f = open(tmpfile, 'w')
f.write('Hello!')
f.close()
doc = {}
self.db['foo'] = doc
self.db.put_attachment(doc, open(tmpfile))
doc = self.db.get('foo')
self.assertTrue(doc['_attachments']['test.txt']['content_type'] == 'text/plain')
shutil.rmtree(tmpdir)
def test_attachment_no_filename(self):
doc = {}
self.db['foo'] = doc
self.assertRaises(ValueError, self.db.put_attachment, doc, '')
def test_json_attachment(self):
doc = {}
self.db['foo'] = doc
self.db.put_attachment(doc, '{}', 'test.json', 'application/json')
self.assertEquals(self.db.get_attachment(doc, 'test.json').read(), '{}')
def test_include_docs(self):
doc = {'foo': 42, 'bar': 40}
self.db['foo'] = doc
rows = list(self.db.query(
'function(doc) { emit(doc._id, null); }',
include_docs=True
))
self.assertEqual(1, len(rows))
self.assertEqual(doc, rows[0].doc)
def test_query_multi_get(self):
for i in range(1, 6):
self.db.save({'i': i})
res = list(self.db.query('function(doc) { emit(doc.i, null); }',
keys=range(1, 6, 2)))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1, 6, 2)):
self.assertEqual(i, res[idx].key)
def test_bulk_update_conflict(self):
docs = [
dict(type='Person', name='John Doe'),
dict(type='Person', name='Mary Jane'),
dict(type='City', name='Gotham City')
]
self.db.update(docs)
# update the first doc to provoke a conflict in the next bulk update
doc = docs[0].copy()
self.db[doc['_id']] = doc
results = self.db.update(docs)
self.assertEqual(False, results[0][0])
assert isinstance(results[0][2], http.ResourceConflict)
def test_bulk_update_all_or_nothing(self):
docs = [
dict(type='Person', name='John Doe'),
dict(type='Person', name='Mary Jane'),
dict(type='City', name='Gotham City')
]
self.db.update(docs)
# update the first doc to provoke a conflict in the next bulk update
doc = docs[0].copy()
doc['name'] = 'Jane Doe'
self.db[doc['_id']] = doc
results = self.db.update(docs, all_or_nothing=True)
self.assertEqual(True, results[0][0])
doc = self.db.get(doc['_id'], conflicts=True)
assert '_conflicts' in doc
revs = self.db.get(doc['_id'], open_revs='all')
assert len(revs) == 2
def test_bulk_update_bad_doc(self):
self.assertRaises(TypeError, self.db.update, [object()])
def test_copy_doc(self):
self.db['foo'] = {'status': 'testing'}
result = self.db.copy('foo', 'bar')
self.assertEqual(result, self.db['bar'].rev)
def test_copy_doc_conflict(self):
self.db['bar'] = {'status': 'idle'}
self.db['foo'] = {'status': 'testing'}
self.assertRaises(http.ResourceConflict, self.db.copy, 'foo', 'bar')
def test_copy_doc_overwrite(self):
self.db['bar'] = {'status': 'idle'}
self.db['foo'] = {'status': 'testing'}
result = self.db.copy('foo', self.db['bar'])
doc = self.db['bar']
self.assertEqual(result, doc.rev)
self.assertEqual('testing', doc['status'])
def test_copy_doc_srcobj(self):
self.db['foo'] = {'status': 'testing'}
self.db.copy(self.db['foo'], 'bar')
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_destobj_norev(self):
self.db['foo'] = {'status': 'testing'}
self.db.copy('foo', {'_id': 'bar'})
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_src_dictlike(self):
class DictLike(object):
def __init__(self, doc):
self.doc = doc
def items(self):
return self.doc.items()
self.db['foo'] = {'status': 'testing'}
self.db.copy(DictLike(self.db['foo']), 'bar')
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_dest_dictlike(self):
class DictLike(object):
def __init__(self, doc):
self.doc = doc
def items(self):
return self.doc.items()
self.db['foo'] = {'status': 'testing'}
self.db['bar'] = {}
self.db.copy('foo', DictLike(self.db['bar']))
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_src_baddoc(self):
self.assertRaises(TypeError, self.db.copy, object(), 'bar')
def test_copy_doc_dest_baddoc(self):
self.assertRaises(TypeError, self.db.copy, 'foo', object())
def test_changes(self):
self.db['foo'] = {'bar': True}
self.assertEqual(self.db.changes(since=0)['last_seq'], 1)
first = self.db.changes(feed='continuous').next()
self.assertEqual(first['seq'], 1)
self.assertEqual(first['id'], 'foo')
def test_changes_releases_conn(self):
# Consume an entire changes feed to read the whole response, then check
# that the HTTP connection made it to the pool.
list(self.db.changes(feed='continuous', timeout=0))
scheme, netloc = urlparse.urlsplit(client.DEFAULT_BASE_URL)[:2]
self.assertTrue(self.db.resource.session.connection_pool.conns[(scheme, netloc)])
def test_changes_releases_conn_when_lastseq(self):
# Consume a changes feed, stopping at the 'last_seq' item, i.e. don't
# let the generator run any further, then check the connection made it
# to the pool.
for obj in self.db.changes(feed='continuous', timeout=0):
if 'last_seq' in obj:
break
scheme, netloc = urlparse.urlsplit(client.DEFAULT_BASE_URL)[:2]
self.assertTrue(self.db.resource.session.connection_pool.conns[(scheme, netloc)])
def test_changes_conn_usable(self):
# Consume a changes feed to get a used connection in the pool.
list(self.db.changes(feed='continuous', timeout=0))
# Try using the connection again to make sure the connection was left
# in a good state from the previous request.
self.assertTrue(self.db.info()['doc_count'] == 0)
def test_changes_heartbeat(self):
def wakeup():
time.sleep(.3)
self.db.save({})
threading.Thread(target=wakeup).start()
for change in self.db.changes(feed='continuous', heartbeat=100):
break
def test_purge(self):
doc = {'a': 'b'}
self.db['foo'] = doc
self.assertEqual(self.db.purge([doc])['purge_seq'], 1)
def test_json_encoding_error(self):
doc = {'now': datetime.now()}
self.assertRaises(TypeError, self.db.save, doc)
class ViewTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_row_object(self):
row = list(self.db.view('_all_docs', keys=['blah']))[0]
self.assertEqual(repr(row), "<Row key=u'blah', error=u'not_found'>")
self.assertEqual(row.id, None)
self.assertEqual(row.key, 'blah')
self.assertEqual(row.value, None)
self.assertEqual(row.error, 'not_found')
self.db.save({'_id': 'xyz', 'foo': 'bar'})
row = list(self.db.view('_all_docs', keys=['xyz']))[0]
self.assertEqual(row.id, 'xyz')
self.assertEqual(row.key, 'xyz')
self.assertEqual(row.value.keys(), ['rev'])
self.assertEqual(row.error, None)
def test_view_multi_get(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
res = list(self.db.view('test/multi_key', keys=range(1, 6, 2)))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1, 6, 2)):
self.assertEqual(i, res[idx].key)
def test_ddoc_info(self):
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'test': {'map': 'function(doc) { emit(doc.type, null); }'}
}
}
info = self.db.info('test')
self.assertEqual(info['view_index']['compact_running'], False)
def test_view_compaction(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
self.db.view('test/multi_key')
self.assertTrue(self.db.compact('test'))
def test_view_cleanup(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
self.db.view('test/multi_key')
ddoc = self.db['_design/test']
ddoc['views'] = {
'ids': {'map': 'function(doc) { emit(doc._id, null); }'}
}
self.db.update([ddoc])
self.db.view('test/ids')
self.assertTrue(self.db.cleanup())
def test_view_function_objects(self):
if 'python' not in self.server.config()['query_servers']:
return
for i in range(1, 4):
self.db.save({'i': i, 'j':2*i})
def map_fun(doc):
yield doc['i'], doc['j']
res = list(self.db.query(map_fun, language='python'))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1,4)):
self.assertEqual(i, res[idx].key)
self.assertEqual(2*i, res[idx].value)
def reduce_fun(keys, values):
return sum(values)
res = list(self.db.query(map_fun, reduce_fun, 'python'))
self.assertEqual(1, len(res))
self.assertEqual(12, res[0].value)
def test_init_with_resource(self):
self.db['foo'] = {}
view = client.PermanentView(self.db.resource('_all_docs').url, '_all_docs')
self.assertEquals(len(list(view())), 1)
def test_iter_view(self):
self.db['foo'] = {}
view = client.PermanentView(self.db.resource('_all_docs').url, '_all_docs')
self.assertEquals(len(list(view)), 1)
def test_tmpview_repr(self):
mapfunc = "function(doc) {emit(null, null);}"
view = client.TemporaryView(self.db.resource('_temp_view'), mapfunc)
self.assertTrue('TemporaryView' in repr(view))
self.assertTrue(mapfunc in repr(view))
def test_wrapper_iter(self):
class Wrapper(object):
def __init__(self, doc):
pass
self.db['foo'] = {}
self.assertTrue(isinstance(list(self.db.view('_all_docs', wrapper=Wrapper))[0], Wrapper))
def test_wrapper_rows(self):
class Wrapper(object):
def __init__(self, doc):
pass
self.db['foo'] = {}
self.assertTrue(isinstance(self.db.view('_all_docs', wrapper=Wrapper).rows[0], Wrapper))
def test_properties(self):
for attr in ['rows', 'total_rows', 'offset']:
self.assertTrue(getattr(self.db.view('_all_docs'), attr) is not None)
def test_rowrepr(self):
self.db['foo'] = {}
rows = list(self.db.query("function(doc) {emit(null, 1);}"))
self.assertTrue('Row' in repr(rows[0]))
self.assertTrue('id' in repr(rows[0]))
rows = list(self.db.query("function(doc) {emit(null, 1);}", "function(keys, values, combine) {return sum(values);}"))
self.assertTrue('Row' in repr(rows[0]))
self.assertTrue('id' not in repr(rows[0]))
class ShowListTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
show_func = """
function(doc, req) {
return {"body": req.id + ":" + (req.query.r || "<default>")};
}
"""
list_func = """
function(head, req) {
start({headers: {'Content-Type': 'text/csv'}});
if (req.query.include_header) {
send('id' + '\\r\\n');
}
var row;
while (row = getRow()) {
send(row.id + '\\r\\n');
}
}
"""
design_doc = {'_id': '_design/foo',
'shows': {'bar': show_func},
'views': {'by_id': {'map': "function(doc) {emit(doc._id, null)}"},
'by_name': {'map': "function(doc) {emit(doc.name, null)}"}},
'lists': {'list': list_func}}
def setUp(self):
super(ShowListTestCase, self).setUp()
# Workaround for possible bug in CouchDB. Adding a timestamp avoids a
# 409 Conflict error when pushing the same design doc that existed in a
# now deleted database.
design_doc = dict(self.design_doc)
design_doc['timestamp'] = time.time()
self.db.save(design_doc)
self.db.update([{'_id': '1', 'name': 'one'}, {'_id': '2', 'name': 'two'}])
def test_show_urls(self):
self.assertEqual(self.db.show('_design/foo/_show/bar')[1].read(), 'null:<default>')
self.assertEqual(self.db.show('foo/bar')[1].read(), 'null:<default>')
def test_show_docid(self):
self.assertEqual(self.db.show('foo/bar')[1].read(), 'null:<default>')
self.assertEqual(self.db.show('foo/bar', '1')[1].read(), '1:<default>')
self.assertEqual(self.db.show('foo/bar', '2')[1].read(), '2:<default>')
def test_show_params(self):
self.assertEqual(self.db.show('foo/bar', r='abc')[1].read(), 'null:abc')
def test_list(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_id')[1].read(), '1\r\n2\r\n')
self.assertEqual(self.db.list('foo/list', 'foo/by_id', include_header='true')[1].read(), 'id\r\n1\r\n2\r\n')
def test_list_keys(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_id', keys=['1'])[1].read(), '1\r\n')
def test_list_view_params(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_name', startkey='o', endkey='p')[1].read(), '1\r\n')
self.assertEqual(self.db.list('foo/list', 'foo/by_name', descending=True)[1].read(), '2\r\n1\r\n')
class UpdateHandlerTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
update_func = """
function(doc, req) {
if (!doc) {
if (req.id) {
return [{_id : req.id}, "new doc"]
}
return [null, "empty doc"];
}
doc.name = "hello";
return [doc, "hello doc"];
}
"""
design_doc = {'_id': '_design/foo',
'language': 'javascript',
'updates': {'bar': update_func}}
def setUp(self):
super(UpdateHandlerTestCase, self).setUp()
# Workaround for possible bug in CouchDB. Adding a timestamp avoids a
# 409 Conflict error when pushing the same design doc that existed in a
# now deleted database.
design_doc = dict(self.design_doc)
design_doc['timestamp'] = time.time()
self.db.save(design_doc)
self.db.update([{'_id': 'existed', 'name': 'bar'}])
def test_empty_doc(self):
self.assertEqual(self.db.update_doc('foo/bar')[1].read(), 'empty doc')
def test_new_doc(self):
self.assertEqual(self.db.update_doc('foo/bar', 'new')[1].read(), 'new doc')
def test_update_doc(self):
self.assertEqual(self.db.update_doc('foo/bar', 'existed')[1].read(), 'hello doc')
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ServerTestCase, 'test'))
suite.addTest(unittest.makeSuite(DatabaseTestCase, 'test'))
suite.addTest(unittest.makeSuite(ViewTestCase, 'test'))
suite.addTest(unittest.makeSuite(ShowListTestCase, 'test'))
suite.addTest(unittest.makeSuite(UpdateHandlerTestCase, 'test'))
suite.addTest(doctest.DocTestSuite(client))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| bsd-3-clause |
lianghongle/yii2test | backend/web/hplus/table_data_tables.html | 79179 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H+ 后台主题UI框架 - 数据表格</title>
<meta name="keywords" content="H+后台主题,后台bootstrap框架,会员中心主题,后台HTML,响应式后台">
<meta name="description" content="H+是一个完全响应式,基于Bootstrop3最新版本开发的扁平化主题,她采用了主流的左右两栏式布局,使用了Html5+CSS3等现代技术">
<link href="css/bootstrap.min.css?v=1.7" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css?v=1.7" rel="stylesheet">
<!-- Data Tables -->
<link href="css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css?v=1.7" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<nav class="navbar-default navbar-static-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav" id="side-menu">
<li class="nav-header">
<div class="dropdown profile-element"> <span>
<img alt="image" class="img-circle" src="img/profile_small.jpg" />
</span>
<a data-toggle="dropdown" class="dropdown-toggle" href="index.html#">
<span class="clear"> <span class="block m-t-xs"> <strong class="font-bold">Beaut-zihan</strong>
</span> <span class="text-muted text-xs block">超级管理员 <b class="caret"></b></span> </span>
</a>
<ul class="dropdown-menu animated fadeInRight m-t-xs">
<li><a href="form_avatar.html">修改头像</a>
</li>
<li><a href="profile.html">个人资料</a>
</li>
<li><a href="contacts.html">联系我们</a>
</li>
<li><a href="mailbox.html">信箱</a>
</li>
<li class="divider"></li>
<li><a href="login.html">安全退出</a>
</li>
</ul>
</div>
<div class="logo-element">
H+
</div>
</li>
<li>
<a href="index.html"><i class="fa fa-th-large"></i> <span class="nav-label">主页</span> <span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="index_1.html">主页示例一</a>
</li>
<li><a href="index_2.html">主页示例二</a>
</li>
<li><a href="index_3.html">主页示例三</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-bar-chart-o"></i> <span class="nav-label">图表</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="graph_echarts.html">百度ECharts</a>
</li>
<li><a href="graph_flot.html">Flot</a>
</li>
<li><a href="graph_morris.html">Morris.js</a>
</li>
<li><a href="graph_rickshaw.html">Rickshaw</a>
</li>
<li><a href="graph_peity.html">Peity</a>
</li>
<li><a href="graph_sparkline.html">Sparkline</a>
</li>
</ul>
</li>
<li>
<a href="mailbox.html"><i class="fa fa-envelope"></i> <span class="nav-label">信箱 </span><span class="label label-warning pull-right">16</span></a>
<ul class="nav nav-second-level">
<li><a href="mailbox.html">收件箱</a>
</li>
<li><a href="mail_detail.html">查看邮件</a>
</li>
<li><a href="mail_compose.html">写信</a>
</li>
</ul>
</li>
<li>
<a href="widgets.html"><i class="fa fa-flask"></i> <span class="nav-label">小工具</span></a>
</li>
<li>
<a href="index.html#"><i class="fa fa-edit"></i> <span class="nav-label">表单</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="form_basic.html">基本表单</a>
</li>
<li><a href="form_validate.html">表单验证</a>
</li>
<li><a href="form_advanced.html">高级插件</a>
</li>
<li><a href="form_wizard.html">步骤条</a>
</li>
<li><a href="form_webuploader.html">百度WebUploader</a>
</li>
<li><a href="form_file_upload.html">文件上传</a>
</li>
<li><a href="form_editors.html">富文本编辑器</a>
</li>
<li><a href="form_simditor.html">simditor</a>
</li>
<li><a href="form_avatar.html">头像裁剪上传</a>
</li>
<li><a href="layerdate.html">日期选择器layerDate</a>
</li>
<li><a href="tree_view.html">树形视图</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-desktop"></i> <span class="nav-label">页面</span> <span class="pull-right label label-primary">推荐</span></a>
<ul class="nav nav-second-level">
<li><a href="contacts.html">联系人</a>
</li>
<li><a href="profile.html">个人资料</a>
</li>
<li><a href="projects.html">项目</a>
</li>
<li><a href="project_detail.html">项目详情</a>
</li>
<li><a href="file_manager.html">文件管理器</a>
</li>
<li><a href="calendar.html">日历</a>
</li>
<li><a href="faq.html">帮助中心</a>
</li>
<li><a href="timeline.html">时间轴</a>
</li>
<li><a href="pin_board.html">标签墙</a>
</li>
<li><a href="invoice.html">单据</a>
</li>
<li><a href="login.html">登录</a>
</li>
<li><a href="register.html">注册</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-files-o"></i> <span class="nav-label">其他页面</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="search_results.html">搜索结果</a>
</li>
<li><a href="lockscreen.html">登录超时</a>
</li>
<li><a href="404.html">404页面</a>
</li>
<li><a href="500.html">500页面</a>
</li>
<li><a href="empty_page.html">空白页</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-flask"></i> <span class="nav-label">UI元素</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="typography.html">排版</a>
</li>
<li><a href="icons.html">字体图标</a>
</li>
<li><a href="iconfont.html">阿里巴巴矢量图标库</a>
</li>
<li><a href="draggable_panels.html">拖动面板</a>
</li>
<li><a href="buttons.html">按钮</a>
</li>
<li><a href="tabs_panels.html">选项卡 & 面板</a>
</li>
<li><a href="notifications.html">通知 & 提示</a>
</li>
<li><a href="badges_labels.html">徽章,标签,进度条</a>
</li>
<li><a href="layer.html">Web弹层组件layer</a>
</li>
</ul>
</li>
<li>
<a href="grid_options.html"><i class="fa fa-laptop"></i> <span class="nav-label">栅格</span></a>
</li>
<li class="active">
<a href="index.html#"><i class="fa fa-table"></i> <span class="nav-label">表格</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="table_basic.html">基本表格</a>
</li>
<li class="active"><a href="table_data_tables.html">数据表格(DataTables)</a>
</li>
<li><a href="table_jqgrid.html">jqGrid</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-picture-o"></i> <span class="nav-label">图库</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="basic_gallery.html">基本图库</a>
</li>
<li><a href="carousel.html">图片切换</a>
</li>
</ul>
</li>
<li>
<a href="index.html#"><i class="fa fa-sitemap"></i> <span class="nav-label">菜单 </span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="index.html#">三级菜单 <span class="fa arrow"></span></a>
<ul class="nav nav-third-level">
<li>
<a href="index.html#">三级菜单 01</a>
</li>
<li>
<a href="index.html#">三级菜单 01</a>
</li>
<li>
<a href="index.html#">三级菜单 01</a>
</li>
</ul>
</li>
<li><a href="index.html#">二级菜单</a>
</li>
<li>
<a href="index.html#">二级菜单</a>
</li>
<li>
<a href="index.html#">二级菜单</a>
</li>
</ul>
</li>
<li>
<a href="webim.html"><i class="fa fa-comments"></i> <span class="nav-label">即时通讯</span><span class="label label-danger pull-right">New</span></a>
</li>
<li>
<a href="css_animation.html"><i class="fa fa-magic"></i> <span class="nav-label">CSS动画</span><span class="label label-info pull-right">62</span></a>
</li>
<li>
<a href="index.html#"><i class="fa fa-cutlery"></i> <span class="nav-label">工具 </span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a href="form_builder.html">表单构建器</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="page-wrapper" class="gray-bg dashbard-1">
<div class="row border-bottom">
<nav class="navbar navbar-static-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<a class="navbar-minimalize minimalize-styl-2 btn btn-primary " href="#"><i class="fa fa-bars"></i> </a>
<form role="search" class="navbar-form-custom" method="post" action="search_results.html">
<div class="form-group">
<input type="text" placeholder="请输入您需要查找的内容 …" class="form-control" name="top-search" id="top-search">
</div>
</form>
</div>
<ul class="nav navbar-top-links navbar-right">
<li>
<span class="m-r-sm text-muted welcome-message"><a href="index.html" title="返回首页"><i class="fa fa-home"></i></a>欢迎使用H+后台主题</span>
</li>
<li class="dropdown">
<a class="dropdown-toggle count-info" data-toggle="dropdown" href="index.html#">
<i class="fa fa-envelope"></i> <span class="label label-warning">16</span>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<div class="dropdown-messages-box">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="img/a7.jpg">
</a>
<div class="media-body">
<small class="pull-right">46小时前</small>
<strong>小四</strong> 项目已处理完结
<br>
<small class="text-muted">3天前 2014.11.8</small>
</div>
</div>
</li>
<li class="divider"></li>
<li>
<div class="dropdown-messages-box">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="img/a4.jpg">
</a>
<div class="media-body ">
<small class="pull-right text-navy">25小时前</small>
<strong>国民岳父</strong> 这是一条测试信息
<br>
<small class="text-muted">昨天</small>
</div>
</div>
</li>
<li class="divider"></li>
<li>
<div class="text-center link-block">
<a href="mailbox.html">
<i class="fa fa-envelope"></i> <strong> 查看所有消息</strong>
</a>
</div>
</li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle count-info" data-toggle="dropdown" href="index.html#">
<i class="fa fa-bell"></i> <span class="label label-primary">8</span>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="mailbox.html">
<div>
<i class="fa fa-envelope fa-fw"></i> 您有16条未读消息
<span class="pull-right text-muted small">4分钟前</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="profile.html">
<div>
<i class="fa fa-qq fa-fw"></i> 3条新回复
<span class="pull-right text-muted small">12分钟钱</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<div class="text-center link-block">
<a href="notifications.html">
<strong>查看所有 </strong>
<i class="fa fa-angle-right"></i>
</a>
</div>
</li>
</ul>
</li>
<li>
<a href="login.html">
<i class="fa fa-sign-out"></i> 退出
</a>
</li>
</ul>
</nav>
</div>
<div class="row wrapper border-bottom white-bg page-heading">
<div class="col-lg-10">
<h2>数据表格</h2>
<ol class="breadcrumb">
<li>
<a href="index.html">主页</a>
</li>
<li>
<a>表格</a>
</li>
<li>
<strong>数据表格</strong>
</li>
</ol>
</div>
<div class="col-lg-2">
</div>
</div>
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>基本 <small>分类,查找</small></h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="table_data_tables.html#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="table_data_tables.html#">选项1</a>
</li>
<li><a href="table_data_tables.html#">选项2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>渲染引擎</th>
<th>浏览器</th>
<th>平台</th>
<th>引擎版本</th>
<th>CSS等级</th>
</tr>
</thead>
<tbody>
<tr class="gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0
</td>
<td>Win 95+</td>
<td class="center">4</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0
</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 5.5
</td>
<td>Win 95+</td>
<td class="center">5.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 6
</td>
<td>Win 98+</td>
<td class="center">6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 7</td>
<td>Win XP SP2+</td>
<td class="center">7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>AOL browser (AOL desktop)</td>
<td>Win XP</td>
<td class="center">6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 1.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 1.5</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 2.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 3.0</td>
<td>Win 2k+ / OSX.3+</td>
<td class="center">1.9</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Camino 1.0</td>
<td>OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Camino 1.5</td>
<td>OSX.3+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape 7.2</td>
<td>Win 95+ / Mac OS 8.6-9.2</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape Browser 8</td>
<td>Win 98SE+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape Navigator 9</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.0</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.1</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.2</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.2</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.3</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.4</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.4</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.5</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.6</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.7</td>
<td>Win 98+ / OSX.1+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.8</td>
<td>Win 98+ / OSX.1+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Seamonkey 1.1</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Epiphany 2.20</td>
<td>Gnome</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 1.2</td>
<td>OSX.3</td>
<td class="center">125.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 1.3</td>
<td>OSX.3</td>
<td class="center">312.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 2.0</td>
<td>OSX.4+</td>
<td class="center">419.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 3.0</td>
<td>OSX.4+</td>
<td class="center">522.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>OmniWeb 5.5</td>
<td>OSX.4+</td>
<td class="center">420</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>iPod Touch / iPhone</td>
<td>iPod</td>
<td class="center">420.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>S60</td>
<td>S60</td>
<td class="center">413</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 7.0</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 7.5</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 8.0</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 8.5</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.0</td>
<td>Win 95+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.2</td>
<td>Win 88+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.5</td>
<td>Win 88+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera for Wii</td>
<td>Wii</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Nokia N800</td>
<td>N800</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Nintendo DS browser</td>
<td>Nintendo DS</td>
<td class="center">8.5</td>
<td class="center">C/A<sup>1</sup>
</td>
</tr>
<tr class="gradeC">
<td>KHTML</td>
<td>Konqureror 3.1</td>
<td>KDE 3.1</td>
<td class="center">3.1</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>KHTML</td>
<td>Konqureror 3.3</td>
<td>KDE 3.3</td>
<td class="center">3.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>KHTML</td>
<td>Konqureror 3.5</td>
<td>KDE 3.5</td>
<td class="center">3.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeX">
<td>Tasman</td>
<td>Internet Explorer 4.5</td>
<td>Mac OS 8-9</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Tasman</td>
<td>Internet Explorer 5.1</td>
<td>Mac OS 7.6-9</td>
<td class="center">1</td>
<td class="center">C</td>
</tr>
<tr class="gradeC">
<td>Tasman</td>
<td>Internet Explorer 5.2</td>
<td>Mac OS 8-X</td>
<td class="center">1</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Misc</td>
<td>NetFront 3.1</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Misc</td>
<td>NetFront 3.4</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Dillo 0.8</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Links</td>
<td>Text only</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Lynx</td>
<td>Text only</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Misc</td>
<td>IE Mobile</td>
<td>Windows Mobile 6</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeC">
<td>Misc</td>
<td>PSP browser</td>
<td>PSP</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeU">
<td>Other browsers</td>
<td>All others</td>
<td>-</td>
<td class="center">-</td>
<td class="center">U</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>渲染引擎</th>
<th>浏览器</th>
<th>平台</th>
<th>引擎版本</th>
<th>CSS等级</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>可编辑表格</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="table_data_tables.html#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="table_data_tables.html#">选项1</a>
</li>
<li><a href="table_data_tables.html#">选项2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="">
<a onclick="fnClickAddRow();" href="javascript:void(0);" class="btn btn-primary ">添加行</a>
</div>
<table class="table table-striped table-bordered table-hover " id="editable">
<thead>
<tr>
<th>渲染引擎</th>
<th>浏览器</th>
<th>平台</th>
<th>引擎版本</th>
<th>CSS等级</th>
</tr>
</thead>
<tbody>
<tr class="gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0
</td>
<td>Win 95+</td>
<td class="center">4</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0
</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 5.5
</td>
<td>Win 95+</td>
<td class="center">5.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 6
</td>
<td>Win 98+</td>
<td class="center">6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>Internet Explorer 7</td>
<td>Win XP SP2+</td>
<td class="center">7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Trident</td>
<td>AOL browser (AOL desktop)</td>
<td>Win XP</td>
<td class="center">6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 1.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 1.5</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 2.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Firefox 3.0</td>
<td>Win 2k+ / OSX.3+</td>
<td class="center">1.9</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Camino 1.0</td>
<td>OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Camino 1.5</td>
<td>OSX.3+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape 7.2</td>
<td>Win 95+ / Mac OS 8.6-9.2</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape Browser 8</td>
<td>Win 98SE+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Netscape Navigator 9</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.0</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.1</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.2</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.2</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.3</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.4</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.4</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.5</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.6</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">1.6</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.7</td>
<td>Win 98+ / OSX.1+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Mozilla 1.8</td>
<td>Win 98+ / OSX.1+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Seamonkey 1.1</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Gecko</td>
<td>Epiphany 2.20</td>
<td>Gnome</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 1.2</td>
<td>OSX.3</td>
<td class="center">125.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 1.3</td>
<td>OSX.3</td>
<td class="center">312.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 2.0</td>
<td>OSX.4+</td>
<td class="center">419.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>Safari 3.0</td>
<td>OSX.4+</td>
<td class="center">522.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>OmniWeb 5.5</td>
<td>OSX.4+</td>
<td class="center">420</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>iPod Touch / iPhone</td>
<td>iPod</td>
<td class="center">420.1</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Webkit</td>
<td>S60</td>
<td>S60</td>
<td class="center">413</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 7.0</td>
<td>Win 95+ / OSX.1+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 7.5</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 8.0</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 8.5</td>
<td>Win 95+ / OSX.2+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.0</td>
<td>Win 95+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.2</td>
<td>Win 88+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera 9.5</td>
<td>Win 88+ / OSX.3+</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Opera for Wii</td>
<td>Wii</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Nokia N800</td>
<td>N800</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>Presto</td>
<td>Nintendo DS browser</td>
<td>Nintendo DS</td>
<td class="center">8.5</td>
<td class="center">C/A<sup>1</sup>
</td>
</tr>
<tr class="gradeC">
<td>KHTML</td>
<td>Konqureror 3.1</td>
<td>KDE 3.1</td>
<td class="center">3.1</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>KHTML</td>
<td>Konqureror 3.3</td>
<td>KDE 3.3</td>
<td class="center">3.3</td>
<td class="center">A</td>
</tr>
<tr class="gradeA">
<td>KHTML</td>
<td>Konqureror 3.5</td>
<td>KDE 3.5</td>
<td class="center">3.5</td>
<td class="center">A</td>
</tr>
<tr class="gradeX">
<td>Tasman</td>
<td>Internet Explorer 4.5</td>
<td>Mac OS 8-9</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Tasman</td>
<td>Internet Explorer 5.1</td>
<td>Mac OS 7.6-9</td>
<td class="center">1</td>
<td class="center">C</td>
</tr>
<tr class="gradeC">
<td>Tasman</td>
<td>Internet Explorer 5.2</td>
<td>Mac OS 8-X</td>
<td class="center">1</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Misc</td>
<td>NetFront 3.1</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeA">
<td>Misc</td>
<td>NetFront 3.4</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">A</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Dillo 0.8</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Links</td>
<td>Text only</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeX">
<td>Misc</td>
<td>Lynx</td>
<td>Text only</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeC">
<td>Misc</td>
<td>IE Mobile</td>
<td>Windows Mobile 6</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeC">
<td>Misc</td>
<td>PSP browser</td>
<td>PSP</td>
<td class="center">-</td>
<td class="center">C</td>
</tr>
<tr class="gradeU">
<td>Other browsers</td>
<td>All others</td>
<td>-</td>
<td class="center">-</td>
<td class="center">U</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>渲染引擎</th>
<th>浏览器</th>
<th>平台</th>
<th>引擎版本</th>
<th>CSS等级</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="pull-right">
By:<a href="http://www.zi-han.net" target="_blank">zihan's blog</a>
</div>
<div>
<strong>Copyright</strong> H+ © 2014
</div>
</div>
</div>
</div>
</div>
<!-- Mainly scripts -->
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/bootstrap.min.js?v=1.7"></script>
<script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
<script src="js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="js/plugins/jeditable/jquery.jeditable.js"></script>
<!-- Data Tables -->
<script src="js/plugins/dataTables/jquery.dataTables.js"></script>
<script src="js/plugins/dataTables/dataTables.bootstrap.js"></script>
<!-- Custom and plugin javascript -->
<script src="js/hplus.js?v=1.7"></script>
<script src="js/plugins/pace/pace.min.js"></script>
<!-- Page-Level Scripts -->
<script>
$(document).ready(function () {
$('.dataTables-example').dataTable();
/* Init DataTables */
var oTable = $('#editable').dataTable();
/* Apply the jEditable handlers to the table */
oTable.$('td').editable('../example_ajax.php', {
"callback": function (sValue, y) {
var aPos = oTable.fnGetPosition(this);
oTable.fnUpdate(sValue, aPos[0], aPos[1]);
},
"submitdata": function (value, settings) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition(this)[2]
};
},
"width": "90%",
"height": "100%"
});
});
function fnClickAddRow() {
$('#editable').dataTable().fnAddData([
"Custom row",
"New row",
"New row",
"New row",
"New row"]);
}
</script>
<script type="text/javascript" src="http://tajs.qq.com/stats?sId=9051096" charset="UTF-8"></script>
</body>
</html>
| bsd-3-clause |
amnona/heatsequer | heatsequer/plots/plotwingui.py | 28472 | #!/usr/bin/env python
"""
heatsequer plot window gui (2nd plot window) module
imported from plotwin.py when you plotexp() and set usegui=True
"""
# amnonscript
__version__ = "0.91"
import heatsequer as hs
import os
import sys
import numpy as np
import matplotlib as mpl
mpl.use('Qt5Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from PyQt5 import QtGui, QtCore, QtWidgets, uic
from PyQt5.QtCore import Qt
#from PyQt4 import QtGui
from PyQt5.QtWidgets import QCompleter,QMessageBox,QListWidgetItem
from PyQt5.QtCore import QStringListModel
import pickle
# for debugging - use XXX()
from pdb import set_trace as XXX
""""
for the GUI
"""
class SListWindow(QtWidgets.QDialog):
def __init__(self,listdata=[],listname=''):
"""
create a list window with items in the list and the listname as specified
input:
listdata - the data to show in the list (a list)
listname - name to display above the list
"""
super(SListWindow, self).__init__()
# uic.loadUi('./ui/listwindow.py', self)
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/listwindow.py'), self)
# uic.loadUi(hs.get_data_path('listwindow.py','ui'), self)
for citem in listdata:
self.lList.addItem(citem)
if listname:
self.lLabel.setText(listname)
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111)
# We want the axes cleared every time plot() is called
# self.axes.hold(False)
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class PlotGUIWindow(QtWidgets.QDialog):
cexp=[]
def __init__(self,expdat):
super(PlotGUIWindow, self).__init__()
hs.Debug(1,hs.get_data_path('plotguiwindow.py','ui'))
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/plotguiwindow.py'), self)
self.bGetSequence.clicked.connect(self.getsequence)
self.bExport.clicked.connect(self.export)
self.bView.clicked.connect(self.view)
self.bSave.clicked.connect(self.save)
self.bDBSave.clicked.connect(self.dbsave)
self.bEnrich.clicked.connect(self.enrich)
self.bExpInfo.clicked.connect(self.expinfo)
self.bSampleInfo.clicked.connect(self.sampleinfo)
self.lCoolDB.doubleClicked.connect(self.showannotation)
self.cSampleField.activated.connect(self.samplefield)
self.FigureTab.currentChanged.connect(self.tabchange)
self.cSampleField.setCurrentIndex(0)
self.cexp=expdat
self.selectionlines={}
self.selection=[]
self.setWindowTitle(self.cexp.studyname)
for cfield in self.cexp.fields:
self.cSampleField.addItem(cfield)
self.cPlotXField.addItem(cfield)
if self.cexp.seqdb:
ontofields,ontonames=hs.bactdb.getontonames(self.cexp.seqdb)
for conto in ontofields:
# for conto in self.cexp.seqdb.OntoGraph.keys():
self.cOntology.addItem(conto)
self.dc=None
self.createaddplot(useqt=True)
# right click menu
self.lCoolDB.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.lCoolDB.customContextMenuRequested.connect(self.listItemRightClicked)
def listItemRightClicked(self, QPos):
self.listMenu= QtWidgets.QMenu()
menuitem = self.listMenu.addAction("Delete annotation")
menuitem.triggered.connect(self.menuDeleteAnnotation)
parentPosition = self.lCoolDB.mapToGlobal(QtCore.QPoint(0, 0))
self.listMenu.move(parentPosition + QPos)
self.listMenu.show()
def menuDeleteAnnotation(self):
if len(self.lCoolDB.selectedItems())>1:
print('more than 1 item')
for citem in self.lCoolDB.selectedItems():
cdetails=citem.data(Qt.UserRole)
if cdetails is None:
print('no details')
return
annotationid=cdetails['annotationid']
qres=QtWidgets.QMessageBox.warning(self,"Delete annotation","Are you sure you want to delete annotation %d?\nThis cannot be undone" % annotationid,QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.Cancel)
if qres==QtWidgets.QMessageBox.Cancel:
return
hs.supercooldb.delete_annotation(hs.scdb,annotationid)
def showannotation(self):
citem=self.lCoolDB.currentItem()
cdetails=citem.data(Qt.UserRole)
print('-----')
print(cdetails)
showannotationdata(cdetails)
def createaddplot(self,useqt=True):
"""
create the additional figure for the ontology/line plots
input:
useqt : boolean
True to embed the plot in the qtgui window, false to open a new figure window (so don't need the qtagg)
"""
if useqt:
# add the matplotlib figure
self.frame = QtWidgets.QWidget(self)
self.dc = MyMplCanvas(self.frame, width=5, height=4, dpi=100)
# add it to an hboxlayout to make it resize with window
layout = QtWidgets.QHBoxLayout(self)
layout.insertSpacing(0,250)
# layout.addWidget(self.dc)
# self.setLayout(layout)
layout2 = QtWidgets.QVBoxLayout()
layout.addLayout(layout2)
layout2.addWidget(self.dc)
self.mpl_toolbar = NavigationToolbar(self.dc, self)
layout2.addWidget(self.mpl_toolbar)
self.setLayout(layout)
else:
addfig=plt.figure()
addax=addfig.add_subplot(1,1,1)
# addax.hold(False)
self.dc=addax
def sampleinfo(self):
if not self.csamp:
return
csamp=self.cexp.samples[self.csamp]
cmap=self.cexp.smap[csamp]
info=[]
for k,v in cmap.items():
info.append(k+':'+v)
slistwin = SListWindow(info,cmap['#SampleID'])
slistwin.exec_()
def tabchange(self,newtab):
hs.Debug(0,"new tab",newtab)
if newtab==2:
self.plotxgraph()
if newtab==1:
self.plotontology()
def plotontology(self):
if self.cexp.seqdb:
self.dc.axes.clear()
hs.Debug(2,"plotting taxonomy for seq %s onto %s" % (self.cexp.seqs[self.cseq],self.cexp.ontofigname))
hs.bactdb.PlotOntologyGraph(self.cexp.seqdb,self.cexp.seqs[self.cseq],field=str(self.cOntology.currentText()),toax=self.dc.axes)
self.dc.draw()
def plotxgraph(self):
if self.dc is None:
self.createaddplot()
self.dc.axes.clear()
seqs=self.getselectedseqs()
if self.cPlotNormalizeY.checkState()==0:
normalizey=False
else:
normalizey=True
if self.cPlotXNumeric.checkState()==0:
xfield=False
else:
xfield=str(self.cPlotXField.currentText())
hs.plotseqfreq(self.cexp,seqs=seqs,toaxis=self.dc.axes,normalizey=normalizey,xfield=xfield)
# is this needed?
# self.dc.draw()
self.dc.figure.canvas.draw_idle()
def samplefield(self,qstr):
cfield=str(qstr)
self.lSampleFieldVal.setText(self.cexp.smap[self.cexp.samples[self.csamp]][cfield])
def getsequence(self):
seq=self.cexp.seqs[self.cseq]
val,ok=QtWidgets.QInputDialog.getText(self,'Sequence',self.cexp.tax[self.cseq],text=seq)
def view(self):
slist=[]
for cseq in self.selection:
slist.append(self.cexp.tax[cseq]+'-'+str(self.cexp.sids[cseq]))
val,ok=QtWidgets.QInputDialog.getItem(self,'Selected bacteria','',slist)
def getselectedseqs(self):
slist=[]
for cseq in self.selection:
slist.append(self.cexp.seqs[cseq])
return slist
def dbsave(self):
"""
save the selected list to the coolseq database
"""
val,ok=QtWidgets.QInputDialog.getText(self,'Save %d bacteria to coolseqDB' % len(self.selection),'Enter description')
hs.Debug(1,ok)
if ok:
seqs=[]
for cid in self.selection:
seqs.append(self.cexp.seqs[cid])
hs.cooldb.savecoolseqs(self.cexp,self.cexp.cdb,seqs,val)
def enrich(self):
"""
check for annotation enrichment for selected sequences (compared to other sequences in this experiment)
"""
if not self.cexp.cdb:
hs.Debug(8,'No cooldb loaded')
return
selseqs=[]
for cid in self.selection:
selseqs.append(self.cexp.seqs[cid])
bmd=hs.cooldb.testenrichment(self.cexp.cdb,self.cexp.seqs,selseqs)
# bmd=hs.annotationenrichment(self.cexp,selseqs)
hs.Debug(6,'found %d items' % len(bmd))
if len(bmd)>0:
slistwin = SListWindow(listname='Enrichment')
bmd=hs.sortenrichment(bmd)
for cbmd in bmd:
if cbmd['observed']<cbmd['expected']:
ccolor=QtGui.QColor(155,0,0)
else:
ccolor=QtGui.QColor(0,155,0)
item = QtWidgets.QListWidgetItem()
item.setText("%s (p:%f o:%d e:%f)" % (cbmd['description'],cbmd['pval'],cbmd['observed'],cbmd['expected']))
item.setForeground(ccolor)
slistwin.lList.addItem(item)
print("%s (p:%f o:%d e:%f)" % (cbmd['description'],cbmd['pval'],cbmd['observed'],cbmd['expected']))
slistwin.exec_()
def save(self):
"""
save the selected list to a fasta file
"""
fname = str(QtWidgets.QFileDialog.getSaveFileName(self, 'Save selection fasta file name','pita'))
slist=[]
for cseq in self.selection:
slist.append(self.cexp.seqs[cseq])
hs.saveseqsfasta(self.cexp,slist,fname)
hs.Debug(6,'Saved %d sequences to file %s' % (len(slist),fname))
def export(self):
"""
export the selected bacteria list to the global variable 'selectlist'
"""
global selectlist
hs.Debug(0,'exporting')
selectlist=[]
for cseq in self.selection:
selectlist.append(self.cexp.seqs[cseq])
def updateinfo(self,csamp,cseq):
"""
update the information about the sample/bacteria
"""
self.csamp=csamp
self.cseq=cseq
self.lSample.setText(self.cexp.samples[self.csamp])
self.lTaxonomy.setText(self.cexp.tax[self.cseq])
self.lID.setText(str(self.cexp.sids[self.cseq]))
self.lReads.setText('%f' % (float(self.cexp.data[self.cseq,self.csamp])/100))
self.lSampleFieldVal.setText(self.cexp.smap[self.cexp.samples[self.csamp]][str(self.cSampleField.currentText())])
# update the stats about the database:
if self.cexp.seqdb:
self.lStudies.clear()
totappear,numstudies,allstudies,studysamples,totdbsamples=hs.bactdb.GetSeqInfo(self.cexp.seqdb,self.cexp.seqs[self.cseq])
if totappear>0:
self.lNumSamples.setText(str('%d/%dK' % (totappear,int(totdbsamples/1000))))
self.lNumStudies.setText(str(numstudies))
res=list(studysamples.items())
vlens=[]
for cv in res:
totsamps=hs.bactdb.SamplesInStudy(self.cexp.seqdb,cv[0])
vlens.append(float(len(cv[1]))/len(totsamps))
sv,si=hs.isort(vlens,reverse=True)
for cind in si:
studyname=hs.bactdb.StudyNameFromID(self.cexp.seqdb,res[cind][0])
self.lStudies.addItem('%s (%f)' % (studyname,vlens[cind]))
else:
self.lNumSamples.setText(str('%d/%dK' % (0,int(totdbsamples/1000))))
self.lNumStudies.setText("0")
if self.FigureTab.currentIndex()==2:
self.plotxgraph()
if self.FigureTab.currentIndex()==1:
self.plotontology()
def updatecdb(self,info):
"""
update the coolseq database info for the bacteria
by adding all lines in list to the listbox
"""
self.lCoolDB.clear()
self.addtocdblist(info)
def addtocdblist(self,info):
"""
add to cdb list without clearing
"""
for cinfo in info:
# test if the supercooldb annotation
if type(cinfo)==tuple:
details=cinfo[0]
newitem=QListWidgetItem(cinfo[1])
newitem.setData(Qt.UserRole,details)
if details['annotationtype']=='diffexp':
ccolor=QtGui.QColor(0,0,200)
elif details['annotationtype']=='contamination':
ccolor=QtGui.QColor(200,0,0)
elif details['annotationtype']=='common':
ccolor=QtGui.QColor(0,200,0)
elif details['annotationtype']=='highfreq':
ccolor=QtGui.QColor(0,200,0)
else:
ccolor=QtGui.QColor(0,0,0)
newitem.setForeground(ccolor)
self.lCoolDB.addItem(newitem)
else:
self.lCoolDB.addItem(cinfo)
def selectbact(self,bactlist,flip=True):
"""
add bacteria from the list bactlist (position in exp) to the selection
flip - if true, if bacteria from list is already in selection, remove it
"""
for cseq in bactlist:
# if already in list and can flip, remove from list instead
if flip:
if cseq in self.selectionlines:
self.clearselection([cseq])
hs.Debug(0,'Flip')
continue
if cseq in self.selectionlines:
continue
cline=self.plotax.plot([-0.5,len(self.cexp.samples)-0.5],[cseq,cseq],':w')
self.selectionlines[cseq]=cline
self.selection.append(cseq)
self.plotfig.canvas.draw()
self.lSelection.setText('%d bacteria' % len(self.selection))
def clearselection(self,seqlist=False):
if not seqlist:
seqlist=list(self.selectionlines.keys())
for cseq in seqlist:
cline=self.selectionlines[cseq]
self.plotax.lines.remove(cline[0])
del self.selectionlines[cseq]
self.selection.remove(cseq)
self.plotfig.canvas.draw()
self.lSelection.setText('%d bacteria' % len(self.selection))
def expinfo(self):
# get the selected sequences
sequences=[]
for cid in self.selection:
sequences.append(self.cexp.seqs[cid])
self.cexp.selectedseqs=sequences
dbs = DBAnnotateSave(self.cexp)
res=dbs.exec_()
if res==QtWidgets.QDialog.Accepted:
# fl=open('/Users/amnon/Python/git/heatsequer/db/ontologyfromid.pickle','rb')
# ontologyfromid=pickle.load(fl)
# fl.close()
ontologyfromid=hs.scdb.ontologyfromid
description=str(dbs.bdescription.text())
# TODO: need to get primer region!!!!
primerid='V4'
method=str(dbs.bmethod.text())
if method=='':
method='na'
submittername='Amnon Amir'
curations=[]
# if it is differential abundance
for citem in qtlistiteritems(dbs.blistall):
cdat=qtlistgetdata(citem)
cval=cdat['value']
ctype=cdat['type']
if cval in ontologyfromid:
cval=ontologyfromid[cval]
else:
hs.Debug(1,"item %s not found in ontologyfromid" % cval)
curations.append((ctype,cval))
if dbs.bdiffpres.isChecked():
curtype='DIFFEXP'
elif dbs.bisa.isChecked():
curtypeval=dbs.bisatype.currentText()
if 'Common' in curtypeval:
curtype='COMMON'
elif 'Contam' in curtypeval:
curtype='CONTAMINATION'
elif 'High' in curtypeval:
curtype='HIGHFREQ'
else:
curtype='OTHER'
else:
hs.Debug(9,"No annotation type selected")
return
scdb=hs.scdb
cdata=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
# if study not in database, ask to add some metadata for it
if cdata is None:
okcontinue=False
while not okcontinue:
hs.Debug(6,'study data info not found based on datamd5, mapmd5. need to add one!!!')
qres=QtWidgets.QMessageBox.warning(self,"No study data","No information added about study data. Add info?",QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No,QtWidgets.QMessageBox.Cancel)
if qres==QtWidgets.QMessageBox.Cancel:
return
if qres==QtWidgets.QMessageBox.No:
cdata=hs.supercooldb.addexpdata(scdb,( ('DataMD5',self.cexp.datamd5), ('MapMD5',self.cexp.mapmd5) ) )
okcontinue=True
if qres==QtWidgets.QMessageBox.Yes:
okcontinue=getstudydata(self.cexp)
cdata=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
hs.Debug(1,'new cdata is %s' % cdata)
hs.Debug(6,'Data found. id is %s' % cdata)
hs.supercooldb.addannotations(scdb,expid=cdata,sequences=sequences,annotationtype=curtype,annotations=curations,submittername=submittername,description=description,method=method,primerid=primerid)
# store the history
try:
hs.lastcurations.append(curations)
except:
hs.lastcurations=[curations]
hs.lastdatamd5=self.cexp.datamd5
class DBStudyAnnotations(QtWidgets.QDialog):
def __init__(self,studyid):
super(DBStudyAnnotations, self).__init__()
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/annotationlist.py'), self)
scdb=hs.scdb
self.scdb=scdb
self.studyid=studyid
info=hs.supercooldb.getexpannotations(scdb,studyid)
for cinfo in info:
self.blist.addItem(cinfo)
self.bdetails.clicked.connect(self.details)
def details(self):
items=self.blist.selectedItems()
if len(items)==0:
return
print(str(items[0].text()))
class DBStudyInfo(QtWidgets.QDialog):
def __init__(self,expdat):
super(DBStudyInfo, self).__init__()
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/studyinfo.py'), self)
scdb=hs.scdb
self.scdb=scdb
self.dataid=0
dataid=hs.supercooldb.finddataid(scdb,datamd5=expdat.datamd5,mapmd5=expdat.mapmd5)
if dataid is not None:
info=hs.supercooldb.getexperimentinfo(scdb,dataid)
for cinfo in info:
qtlistadd(self.blist,cinfo[0]+':'+cinfo[1],{'fromdb':True,'type':cinfo[0],'value':cinfo[1]},color='grey')
self.dataid=dataid
else:
qtlistadd(self.blist,"DataMD5:%s" % expdat.datamd5,{'fromdb':False,'type':"DataMD5",'value':expdat.datamd5},color='black')
qtlistadd(self.blist,"MapMD5:%s" % expdat.mapmd5,{'fromdb':False,'type':"MapMD5",'value':expdat.mapmd5},color='black')
self.bplus.clicked.connect(self.plus)
self.bvalue.returnPressed.connect(self.plus)
self.bminus.clicked.connect(self.minus)
self.bannotations.clicked.connect(self.annotations)
self.cexp=expdat
self.setWindowTitle(self.cexp.studyname)
self.prepstudyinfo()
self.bvalue.setFocus()
def keyPressEvent(self, e):
"""
override the enter event so will not close dialog
"""
e.ignore()
def addentry(self,fromdb,ctype,value,color='black'):
if len(ctype)>0 and len(value)>0:
newentry='%s:%s' % (ctype,value)
for citem in getqtlistitems(self.blist):
if citem==newentry:
hs.Debug(2,'item already in list %s' % newentry)
return
qtlistadd(self.blist,newentry,{'fromdb':False,'type':ctype,'value':value},color="black")
def plus(self):
ctype=str(self.btype.currentText())
cval=str(self.bvalue.text())
self.addentry(fromdb=False,ctype=ctype,value=cval,color='black')
self.bvalue.setText('')
def minus(self):
items=self.blist.selectedItems()
for citem in items:
cdata=qtlistgetdata(citem)
if cdata['fromdb']:
print('delete from db')
self.blist.takeItem(self.blist.row(citem))
def annotations(self):
dbsa = DBStudyAnnotations(self.dataid)
dbsa.exec_()
def prepstudyinfo(self):
"""
add the study info from the mapping file if available
"""
fieldlist=[('SRA_Study_s','sra'),('project_name_s','name'),('experiment_title','name'),('experiment_design_description','name'),('BioProject_s','sra')]
cexp=self.cexp
for (cfield,infofield) in fieldlist:
if cfield in cexp.fields:
uvals=hs.getfieldvals(cexp,cfield,ounique=True)
if len(uvals)==1:
self.addentry(fromdb=False,ctype=infofield,value=uvals[0].lower(),color='black')
class DBAnnotateSave(QtWidgets.QDialog):
def __init__(self,expdat):
super(DBAnnotateSave, self).__init__()
print("DBAnnotateSave")
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/manualdata.py'), self)
self.bplus.clicked.connect(self.plus)
self.bminus.clicked.connect(self.minus)
self.bontoinput.returnPressed.connect(self.plus)
self.bstudyinfo.clicked.connect(self.studyinfo)
self.bisa.toggled.connect(self.radiotoggle)
self.bdiffpres.toggled.connect(self.radiotoggle)
self.bisatype.currentIndexChanged.connect(self.isatypechanged)
self.bhistory.clicked.connect(self.history)
self.cexp=expdat
self.lnumbact.setText(str(len(expdat.selectedseqs)))
completer = QCompleter()
self.bontoinput.setCompleter(completer)
scdb=hs.scdb
self.scdb=scdb
self.dataid=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
model = QStringListModel()
completer.setModel(model)
# completer.setCompletionMode(QCompleter.InlineCompletion)
completer.maxVisibleItems=10
completer.setCaseSensitivity(Qt.CaseInsensitive)
# make the completer selection also erase the text edit
completer.activated.connect(self.cleartext,type=Qt.QueuedConnection)
# in qt5 should work with middle complete as well...
# completer.setFilterMode(Qt.MatchContains)
if not hs.scdb.ontologyfromid:
hs.scdb=hs.supercooldb.loaddbonto(hs.scdb)
self.ontology=hs.scdb.ontology
self.ontologyfromid=hs.scdb.ontologyfromid
nlist=list(self.ontology.keys())
# nlist=sorted(nlist)
nlist=sorted(nlist, key=lambda s: s.lower())
print("sorted ontology")
model.setStringList(nlist)
self.setWindowTitle(self.cexp.studyname)
try:
tt=hs.lastdatamd5
except:
hs.lastdatamd5=''
if self.cexp.datamd5==hs.lastdatamd5:
self.fillfromcuration(hs.lastcurations[-1],onlyall=True)
self.prefillinfo()
self.bontoinput.setFocus()
def history(self):
curtext=[]
for cur in hs.lastcurations:
ct=''
for dat in cur:
ct+=dat[0]+'-'+dat[1]+','
curtext.append(ct)
slistwin = SListWindow(curtext,'select curation from history')
res=slistwin.exec_()
if res:
items=slistwin.lList.selectedItems()
for citem in items:
print(citem)
spos=slistwin.lList.row(citem)
print(spos)
self.fillfromcuration(hs.lastcurations[spos],onlyall=False)
def fillfromcuration(self,curation,onlyall=True,clearit=True):
"""
fill gui list from curation
input:
curation : from hs.lastcurations
onlyall : bool
True to show only curations which have ALL, False to show also HIGH/LOW
clearit : bool
True to remove previous curations from list, False to keep
"""
if clearit:
self.blistall.clear()
for cdat in curation:
if onlyall:
if cdat[0]!='ALL':
continue
self.addtolist(cdat[0],cdat[1])
def radiotoggle(self):
if self.bisa.isChecked():
self.blow.setDisabled(True)
self.bhigh.setDisabled(True)
if self.bdiffpres.isChecked():
self.blow.setEnabled(True)
self.bhigh.setEnabled(True)
def isatypechanged(self):
"""
changed the selection of isatype combobox so need to activate the isa radio button
"""
self.bisa.setChecked(True)
def studyinfo(self):
getstudydata(self.cexp)
def keyPressEvent(self, e):
"""
override the enter event so will not close dialog
"""
# print(e.key())
e.ignore()
def minus(self):
"""
delete selected item from current list
"""
items=self.blistall.selectedItems()
for citem in items:
self.blistall.takeItem(self.blistall.row(citem))
def cleartext(self):
self.bontoinput.setText('')
def plus(self):
conto=str(self.bontoinput.text())
cgroup=self.getontogroup()
self.addtolist(cgroup,conto)
self.cleartext()
def addtolist(self,cgroup,conto):
"""
add an ontology term to the list
input:
cgroup : str
the group (i.e. 'low/high/all')
conto : str
the ontology term to add
"""
if conto=='':
hs.Debug(2,'no string to add to list')
return
print('addtolist %s %s' % (cgroup,conto))
if conto in self.ontology:
conto=self.ontologyfromid[self.ontology[conto]]
else:
hs.Debug(1,'Not in ontology!!!')
# TODO: add are you sure... not in ontology list....
# if item already in list, don't do anything
for citem in qtlistiteritems(self.blistall):
cdata=qtlistgetdata(citem)
if cdata['value']==conto:
hs.Debug(2,'item already in list')
return
if cgroup=='LOW':
ctext="LOW:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'LOW','value':conto},color='red')
if cgroup=='HIGH':
ctext="HIGH:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'HIGH','value':conto},color='blue')
if cgroup=='ALL':
ctext="ALL:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'ALL','value':conto},color='black')
def getontogroup(self):
if self.ball.isChecked():
return('ALL')
if self.blow.isChecked():
return('LOW')
if self.bhigh.isChecked():
return('HIGH')
def prefillinfo(self):
"""
prefill "ALL" data fields based on mapping file
if all samples have same info
"""
hs.Debug(1,'prefill info')
ontologyfromid=self.ontologyfromid
# fl=open('/Users/amnon/Python/git/heatsequer/db/ncbitaxontofromid.pickle','rb')
fl=open(os.path.join(hs.heatsequerdir,'db/ncbitaxontofromid.pickle'),'rb')
ncbitax=pickle.load(fl)
fl.close()
cexp=self.cexp
for cfield in cexp.fields:
uvals=[]
if cfield in cexp.fields:
uvals=hs.getfieldvals(cexp,cfield,ounique=True)
# if we have 1 value
if len(uvals)==1:
cval=uvals[0]
hs.Debug(1,'found 1 value %s' % cval)
if cfield=='HOST_TAXID' or cfield=='host_taxid':
hs.Debug(2,'%s field has 1 value %s' % (cfield,cval))
# if ncbi taxonomy (field used differently)
cval='NCBITaxon:'+cval
if cval in ncbitax:
hs.Debug(2,'found in ncbitax %s' % cval)
cval=ncbitax[cval]
else:
# get the XXX from ENVO:XXX value
uvalspl=cval.split(':',1)
if len(uvalspl)>1:
cval=uvalspl[1]
cval=uvalspl[1]+' :'+uvalspl[0]
if cval in self.ontology:
cval=ontologyfromid[self.ontology[cval]]
hs.Debug(2,'term %s found in ontologyfromid' % cval)
conto=cval
hs.Debug(1,'add prefill %s' % conto)
self.addtolist('ALL',conto)
else:
hs.Debug(3,'term %s NOT found in ontologyfromid' % uvals[0])
else:
hs.Debug(1,'found %d values' % len(uvals))
def getqtlistitems(qtlist):
"""
get a list of strings of the qtlist
input:
qtlist : QTListWidget
output:
item : list of str
"""
items = []
for index in range(qtlist.count()):
items.append(str(qtlist.item(index).text()))
return items
def qtlistadd(qtlist,text,data,color="black"):
"""
Add an entry (text) to qtlist and associaxte metadata data
input:
qtlist : QTListWidget
text : str
string to add to list
data : arbitrary python var
the data to associate with the item (get it by qtlistgetdata)
color : (R,G,B)
the color of the text in the list
"""
item = QtWidgets.QListWidgetItem()
item.setText(text)
ccol=QtGui.QColor()
ccol.setNamedColor(color)
item.setForeground(ccol)
item.setData(Qt.UserRole,data)
qtlist.addItem(item)
def qtlistgetdata(item):
"""
Get the metadata associated with item as position pos
input:
qtlist : QtListWidget
index : QtListWidgetItem
the item to get the info about
output:
data : arbitrary
the data associated with the item (using qtlistadd)
"""
# item=qtlist.item(index)
if sys.version_info[0] < 3:
# QVariant version 1 API (python2 default)
data=item.data(Qt.UserRole).toPyObject()
else:
# QVariant version 2 API (python3 default)
data=item.data(Qt.UserRole)
return data
def qtlistiteritems(qtlist):
"""
iterate all items in a list
input:
qtlist : QtListWidget
"""
for i in range(qtlist.count()):
yield qtlist.item(i)
def getstudydata(cexp):
"""
open the study info window and show/get new references for the study data
input:
cexp : Experiment
the experiment for which to show the data (uses the datamd5 and mapmd5)
output:
hasdata : Bool
True if the study has data, False if not
"""
dbsi = DBStudyInfo(cexp)
res=dbsi.exec_()
if res==QtWidgets.QDialog.Accepted:
newstudydata=[]
allstudydata=[]
for citem in qtlistiteritems(dbsi.blist):
cdata=qtlistgetdata(citem)
allstudydata.append( (cdata['type'],cdata['value']) )
if cdata['fromdb']==False:
newstudydata.append( (cdata['type'],cdata['value']) )
if len(newstudydata)==0:
hs.Debug(6,'No new items. not saving anything')
return True
# look if study already in table
cid=hs.supercooldb.finddataid(dbsi.scdb,datamd5=cexp.datamd5,mapmd5=cexp.mapmd5)
if cid is None:
hs.Debug(6,'no studyid found for datamd5 %s, mapmd5 %s' % (cexp.datamd5,cexp.mapmd5))
# cdata=hs.supercooldb.addexpdata(scdb,( ('DataMD5',cexp.datamd5), ('MapMD5',cexp.mapmd5) ) )
hs.Debug(3,'Adding to new experiment')
dataid=hs.supercooldb.addexpdata(dbsi.scdb,newstudydata,studyid=cid)
hs.Debug(6,'Study data saved to id %d' % dataid)
if len(allstudydata)>2:
return True
return False
def showannotationdata(annotationdetails):
"""
show the list of annotation details and the sequences associated with it
intput:
annotationdetails : dict
dict of various fields of the annotation (includeing annotationid)
from scdb.getannotationstrings()
cexp : experiment
the experiment (for rhe scdb pointer)
"""
info=[]
if annotationdetails is None:
return
for k,v in annotationdetails.items():
if type(v)==list:
for cv in v:
info.append('%s:%s' % (k,cv))
else:
info.append('%s:%s' % (k,v))
# get the annotation sequences:
if 'annotationid' in annotationdetails:
seqs=hs.supercooldb.getannotationseqs(hs.scdb,annotationdetails['annotationid'])
info.append('sequences: %d' % len(seqs))
# get the experiment details:
if 'expid' in annotationdetails:
expinfo=hs.supercooldb.getexperimentinfo(hs.scdb,annotationdetails['expid'])
for cinfo in expinfo:
info.append('experiment %s:%s' % (cinfo[0],cinfo[1]))
slistwin = SListWindow(info,'Annotation details')
slistwin.exec_()
| bsd-3-clause |
headupinclouds/gatherer | src/lib/graphics/Logger.h | 416 | #ifndef __gatherer__Logger__
#define __gatherer__Logger__
#include <spdlog/spdlog.h>
#include "graphics/gatherer_graphics.h"
_GATHERER_GRAPHICS_BEGIN
class Logger
{
public:
using Pointer = std::shared_ptr<spdlog::logger>;
static Pointer create(const char* name);
static Pointer get(const char* name);
static void drop(const char* name);
};
_GATHERER_GRAPHICS_END
#endif // __gatherer__Logger__
| bsd-3-clause |
mpontus/jest | website/core/Marked.js | 23888 | /**
* marked - a markdown parser
* Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*
* @providesModule Marked
* @jsx React.DOM
*/
/* eslint-disable sort-keys */
const React = require('React');
const Prism = require('Prism');
const Header = require('Header');
/**
* Block-Level Grammar
*/
const block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){3,} *\n*/,
blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/,
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')(/bull/g, block.bullet)();
block.list = replace(block.list)(/bull/g, block.bullet)('hr', /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/)();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|@)\\b';
block.html = replace(block.html)('comment', /<!--[\s\S]*?-->/)('closed', /<(tag)[\s\S]+?<\/\1>/)('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)();
block.paragraph = replace(block.paragraph)('hr', block.hr)('heading', block.heading)('lheading', block.lheading)('blockquote', block.blockquote)('tag', '<' + block._tag)('def', block.def)();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
});
block.gfm.paragraph = replace(block.paragraph)('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|')();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
const lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(_src, top) {
let src = _src.replace(/^ +$/gm, '');
let next;
let loose;
let cap;
let bull;
let b;
let item;
let space;
let i;
let l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space',
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap,
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3],
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2],
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n'),
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1],
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr',
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start',
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top);
this.tokens.push({
type: 'blockquote_end',
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1,
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) { // eslint-disable-line
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item[item.length - 1] === '\n';
if (!loose) {loose = next;}
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start',
});
// Recurse.
this.token(item, false);
this.tokens.push({
type: 'list_item_end',
});
}
this.tokens.push({
type: 'list_end',
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: cap[1] === 'pre' || cap[1] === 'script',
text: cap[0],
});
continue;
}
// def
if (top && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3],
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n'),
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1][cap[1].length - 1] === '\n'
? cap[1].slice(0, -1)
: cap[1],
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0],
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
const inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/,
};
inline._inside = /(?:\[[^\]]*\]|[^\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([^\s]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)('inside', inline._inside)('href', inline._href)();
inline.reflink = replace(inline.reflink)('inside', inline._inside)();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)(']|', '~]|')('|', '|https?://|')(),
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')(),
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
const inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
const out = [];
let link;
let text;
let href;
let cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out.push(cap[1]);
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1][6] === ':'
? cap[1].substring(7)
: cap[1];
href = 'mailto:' + text;
} else {
text = cap[1];
href = text;
}
out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text));
continue;
}
// url (gfm)
if (cap = this.rules.url.exec(src)) {
src = src.substring(cap[0].length);
text = cap[1];
href = text;
out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text));
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
src = src.substring(cap[0].length);
// TODO(alpert): Don't escape if sanitize is false
out.push(cap[0]);
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
out.push(this.outputLink(cap, {
href: cap[2],
title: cap[3],
}));
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out.push.apply(out, this.output(cap[0][0]));
src = cap[0].substring(1) + src;
continue;
}
out.push(this.outputLink(cap, link));
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.strong(null, this.output(cap[2] || cap[1])));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.em(null, this.output(cap[2] || cap[1])));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.code(null, cap[2]));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.br(null, null));
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.del(null, this.output(cap[1])));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out.push(this.smartypants(cap[0]));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Sanitize a URL for a link or image
*/
InlineLexer.prototype.sanitizeUrl = function(url) {
if (this.options.sanitize) {
try {
const prot = decodeURIComponent(url)
.replace(/[^A-Za-z0-9:]/g, '')
.toLowerCase();
if (prot.indexOf('javascript:') === 0) { // eslint-disable-line
return '#';
}
} catch (e) {
return '#';
}
}
return url;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
if (cap[0][0] !== '!') {
const shouldOpenInNewWindow =
link.href.charAt(0) !== '/'
&& link.href.charAt(0) !== '#';
return React.DOM.a({
href: this.sanitizeUrl(link.href),
title: link.title,
target: shouldOpenInNewWindow ? '_blank' : '',
}, this.output(cap[1]));
} else {
return React.DOM.img({
src: this.sanitizeUrl(link.href),
alt: cap[1],
title: link.title,
}, null);
}
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) {return text;}
return text
.replace(/--/g, '\u2014')
.replace(/'([^']*)'/g, '\u2018$1\u2019')
.replace(/"([^"]*)"/g, '\u201C$1\u201D')
.replace(/\.{3}/g, '\u2026');
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options) {
const parser = new Parser(options);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options);
this.tokens = src.reverse();
const out = [];
while (this.next()) {
out.push(this.tok());
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
let body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() { // eslint-disable-line
switch (this.token.type) {
case 'space': {
return [];
}
case 'hr': {
return React.DOM.hr(null, null);
}
case 'heading': {
return (
<Header level={this.token.depth} toSlug={this.token.text}>
{this.inline.output(this.token.text)}
</Header>
);
}
case 'code': {
return <Prism>{this.token.text}</Prism>;
}
case 'table': {
const table = [];
const body = [];
let row = [];
let heading;
let i;
let cells;
let j;
// header
for (i = 0; i < this.token.header.length; i++) {
heading = this.inline.output(this.token.header[i]);
row.push(React.DOM.th(
this.token.align[i]
? {style: {textAlign: this.token.align[i]}}
: null,
heading
));
}
table.push(React.DOM.thead(null, React.DOM.tr(null, row)));
// body
for (i = 0; i < this.token.cells.length; i++) {
row = [];
cells = this.token.cells[i];
for (j = 0; j < cells.length; j++) {
row.push(React.DOM.td(
this.token.align[j]
? {style: {textAlign: this.token.align[j]}}
: null,
this.inline.output(cells[j])
));
}
body.push(React.DOM.tr(null, row));
}
table.push(React.DOM.thead(null, body));
return React.DOM.table(null, table);
}
case 'blockquote_start': {
const body = [];
while (this.next().type !== 'blockquote_end') {
body.push(this.tok());
}
return React.DOM.blockquote(null, body);
}
case 'list_start': {
const type = this.token.ordered ? 'ol' : 'ul';
const body = [];
while (this.next().type !== 'list_end') {
body.push(this.tok());
}
return React.DOM[type](null, body);
}
case 'list_item_start': {
const body = [];
while (this.next().type !== 'list_item_end') {
body.push(this.token.type === 'text'
? this.parseText()
: this.tok());
}
return React.DOM.li(null, body);
}
case 'loose_item_start': {
const body = [];
while (this.next().type !== 'list_item_end') {
body.push(this.tok());
}
return React.DOM.li(null, body);
}
case 'html': {
return React.DOM.div({
dangerouslySetInnerHTML: {
__html: this.token.text,
},
});
}
case 'paragraph': {
return this.options.paragraphFn
? this.options.paragraphFn.call(null, this.inline.output(this.token.text))
: React.DOM.p(null, this.inline.output(this.token.text));
}
case 'text': {
return this.options.paragraphFn
? this.options.paragraphFn.call(null, this.parseText())
: React.DOM.p(null, this.parseText());
}
}
};
/**
* Helpers
*/
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) {return new RegExp(regex, opt);}
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
let i = 1;
let target;
let key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
if (opt) {opt = merge({}, marked.defaults, opt);}
const highlight = opt.highlight;
let tokens;
let pending;
let i = 0;
try {
tokens = Lexer.lex(src, opt);
} catch (e) {
return callback(e);
}
pending = tokens.length;
const done = function(hi) {
let out, err;
if (hi !== true) {
delete opt.highlight;
}
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done(true);
}
if (!pending) {return done();}
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, (err, code) => {
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
return undefined;
});
})(tokens[i]);
}
return undefined;
}
try {
if (opt) {opt = merge({}, marked.defaults, opt);}
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return [React.DOM.p(null, 'An error occurred:'),
React.DOM.pre(null, e.message)];
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
paragraphFn: null,
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
const Marked = React.createClass({
render() {
return <div>{marked(this.props.children, this.props)}</div>;
},
});
module.exports = Marked;
| bsd-3-clause |
firmlyjin/brython | www/tests/editor.py | 2743 | import sys
import time
import traceback
import dis
from browser import document as doc, window, alert
from javascript import JSObject
# set height of container to 66% of screen
_height = doc.documentElement.clientHeight
_s = doc['container']
_s.style.height = '%spx' % int(_height * 0.66)
has_ace = True
try:
editor = window.ace.edit("editor")
session = editor.getSession()
session.setMode("ace/mode/python")
editor.setOptions({
'enableLiveAutocompletion': True,
'enableSnippets': True,
'highlightActiveLine': False,
'highlightSelectedWord': True
})
except:
from browser import html
editor = html.TEXTAREA(rows=20, cols=70)
doc["editor"] <= editor
def get_value(): return editor.value
def set_value(x):editor.value = x
editor.getValue = get_value
editor.setValue = set_value
has_ace = False
if sys.has_local_storage:
from browser.local_storage import storage
else:
storage = None
if 'set_debug' in doc:
__BRYTHON__.debug = int(doc['set_debug'].checked)
def reset_src():
if storage is not None and "py_src" in storage:
editor.setValue(storage["py_src"])
else:
editor.setValue('for i in range(10):\n\tprint(i)')
editor.scrollToRow(0)
editor.gotoLine(0)
def reset_src_area():
if storage and "py_src" in storage:
editor.value = storage["py_src"]
else:
editor.value = 'for i in range(10):\n\tprint(i)'
class cOutput:
def write(self, data):
doc["console"].value += str(data)
def flush(self):
pass
sys.stdout = cOutput()
sys.stderr = cOutput()
def to_str(xx):
return str(xx)
info = sys.implementation.version
doc['version'].text = '%s.%s.%s' % (info.major, info.minor, info.micro)
output = ''
def show_console(ev):
doc["console"].value = output
doc["console"].cols = 60
# load a Python script
def load_script(evt):
_name = evt.target.value + '?foo=%s' % time.time()
editor.setValue(open(_name).read())
# run a script, in global namespace if in_globals is True
def run(in_globals=False):
global output
doc["console"].value = ''
src = editor.getValue()
if storage is not None:
storage["py_src"] = src
t0 = time.perf_counter()
try:
if(in_globals):
exec(src)
else:
ns = {}
exec(src, ns)
state = 1
except Exception as exc:
traceback.print_exc(file=sys.stderr)
state = 0
output = doc["console"].value
print('<completed in %6.2f ms>' % ((time.perf_counter() - t0) * 1000.0))
return state
def show_js(ev):
src = editor.getValue()
doc["console"].value = dis.dis(src)
if has_ace:
reset_src()
else:
reset_src_area()
| bsd-3-clause |
Tankske/InfoVisNBA | about.html | 8776 | <html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body class="aboutPage">
<h1><a href="./index.html">The visualisation</a></h1>
<p> The visualization consists of three parts: </p>
<ul>
<li>The bubble view: a compact view on the play-offs per season</li>
<li>The statistics (zoom) view: a more detailed view on a statistic of a selected team</li>
<li>The team view: a detailed view on how good or bad a team scores on a specific field position</li>
</ul>
<p>There is a context section in each view where you get some information about the selected team or the team where the pointer is on.
There is also a timeline in each view so you can select different seasons.</p>
<h2>The bubble view</h2>
<p>This view represents the playoffs of the current season. Only the 16 best teams compete in the playoffs to be the NBA champion. Every confrontation is between two teams of the same Conference, except for the final.
Each circle represents a team, and the size of the circle represents the SRS-score of the team for the selected season.
The stroke of a circle is gold, silver or bronze to show the teams that ended first, respectively second and third in their own Conference. All the other teams their stroke is red if the team is part of the Western Conference, or blue if the team is part of the Eastern Conference.
The two up most teams are the winners of the playoffs in their own conference and compete in the final.
The lines between teams represent that those teams have encountered each other in the playoffs. A connection is always made between a team that stands higher and a team that stands lower. The highest team of the two teams has won the confrontation.
The higher a team is, the further it has come. Their are 6 different levels. From top to bottom: Winner of the final (place 1), loser of the final (place 2), losers of the semi-finals (place 3), losers of the quarter-finals (place 4), losers of the 1/8-finales (place 5), teams that did not make it to the playoffs (place 6).
If you go over a team, only the confrontations for that team are shown. If it is green, the confrontation was won by that team (and the team will be higher than the opponent team). If it is red, the confrontation was lost (and the team will be lower than the opponent team).</p>
<h2>The statics (zoom) view</h2>
<p>This view represents a more detailed view of the selected team.
Their is a small bubble view to keep the overview of where the team is finished in the selected season.
The circle with black stroke and with the team logo represents the selected team, and the size of the circle represents the SRS-score of the team for the selected season. The three circles with the grey stroke represent the maximum SRS score of all teams the current season, the average SRS score of all teams of the current season (always zero) and the minimum SRS score of all the teams of the current season.
The arrows represent a selected statistic for transferred and stayed players.
The green arrow on the left is the arrow for incoming transfers, meaning it represents a value for players that played for the selected team in the selected season, but did not play for the team in the previous season. The value represented by the arrow is the value of the selected season for the selected statistic.
The red arrow on the left is the arrow for outgoing transfers, meaning it represents a value for players that played for the selected team in the previous season, but did not play for the team in the current season. The value represented by the arrow is the value of the previous season for the selected statistic.
the arrow on the right represents a value for the stayed players (player for the team both current and previous season). The value represented by the arrow is the difference between the value of the current season and the value of the previous season for the selected statistic. If the overall score for the statistic is increased for the stayed players, the arrow is green and pointing upwards. If the overall score for the statistic is decreases for the stayed players, the arrow is red and pointing downwards.
For the incoming, outgoing and positive stayed arrow the shirts of the two best players are drawn and for the negative stayed arrow the shirts of the two worst players . The bigger (smaller) the value, the greater (smaller) the shirt.
Their are five statistics you can select. This will change the size and value of the arrows as well as which shirts are drawn. The meaning of the different statistics is explained in the general information
Beneath the arrow/circle section there is a section with team statistics. Here you can see on different line and area charts how the selected team has performed over the years. The current season is selected and shown.
The different team statistics are the total PER (see general information) of the whole team, the league rank (the position after the regular competition), the playoff rank (the finished position in the playoffs (see bubble view explanation)), the average age of the team, the audience (the average amount of spectators), the SRS-value (see general information) of the team, the offensive rating and the defensive rating of the team (see general information).</p>
<h2>The team view</h2>
<p>This view gives a more detailed view on how good or bad a team scores on a specific field position.
Their are 5 different positions. Each player is represented by his shirt on his position.
Their are five statistics you can select just as in the statistic view.
Beneath the team section there is a section with team statistics (the same as in the statistic zoom view.</p>
<h1>Data</h1>
<p>
<a href="http://www.basketball-reference.com/">Basketball Reference</a>
</p>
<h1>Background Information</h1>
<p> The NBA season is divided in two parts. First the regular competition is played, and afterwards the playoffs are played.
There are 30 teams in the NBA league, divided in two groups. The Eastern Conference and the Western Conference. In each Conference, the teams are divided into three divisions based on their geographical position.
For each Conference, the 3 division winners along with the 5 best teams go to the playoffs, which is a best-of-seven elimination system.
For more information, check <a href="https://en.wikipedia.org/wiki/National_Basketball_Association">Wikipedia</a>.</p>
<h1>Terminology</h1>
<ul>
<li>SRS: Simple Rating/Ranking System. The SRS (value) is the result of a basic ranking algorithm that calculates a score for a team. Every team's rating is their average point margin, adjusted up or down depending on the strength of their opponents. An average team would have a rating of zero. For a complete explanation, check <a href="http://www.pro-football-reference.com/blog/?p=37">SRS</a></li>
<li>PER: Player Efficiency Rating. A measure of per-minute production (attempts to take add up the good things, subtract the bad things, and account for team pace) standardized such that the league average is 15.</li>
<li>eFG%: Effective Field Goal Percentage. The number of field goals scored relative to the number of attempts. It is the effective field goal percentage because it adjusts for the fact that a 3-point field goal is worth one more point than a 2-point field goal.</li>
<li>ORtg: Offensive Rating. An estimate of points produced (players) or scored (teams) per 100 possessions. (a possession is the time a team gains offensive possession of the ball until it scores, loses the ball, or commits a violation or fault)</li>
<li>DRtg: Defensive Rating. An estimate of points allowed per 100 possessions. (a possession is the time a team gains offensive possession of the ball until it scores, loses the ball, or commits a violation or fault)</li>
</ul>
<h2>Positions</h2>
<ul>
<li>SF: Small Forward </li>
<li>SG: Shooting Guard</li>
<li>PF: Power Forward</li>
<li>PG: Point Guard</li>
<li>C: Center</li>
</ul>
<p>For more information about the different positions, please check <a href="https://en.wikipedia.org/wiki/Basketball_positions">Wikipedia</a></p>
</body>
</html>
| bsd-3-clause |
CUBRID/cubrid-testcases | sql/_14_mysql_compatibility_2/_15_host_variable/_11_unary_minus/cases/number.sql | 414 | --- number
create table t1 (d1 double, i1 int, n1 numeric(10,3));
insert into t1 values (2.00123e1,3,100.21);
select -(d1) from t1;
select -(n1) from t1;
select -(i1) from t1;
drop table t1;
select -(4);
select -(4.4);
select -(4.001e1);
prepare st from 'select -(?)';
execute st using 4;
prepare st from 'select -(?)';
execute st using 4.12;
prepare st from 'select -(?)';
execute st using 4.001123e1;
| bsd-3-clause |
seem-sky/treefrog-framework | src/thttpsocket.h | 844 | #ifndef THTTPSOCKET_H
#define THTTPSOCKET_H
#include <QTcpSocket>
#include <QByteArray>
#include <QDateTime>
#include <THttpRequest>
#include <TTemporaryFile>
#include <TGlobal>
#ifdef Q_OS_UNIX
# include "tfcore_unix.h"
#endif
class T_CORE_EXPORT THttpSocket : public QTcpSocket
{
Q_OBJECT
public:
THttpSocket(QObject *parent = 0);
~THttpSocket();
QList<THttpRequest> read();
bool canReadRequest() const;
qint64 write(const THttpHeader *header, QIODevice *body);
int idleTime() const;
protected:
qint64 writeRawData(const char *data, qint64 size);
protected slots:
void readRequest();
signals:
void newRequest();
private:
Q_DISABLE_COPY(THttpSocket)
qint64 lengthToRead;
QByteArray readBuffer;
TTemporaryFile fileBuffer;
QDateTime lastProcessed;
};
#endif // THTTPSOCKET_H
| bsd-3-clause |
xZ1mEFx/y2shop | backend/models/forms/LoginForm.php | 3073 | <?php
namespace backend\models\forms;
use backend\models\User;
use Yii;
use yii\base\Model;
use yii\behaviors\TimestampBehavior;
/**
* Login form
*/
class LoginForm extends Model
{
public $email;
public $password;
public $rememberMe = TRUE;
private $_user;
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => time(),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// email and password are both required
[['email', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'email' => Yii::t('admin-side', 'Email'),
'password' => Yii::t('admin-side', 'Password'),
'rememberMe' => Yii::t('admin-side', 'Remember Me'),
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, Yii::t('admin-side', 'Incorrect login or password'));
}
}
}
/**
* Finds user by [[email]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === NULL) {
$this->_user = User::findByEmail($this->email);
}
return $this->_user;
}
/**
* Logs in a user using the provided email and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
if (Yii::$app->user->login($this->getUser(), $this->rememberMe ? (3600 * 24 * 30) : 0)) {
if (
Yii::$app->user->cannot([
User::ROLE_ROOT,
User::ROLE_ADMIN,
User::ROLE_MANAGER,
User::ROLE_SELLER,
])
) {
Yii::$app->user->logout();
Yii::$app->session->addFlash('error', Yii::t('admin-side', 'You have insufficient privileges!'));
return FALSE;
}
return TRUE;
}
}
return FALSE;
}
}
| bsd-3-clause |
troikaitsulutions/templeadvisor | protected/controllers/BepujapurposeController.php | 1386 | <?php
/**
* Backend Object Controller.
*
* @package backend.controllers
*
*/
class BepujapurposeController extends BeController
{
public function __construct($id,$module=null)
{
parent::__construct($id,$module);
$this->menu=array(
array('label'=>t('Add Puja Purpose'), 'url'=>array('create'),'linkOptions'=>array('class'=>'btn btn-mini')),
);
}
/**
* The function that do Create new Object
*
*/
public function actionCreate()
{
$this->render('purpose_create');
}
/**
* The function that do Update Object
*
*/
public function actionUpdate()
{
$id=isset($_GET['id']) ? (int) ($_GET['id']) : 0 ;
$this->render('purpose_update');
}
/**
* The function that do View User
*
*/
public function actionView()
{
$id=isset($_GET['id']) ? (int) ($_GET['id']) : 0 ;
$this->render('purpose_view');
}
/**
* The function that do Manage Object
*
*/
public function actionAdmin()
{
$this->render('purpose_admin');
}
public function actionDelete($id)
{
GxcHelpers::deleteModel('Pujapurpose', $id);
}
} | bsd-3-clause |
ssmith353/alloy-ui | src/aui-image-viewer/assets/aui-image-viewer-core.css | 2497 | .yui3-widget-mask.image-viewer-mask {
opacity: 0.9;
}
.image-viewer-base, .image-viewer-base-control.carousel-control {
position: fixed;
z-index: 3000;
}
.image-viewer-close {
color: #fff;
font-size: 30px;
opacity: 0.5;
position: fixed;
right: 20px;
top: 10px;
z-index: 3000;
}
.image-viewer-close:hover {
color: #fff;
opacity: 1;
}
.image-viewer-hidden, .image-viewer-loading .yui3-widget-ft {
display: none;
}
.image-viewer .yui3-widget-ft {
padding: 5px 0;
}
.image-viewer-caption, .image-viewer-info {
line-height: 1.3;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.image-viewer-caption {
color: #ccc;
}
.image-viewer-info {
color: #777;
display: inline;
font-size: 15px;
}
.ie6 .image-viewer-close {
position: absolute;
}
.image-viewer .image-viewer-content, .image-viewer .image-gallery-content {
padding: 5px 0;
text-align: center;
}
.image-viewer .image-viewer-base-image-container {
left: 0;
padding: 0 5px;
position: relative;
top: 0;
vertical-align: top;
}
.image-viewer .image-viewer-footer-buttons {
padding-left: 15px;
}
.image-viewer .image-viewer-footer-buttons .glyphicon {
color: #777;
cursor: pointer;
opacity: 1;
padding: 0 2px;
}
.image-viewer .image-viewer-footer-buttons .glyphicon:hover {
color: #fff;
}
.image-viewer .image-viewer-thumbnails {
height: 70px;
}
.image-viewer .image-viewer-thumbnails .image-viewer-multiple .image-viewer-base-image-container,
.image-viewer .image-viewer-thumbnails .image-viewer-multiple .image-viewer-base-image {
height: 56px;
padding: 0;
width: 56px;
}
.image-viewer .image-viewer-thumbnails .image-viewer-multiple {
padding: 10px 0;
}
.image-viewer .image-viewer-thumbnails .image-viewer-multiple .image-viewer-base-loading-icon {
line-height: 50px;
}
.image-viewer .image-viewer-thumbnails .image-viewer-multiple .image-viewer-base-image-container:hover {
border: 3px solid #777;
}
.image-viewer .image-viewer-thumbnails .image-viewer-multiple .image-viewer-base-image-container.image-viewer-base-current-image {
border: 3px solid #ccc;
}
.widget-swipe.image-viewer .yui3-widget-bd {
white-space: nowrap;
}
.widget-swipe.image-viewer .image-viewer-image-container,
.widget-swipe.image-viewer .image-viewer-image-container.image-viewer-current-image {
display: inline-block;
width: 100%;
}
| bsd-3-clause |
leo14/EPI_TESIS | EPI/protected/views/actividades/_view.php | 572 | <?php
/* @var $this ActividadesController */
/* @var $data Actividades */
?>
<div class="view" style="width: inherit;border: 2px solid #949494;background-color: white;padding: 10px;">
<h4><?php echo CHtml::encode($data->act_nombre); ?></h4>
Se realizara el <?php echo CHtml::encode($data->act_fecha); ?> entre las <?php echo CHtml::encode($data->act_horaInicio); ?> y las <?php echo CHtml::encode($data->act_horaFin); ?>.
<br>
Lugar: <?php echo CHtml::encode($data->act_lugar); ?>.
<br>
Descripción: <?php echo CHtml::encode($data->act_descripcion); ?>.
</div> | bsd-3-clause |
hradec/cortex | src/IECoreMaya/SceneShapeInterface.cpp | 49682 | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2015, Image Engine Design 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER 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.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "IECoreMaya/SceneShapeInterface.h"
#include "IECoreMaya/SceneShapeInterfaceComponentBoundIterator.h"
#include "boost/python.hpp"
#include "boost/tokenizer.hpp"
#include "OpenEXR/ImathMatrixAlgo.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "IECoreGL/Renderer.h"
#include "IECoreGL/Scene.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/NameStateComponent.h"
#include "IECoreGL/State.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/Renderable.h"
#include "IECoreGL/Group.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaMeshConverter.h"
#include "IECoreMaya/ToMayaCurveConverter.h"
#include "IECoreMaya/MayaTypeIds.h"
#include "IECoreMaya/PostLoadCallback.h"
#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/ScopedGILRelease.h"
#include "IECore/VectorOps.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CompoundParameter.h"
#include "IECore/AngleConversion.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/TransformBlock.h"
#include "IECore/AttributeBlock.h"
#include "IECore/SampledSceneInterface.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/TransformOp.h"
#include "IECore/CoordinateSystem.h"
#include "IECore/Transform.h"
#include "IECore/MatrixAlgo.h"
#include "IECore/LinkedScene.h"
#include "maya/MArrayDataBuilder.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnEnumAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnGenericAttribute.h"
#include "maya/MFnUnitAttribute.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnSingleIndexedComponent.h"
#include "maya/MSelectionList.h"
#include "maya/MAttributeSpec.h"
#include "maya/MAttributeIndex.h"
#include "maya/MAttributeSpecArray.h"
#include "maya/MDagPath.h"
#include "maya/MFnStringData.h"
#include "maya/MFnMeshData.h"
#include "maya/MFnNurbsCurveData.h"
#include "maya/MFnGeometryData.h"
#include "maya/MPlugArray.h"
#include "maya/MFileIO.h"
#if MAYA_API_VERSION >= 201600
#include "maya/MEvaluationNode.h"
#endif
using namespace Imath;
using namespace IECore;
using namespace IECoreMaya;
MTypeId SceneShapeInterface::id = SceneShapeInterfaceId;
MObject SceneShapeInterface::aObjectOnly;
MObject SceneShapeInterface::aDrawGeometry;
MObject SceneShapeInterface::aDrawRootBound;
MObject SceneShapeInterface::aDrawChildBounds;
MObject SceneShapeInterface::aDrawTagsFilter;
MObject SceneShapeInterface::aQuerySpace;
MObject SceneShapeInterface::aTime;
MObject SceneShapeInterface::aOutTime;
MObject SceneShapeInterface::aSceneQueries;
MObject SceneShapeInterface::aAttributeQueries;
MObject SceneShapeInterface::aConvertParamQueries;
MObject SceneShapeInterface::aOutputObjects;
MObject SceneShapeInterface::aObjectDependency;
MObject SceneShapeInterface::aAttributes;
MObject SceneShapeInterface::aAttributeValues;
MObject SceneShapeInterface::aTransform;
MObject SceneShapeInterface::aTranslate;
MObject SceneShapeInterface::aTranslateX;
MObject SceneShapeInterface::aTranslateY;
MObject SceneShapeInterface::aTranslateZ;
MObject SceneShapeInterface::aRotate;
MObject SceneShapeInterface::aRotateX;
MObject SceneShapeInterface::aRotateY;
MObject SceneShapeInterface::aRotateZ;
MObject SceneShapeInterface::aScale;
MObject SceneShapeInterface::aScaleX;
MObject SceneShapeInterface::aScaleY;
MObject SceneShapeInterface::aScaleZ;
MObject SceneShapeInterface::aBound;
MObject SceneShapeInterface::aBoundMin;
MObject SceneShapeInterface::aBoundMinX;
MObject SceneShapeInterface::aBoundMinY;
MObject SceneShapeInterface::aBoundMinZ;
MObject SceneShapeInterface::aBoundMax;
MObject SceneShapeInterface::aBoundMaxX;
MObject SceneShapeInterface::aBoundMaxY;
MObject SceneShapeInterface::aBoundMaxZ;
MObject SceneShapeInterface::aBoundCenter;
MObject SceneShapeInterface::aBoundCenterX;
MObject SceneShapeInterface::aBoundCenterY;
MObject SceneShapeInterface::aBoundCenterZ;
// This post load callback is used to dirty the aOutputObjects elements
// following loading - see further comments in initialize.
class SceneShapeInterface::PostLoadCallback : public IECoreMaya::PostLoadCallback
{
public :
PostLoadCallback( SceneShapeInterface *node ) : m_node( node )
{
}
protected :
SceneShapeInterface *m_node;
virtual void postLoad()
{
MFnDependencyNode fnDN( m_node->thisMObject() );
MPlug plug = fnDN.findPlug( aObjectDependency );
plug.setValue( 1 );
m_node->m_postLoadCallback = 0; // remove this callback
}
};
SceneShapeInterface::SceneShapeInterface()
: m_previewSceneDirty( true )
{
// We only create the post load callback when Maya is reading a scene,
// so that it does not effect nodes as they are created by users.
m_postLoadCallback = ( MFileIO::isReadingFile() ) ? new PostLoadCallback( this ) : NULL;
}
SceneShapeInterface::~SceneShapeInterface()
{
}
void *SceneShapeInterface::creator()
{
return new SceneShapeInterface;
}
void SceneShapeInterface::postConstructor()
{
setExistWithoutInConnections(true);
setExistWithoutOutConnections(true);
}
MStatus SceneShapeInterface::initialize()
{
MFnNumericAttribute nAttr;
MFnTypedAttribute tAttr;
MFnCompoundAttribute cAttr;
MFnGenericAttribute gAttr;
MFnUnitAttribute uAttr;
MFnEnumAttribute eAttr;
MStatus s;
aObjectOnly = nAttr.create( "objectOnly", "obj", MFnNumericData::kBoolean, 0 );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
addAttribute( aObjectOnly );
aDrawGeometry = nAttr.create( "drawGeometry", "drg", MFnNumericData::kBoolean, 0, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawGeometry );
aDrawRootBound = nAttr.create( "drawRootBound", "drbd", MFnNumericData::kBoolean, 1, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawRootBound );
aDrawChildBounds = nAttr.create( "drawChildBounds", "dchd", MFnNumericData::kBoolean, 0, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawChildBounds );
aDrawTagsFilter = tAttr.create( "drawTagsFilter", "dtf", MFnData::kString, MFnStringData().create( "" ), &s );
assert( s );
s = addAttribute( aDrawTagsFilter );
assert( s );
aQuerySpace = eAttr.create( "querySpace", "qsp", 0);
eAttr.addField( "World", World );
eAttr.addField( "Local", Local );
s = addAttribute( aQuerySpace );
aTime = uAttr.create( "time", "tim", MFnUnitAttribute::kTime, 0.0, &s );
uAttr.setConnectable( true );
uAttr.setHidden( false );
uAttr.setReadable( true );
uAttr.setWritable( true );
uAttr.setStorable( true );
s = addAttribute( aTime );
aOutTime = uAttr.create( "outTime", "otm", MFnUnitAttribute::kTime, 0.0, &s );
uAttr.setReadable( true );
uAttr.setWritable( false );
uAttr.setStorable( false );
s = addAttribute( aOutTime );
// Queries
aSceneQueries = tAttr.create( "queryPaths", "qpa", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aSceneQueries );
aAttributeQueries = tAttr.create( "queryAttributes", "qat", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aAttributeQueries );
aConvertParamQueries = tAttr.create( "queryConvertParameters", "qcp", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aConvertParamQueries );
// Output objects
aOutputObjects = gAttr.create( "outObjects", "oob", &s );
gAttr.addDataAccept( MFnMeshData::kMesh );
gAttr.addDataAccept( MFnNurbsCurveData::kNurbsCurve );
gAttr.addNumericDataAccept( MFnNumericData::k3Double );
gAttr.setReadable( true );
gAttr.setWritable( false );
gAttr.setArray( true );
gAttr.setIndexMatters( true );
gAttr.setUsesArrayDataBuilder( true );
gAttr.setStorable( false );
s = addAttribute( aOutputObjects );
// A Maya bug causes mesh attributes to compute on scene open, even when nothing should be
// pulling on them. While dynamic attributes can work around this issue for single meshes,
// arrays of meshes suffer from the erroneous compute as either static or dynamic attributes.
//
// We work around the problem by adding a PostLoadCallback if the node was created while the
// scene is being read from disk. This callback is used to short circuit the compute which
// was triggered on scene open. Since the compute may have actually been necessary, we use
// this dummy dependency attribute to dirty the output object attributes immediately following
// load. At this point the callback deletes itself, and the newly dirtied output objects will
// re-compute if something was actually pulling on them.
aObjectDependency = nAttr.create( "objectDependency", "objDep", MFnNumericData::kInt, 0 );
nAttr.setStorable( false );
nAttr.setHidden( true );
s = addAttribute( aObjectDependency );
// Transform
aTranslateX = nAttr.create( "outTranslateX", "otx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslateY = nAttr.create( "outTranslateY", "oty", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslateZ = nAttr.create( "outTranslateZ", "otz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslate = nAttr.create( "outTranslate", "obt", aTranslateX, aTranslateY, aTranslateZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aRotateX = uAttr.create( "outRotateX", "orx", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotateY = uAttr.create( "outRotateY", "ory", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotateZ = uAttr.create( "outRotateZ", "orz", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotate = nAttr.create( "outRotate", "obr", aRotateX, aRotateY, aRotateZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleX = nAttr.create( "outScaleX", "osx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleY = nAttr.create( "outScaleY", "osy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleZ = nAttr.create( "outScaleZ", "osz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScale = nAttr.create( "outScale", "obs", aScaleX, aScaleY, aScaleZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTransform = cAttr.create( "outTransform", "otr" );
cAttr.addChild( aTranslate );
cAttr.addChild( aRotate );
cAttr.addChild( aScale );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setStorable( false );
s = addAttribute( aTransform );
// Bounding box
aBoundMinX = nAttr.create( "outBoundMinX", "obminx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMinY = nAttr.create( "outBoundMinY", "cobminy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMinZ = nAttr.create( "outBoundMinZ", "obminz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMin = nAttr.create( "outBoundMin", "obmin", aBoundMinX, aBoundMinY, aBoundMinZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxX = nAttr.create( "outBoundMaxX", "obmaxx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxY = nAttr.create( "outBoundMaxY", "cobmaxy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxZ = nAttr.create( "outBoundMaxZ", "obmaxz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMax = nAttr.create( "outBoundMax", "obmax", aBoundMaxX, aBoundMaxY, aBoundMaxZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterX = nAttr.create( "outBoundCenterX", "obcx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterY = nAttr.create( "outBoundCenterY", "obcy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterZ = nAttr.create( "outBoundCenterZ", "obcz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenter = nAttr.create( "outBoundCenter", "obc", aBoundCenterX, aBoundCenterY, aBoundCenterZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBound = cAttr.create( "outBound", "obd" );
cAttr.addChild( aBoundMin );
cAttr.addChild( aBoundMax );
cAttr.addChild( aBoundCenter );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setStorable( false );
s = addAttribute( aBound );
assert( s );
// Attributes
MFnGenericAttribute genAttr;
aAttributeValues = genAttr.create( "attributeValues", "atv", &s );
genAttr.addNumericDataAccept( MFnNumericData::kBoolean );
genAttr.addNumericDataAccept( MFnNumericData::kInt );
genAttr.addNumericDataAccept( MFnNumericData::kFloat );
genAttr.addNumericDataAccept( MFnNumericData::kDouble );
genAttr.addDataAccept( MFnData::kString );
genAttr.setReadable( true );
genAttr.setWritable( false );
genAttr.setStorable( false );
genAttr.setConnectable( true );
genAttr.setArray( true );
genAttr.setIndexMatters( true );
genAttr.setUsesArrayDataBuilder( true );
addAttribute( aAttributeValues );
aAttributes = cAttr.create( "attributes", "ott" );
cAttr.addChild( aAttributeValues );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setReadable( true );
cAttr.setStorable( false );
s = addAttribute( aAttributes );
attributeAffects( aSceneQueries, aTransform );
attributeAffects( aSceneQueries, aBound );
attributeAffects( aSceneQueries, aOutputObjects );
attributeAffects( aSceneQueries, aAttributes );
attributeAffects( aAttributeQueries, aAttributes );
attributeAffects( aConvertParamQueries, aOutputObjects );
attributeAffects( aQuerySpace, aTransform );
attributeAffects( aQuerySpace, aBound );
attributeAffects( aQuerySpace, aOutputObjects );
attributeAffects( aTime, aOutTime );
return s;
}
ConstSceneInterfacePtr SceneShapeInterface::getSceneInterface( )
{
throw Exception( "SceneShapeInterface: getSceneInterface not implemented!" );
}
bool SceneShapeInterface::isBounded() const
{
return true;
}
double SceneShapeInterface::time() const
{
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
return time.as( MTime::kSeconds );
}
MBoundingBox SceneShapeInterface::boundingBox() const
{
MBoundingBox bound( MPoint( -1, -1, -1 ), MPoint( 1, 1, 1 ) );
ConstSceneInterfacePtr scn = const_cast<SceneShapeInterface*>(this)->getSceneInterface();
if( scn )
{
try
{
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
// Check what bounding box we need. If objectOnly we want the objectBound, else the scene bound.
// If objectOnly and no object, return the scene bound to have something sensible. It won't be drawn.
MPlug pObjectOnly( thisMObject(), aObjectOnly );
bool objectOnly;
pObjectOnly.getValue( objectOnly );
bool objectBound = objectOnly;
if( objectOnly )
{
// Check for an object
if( scn->hasObject() )
{
ConstObjectPtr object = scn->readObject( time.as( MTime::kSeconds ) );
const VisibleRenderable *obj = runTimeCast< const VisibleRenderable >( object.get() );
if( obj )
{
Box3f objBox = obj->bound();
if( !objBox.isEmpty() )
{
bound = convert<MBoundingBox>( objBox );
}
}
}
else
{
objectBound = false;
}
}
if( !objectBound )
{
Box3d b = scn->readBound( time.as( MTime::kSeconds ) );
if( !b.isEmpty() )
{
bound = convert<MBoundingBox>( b );
}
}
}
catch( std::exception &e )
{
msg( Msg::Error, "SceneShapeInterface::boundingBox", e.what() );
}
catch( ... )
{
msg( Msg::Error, "SceneShapeInterface::boundingBox", "Exception thrown in SceneShapeInterface::bound" );
}
}
return bound;
}
MStatus SceneShapeInterface::setDependentsDirty( const MPlug &plug, MPlugArray &plugArray )
{
if( plug == aTime )
{
// Check if sceneInterface is animated. If not, plugs are not dependent on time
if( animatedScene() )
{
m_previewSceneDirty = true;
childChanged( kBoundingBoxChanged ); // needed to tell maya the bounding box has changed
// Need to go through all output plugs, since Maya doesn't propagate dirtiness from parent plug to the children in setDependentsDirty
MPlug pObjects( thisMObject(), aOutputObjects );
for( unsigned i=0; i<pObjects.numElements(); i++ )
{
MPlug p = pObjects[i];
plugArray.append( p );
}
MPlug pTransform( thisMObject(), aTransform );
for( unsigned i=0; i<pTransform.numElements(); i++ )
{
MPlug p = pTransform[i];
for( unsigned j=0; j<p.numChildren(); j++ )
{
plugArray.append( p.child( j ) );
plugArray.append( p.child( j ).child( 0 ) );
plugArray.append( p.child( j ).child( 1 ) );
plugArray.append( p.child( j ).child( 2 ) );
}
}
MPlug pBound( thisMObject(), aBound);
for( unsigned i=0; i<pBound.numElements(); i++ )
{
MPlug p = pBound[i];
for( unsigned j=0; j<p.numChildren(); j++ )
{
plugArray.append( p.child( j ) );
plugArray.append( p.child( j ).child( 0 ) );
plugArray.append( p.child( j ).child( 1 ) );
plugArray.append( p.child( j ).child( 2 ) );
}
}
MPlug pAttributes( thisMObject(), aAttributes);
for( unsigned i=0; i<pAttributes.numElements(); i++ )
{
MPlug p = pAttributes[i];
MPlug pChild = p.child(0);
plugArray.append( pChild );
for( unsigned j=0; j<pChild.numElements(); j++ )
{
plugArray.append( pChild[j] );
}
}
}
}
else if( plug == aDrawGeometry || plug == aDrawChildBounds || plug == aObjectOnly || plug == aDrawTagsFilter )
{
// Preview plug values have changed, GL Scene is dirty
m_previewSceneDirty = true;
}
else if ( plug == aObjectDependency )
{
MPlug pObjects( thisMObject(), aOutputObjects );
for( unsigned i=0; i<pObjects.numElements(); i++ )
{
MPlug p = pObjects[i];
plugArray.append( p );
}
}
return MS::kSuccess;
}
#if MAYA_API_VERSION >= 201600
MStatus SceneShapeInterface::preEvaluation( const MDGContext &context, const MEvaluationNode &evaluationNode )
{
// this is in the Maya devkit simpleEvaluationNode example so
// I'm including it here, though I'm not sure when/why we'd
// be called with a non-normal context.
if( !context.isNormal() )
{
return MStatus::kFailure;
}
if(
( evaluationNode.dirtyPlugExists( aTime ) && animatedScene() ) ||
evaluationNode.dirtyPlugExists( aDrawGeometry ) ||
evaluationNode.dirtyPlugExists( aDrawChildBounds ) ||
evaluationNode.dirtyPlugExists( aObjectOnly ) ||
evaluationNode.dirtyPlugExists( aDrawTagsFilter )
)
{
m_previewSceneDirty = true;
}
return MS::kSuccess;
}
#endif
MStatus SceneShapeInterface::compute( const MPlug &plug, MDataBlock &dataBlock )
{
MStatus s;
MPlug topLevelPlug = plug;
int index = -1;
// Look for parent plug index
while( topLevelPlug.isChild() || topLevelPlug.isElement() )
{
if( topLevelPlug.isChild() )
{
topLevelPlug = topLevelPlug.parent();
}
if( topLevelPlug.isElement() )
{
index = topLevelPlug.logicalIndex();
topLevelPlug = topLevelPlug.array();
}
}
if ( topLevelPlug == aOutputObjects && m_postLoadCallback )
{
return MS::kFailure;
}
if( topLevelPlug == aOutputObjects || topLevelPlug == aTransform || topLevelPlug == aBound || topLevelPlug == aAttributes )
{
MIntArray indices;
if( index == -1 )
{
// in parallel evaluation mode, we may receive the top level plug
// directly, which means we need to compute all child plugs.
topLevelPlug.getExistingArrayAttributeIndices( indices );
}
else
{
// we still get the direct element if we're in DG mode.
indices.append( index );
}
MDataHandle timeHandle = dataBlock.inputValue( aTime );
MTime time = timeHandle.asTime();
MPlug pQuerySpace( thisMObject(), aQuerySpace );
int querySpace;
pQuerySpace.getValue( querySpace );
MString name;
SceneInterface::Path path;
MPlug pSceneQueries( thisMObject(), aSceneQueries );
ConstSceneInterfacePtr sc = getSceneInterface();
if( !sc )
{
// Scene Interface isn't valid
MFnDagNode dag(thisMObject());
msg( Msg::Error, dag.fullPathName().asChar(), "Input values are invalid." );
return MS::kFailure;
}
unsigned numIndices = indices.length();
for( unsigned i = 0; i < numIndices; ++i )
{
MPlug pQuery = pSceneQueries.elementByLogicalIndex( indices[i] );
pQuery.getValue( name );
path = fullPathName( name.asChar() );
ConstSceneInterfacePtr scene = sc->scene( path, SceneInterface::NullIfMissing );
if( !scene )
{
// Queried element doesn't exist
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Queried element '%s' at index '%s' does not exist " ) % name.asChar() % indices[i] );
return MS::kFailure;
}
s = computeOutputPlug( plug, topLevelPlug, dataBlock, scene.get(), indices[i], querySpace, time );
if( !s )
{
return s;
}
}
}
else if( topLevelPlug == aOutTime )
{
MDataHandle timeHandle = dataBlock.inputValue( aTime );
MTime time = timeHandle.asTime();
MDataHandle outTimeHandle = dataBlock.outputValue( aOutTime );
outTimeHandle.setMTime( time );
}
return MS::kSuccess;
}
MStatus SceneShapeInterface::computeOutputPlug( const MPlug &plug, const MPlug &topLevelPlug, MDataBlock &dataBlock, const IECore::SceneInterface *scene, int topLevelIndex, int querySpace, MTime &time )
{
MStatus s;
if( topLevelPlug == aTransform )
{
MArrayDataHandle transformHandle = dataBlock.outputArrayValue( aTransform );
MArrayDataBuilder transformBuilder = transformHandle.builder();
M44d transformd;
if( querySpace == World )
{
// World Space (starting from scene root)
transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
}
else if( querySpace == Local )
{
// Local space
transformd = scene->readTransformAsMatrix( time.as( MTime::kSeconds ) );
}
V3f translate( 0 ), shear( 0 ), rotate( 0 ), scale( 1 );
extractSHRT( convert<M44f>( transformd ), scale, shear, rotate, translate );
MDataHandle transformElementHandle = transformBuilder.addElement( topLevelIndex );
transformElementHandle.child( aTranslate ).set3Float( translate[0], translate[1], translate[2] );
transformElementHandle.child( aRotate ).child( aRotateX ).setMAngle( MAngle( rotate[0] ) );
transformElementHandle.child( aRotate ).child( aRotateY ).setMAngle( MAngle( rotate[1] ) );
transformElementHandle.child( aRotate ).child( aRotateZ ).setMAngle( MAngle( rotate[2] ) );
transformElementHandle.child( aScale ).set3Float( scale[0], scale[1], scale[2] );
}
else if( topLevelPlug == aOutputObjects && scene->hasObject() )
{
MArrayDataHandle outputDataHandle = dataBlock.outputArrayValue( aOutputObjects, &s );
MArrayDataBuilder outputBuilder = outputDataHandle.builder();
ConstObjectPtr object = scene->readObject( time.as( MTime::kSeconds ) );
if( querySpace == World )
{
// If world space, need to transform the object using the concatenated matrix from the sceneInterface path to the query path
M44d transformd;
transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
TransformOpPtr transformer = new TransformOp();
transformer->inputParameter()->setValue( const_cast< Object *>(object.get()) ); /// safe const_cast because the op will duplicate the Object.
transformer->copyParameter()->setTypedValue( true );
transformer->matrixParameter()->setValue( new M44dData( transformd ) );
object = transformer->operate();
}
IECore::TypeId type = object->typeId();
if( type == CoordinateSystemTypeId )
{
IECore::ConstCoordinateSystemPtr coordSys = IECore::runTimeCast<const CoordinateSystem>( object );
Imath::M44f m;
if( coordSys->getTransform() )
{
m = coordSys->getTransform()->transform();
}
Imath::V3f s(0), h(0), r(0), t(0);
Imath::extractSHRT(m, s, h, r, t);
MFnNumericData fnData;
MObject data = fnData.create( MFnNumericData::k3Double );
fnData.setData( (double)t[0], (double)t[1], (double)t[2] );
MDataHandle handle = outputBuilder.addElement( topLevelIndex );
handle.set( data );
}
else
{
ToMayaObjectConverterPtr converter = ToMayaObjectConverter::create( object );
if( converter )
{
bool isParamRead = readConvertParam( converter->parameters(), topLevelIndex );
if( ! isParamRead )
{
return MS::kFailure;
}
MObject data;
// Check the type for now, because a dag node is created if you pass an empty MObject to the converter
// Won't be needed anymore when the related todo is addressed in the converter
if( type == MeshPrimitiveTypeId )
{
MFnMeshData fnData;
data = fnData.create();
}
else if( type == CurvesPrimitiveTypeId )
{
MFnNurbsCurveData fnData;
data = fnData.create();
}
if( !data.isNull() )
{
bool conversionSuccess = converter->convert( data );
if ( conversionSuccess )
{
MDataHandle h = outputBuilder.addElement( topLevelIndex, &s );
s = h.set( data );
}
else
{
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Convert object failed! index=" ) % topLevelIndex );
}
}
}
}
}
else if( topLevelPlug == aBound )
{
MArrayDataHandle boundHandle = dataBlock.outputArrayValue( aBound );
MArrayDataBuilder boundBuilder = boundHandle.builder();
Box3d bboxd = scene->readBound( time.as( MTime::kSeconds ) );
if( querySpace == World )
{
// World Space (from root path)
M44d transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
bboxd = transform( bboxd, transformd );
}
Box3f bound( bboxd.min, bboxd.max );
MDataHandle boundElementHandle = boundBuilder.addElement( topLevelIndex );
boundElementHandle.child( aBoundMin ).set3Float( bound.min[0], bound.min[1], bound.min[2] );
boundElementHandle.child( aBoundMax ).set3Float( bound.max[0], bound.max[1], bound.max[2] );
V3f boundCenter = bound.center();
boundElementHandle.child( aBoundCenter ).set3Float( boundCenter[0], boundCenter[1], boundCenter[2] );
}
else if( topLevelPlug == aAttributes )
{
MIntArray attrIndices;
if( plug.isElement() && !plug.isCompound() )
{
attrIndices.append( plug.logicalIndex() );
}
else
{
// in parallel evaluation mode, we may receive the top level plug
// directly, which means we need to compute all child plugs.
topLevelPlug.elementByLogicalIndex( topLevelIndex ).getExistingArrayAttributeIndices( attrIndices );
}
MPlug pAttributeQueries( thisMObject(), aAttributeQueries );
unsigned numAttrs = attrIndices.length();
for( unsigned i = 0; i < numAttrs; ++i )
{
MPlug pAttributeQuery = pAttributeQueries.elementByLogicalIndex( attrIndices[i] );
MString attrName;
pAttributeQuery.getValue( attrName );
if( !scene->hasAttribute( attrName.asChar() ) )
{
// Queried attribute doesn't exist
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Queried attribute '%s' at index '%s' does not exist " ) % attrName.asChar() % attrIndices[i] );
return MS::kFailure;
}
// Attribute query results are returned as attributes[ sceneQuery index ].attributeValues[ attributeQuery index ]
MArrayDataHandle attributesHandle = dataBlock.outputArrayValue( aAttributes );
MArrayDataBuilder builder = attributesHandle.builder();
MDataHandle elementHandle = builder.addElement( topLevelIndex );
MDataHandle attributeValuesHandle = elementHandle.child( aAttributeValues );
MArrayDataHandle arrayHandle( attributeValuesHandle );
arrayHandle.jumpToElement( attrIndices[i] );
MDataHandle currentElement = arrayHandle.outputValue();
ConstObjectPtr attrValue = scene->readAttribute( attrName.asChar(), time.as( MTime::kSeconds ) );
/// \todo Use a generic data converter that would be compatible with a generic attribute.
IECore::TypeId type = attrValue->typeId();
if( type == BoolDataTypeId )
{
bool value = static_cast< const BoolData * >(attrValue.get())->readable();
currentElement.setGenericBool( value, true);
}
else if( type == FloatDataTypeId )
{
float value = static_cast< const FloatData * >(attrValue.get())->readable();
currentElement.setGenericFloat( value, true);
}
else if( type == DoubleDataTypeId )
{
float value = static_cast< const DoubleData * >(attrValue.get())->readable();
currentElement.setGenericDouble( value, true);
}
else if( type == IntDataTypeId )
{
int value = static_cast< const IntData * >(attrValue.get())->readable();
currentElement.setGenericInt( value, true);
}
else if( type == StringDataTypeId )
{
MString value( static_cast< const StringData * >(attrValue.get())->readable().c_str() );
currentElement.setString( value );
}
}
}
return s;
}
M44d SceneShapeInterface::worldTransform( ConstSceneInterfacePtr scene, double time )
{
SceneInterface::Path p;
scene->path( p );
ConstSceneInterfacePtr tmpScene = getSceneInterface();
SceneInterface::Path pRoot;
tmpScene->path( pRoot );
M44d result;
for ( SceneInterface::Path::const_iterator it = p.begin()+pRoot.size(); tmpScene && it != p.end(); ++it )
{
tmpScene = tmpScene->child( *it, SceneInterface::NullIfMissing );
if ( !tmpScene )
{
break;
}
result = tmpScene->readTransformAsMatrix( time ) * result;
}
return result;
}
MPxSurfaceShape::MatchResult SceneShapeInterface::matchComponent( const MSelectionList &item, const MAttributeSpecArray &spec, MSelectionList &list )
{
if( spec.length() == 1 )
{
MAttributeSpec attrSpec = spec[0];
MStatus s;
int dim = attrSpec.dimensions();
if ( (dim > 0) && attrSpec.name() == "f" )
{
int numElements = m_nameToGroupMap.size();
MAttributeIndex attrIndex = attrSpec[0];
if ( attrIndex.type() != MAttributeIndex::kInteger )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
int upper = numElements - 1;
int lower = 0;
if ( attrIndex.hasLowerBound() )
{
attrIndex.getLower( lower );
}
if ( attrIndex.hasUpperBound() )
{
attrIndex.getUpper( upper );
}
// Check the attribute index range is valid
if ( (attrIndex.hasRange() && !attrIndex.hasValidRange() ) || (upper >= numElements) || (lower < 0 ) )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
MDagPath path;
item.getDagPath( 0, path );
MFnSingleIndexedComponent fnComp;
MObject comp = fnComp.create( MFn::kMeshPolygonComponent, &s );
for ( int i=lower; i<=upper; i++ )
{
fnComp.addElement( i );
}
list.add( path, comp );
return MPxSurfaceShape::kMatchOk;
}
}
return MPxSurfaceShape::matchComponent( item, spec, list );
}
/// Blank implementation of this method. This is to avoid a crash when you try and use the rotation manipulator maya gives
/// you when you've selected procedural components in rotation mode (maya 2013)
void SceneShapeInterface::transformUsing( const MMatrix &mat, const MObjectArray &componentList, MPxSurfaceShape::MVertexCachingMode cachingMode, MPointArray *pointCache )
{
}
/// This method is overridden to supply a geometry iterator, which maya uses to work out
/// the bounding boxes of the components you've selected in the viewport
MPxGeometryIterator* SceneShapeInterface::geometryIteratorSetup( MObjectArray& componentList, MObject& components, bool forReadOnly )
{
if ( components.isNull() )
{
return new SceneShapeInterfaceComponentBoundIterator( this, componentList );
}
else
{
return new SceneShapeInterfaceComponentBoundIterator( this, components );
}
}
Imath::Box3d SceneShapeInterface::componentBound( int idx )
{
// get relative path name from index
IECore::InternedString name = selectionName( idx );
SceneInterface::Path path;
path = fullPathName( name.value() );
ConstSceneInterfacePtr scene = getSceneInterface()->scene( path, SceneInterface::NullIfMissing );
if( !scene )
{
msg( Msg::Warning, "SceneShapeInterface::componentBound", boost::format( "no scene for component %s" ) % name.value() );
return Imath::Box3d( Imath::V3d(-1), Imath::V3d(1) );
}
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
// read bound from scene interface and return it in world space
Imath::Box3d componentBound = scene->readBound( time.as( MTime::kSeconds ) );
M44d transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
componentBound = transform( componentBound, transformd );
return componentBound;
}
void SceneShapeInterface::buildScene( IECoreGL::RendererPtr renderer, ConstSceneInterfacePtr subSceneInterface )
{
// Grab plug values to know what we need to render
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
MPlug pDrawBounds( thisMObject(), aDrawChildBounds );
bool drawBounds;
pDrawBounds.getValue( drawBounds );
MPlug pDrawGeometry( thisMObject(), aDrawGeometry );
bool drawGeometry;
pDrawGeometry.getValue( drawGeometry );
MPlug pObjectOnly( thisMObject(), aObjectOnly );
bool objectOnly;
pObjectOnly.getValue( objectOnly );
if( !drawGeometry && !drawBounds )
{
return;
}
MPlug pDrawTagsFilter( thisMObject(), aDrawTagsFilter );
MString drawTagsFilter;
pDrawTagsFilter.getValue( drawTagsFilter );
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
std::string txt(drawTagsFilter.asChar());
Tokenizer tokens( txt, boost::char_separator<char>(" "));
Tokenizer::iterator t = tokens.begin();
SceneInterface::NameList drawTags;
for ( ; t != tokens.end(); t++ )
{
if ( t->size() )
{
/// test if the scene location has the tag to start with..
if ( subSceneInterface->hasTag( *t, SceneInterface::EveryTag ) )
{
drawTags.push_back( *t );
}
else
{
msg( Msg::Warning, name().asChar(), std::string("Tag '") + *t + "'does not exist in scene. Ignoring it for filtering.");
}
}
}
renderer->concatTransform( convert<M44f>( worldTransform( subSceneInterface, time.as( MTime::kSeconds ) ) ) );
recurseBuildScene( renderer.get(), subSceneInterface.get(), time.as( MTime::kSeconds ), drawBounds, drawGeometry, objectOnly, drawTags );
}
void SceneShapeInterface::recurseBuildScene( IECoreGL::Renderer * renderer, const SceneInterface *subSceneInterface, double time, bool drawBounds, bool drawGeometry, bool objectOnly, const SceneInterface::NameList &drawTags )
{
if ( drawTags.size() )
{
SceneInterface::NameList::const_iterator it;
for ( it = drawTags.begin(); it != drawTags.end(); it++ )
{
if ( subSceneInterface->hasTag( *it, SceneInterface::EveryTag ) )
{
break;
}
}
/// stop drawing if the current scene location does not have the required tags.
if ( it == drawTags.end() )
{
return;
}
}
if ( subSceneInterface->hasAttribute( "scene:visible" ) )
{
if( ConstBoolDataPtr vis = runTimeCast<const BoolData>( subSceneInterface->readAttribute( "scene:visible", time ) ) )
{
if( !vis->readable() )
{
return;
}
}
}
AttributeBlock a(renderer);
SceneInterface::Path pathName;
subSceneInterface->path( pathName );
std::string pathStr = relativePathName( pathName );
renderer->setAttribute( "name", new StringData( pathStr ) );
renderer->setAttribute( "gl:curvesPrimitive:useGLLines", new BoolData( true ) );
if(pathStr != "/")
{
// Path space
renderer->concatTransform( convert<M44f>( subSceneInterface->readTransformAsMatrix( time ) ) );
}
// Need to add this attribute block to get a parent group with that name that includes the object and/or bound
AttributeBlock aNew(renderer);
if ( subSceneInterface->hasAttribute( LinkedScene::fileNameLinkAttribute ) )
{
// we are at a link location... create a hash to uniquely identify it.
MurmurHash hash;
subSceneInterface->readAttribute( LinkedScene::fileNameLinkAttribute, time )->hash( hash );
subSceneInterface->readAttribute( LinkedScene::rootLinkAttribute, time )->hash( hash );
subSceneInterface->readAttribute( LinkedScene::timeLinkAttribute, time )->hash( hash );
/// register the hash mapped to the name of the group
InternedString pathInternedStr(pathStr);
std::pair< HashToName::iterator, bool > ret = m_hashToName.insert( HashToName::value_type( hash, pathInternedStr ) );
if ( !ret.second )
{
/// the same location was already rendered, so we store the current location for instanting later...
m_instances.push_back( InstanceInfo(pathInternedStr, ret.first->second) );
return;
}
}
if( drawGeometry && subSceneInterface->hasObject() )
{
ConstObjectPtr object = subSceneInterface->readObject( time );
if( runTimeCast< const CoordinateSystem >(object.get()) )
{
// manually draw coordinate systems so they don't override the gl name state:
AttributeBlock a(renderer);
renderer->setAttribute( "gl:curvesPrimitive:useGLLines", new IECore::BoolData( true ) );
renderer->setAttribute( "gl:curvesPrimitive:glLineWidth", new IECore::FloatData( 2 ) );
IECore::V3fVectorDataPtr p = new IECore::V3fVectorData;
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 1, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 1, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 1 ) );
IECore::IntVectorDataPtr inds = new IECore::IntVectorData;
inds->writable().resize( 3, 2 );
CurvesPrimitivePtr curves = new IECore::CurvesPrimitive( inds, IECore::CubicBasisf::linear(), false, p );
curves->render( renderer );
}
else if( const Renderable *o = runTimeCast< const Renderable >(object.get()) )
{
o->render(renderer);
}
}
if( drawBounds && pathStr != "/" )
{
Box3d b = subSceneInterface->readBound( time );
Box3f bbox( b.min, b.max );
if( !bbox.isEmpty() )
{
CurvesPrimitive::createBox( bbox )->render( renderer );
}
}
if( !objectOnly )
{
// We need the entire hierarchy, iterate through all the sceneInterface children
SceneInterface::NameList childNames;
subSceneInterface->childNames( childNames );
for ( SceneInterface::NameList::const_iterator it = childNames.begin(); it != childNames.end(); ++it )
{
ConstSceneInterfacePtr childScene = subSceneInterface->child( *it );
recurseBuildScene( renderer, childScene.get(), time, drawBounds, drawGeometry, objectOnly, drawTags );
}
}
}
void SceneShapeInterface::createInstances()
{
for ( InstanceArray::iterator it = m_instances.begin(); it != m_instances.end(); it++ )
{
const InternedString &instanceName = it->first;
const InternedString &instanceSourceName = it->second;
NameToGroupMap::const_iterator srcIt = m_nameToGroupMap.find( instanceSourceName );
assert ( srcIt != m_nameToGroupMap.end() );
const IECoreGL::Group *srcGroup = srcIt->second.second.get();
NameToGroupMap::iterator trgIt = m_nameToGroupMap.find( instanceName );
IECoreGL::Group *trgGroup = trgIt->second.second.get();
// copy the src group to the trg group (empty instance group)
recurseCopyGroup( srcGroup, trgGroup, instanceName.value() );
}
/// clear the maps we don't need them.
m_hashToName.clear();
m_instances.clear();
}
void SceneShapeInterface::recurseCopyGroup( const IECoreGL::Group *srcGroup, IECoreGL::Group *trgGroup, const std::string &namePrefix )
{
const IECoreGL::Group::ChildContainer &children = srcGroup->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
IECoreGL::Group *group = runTimeCast< IECoreGL::Group >( it->get() );
if ( group )
{
IECoreGL::GroupPtr newGroup = new IECoreGL::Group();
// copy state, including the name state component
IECoreGL::StatePtr newState = new IECoreGL::State( *group->getState() );
newGroup->setState( newState );
std::string newName;
const IECoreGL::NameStateComponent *nameState = newState->get< IECoreGL::NameStateComponent >();
/// now override the name state component
if ( nameState )
{
const std::string &srcName = nameState->name();
size_t found = srcName.rfind('/');
if (found!=std::string::npos)
{
// we take the current "directory" and prepend it with the namePrefix
newName = namePrefix;
newName.append( srcName, found, std::string::npos );
newState->add( new IECoreGL::NameStateComponent( newName ) );
// we also need to register the group in the selection maps...
registerGroup( newName, newGroup );
}
}
newGroup->setTransform( group->getTransform() );
recurseCopyGroup( group, newGroup.get(), newName.size() ? newName.c_str() : namePrefix );
trgGroup->addChild( newGroup );
}
else
{
trgGroup->addChild( *it );
}
}
}
IECoreGL::ConstScenePtr SceneShapeInterface::glScene()
{
if(!m_previewSceneDirty)
{
return m_scene;
}
ConstSceneInterfacePtr sceneInterface = getSceneInterface();
if( sceneInterface )
{
SceneInterface::NameList childNames;
sceneInterface->childNames( childNames );
IECoreGL::RendererPtr renderer = new IECoreGL::Renderer();
renderer->setOption( "gl:mode", new StringData( "deferred" ) );
renderer->worldBegin();
{
buildScene( renderer, sceneInterface );
}
renderer->worldEnd();
m_scene = renderer->scene();
m_scene->setCamera( 0 );
}
// Update component name to group map
m_nameToGroupMap.clear();
m_indexToNameMap.clear();
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
buildGroups( defaultState->get<const IECoreGL::NameStateComponent>(), m_scene->root() );
createInstances();
m_previewSceneDirty = false;
return m_scene;
}
void SceneShapeInterface::registerGroup( const std::string &name, IECoreGL::GroupPtr &group )
{
int index = m_nameToGroupMap.size();
std::pair< NameToGroupMap::iterator, bool> ret;
ret = m_nameToGroupMap.insert( std::pair< InternedString, NameToGroupMap::mapped_type > (name, NameToGroupMap::mapped_type( index, group )) );
if( ret.second )
{
m_indexToNameMap.push_back( name );
}
}
void SceneShapeInterface::buildGroups( IECoreGL::ConstNameStateComponentPtr nameState, IECoreGL::GroupPtr group )
{
assert( nameState );
assert( group );
assert( group->getState() );
if ( group->getState()->get< IECoreGL::NameStateComponent >() )
{
nameState = group->getState()->get< IECoreGL::NameStateComponent >();
}
const std::string &name = nameState->name();
if( name != "unnamed" )
{
registerGroup( name, group );
}
const IECoreGL::Group::ChildContainer &children = group->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
assert( *it );
group = runTimeCast< IECoreGL::Group >( *it );
if ( group )
{
buildGroups( nameState, group );
}
}
}
void SceneShapeInterface::setDirty()
{
m_previewSceneDirty = true;
}
IECoreGL::GroupPtr SceneShapeInterface::glGroup( const IECore::InternedString &name )
{
NameToGroupMap::const_iterator elementIt = m_nameToGroupMap.find( name );
if( elementIt != m_nameToGroupMap.end() )
{
return elementIt->second.second;
}
else
{
return 0;
}
}
int SceneShapeInterface::selectionIndex( const IECore::InternedString &name )
{
NameToGroupMap::const_iterator elementIt = m_nameToGroupMap.find( name );
if( elementIt != m_nameToGroupMap.end() )
{
return elementIt->second.first;
}
else
{
return -1;
}
}
IECore::InternedString SceneShapeInterface::selectionName( int index )
{
// make sure the gl scene's been built, as this keeps m_indexToNameMap up to date
const_cast<SceneShapeInterface*>( this )->glScene();
return m_indexToNameMap[index];
}
const std::vector< InternedString > & SceneShapeInterface::componentNames() const
{
// make sure the gl scene's been built, as this keeps m_indexToNameMap up to date
const_cast<SceneShapeInterface*>( this )->glScene();
return m_indexToNameMap;
}
std::string SceneShapeInterface::relativePathName( SceneInterface::Path path )
{
SceneInterface::Path root;
getSceneInterface()->path( root );
assert( root.size() <= path.size() );
if( root == path )
{
return "/";
}
std::string pathName;
SceneInterface::Path::const_iterator it = path.begin();
it += root.size();
for ( ; it != path.end(); it++ )
{
pathName += '/';
pathName += it->value();
}
return pathName;
}
SceneInterface::Path SceneShapeInterface::fullPathName( std::string relativeName )
{
SceneInterface::Path root;
getSceneInterface()->path( root );
SceneInterface::Path relativePath;
SceneInterface::stringToPath( relativeName, relativePath );
SceneInterface::Path fullPath( root );
fullPath.insert( fullPath.end(), relativePath.begin(), relativePath.end() );
return fullPath;
}
bool SceneShapeInterface::readConvertParam( CompoundParameterPtr parameters, int attrIndex ) const
{
IECorePython::ScopedGILLock gilLock;
boost::python::list parserArgList;
{
MPlug pConvertParamQueries( thisMObject(), aConvertParamQueries );
MPlug pConvertParamQuery = pConvertParamQueries.elementByLogicalIndex( attrIndex );
MString paramsStr;
pConvertParamQuery.getValue( paramsStr );
const std::string pstr = paramsStr.asChar();
boost::tokenizer<boost::char_separator<char> > t( pstr, boost::char_separator<char>( " " ) );
boost::tokenizer<boost::char_separator<char> >::const_iterator it, endIt;
for ( it = t.begin(), endIt = t.end(); it != endIt; ++it )
{
parserArgList.append( *it );
}
}
try
{
boost::python::import( "IECore" ).attr( "ParameterParser" )().attr( "parse" )( parserArgList, parameters );
}
catch( const std::exception& e )
{
MFnDagNode dag( thisMObject() );
msg( Msg::Error, dag.fullPathName().asChar(), boost::format( "Convert parameter parse error %s. %d" ) % e.what() % attrIndex );
return false;
}
return true;
}
bool SceneShapeInterface::animatedScene()
{
ConstSampledSceneInterfacePtr scene = runTimeCast< const SampledSceneInterface >( getSceneInterface() );
return ( !scene || scene->numBoundSamples() > 1 );
}
| bsd-3-clause |
LABETE/TestYourProject | staticfiles/js/controllers/logout.js | 143 | 'use strict';
angular.module('authApp')
.controller('LogoutCtrl', function ($scope, $location, djangoAuth) {
djangoAuth.logout();
});
| bsd-3-clause |
paulorobto11/consultorioWeb | modules/auth/views/auth-user/lembrete.php | 2659 | <?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
$this->title = 'Lembrete';
?>
<div class="login-box ">
<div class="login-logo">
<a href="../../index2.html"><i><b>Consultorio</b></i> <b>Médico</b></a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg"><b>Senha do Usuario <br> Informe os Dados para Envio de Senha:</b></p>
<?php $form = ActiveForm::begin([
'id' => 'lembrete-form',
'enableClientValidation' => false,
'options' => ['validateOnSubmit' => false,'class' => 'form-horizontal'],
]); ?>
<div class="col-xs-12">
<div class="row">
<?= $form->field($model, 'username',
[
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('username'),
],
'options' => [
'tag' => 'div',
'class' => 'form-group has-feedback'
],
'template' => '{input} <span class="glyphicon glyphicon-user form-control-feedback"></span><div class="col-lg-10">{error}</div>',
])->textInput() ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder' => '[email protected]'])->label(false) ?>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<?php echo Html::submitButton('Enviar Senha', ['class' => 'btn btn-primary btn-block btn-flat', 'name' => 'login-button']) ?>
<?php echo Html::button('Voltar Login', ['onclick'=>'cancelar()','class' => 'btn btn-danger btn-block btn-flat', 'name' => 'cancelar-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div> <!-- /.login-box-body -->
</div> <!-- /.login-box -->
<?php
$script = <<< JS
loading.turn.off('.loading-fog-login','.cssload-loader');
function mostrar_campo(valor) {
if (valor == 3) {
bb = '#dv_cpf';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).hide();
bb = '#dv_cnpj';
$(bb).show();
}
if (valor == 2) {
bb = '#dv_cnpj';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).hide();
bb = '#dv_cpf';
$(bb).show();
}
if (valor == 1) {
bb = '#dv_cpf';
$(bb).hide();
bb = '#dv_cnpj';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).show();
}
}
function cancelar() {
var url = BASE_PATH + "site/login";
location.href = url;
}
JS;
if($model->hasErrors() )
{
$this->registerJs($script,\yii\web\View::POS_END);
}
$this->registerJs($script,\yii\web\View::POS_END);
?> | bsd-3-clause |
mishbahr/django-staticgen | staticgen/apps.py | 186 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class StaticgenAppConfig(AppConfig):
name = 'staticgen'
verbose_name = _('StaticGen')
| bsd-3-clause |
icecaster/advancedworkflow | javascript/lang/fi.js | 766 | // This file was generated by silverstripe/cow from javascript/lang/src/fi.js.
// See https://github.com/tractorcow/cow for details
if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
if(typeof(console) != 'undefined') console.error('Class ss.i18n not defined');
} else {
ss.i18n.addDictionary('fi', {
"Workflow.DeleteQuestion": "Are you sure you want to permanently delete this?",
"Workflow.EMBARGOMESSAGETIME": "Saved drafts of this page will auto publish today at <a>%s</a>",
"Workflow.EMBARGOMESSAGEDATE": "Saved drafts of this page will auto publish on <a>%s</a>",
"Workflow.EMBARGOMESSAGEDATETIME": "Saved drafts of this page will auto publish on <a>%s at %s</a>",
"Workflow.ProcessError": "Could not process workflow"
});
} | bsd-3-clause |
fitnr/polyencoder | polyencoder/polyencode_layer.py | 3370 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# polyencoder
# Copyright 2015 Neil Freeman [email protected]
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 <COPYRIGHT HOLDER> 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.
from __future__ import print_function
import sys
import csv
from urllib import quote_plus
import fiona
from .polyencoder import polyencode
def getproperties(feature, keys):
'''Return a list of properties from feature'''
return [feature['properties'].get(k) for k in keys]
def encodelayer(infile, keys, encode=None, delimiter=None):
keys = keys.split(',')
writer = csv.writer(sys.stdout, delimiter=delimiter or '\t')
with fiona.drivers():
with fiona.open(infile, 'r') as layer:
for feature in layer:
if feature['geometry']['type'] == 'MultiPolygon':
# list of list of lists of tuples
coords = feature['geometry']['coordinates'][0][0]
elif feature['geometry']['type'] == 'Polygon' or feature['geometry']['type'] == 'MultiLineString':
# list of lists of tuples
coords = feature['geometry']['coordinates'][0]
elif feature['geometry']['type'] == 'Linestring':
# list of tuples
coords = feature['geometry']['coordinates']
else:
raise NotImplementedError(
"Polyencode not available for geometry type: {}".format(feature['geometry']['type']))
try:
encoded = polyencode(coords)
except TypeError:
print("Unexpected issue with {}".format(feature['properties'].get(keys[0])), file=sys.stderr)
raise
if encode:
encoded = quote_plus(encoded)
props = getproperties(feature, keys) + [encoded]
writer.writerow(props)
| bsd-3-clause |
hlzz/dotfiles | graphics/cgal/Alpha_shapes_2/doc/Alpha_shapes_2/Concepts/AlphaShapeFace_2.h | 2519 |
/*!
\ingroup PkgAlphaShape2Concepts
\cgalConcept
\cgalRefines `TriangulationFaceBase_2`
\cgalHasModel `CGAL::Alpha_shape_face_base_2`
*/
class AlphaShapeFace_2 {
public:
/// \name Types
/// @{
/*!
A container type to get (and put) the three special values
(\f$ \alpha_1, \alpha_2, \alpha_3\f$) associated with an alpha shape edge.
*/
typedef unspecified_type Interval_3;
/*!
A coordinate type.
The type must provide a copy constructor, assignment, comparison
operators, negation, multiplication, division and allow the
declaration and initialization with a small integer constant
(cf. requirements for number types). An obvious choice would be
coordinate type of the point class
*/
typedef unspecified_type FT;
/// @}
/// \name Creation
/// @{
/*!
default constructor.
*/
AlphaShapeFace_2();
/*!
constructor setting the incident vertices.
*/
AlphaShapeFace_2(const Vertex_handle& v0, const Vertex_handle& v1, const Vertex_handle& v2);
/*!
constructor setting the incident vertices and the neighboring faces.
*/
AlphaShapeFace_2(const Vertex_handle& v0, const Vertex_handle& v1, const Vertex_handle& v2, const Face_handle& n0, const Face_handle& n1, const Face_handle& n2);
/// @}
/// \name Access Functions
/// @{
/*!
returns the interval associated with the edge indexed with \f$ i\f$, which contains
three alpha values
\f$ \alpha_1 \leq\alpha_2 \leq\alpha_3\f$, such as for
\f$ \alpha\f$ between \f$ \alpha_1\f$ and \f$ \alpha_2\f$, the edge indexed with \f$ i\f$ is
attached but singular,
for \f$ \alpha\f$ between \f$ \alpha_2\f$ and \f$ \alpha_3\f$, the edge is regular, and for \f$ \alpha\f$
greater than \f$ \alpha_3\f$, the edge is interior.
*/
Interval_3 get_ranges(const int& i);
/*!
return the alpha value, under which the alpha shape contains the
face.
*/
FT get_alpha();
/// @}
/// \name Modifiers
/// @{
/*!
sets the interval associated with the edge indexed with \f$ i\f$, which contains three
alpha values
\f$ \alpha_1 \leq\alpha_2 \leq\alpha_3\f$, such as for
\f$ \alpha\f$ between \f$ \alpha_1\f$ and \f$ \alpha_2\f$, the edge indexed with \f$ i\f$ is
attached but singular,
for \f$ \alpha\f$ between \f$ \alpha_2\f$ and \f$ \alpha_3\f$, the edge is regular, and for \f$ \alpha\f$
greater than \f$ \alpha_3\f$, the edge is interior.
*/
void set_ranges(const int& i, const Interval_3& V);
/*!
sets the alpha value, under which the alpha shape contains the
face.
*/
void set_alpha(FT A);
/// @}
}; /* end AlphaShapeFace_2 */
| bsd-3-clause |
NCIP/i-spy | WebRoot/helpDocs/I-SPY_Online_Help/Welcome.1.1.html | 11030 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<!-- MOTW-DISABLED saved from url=(0014)about:internet -->
<title>Welcome to I-SPY Online Help</title>
<link rel="StyleSheet" href="css/Welcome.css" type="text/css" media="all" />
<link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />
<script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/context.js"></script>
<script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/towwhdir.js"></script>
<script type="text/javascript" language="JavaScript1.2" src="wwhdata/common/wwhpagef.js"></script>
<script type="text/javascript" language="JavaScript1.2">
<!--
var WebWorksRootPath = "";
// -->
</script>
<script type="text/javascript" language="JavaScript1.2">
<!--
// Set reference to top level help frame
//
var WWHFrame = WWHGetWWHFrame("", true);
// -->
</script>
<script type="text/javascript" language="JavaScript1.2" src="scripts/expand.js"></script>
</head>
<body style="" onLoad="WWHUpdate();" onUnload="WWHUnload();" onKeyDown="WWHHandleKeyDown((document.all||document.getElementById||document.layers)?event:null);" onKeyPress="WWHHandleKeyPress((document.all||document.getElementById||document.layers)?event:null);" onKeyUp="WWHHandleKeyUp((document.all||document.getElementById||document.layers)?event:null);">
<br />
<div class="WebWorks_Breadcrumbs" style="text-align: left;">Welcome to I-SPY Online Help</div>
<hr align="left" />
<blockquote>
<div class="Chapter_Name"><a name="1052621">Welcome to I-SPY Online Help</a></div>
<div class="Body_Text"><a name="1073952">The following topics introduce you to I-SPY and describe concepts you need to know to </a>use I-SPY:</div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079724">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="baggage/i-spy_About_I-SPY.fm" target="_window" name="1079724">About I-SPY</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1079992">Provides an overview of the I-SPY program.</a></div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079775">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_Getting_Started.4.1.html#1052621', '');" name="1079775">Getting Started with I-SPY</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1079996">Provides instructions to start using I-SPY.</a></div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1080031">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_ID_Lookup.5.1.html#1137820', '');" name="1080031">Conducting an Identifier Lookup</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080032">Describes how to search on patient or sample identiers. The results show the </a>patients that fulfill the criteria.</div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079880">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_Searches.6.1.html#1052621', '');" name="1079880">Conducting Searches</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080004">Describes how to perform a clinical and an </a><span class="Popup" style="font-size: 10.0pt;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_Glossary.11.1.html#1065495', 'popups/i-spy_Glossary-1065495.html');" onMouseOver="javascript:WWHShowPopup('I-SPY_Online_Help', 'popups/i-spy_Glossary-1065495.html', (document.all||document.getElementById||document.layers)?event:null);" onMouseOut="WWHHidePopup();">IHC (Immunohistochemistry)</a></span> Level of Expression and Loss of Expression query. </div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079783">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_High_Order_Analysis.7.1.html#1095067', '');" name="1079783">High Order Analysis</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080008">Describes how to work with high order analyses.</a></div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079787">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_View%20Results.8.1.html#1052621', '');" name="1079787">Viewing Results</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080012">Describes how to view all the results generated from searches and high order </a>analyses.</div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079791">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_Manage_Lists.9.1.html#1052621', '');" name="1079791">Managing Lists</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080016">Describes how to manage user-defined and study-defined patient, gene, </a>reporter lists.</div>
<div class="Bullet_outer" style="margin-left: 18pt;margin-bottom: 6.0pt; margin-top: 0.0pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1080044">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;text-align: Left;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner" style="text-align: Left;"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_appa_datadictionary.10.1.html#1056643', '');" name="1080044">Data Dictionary</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080055">Provides a data dictionary listing the variables for I-SPY.</a></div>
<div class="Bullet_outer" style="margin-left: 18pt;">
<table border="0" cellspacing="0" cellpadding="0" id="SummaryNotRequired_np1079795">
<tr style="vertical-align: baseline;">
<td>
<div class="Bullet_inner" style="width: 18pt; white-space: nowrap;">•</div>
</td>
<td width="100%">
<div class="Bullet_inner"><span class="Emphasis" style="color: #515186;"><a href="javascript:WWHClickedPopup('I-SPY_Online_Help', 'i-spy_Glossary.11.1.html#1065436', '');" name="1079795">Glossary</a></span></div>
</td>
</tr>
</table>
</div>
<div class="Body_Text_Indent_2"><a name="1080023">Describes terms used in I-SPY.</a></div>
<script type="text/javascript" language="JavaScript1.2">
<!--
// Clear related topics
//
WWHClearRelatedTopics();
// Add related topics
//
WWHAddRelatedTopic("Logging In", "I-SPY_Online_Help", "i-spy_Getting_Started.4.5.html#1115560");
WWHAddRelatedTopic("Logging Out", "I-SPY_Online_Help", "i-spy_Getting_Started.4.12.html#1111610");
WWHAddRelatedTopic("Getting Help", "I-SPY_Online_Help", "i-spy_Getting_Started.4.1.html#1052621");
WWHAddRelatedTopic("Application Support", "I-SPY_Online_Help", "i-spy_Getting_Started.4.11.html#1111569");
WWHAddRelatedTopic("Using Online Help", "I-SPY_Online_Help", "OnlineHelpBoilerplate.3.1.html#1060342");
document.writeln(WWHRelatedTopicsInlineHTML());
// -->
</script>
</blockquote>
<script type="text/javascript" language="JavaScript1.2">
<!--
document.write(WWHRelatedTopicsDivTag() + WWHPopupDivTag() + WWHALinksDivTag());
// -->
</script>
</body>
</html> | bsd-3-clause |
JoshuaTaylorBW/Prework_Transfer | _02_html/your-solution/index.html | 2581 | <!DOCTYPE html>
<html>
<head>
<title>gSchool Pre Work</title>
<link rel="stylesheet" type="text/css" href="Style.css">
</head>
<body>
<h1>Results For "Hackers"</h1>
<div id="First_Column">
<h2>Titles</h2>
<table>
<tr>
<td><img height="44px" width="32px" src="../images/hackers.jpg"></td>
<td><a href="../readme.md">Hackers (1995)</a></td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/2000.jpg"></td>
<td><a href="../readme.md">2000 AD (2000)<br> <i>aka "Hackers"</i></a></td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/frontline.jpg"></td>
<td><a href="../readme.md">Hackers (2001) TV Episode <br> -Frontline (1983) (TV Series)</a></td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/hackersgame.jpg"></td>
<td><a href="../readme.md">Hacker's Game (2015) <br> <i>aka "The Hackers"</i></a></td>
</tr>
</table>
<h2>Names</h2>
<table>
<tr>
<td><img height="44px" width="32px" src="../images/amyacker.jpg"></td>
<td>Amy Acker (Actress, Angel (1999))</td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/drewvan.jpg"></td>
<td>Drew Van Acker (Actor, Pretty Little Liars (2010))</td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/buddyhackett.jpg"></td>
<td>Buddy Hackett (Actor, The Little Mermaid (1989))</td>
</tr>
<tr>
<td><img height="44px" width="32px" src="../images/emilywilkersham.jpg"></td>
<td>Emily Wickersham (Actress, I Am Number Four (2011))</td>
</tr>
</table>
<h2>Keyword</h2>
<table>
<tr>
<td>hacker</td>
<td>(180 titles)</td>
</tr>
</table>
<h2>Companies</h2>
<table>
<tr>
<td>Douglas, Gorman, Rothacker & Wilheml (DGRW)</td>
</tr>
<tr>
<td>Crackerjack Management</td>
</tr>
<tr>
<td>Bleeker Street Media</td>
</tr>
<tr>
<td>Bleeker Street Entertainment</td>
</tr>
</table>
</div>
<div id="Second_Column">
<h2>Category Search</h2>
<ul>
<li>All</li>
<li>Name</li>
<li>Title
<ul>
<li>Movie</li>
<li>TV</li>
<li>TV Episode</li>
<li>Video Game</li>
</ul>
</li>
<li>Character</li>
<li>Company</li>
<li>Keyword</li>
<li>Plot Summaries</li>
<li>Biographies</li>
<li>Quotes</li>
</ul>
<h2>Additional Search Options</h2>
<ul>
<li>Advanced Search</li>
<li>Advanced Title Search</li>
<li>Advanced Name Search</li>
</ul>
</div>
</body>
</html> | bsd-3-clause |
all-of-us/workbench | e2e/tests/workspace/workspace-duplicate.spec.ts | 4823 | import { findOrCreateWorkspace, findOrCreateWorkspaceCard, signInWithAccessToken } from 'utils/test-utils';
import { MenuOption } from 'app/text-labels';
import WorkspaceDataPage from 'app/page/workspace-data-page';
import Navigation, { NavLink } from 'app/component/navigation';
import WorkspaceCard from 'app/component/card/workspace-card';
import WorkspaceEditPage from 'app/page/workspace-edit-page';
import WorkspacesPage from 'app/page/workspaces-page';
import { config } from 'resources/workbench-config';
import OldCdrVersionModal from 'app/modal/old-cdr-version-modal';
describe('Duplicate workspace', () => {
beforeEach(async () => {
await signInWithAccessToken(page);
});
const workspaceName = 'e2eCloneWorkspaceTest';
/**
* Test:
* - Find an existing workspace. Create a new workspace if none exists.
* - Select "Duplicate" thru the Ellipsis menu located inside the Workspace card.
* - Enter a new workspace name and save the duplicate.
* - Delete duplicate workspace.
*/
test('Duplicate workspace', async () => {
await findOrCreateWorkspace(page, { workspaceName });
// Access Workspace Duplicate page via Workspace action menu.
const dataPage = new WorkspaceDataPage(page);
await dataPage.selectWorkspaceAction(MenuOption.Duplicate);
// Fill out Workspace Name should be just enough for successful duplication
const workspaceEditPage = new WorkspaceEditPage(page);
await workspaceEditPage.getWorkspaceNameTextbox().clear();
const duplicateWorkspaceName = await workspaceEditPage.fillOutWorkspaceName();
// observe that we cannot change the Data Access Tier.
const accessTierSelect = workspaceEditPage.getDataAccessTierSelect();
expect(await accessTierSelect.isDisabled()).toEqual(true);
const finishButton = workspaceEditPage.getDuplicateWorkspaceButton();
await workspaceEditPage.requestForReviewRadiobutton(false);
await finishButton.waitUntilEnabled();
await workspaceEditPage.clickCreateFinishButton(finishButton);
// Duplicate workspace Data page is loaded.
await dataPage.waitForLoad();
expect(page.url()).toContain(duplicateWorkspaceName.replace(/-/g, '')); // Remove dash from workspace name
// Delete duplicate workspace via Workspace card in Your Workspaces page.
await Navigation.navMenu(page, NavLink.YOUR_WORKSPACES);
const workspacesPage = new WorkspacesPage(page);
await workspacesPage.waitForLoad();
await new WorkspaceCard(page).delete({ name: duplicateWorkspaceName });
});
test('Cannot duplicate workspace with older CDR version without consent to restrictions', async () => {
const workspaceCard = await findOrCreateWorkspaceCard(page, { workspaceName });
await (await workspaceCard.asElement()).hover();
await workspaceCard.selectSnowmanMenu(MenuOption.Duplicate, { waitForNav: true });
const workspaceEditPage = new WorkspaceEditPage(page);
// Fill out the fields required for duplication and observe that duplication is enabled
const duplicateWorkspaceName = await workspaceEditPage.fillOutRequiredDuplicationFields();
const duplicateButton = workspaceEditPage.getDuplicateWorkspaceButton();
await duplicateButton.waitUntilEnabled();
// Change CDR version to an old CDR version.
await workspaceEditPage.selectCdrVersion(config.OLD_CDR_VERSION_NAME);
expect(await duplicateButton.isCursorNotAllowed()).toBe(true);
const modal = new OldCdrVersionModal(page);
const cancelButton = modal.getCancelButton();
await cancelButton.click();
// The CDR version is forcibly reverted back to the default
const cdrVersionSelect = workspaceEditPage.getCdrVersionSelect();
expect(await cdrVersionSelect.getSelectedValue()).toBe(config.DEFAULT_CDR_VERSION_NAME);
// Try again. This time consent to restriction.
// Duplicate workspace with an older CDR Version can proceed after consenting to restrictions.
await workspaceEditPage.selectCdrVersion(config.OLD_CDR_VERSION_NAME);
await modal.consentToOldCdrRestrictions();
// Finish creation of workspace.
await workspaceEditPage.requestForReviewRadiobutton(false);
await duplicateButton.waitUntilEnabled();
await workspaceEditPage.clickCreateFinishButton(duplicateButton);
// Duplicate workspace Data page is loaded.
const dataPage = new WorkspaceDataPage(page);
await dataPage.waitForLoad();
expect(page.url()).toContain(`/${duplicateWorkspaceName.toLowerCase()}/data`);
// Delete duplicate workspace via Workspace card in Your Workspaces page.
await Navigation.navMenu(page, NavLink.YOUR_WORKSPACES);
const workspacesPage = new WorkspacesPage(page);
await workspacesPage.waitForLoad();
await new WorkspaceCard(page).delete({ name: duplicateWorkspaceName });
});
});
| bsd-3-clause |
hieutrieu/hiva1 | protected/modules/admin/controllers/CategoryController.php | 3692 | <?php
class CategoryController extends AdminController {
public function actionSave() {
if (Yii::app()->getRequest()->getIsPostRequest()) {
$category = Yii::app()->getRequest()->getPost('Category', array());
if(Yii::app()->session['id']) {
$model = $this->loadModel(Yii::app()->session['id'], 'Category');
} else {
$model = new Category();
//pushing newly added item to last
$maxRight = $model->getMaxRight();
$model->lft = $maxRight + 1;
$model->rgt = $maxRight + 2;
}
$model->setAttributes($_POST['Category']);
if (isset($_POST['Category']['parent_id']) && $_POST['Category']['parent_id'] > 0) {
$modelCategory = $this->loadModel($_POST['Category']['parent_id'], 'Category');
$model->level = $modelCategory->level + 1;
$model->lft = $modelCategory->rgt + 1;
$model->rgt = $modelCategory->rgt + 2;
} else {
$model->level = 1;
}
$model->image = str_replace(Yii::getPathOfAlias('webroot'), '', $model->image);
if ($model->save()) {
Yii::app()->user->setFlash('success', $this->t('Save successfull.'));
} else {
Yii::app()->user->setFlash('success', $this->t('Save can\'t successfull.'));
}
}
unset(Yii::app()->session['id']);
$this->redirect(array('index'));
}
public function actionEdit($id = 0) {
if ($id || Yii::app()->getRequest()->getIsPostRequest()) {
$cid = Yii::app()->getRequest()->getPost('cid', array());
if(count($cid)) {
$id = $cid[0];
}
if($id){
$model = $this->loadModel($id, 'Category');
Yii::app()->session['id'] = $id;
} else {
$model = new Category();
Yii::app()->session['id'] = 0;
}
$this->render('edit', array(
'model' => $model,
));
} else {
Yii::app()->user->setFlash('warning', $this->t('Access denied.'));
$this->redirect(array('index'));
}
}
public function actionNew() {
$model = new Category();
Yii::app()->session['id'] = 0;
$this->render('edit', array(
'model' => $model,
));
}
public function actionDelete() {
if (Yii::app()->getRequest()->getIsPostRequest()) {
$cid = Yii::app()->getRequest()->getPost('cid', array());
$model = new Category();
$model->deleteAll('id IN ('. implode($cid, ',') .')');
Yii::app()->user->setFlash('success', 'Delete successfull.');
} else {
Yii::app()->user->setFlash('error', 'Please select at least one record to delete.');
}
$this->redirect(array('index'));
}
public function actionIndex() {
$viewDefault = 'index';
if($this->pageAjax) {
$viewDefault = 'model_'.$viewDefault;
}
$model = new Category('search');
$model->unsetAttributes();
$this->setPageTitle(yii::t('app', 'Category Manager'));
if (isset($_GET['Category']))
$model->setAttributes($_GET['Category']);
$this->render($viewDefault, array(
'model' => $model,
'function' => $this->function,
'pageAjax' => $this->pageAjax,
));
}
public function actionToggle($id, $attribute, $model) {
if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
$model = $this->loadModel($id, $model);
//loadModel($id, $model) from giix
($model->$attribute == 1) ? $model->$attribute = 0 : $model->$attribute = 1;
$model->save();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/index'));
}
return false;
}
} | bsd-3-clause |
Winkelor/yii2store | common/messages/en-US/languages.php | 240 | <?php
return [
'id' =>'ID',
'en_name' =>'En Name',
'iso639_1' =>'Iso639 1',
'native_name' =>'Native Name',
'native_name_short' =>'Native Name Short',
'created_at' =>'Created At',
'updated_at' =>'Updated At',
];
| bsd-3-clause |
Workday/OpenFrame | third_party/WebKit/Source/core/html/HTMLProgressElement.cpp | 6371 | /*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/html/HTMLProgressElement.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/HTMLNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/UseCounter.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/ProgressShadowElement.h"
#include "core/layout/LayoutProgress.h"
namespace blink {
using namespace HTMLNames;
const double HTMLProgressElement::IndeterminatePosition = -1;
const double HTMLProgressElement::InvalidPosition = -2;
HTMLProgressElement::HTMLProgressElement(Document& document)
: LabelableElement(progressTag, document)
, m_value(nullptr)
{
UseCounter::count(document, UseCounter::ProgressElement);
}
HTMLProgressElement::~HTMLProgressElement()
{
}
PassRefPtrWillBeRawPtr<HTMLProgressElement> HTMLProgressElement::create(Document& document)
{
RefPtrWillBeRawPtr<HTMLProgressElement> progress = adoptRefWillBeNoop(new HTMLProgressElement(document));
progress->ensureUserAgentShadowRoot();
return progress.release();
}
LayoutObject* HTMLProgressElement::createLayoutObject(const ComputedStyle& style)
{
if (!style.hasAppearance() || openShadowRoot())
return LayoutObject::createObject(this, style);
return new LayoutProgress(this);
}
LayoutProgress* HTMLProgressElement::layoutProgress() const
{
if (layoutObject() && layoutObject()->isProgress())
return toLayoutProgress(layoutObject());
LayoutObject* layoutObject = userAgentShadowRoot()->firstChild()->layoutObject();
ASSERT_WITH_SECURITY_IMPLICATION(!layoutObject || layoutObject->isProgress());
return toLayoutProgress(layoutObject);
}
void HTMLProgressElement::parseAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& value)
{
if (name == valueAttr)
didElementStateChange();
else if (name == maxAttr)
didElementStateChange();
else
LabelableElement::parseAttribute(name, oldValue, value);
}
void HTMLProgressElement::attach(const AttachContext& context)
{
LabelableElement::attach(context);
if (LayoutProgress* layoutObject = layoutProgress())
layoutObject->updateFromElement();
}
double HTMLProgressElement::value() const
{
double value = getFloatingPointAttribute(valueAttr);
// Otherwise, if the parsed value was greater than or equal to the maximum
// value, then the current value of the progress bar is the maximum value
// of the progress bar. Otherwise, if parsing the value attribute's value
// resulted in an error, or a number less than or equal to zero, then the
// current value of the progress bar is zero.
return !std::isfinite(value) || value < 0 ? 0 : std::min(value, max());
}
void HTMLProgressElement::setValue(double value)
{
setFloatingPointAttribute(valueAttr, std::max(value, 0.));
}
double HTMLProgressElement::max() const
{
double max = getFloatingPointAttribute(maxAttr);
// Otherwise, if the element has no max attribute, or if it has one but
// parsing it resulted in an error, or if the parsed value was less than or
// equal to zero, then the maximum value of the progress bar is 1.0.
return !std::isfinite(max) || max <= 0 ? 1 : max;
}
void HTMLProgressElement::setMax(double max)
{
// FIXME: The specification says we should ignore the input value if it is inferior or equal to 0.
setFloatingPointAttribute(maxAttr, max > 0 ? max : 1);
}
double HTMLProgressElement::position() const
{
if (!isDeterminate())
return HTMLProgressElement::IndeterminatePosition;
return value() / max();
}
bool HTMLProgressElement::isDeterminate() const
{
return fastHasAttribute(valueAttr);
}
void HTMLProgressElement::didElementStateChange()
{
m_value->setWidthPercentage(position() * 100);
if (LayoutProgress* layoutObject = layoutProgress()) {
bool wasDeterminate = layoutObject->isDeterminate();
layoutObject->updateFromElement();
if (wasDeterminate != isDeterminate())
pseudoStateChanged(CSSSelector::PseudoIndeterminate);
}
}
void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
ASSERT(!m_value);
RefPtrWillBeRawPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
inner->setShadowPseudoId(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
root.appendChild(inner);
RefPtrWillBeRawPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
bar->setShadowPseudoId(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
RefPtrWillBeRawPtr<ProgressValueElement> value = ProgressValueElement::create(document());
m_value = value.get();
m_value->setShadowPseudoId(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
bar->appendChild(m_value);
inner->appendChild(bar);
}
bool HTMLProgressElement::shouldAppearIndeterminate() const
{
return !isDeterminate();
}
void HTMLProgressElement::willAddFirstAuthorShadowRoot()
{
ASSERT(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled());
lazyReattachIfAttached();
}
DEFINE_TRACE(HTMLProgressElement)
{
visitor->trace(m_value);
LabelableElement::trace(visitor);
}
} // namespace
| bsd-3-clause |
OstapHEP/ostap | docs/conf.py | 2147 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'ostap'
copyright = '2019, Ostap developers'
author = 'Ostap developers'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'breathe' ,
'sphinx.ext.autodoc' ,
'sphinx.ext.mathjax' ,
]
breathe_default_project = 'ostap'
breathe_domain_by_extension = {
"h" : "cpp" ,
"C" : "cpp" ,
"py" : "python" ,
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
## html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
| bsd-3-clause |
jinnykoo/wuyisj.com | src/oscar/templates/oscar/base.html | 3849 | {% load i18n compress %}
{% load staticfiles %}
<!DOCTYPE html>
<!--[if lt IE 7]> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="{{ LANGUAGE_CODE|default:"en-gb" }}" class="no-js"> <!--<![endif]-->
<head>
<title>{% if display_version %}[{% trans "Build" %} {{ version }}] {% endif %}{% block title %}{{ shop_name }} - {{ shop_tagline }}{% endblock %}</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="created" content="{% now "jS M Y h:i" %}" />
<meta name="description" content="{% block description %}{% endblock %}" />
<meta name="keywords" content="{% block keywords %}{% endblock %}" />
<meta name="viewport" content="{% block viewport %}width=device-width{% endblock %}" />
<meta name="robots" content="NOARCHIVE,NOCACHE" />
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
{% block favicon %}
<link rel="shortcut icon" href="{% static "oscar/favicon.ico" %}" />
{% endblock %}
{% block mainstyles %}
{% comment %}
We use an inner block to work-around the fact that django-compressor doesn't work with
template inheritance. Ie, we can't just wrap the {% block mainstyles %} with compress tags and
expect it to compress CSS files added in child templates.
{% endcomment %}
{% block styles %}
{% comment %}
If you are developing Oscar's CSS, or overriding Oscar's CSS
files in your project, then set USE_LESS = True in your
settings file. You will also need to ensure that the 'lessc'
executable is available and you have COMPRESS_PRECOMPILERS specified
correctly.
{% endcomment %}
{% endblock %}
{% endblock %}
{# Additional CSS - specific to certain pages #}
{% block extrastyles %}{% endblock %}
{% block extrahead %}{% endblock %}
{% block tracking %}
{# Default to using Google analytics #}
{% include "partials/google_analytics.html" %}
{% endblock %}
</head>
<body id="{% block body_id %}default{% endblock %}" class="wuyi_container">
{# Main content goes in this 'layout' block #}
{% block layout %}{% endblock %}
{% comment %}
Scripts loaded from a CDN. These can't be wrapped by the 'compress' tag and so we
use a separate block for them.
{% endcomment %}
{% block cdn_scripts %}
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{% static "oscar/js/jquery/jquery-1.9.1.min.js" %}"><\/script>')</script>
{% endblock %}
{# Local scripts #}
{% block scripts %}
{% endblock %}
{# Additional JS scripts #}
{% block extrascripts %}{% endblock %}
{# Block for body onload functions #}
<script type="text/javascript">
$(function() {
{% block onbodyload %}{% endblock %}
});
</script>
{# Page meta-data - this is populated by the 'metadata' template context processor #}
<!-- {% trans "Version:" %} {{ version }} -->
</body>
</html>
| bsd-3-clause |
retronym/scala-java8-compat | release.sh | 730 | #! /bin/bash -e
function sbt211() {
sbt 'set scalaVersion := "2.11.0-RC3"' 'set scalaBinaryVersion := scalaVersion.value' $@
return $?
}
die () {
echo "$@"
exit 1
}
CHECK=";clean;test;publishLocal"
RELEASE=";clean;test;publish"
VERSION=`gsed -rn 's/version :=.*"(.+).*"/\1/p' build.sbt`
[[ -n "$(git status --porcelain)" ]] && die "working directory is not clean!"
sbt $CHECK
sbt $RELEASE
sbt211 $CHECK
sbt211 $RELEASE
cat <<EOM
Released! For non-snapshot releases:
- tag: git tag -s -a v$VERSION -m "scala-java8-compat $VERSION"
- push tag: git push origin v$VERSION
- close and release the staging repository: https://oss.sonatype.org
- change the version number in build.sbt to a suitable -SNAPSHOT version
EOM
| bsd-3-clause |
olebole/astrometry.net | include/astrometry/starkd.h | 5964 | /*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#ifndef STAR_KD_H
#define STAR_KD_H
#include <stdint.h>
#include <stdio.h>
#include "astrometry/kdtree.h"
#include "astrometry/kdtree_fits_io.h"
#include "astrometry/fitstable.h"
#include "astrometry/keywords.h"
#include "astrometry/anqfits.h"
#ifdef SWIG
// this keyword (from keywords.h) confuses swig
#define Malloc
#endif
#define AN_FILETYPE_STARTREE "SKDT"
#define AN_FILETYPE_TAGALONG "TAGALONG"
#define STARTREE_NAME "stars"
typedef struct {
kdtree_t* tree;
qfits_header* header;
int* inverse_perm;
uint8_t* sweep;
// reading or writing?
int writing;
// reading: tagged-along data (a FITS BINTABLE with one row per star,
// in the same order); access this via startree_get_tagalong() ONLY!
fitstable_t* tagalong;
} startree_t;
startree_t* startree_open(const char* fn);
startree_t* startree_open_fits(anqfits_t* fits);
/**
Searches for stars within a radius of a point.
xyzcenter: double[3]: unit-sphere coordinates of point; see
starutil.h : radecdeg2xyzarr() to convert RA,Decs to this form.
radius2: radius-squared on the unit sphere; see starutil.h :
deg2distsq() or arcsec2distsq().
xyzresults: if non-NULL, returns the xyz positions of the stars that
are found, in a newly-allocated array.
radecresults: if non-NULL, returns the RA,Dec positions (in degrees)
of the stars within range.
starinds: if non-NULL, returns the indices of stars within range.
This can be used to retrieve extra information about the stars, using
the 'startree_get_data_column()' function.
*/
void startree_search_for(const startree_t* s, const double* xyzcenter, double radius2,
double** xyzresults, double** radecresults,
int** starinds, int* nresults);
/**
RA, Dec, and radius in degrees. Otherwise same as startree_search_for().
*/
void startree_search_for_radec(const startree_t* s, double ra, double dec, double radius,
double** xyzresults, double** radecresults,
int** starinds, int* nresults);
void startree_search(const startree_t* s, const double* xyzcenter, double radius2,
double** xyzresults, double** radecresults, int* nresults);
/**
Reads a column of data from the "tag-along" table.
Get the "inds" and "N" from "startree_search" or "startree_search_for".
To get all entries, set "inds" = NULL and N = startree_N().
The return value is a newly-allocated array of size N. It should be
freed using "startree_free_data_column"
*/
Malloc
double* startree_get_data_column(startree_t* s, const char* colname, const int* indices, int N);
/**
Same as startree_get_data_column but for int64_t. Don't you love C templating?
*/
Malloc
int64_t* startree_get_data_column_int64(startree_t* s, const char* colname, const int* indices, int N);
/**
Reads a column of data from the "tag-along" table.
The column may be an array (that is, each row contains multiple
entries); the array size is placed in "arraysize".
The array entries
*/
Malloc
double* startree_get_data_column_array(startree_t* s, const char* colname, const int* indices, int N, int* arraysize);
void startree_free_data_column(startree_t* s, double* d);
anbool startree_has_tagalong(startree_t* s);
fitstable_t* startree_get_tagalong(startree_t* s);
/*
Returns a string-list of the names of the columns in the "tagalong" table of this star kdtree.
If you pass in a non-NULL "lst", the names will be added to that list; otherwise, a new sl*
will be allocated (free it with sl_free2()).
If you want to avoid "sl*", see:
-- startree_get_tagalong_N_columns(s)
-- startree_get_tagalong_column_name(s, i)
*/
sl* startree_get_tagalong_column_names(startree_t* s, sl* lst);
/**
Returns the number of columns in the tagalong table.
*/
int startree_get_tagalong_N_columns(startree_t* s);
/**
Returns the name of the 'i'th column in the tagalong table.
The lifetime of the returned string is the lifetime of this starkd.
*/
const char* startree_get_tagalong_column_name(startree_t* s, int i);
/**
Returns the FITS type of the 'i'th column in the tagalong table.
*/
tfits_type startree_get_tagalong_column_fits_type(startree_t* s, int i);
/**
Returns the array size of the 'i'th column in the tagalong table.
For scalar columns, this is 1.
*/
int startree_get_tagalong_column_array_size(startree_t* s, int i);
/*
Retrieve parameters of the cut-an process, if they are available.
Older index files may not have these header cards.
*/
// healpix nside, or -1
int startree_get_cut_nside(const startree_t* s);
int startree_get_cut_nsweeps(const startree_t* s);
// in arcsec; 0 if none.
double startree_get_cut_dedup(const startree_t* s);
// band (one of several static strings), or NULL
char* startree_get_cut_band(const startree_t* s);
// margin, in healpix, or -1
int startree_get_cut_margin(const startree_t* s);
double startree_get_jitter(const startree_t* s);
void startree_set_jitter(startree_t* s, double jitter_arcsec);
//uint64_t startree_get_starid(const startree_t* s, int ind);
// returns the sweep number of star 'ind', or -1 if the index is out of bounds
// or the tree has no sweep numbers.
int startree_get_sweep(const startree_t* s, int ind);
int startree_N(const startree_t* s);
int startree_nodes(const startree_t* s);
int startree_D(const startree_t* s);
qfits_header* startree_header(const startree_t* s);
int startree_get(startree_t* s, int starid, double* posn);
int startree_get_radec(startree_t* s, int starid, double* ra, double* dec);
int startree_close(startree_t* s);
void startree_compute_inverse_perm(startree_t* s);
int startree_check_inverse_perm(startree_t* s);
// for writing
startree_t* startree_new(void);
int startree_write_to_file(startree_t* s, const char* fn);
int startree_write_to_file_flipped(startree_t* s, const char* fn);
int startree_append_to(startree_t* s, FILE* fid);
#endif
| bsd-3-clause |
greggman/other-window-ipc | lib/ipc-stream.js | 1463 | "use strict";
const debug = require('debug')('ipc-stream');
const EventEmitter = require('events');
class IPCStream extends EventEmitter {
// otherWindowId is the id of the window
// channelId is the id of the service you want to communicate wth
// running in that other window
constructor(closeFn, remote, localStreamId, channelId) {
super();
this._closeFn = closeFn; // so we can close
this._remote = remote;
this._localStreamId = localStreamId;
this._remoteStreamId;
this._channelId = channelId; // this is for debugging only
}
// DO NOT CALL this (it is called by IPChannel
setRemoteStreamId(remoteStreamId) {
debug("setRemoteStream:", remoteStreamId);
if (this._remoteStreamId) {
throw new Error("remoteStreamId already set");
}
this._remoteStreamId = remoteStreamId;
}
send(...args) {
if (!this._remoteStreamId) {
throw new Error("remoteStreamId not set");
}
this._remote.send('relay', this._remoteStreamId, ...args);
}
// do not call this directly
disconnect() {
debug("disconnect stream:", this._remoteStreamId, this._channelId);
this.emit('disconnect');
this._remoteStreamId = null;
}
close() {
debug("close:", this._localStreamId, this._channelId);
if (this._remoteStreamId) {
this._closeFn();
this._remote.send('disconnect', this._remoteStreamId);
this._remoteStreamId = null;
}
}
}
module.exports = IPCStream;
| bsd-3-clause |
zackgalbreath/CDash | models/buildupdatefile.php | 3579 | <?php
/*=========================================================================
Program: CDash - Cross-Platform Dashboard System
Module: $Id: buildupdatefile.php 3179 2012-02-13 08:59:24Z jjomier $
Language: PHP
Date: $Date: 2012-02-13 08:59:24 +0000 (Mon, 13 Feb 2012) $
Version: $Revision: 3179 $
Copyright (c) 2002 Kitware, Inc. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// It is assumed that appropriate headers should be included before including this file
class BuildUpdateFile
{
var $Filename;
var $CheckinDate;
var $Author;
var $Email;
var $Committer;
var $CommitterEmail;
var $Log;
var $Revision;
var $PriorRevision;
var $Status; //MODIFIED | CONFLICTING | UPDATED
var $UpdateId;
// Insert the update
function Insert()
{
if(strlen($this->UpdateId)==0)
{
echo "BuildUpdateFile:Insert UpdateId not set";
return false;
}
$this->Filename = pdo_real_escape_string($this->Filename);
// Sometimes the checkin date is not found in that case we put the usual date
if($this->CheckinDate == "Unknown")
{
$this->CheckinDate = "1980-01-01";
}
if(strtotime($this->CheckinDate) === false && is_numeric($this->CheckinDate))
{
$this->CheckinDate = date(FMT_DATETIME,$this->CheckinDate);
}
else if(strtotime($this->CheckinDate) !== false)
{
$this->CheckinDate = date(FMT_DATETIME,strtotime($this->CheckinDate));
}
else
{
$this->CheckinDate = "1980-01-01";
}
$this->Author = pdo_real_escape_string($this->Author);
$this->UpdateId = pdo_real_escape_string($this->UpdateId);
// Check if we have a robot file for this build
$robot = pdo_query("SELECT authorregex FROM projectrobot,build,build2update
WHERE projectrobot.projectid=build.projectid
AND build2update.buildid=build.id
AND build2update.updateid=".qnum($this->UpdateId)." AND robotname='".$this->Author."'");
if(pdo_num_rows($robot)>0)
{
$robot_array = pdo_fetch_array($robot);
$regex = $robot_array['authorregex'];
preg_match($regex,$this->Log,$matches);
if(isset($matches[1]))
{
$this->Author = $matches[1];
}
}
$this->Email = pdo_real_escape_string($this->Email);
$this->Committer = pdo_real_escape_string($this->Committer);
$this->CommitterEmail = pdo_real_escape_string($this->CommitterEmail);
$this->Log = pdo_real_escape_string($this->Log);
$this->Revision = pdo_real_escape_string($this->Revision);
$this->PriorRevision = pdo_real_escape_string($this->PriorRevision);
$query = "INSERT INTO updatefile (updateid,filename,checkindate,author,email,log,revision,priorrevision,status,committer,committeremail)
VALUES (".qnum($this->UpdateId).",'$this->Filename','$this->CheckinDate','$this->Author','$this->Email',
'$this->Log','$this->Revision','$this->PriorRevision','$this->Status','$this->Committer','$this->CommitterEmail')";
if(!pdo_query($query))
{
add_last_sql_error("BuildUpdateFile Insert",0,$this->UpdateId);
return false;
}
} // end function insert
}
?>
| bsd-3-clause |
Bysmyyr/chromium-crosswalk | third_party/WebKit/Source/core/inspector/AsyncCallChain.cpp | 1222 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/inspector/AsyncCallChain.h"
#include "wtf/text/WTFString.h"
namespace blink {
AsyncCallStack::AsyncCallStack(const String& description, v8::Local<v8::Object> callFrames)
: m_description(description)
, m_callFrames(callFrames->GetIsolate(), callFrames)
{
}
AsyncCallStack::~AsyncCallStack()
{
}
PassRefPtr<AsyncCallChain> AsyncCallChain::create(PassRefPtr<AsyncCallStack> stack, AsyncCallChain* prevChain, unsigned asyncCallChainMaxLength)
{
return adoptRef(new AsyncCallChain(stack, prevChain, asyncCallChainMaxLength));
}
AsyncCallChain::AsyncCallChain(PassRefPtr<AsyncCallStack> stack, AsyncCallChain* prevChain, unsigned asyncCallChainMaxLength)
{
if (stack)
m_callStacks.append(stack);
if (prevChain) {
const AsyncCallStackVector& other = prevChain->m_callStacks;
for (size_t i = 0; i < other.size() && m_callStacks.size() < asyncCallChainMaxLength; i++)
m_callStacks.append(other[i]);
}
}
AsyncCallChain::~AsyncCallChain()
{
}
} // namespace blink
| bsd-3-clause |
wavebitscientific/wavy | docs/proc/getcurrent_u.html | 66618 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="A spectral ocean wave modeling framework">
<meta name="author" content="Wavebit Scientific LLC" >
<link rel="icon" href="../favicon.png">
<title>getCurrent_u – wavy</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/pygments.css" rel="stylesheet">
<link href="../css/font-awesome.min.css" rel="stylesheet">
<link href="../css/local.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[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]-->
<script src="../js/jquery-2.1.3.min.js"></script>
<script src="../js/svg-pan-zoom.min.js"></script>
<script src="../tipuesearch/tipuesearch_content.js"></script>
<link href="../tipuesearch/tipuesearch.css" rel="stylesheet">
<script src="../tipuesearch/tipuesearch_set.js"></script>
<script src="../tipuesearch/tipuesearch.js"></script>
</head>
<body>
<!-- Fixed navbar -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">wavy </a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown hidden-xs visible-sm visible-md hidden-lg">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button"
aria-haspopup="true"
aria-expanded="false">Contents <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="../lists/files.html">Source Files</a></li>
<li><a href="../lists/modules.html">Modules</a></li>
<li><a href="../lists/procedures.html">Procedures</a></li>
<li><a href="../lists/types.html">Derived Types</a></li>
</ul>
</li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/files.html">Source Files</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/modules.html">Modules</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/procedures.html">Procedures</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/types.html">Derived Types</a></li>
</ul>
<form action="../search.html" class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="q" id="tipue_search_input" autocomplete="off" required>
</div>
<!--
<button type="submit" class="btn btn-default">Submit</button>
-->
</form>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="row">
<h1>getCurrent_u
<small>Function</small>
</h1>
<div class="row">
<div class="col-lg-12">
<div class="well well-sm">
<ul class="list-inline" style="margin-bottom:0px;display:inline">
<li><i class="fa fa-list-ol"></i>
<a data-toggle="tooltip"
data-placement="bottom" data-html="true"
title=" 0.6% of total for procedures.">13 statements</a>
</li>
<li><i class="fa fa-code"></i><a href="../src/mod_domain.f90"> Source File</a></li>
</ul>
<ol class="breadcrumb in-well text-right">
<li><a href='../sourcefile/mod_domain.f90.html'>mod_domain.f90</a></li>
<li><a href='../module/mod_domain.html'>mod_domain</a></li>
<li class="active">getCurrent_u</li>
</ol>
</div>
</div>
</div>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
</div>
<div class="row">
<div class="col-md-3 hidden-xs hidden-sm visible-md visible-lg">
<div id="sidebar">
<div class="panel panel-primary">
<div class="panel-heading text-left"><h3 class="panel-title">Source Code</h3></div>
<div class="list-group">
<a class="list-group-item" href="../proc/getcurrent_u.html#src">getCurrent_u</a>
</div>
</div>
<hr>
<div class="panel panel-default">
<div class="panel-heading text-left"><h3 class="panel-title"><a data-toggle="collapse" href="#allprocs-0">All Procedures</a></h3></div>
<div id="allprocs-0" class="panel-collapse collapse">
<div class="list-group">
<a class="list-group-item" href="../proc/advect1drank1.html">advect1dRank1</a>
<a class="list-group-item" href="../proc/advect1drank2.html">advect1dRank2</a>
<a class="list-group-item" href="../proc/advect2drank2.html">advect2dRank2</a>
<a class="list-group-item" href="../interface/advectcentered2ndorder.html">advectCentered2ndOrder</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank0.html">advectCentered2ndOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank1.html">advectCentered2ndOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank2.html">advectCentered2ndOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank0.html">advectCentered2ndOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank1.html">advectCentered2ndOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank2.html">advectCentered2ndOrder2dRank2</a>
<a class="list-group-item" href="../interface/advectupwind1storder.html">advectUpwind1stOrder</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank0.html">advectUpwind1stOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank1.html">advectUpwind1stOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank2.html">advectUpwind1stOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank0.html">advectUpwind1stOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank1.html">advectUpwind1stOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank2.html">advectUpwind1stOrder2dRank2</a>
<a class="list-group-item" href="../proc/assign_array_1d.html">assign_array_1d</a>
<a class="list-group-item" href="../proc/assign_array_2d.html">assign_array_2d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_1d.html">assign_spectrum_array_1d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_2d.html">assign_spectrum_array_2d</a>
<a class="list-group-item" href="../interface/backward_euler.html">backward_euler</a>
<a class="list-group-item" href="../proc/backward_euler_domain.html">backward_euler_domain</a>
<a class="list-group-item" href="../proc/backward_euler_spectrum.html">backward_euler_spectrum</a>
<a class="list-group-item" href="../proc/constructor.html">constructor</a>
<a class="list-group-item" href="../proc/constructor%7E2.html">constructor</a>
<a class="list-group-item" href="../proc/constructor_1d.html">constructor_1d</a>
<a class="list-group-item" href="../proc/constructor_2d.html">constructor_2d</a>
<a class="list-group-item" href="../interface/diff.html">diff</a>
<a class="list-group-item" href="../proc/diff_1d.html">diff_1d</a>
<a class="list-group-item" href="../proc/diff_2d.html">diff_2d</a>
<a class="list-group-item" href="../interface/diff_periodic.html">diff_periodic</a>
<a class="list-group-item" href="../proc/diff_periodic_1d.html">diff_periodic_1d</a>
<a class="list-group-item" href="../proc/diff_periodic_2d.html">diff_periodic_2d</a>
<a class="list-group-item" href="../proc/domain_add_domain.html">domain_add_domain</a>
<a class="list-group-item" href="../proc/domain_add_real.html">domain_add_real</a>
<a class="list-group-item" href="../proc/domain_div_domain.html">domain_div_domain</a>
<a class="list-group-item" href="../proc/domain_div_real.html">domain_div_real</a>
<a class="list-group-item" href="../proc/domain_mult_domain.html">domain_mult_domain</a>
<a class="list-group-item" href="../proc/domain_mult_real.html">domain_mult_real</a>
<a class="list-group-item" href="../proc/domain_sub_domain.html">domain_sub_domain</a>
<a class="list-group-item" href="../proc/domain_sub_real.html">domain_sub_real</a>
<a class="list-group-item" href="../interface/domain_type.html">domain_type</a>
<a class="list-group-item" href="../proc/domain_unary_minus.html">domain_unary_minus</a>
<a class="list-group-item" href="../proc/donelanhamiltonhui.html">donelanHamiltonHui</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspectrum.html">donelanHamiltonHuiDirectionalSpectrum</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspreading.html">donelanHamiltonHuiDirectionalSpreading</a>
<a class="list-group-item" href="../proc/elevation.html">elevation</a>
<a class="list-group-item" href="../proc/eq.html">eq</a>
<a class="list-group-item" href="../proc/eq%7E2.html">eq</a>
<a class="list-group-item" href="../interface/exact_exponential.html">exact_exponential</a>
<a class="list-group-item" href="../proc/exact_exponential_domain.html">exact_exponential_domain</a>
<a class="list-group-item" href="../proc/exact_exponential_spectrum.html">exact_exponential_spectrum</a>
<a class="list-group-item" href="../interface/forward_euler.html">forward_euler</a>
<a class="list-group-item" href="../proc/forward_euler_domain.html">forward_euler_domain</a>
<a class="list-group-item" href="../proc/forward_euler_spectrum.html">forward_euler_spectrum</a>
<a class="list-group-item" href="../proc/frequencymoment.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/frequencymoment%7E2.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/ge.html">ge</a>
<a class="list-group-item" href="../proc/getairdensity.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getairdensity%7E2.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getamplitude.html">getAmplitude</a>
<a class="list-group-item" href="../proc/getaxisx.html">getAxisX</a>
<a class="list-group-item" href="../proc/getaxisy.html">getAxisY</a>
<a class="list-group-item" href="../proc/getcurrent_u.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_u%7E2.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_v.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getcurrent_v%7E2.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getdepth.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepth%7E2.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepthlevels.html">getDepthLevels</a>
<a class="list-group-item" href="../proc/getdirections.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections%7E2.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections2d.html">getDirections2d</a>
<a class="list-group-item" href="../proc/getelevation.html">getElevation</a>
<a class="list-group-item" href="../proc/getelevation%7E2.html">getElevation</a>
<a class="list-group-item" href="../proc/getfrequency.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency%7E2.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency2d.html">getFrequency2d</a>
<a class="list-group-item" href="../proc/getgravity.html">getGravity</a>
<a class="list-group-item" href="../proc/getgravity%7E2.html">getGravity</a>
<a class="list-group-item" href="../proc/getgrid.html">getGrid</a>
<a class="list-group-item" href="../proc/getgridrotation.html">getGridRotation</a>
<a class="list-group-item" href="../proc/getgridspacingx.html">getGridSpacingX</a>
<a class="list-group-item" href="../proc/getgridspacingxwithhalo.html">getGridSpacingXWithHalo</a>
<a class="list-group-item" href="../proc/getgridspacingy.html">getGridSpacingY</a>
<a class="list-group-item" href="../proc/getgridspacingywithhalo.html">getGridSpacingYWithHalo</a>
<a class="list-group-item" href="../proc/getgroupspeed.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed%7E2.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed2d.html">getGroupSpeed2d</a>
<a class="list-group-item" href="../proc/getlatitude.html">getLatitude</a>
<a class="list-group-item" href="../proc/getlongitude.html">getLongitude</a>
<a class="list-group-item" href="../proc/getlowerbounds.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getlowerbounds%7E2.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getphasespeed.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed%7E2.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed2d.html">getPhaseSpeed2d</a>
<a class="list-group-item" href="../proc/getspectrum.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrum%7E2.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrumarray.html">getSpectrumArray</a>
<a class="list-group-item" href="../proc/getsurfacetension.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getsurfacetension%7E2.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getupperbounds.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getupperbounds%7E2.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getwaterdensity.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaterdensity%7E2.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaveaction.html">getWaveAction</a>
<a class="list-group-item" href="../proc/getwavelength.html">getWavelength</a>
<a class="list-group-item" href="../proc/getwavenumber.html">getWavenumber</a>
<a class="list-group-item" href="../proc/getwavenumber2d.html">getWavenumber2d</a>
<a class="list-group-item" href="../proc/getwavenumberspacing.html">getWavenumberSpacing</a>
<a class="list-group-item" href="../proc/gravityclairaut.html">gravityClairaut</a>
<a class="list-group-item" href="../interface/grid_type.html">grid_type</a>
<a class="list-group-item" href="../proc/gt.html">gt</a>
<a class="list-group-item" href="../proc/horizontalacceleration.html">horizontalAcceleration</a>
<a class="list-group-item" href="../proc/horizontalvelocity.html">horizontalVelocity</a>
<a class="list-group-item" href="../interface/integrate.html">integrate</a>
<a class="list-group-item" href="../proc/integrate_domain.html">integrate_domain</a>
<a class="list-group-item" href="../proc/integrate_spectrum.html">integrate_spectrum</a>
<a class="list-group-item" href="../proc/isallocated.html">isAllocated</a>
<a class="list-group-item" href="../proc/isallocated%7E2.html">isAllocated</a>
<a class="list-group-item" href="../proc/ismonochromatic.html">isMonochromatic</a>
<a class="list-group-item" href="../proc/isomnidirectional.html">isOmnidirectional</a>
<a class="list-group-item" href="../proc/jonswap.html">jonswap</a>
<a class="list-group-item" href="../proc/jonswappeakfrequency.html">jonswapPeakFrequency</a>
<a class="list-group-item" href="../proc/le.html">le</a>
<a class="list-group-item" href="../proc/lt.html">lt</a>
<a class="list-group-item" href="../proc/meanperiod.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiod%7E2.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing%7E2.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meansquareslope.html">meanSquareSlope</a>
<a class="list-group-item" href="../proc/meansquareslopedirectional.html">meanSquareSlopeDirectional</a>
<a class="list-group-item" href="../proc/momentum_x.html">momentum_x</a>
<a class="list-group-item" href="../proc/momentum_y.html">momentum_y</a>
<a class="list-group-item" href="../proc/momentumflux_xx.html">momentumFlux_xx</a>
<a class="list-group-item" href="../proc/momentumflux_xy.html">momentumFlux_xy</a>
<a class="list-group-item" href="../proc/momentumflux_yy.html">momentumFlux_yy</a>
<a class="list-group-item" href="../proc/neq.html">neq</a>
<a class="list-group-item" href="../proc/neq%7E2.html">neq</a>
<a class="list-group-item" href="../proc/nondimensionaldepth.html">nondimensionalDepth</a>
<a class="list-group-item" href="../proc/nondimensionalenergy.html">nondimensionalEnergy</a>
<a class="list-group-item" href="../proc/nondimensionalfetch.html">nondimensionalFetch</a>
<a class="list-group-item" href="../proc/nondimensionalfrequency.html">nondimensionalFrequency</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_h1986.html">nondimensionalRoughness_H1986</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_s1974.html">nondimensionalRoughness_S1974</a>
<a class="list-group-item" href="../proc/nondimensionaltime.html">nondimensionalTime</a>
<a class="list-group-item" href="../proc/omnidirectionalspectrum.html">omnidirectionalSpectrum</a>
<a class="list-group-item" href="../interface/ones.html">ones</a>
<a class="list-group-item" href="../proc/ones_int.html">ones_int</a>
<a class="list-group-item" href="../proc/ones_real.html">ones_real</a>
<a class="list-group-item" href="../proc/peakedness.html">peakedness</a>
<a class="list-group-item" href="../proc/peakfrequency.html">peakFrequency</a>
<a class="list-group-item" href="../proc/peakfrequencydiscrete.html">peakFrequencyDiscrete</a>
<a class="list-group-item" href="../proc/phillips.html">phillips</a>
<a class="list-group-item" href="../proc/piersonmoskowitz.html">piersonMoskowitz</a>
<a class="list-group-item" href="../proc/piersonmoskowitzpeakfrequency.html">piersonMoskowitzPeakFrequency</a>
<a class="list-group-item" href="../proc/pressure.html">pressure</a>
<a class="list-group-item" href="../interface/range.html">range</a>
<a class="list-group-item" href="../proc/range_int.html">range_int</a>
<a class="list-group-item" href="../proc/range_real.html">range_real</a>
<a class="list-group-item" href="../proc/readjson.html">readJSON</a>
<a class="list-group-item" href="../proc/real2d_mult_spectrum.html">real2d_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_add_domain.html">real_add_domain</a>
<a class="list-group-item" href="../proc/real_add_spectrum.html">real_add_spectrum</a>
<a class="list-group-item" href="../proc/real_div_domain.html">real_div_domain</a>
<a class="list-group-item" href="../proc/real_div_spectrum.html">real_div_spectrum</a>
<a class="list-group-item" href="../proc/real_mult_domain.html">real_mult_domain</a>
<a class="list-group-item" href="../proc/real_mult_spectrum.html">real_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_sub_domain.html">real_sub_domain</a>
<a class="list-group-item" href="../proc/real_sub_spectrum.html">real_sub_spectrum</a>
<a class="list-group-item" href="../proc/saturationspectrum.html">saturationSpectrum</a>
<a class="list-group-item" href="../proc/sbf_dccm2012.html">sbf_DCCM2012</a>
<a class="list-group-item" href="../proc/sbf_jonswap.html">sbf_JONSWAP</a>
<a class="list-group-item" href="../proc/sds_dccm2012.html">sds_DCCM2012</a>
<a class="list-group-item" href="../proc/sdt_dccm2012.html">sdt_DCCM2012</a>
<a class="list-group-item" href="../proc/setairdensity.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setairdensity%7E2.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setcurrent1d.html">setCurrent1d</a>
<a class="list-group-item" href="../proc/setcurrent2d.html">setCurrent2d</a>
<a class="list-group-item" href="../proc/setdepth.html">setDepth</a>
<a class="list-group-item" href="../proc/setdepth%7E2.html">setDepth</a>
<a class="list-group-item" href="../proc/setelevation.html">setElevation</a>
<a class="list-group-item" href="../proc/setelevation%7E2.html">setElevation</a>
<a class="list-group-item" href="../proc/setgravity.html">setGravity</a>
<a class="list-group-item" href="../proc/setgravity%7E2.html">setGravity</a>
<a class="list-group-item" href="../proc/setspectrum1d.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum1d%7E2.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum2d.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrum2d%7E2.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d1d.html">setSpectrumArray1d1d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d2d.html">setSpectrumArray1d2d</a>
<a class="list-group-item" href="../proc/setspectrumarray2d2d.html">setSpectrumArray2d2d</a>
<a class="list-group-item" href="../proc/setsurfacetension.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setsurfacetension%7E2.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setwaterdensity.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/setwaterdensity%7E2.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/significantsurfaceorbitalvelocity.html">significantSurfaceOrbitalVelocity</a>
<a class="list-group-item" href="../proc/significantwaveheight.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/significantwaveheight%7E2.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/sin_dccm2012.html">sin_DCCM2012</a>
<a class="list-group-item" href="../proc/snl_dccm2012.html">snl_DCCM2012</a>
<a class="list-group-item" href="../proc/spectrum_add_real.html">spectrum_add_real</a>
<a class="list-group-item" href="../proc/spectrum_add_spectrum.html">spectrum_add_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_div_real.html">spectrum_div_real</a>
<a class="list-group-item" href="../proc/spectrum_div_spectrum.html">spectrum_div_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_mult_real.html">spectrum_mult_real</a>
<a class="list-group-item" href="../proc/spectrum_mult_real2d.html">spectrum_mult_real2d</a>
<a class="list-group-item" href="../proc/spectrum_mult_spectrum.html">spectrum_mult_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_sub_real.html">spectrum_sub_real</a>
<a class="list-group-item" href="../proc/spectrum_sub_spectrum.html">spectrum_sub_spectrum</a>
<a class="list-group-item" href="../interface/spectrum_type.html">spectrum_type</a>
<a class="list-group-item" href="../proc/spectrum_unary_minus.html">spectrum_unary_minus</a>
<a class="list-group-item" href="../proc/stokesdrift.html">stokesDrift</a>
<a class="list-group-item" href="../proc/stokesdrift2d.html">stokesDrift2d</a>
<a class="list-group-item" href="../interface/tile.html">tile</a>
<a class="list-group-item" href="../proc/tile_1d_int.html">tile_1d_int</a>
<a class="list-group-item" href="../proc/tile_1d_real.html">tile_1d_real</a>
<a class="list-group-item" href="../proc/tile_2d_int.html">tile_2d_int</a>
<a class="list-group-item" href="../proc/tile_2d_real.html">tile_2d_real</a>
<a class="list-group-item" href="../proc/tile_3d_int.html">tile_3d_int</a>
<a class="list-group-item" href="../proc/tile_3d_real.html">tile_3d_real</a>
<a class="list-group-item" href="../proc/ursellnumber.html">ursellNumber</a>
<a class="list-group-item" href="../proc/verticalacceleration.html">verticalAcceleration</a>
<a class="list-group-item" href="../proc/verticalvelocity.html">verticalVelocity</a>
<a class="list-group-item" href="../proc/waveage.html">waveAge</a>
<a class="list-group-item" href="../proc/wavenumber.html">wavenumber</a>
<a class="list-group-item" href="../proc/wavenumbermoment.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumbermoment%7E2.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumberspectrum.html">wavenumberSpectrum</a>
<a class="list-group-item" href="../proc/writejson.html">writeJSON</a>
<a class="list-group-item" href="../proc/writejson%7E2.html">writeJSON</a>
<a class="list-group-item" href="../interface/zeros.html">zeros</a>
<a class="list-group-item" href="../proc/zeros_int.html">zeros_int</a>
<a class="list-group-item" href="../proc/zeros_real.html">zeros_real</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-9" id='text'>
<h2>
private pure function getCurrent_u(self) result(u)
</h2>
<p>Returns the 3-d array with values of Eulerian velocity (mean current) in
x-direction [m/s].</p>
<p>Note: this implementation assumes that all u and v velocity arrays in
the domain instance are of same length in depth, such that the resulting
u and v arrays are regular 3-d arrays.</p>
<h3>Arguments</h3>
<table class="table table-striped varlist">
<thead><tr><th>Type</th>
<th>Intent</th><th>Optional</th>
<th>Attributes</th><th></th><th>Name</th><th></th></thead>
<tbody>
<tr>
<td><span class="anchor" id="variable-self%7E29"></span>class(<a href='../type/domain_type.html'>domain_type</a>),</td>
<td>intent(in)</td>
<td></td>
<td></td><td>::</td>
<td><strong>self</strong></td><td><p>Domain instance</p></td>
</tr>
</tbody>
</table>
<h3>Return Value <small><span class="anchor" id="variable-u%7E3"></span>real(kind=rk),
dimension(:,:,:),allocatable</small></h3>
<p>Eulerian u-velocity [m/s]</p>
<h3>Calls</h3>
<div class="depgraph"><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: proc~~getcurrent_u~~CallsGraph Pages: 1 -->
<svg id="procgetcurrent_uCallsGraph" width="177pt" height="116pt"
viewBox="0.00 0.00 177.00 116.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="proc~~getcurrent_u~~CallsGraph" class="graph" transform="scale(1 1) rotate(0) translate(4 112)">
<title>proc~~getcurrent_u~~CallsGraph</title>
<polygon fill="white" stroke="none" points="-4,4 -4,-112 173,-112 173,4 -4,4"/>
<!-- proc~getcurrent_u -->
<g id="proc~~getcurrent_u~~CallsGraph_node1" class="node"><title>proc~getcurrent_u</title>
<polygon fill="none" stroke="black" points="76,-66 0,-66 0,-42 76,-42 76,-66"/>
<text text-anchor="middle" x="38" y="-51.6" font-family="Helvetica,sans-Serif" font-size="10.50">getCurrent_u</text>
</g>
<!-- proc~getcurrent_u->proc~getcurrent_u -->
<g id="proc~~getcurrent_u~~CallsGraph_edge4" class="edge"><title>proc~getcurrent_u->proc~getcurrent_u</title>
<path fill="none" stroke="#000000" d="M21.1349,-66.0139C15.2455,-74.9717 20.8672,-84 38,-84 48.4403,-84 54.6061,-80.6474 56.4974,-76.0013"/>
<polygon fill="#000000" stroke="#000000" points="59.9323,-75.3184 54.8651,-66.0139 53.024,-76.4475 59.9323,-75.3184"/>
</g>
<!-- lb -->
<g id="proc~~getcurrent_u~~CallsGraph_node2" class="node"><title>lb</title>
<polygon fill="#777777" stroke="#777777" points="167.5,-108 113.5,-108 113.5,-84 167.5,-84 167.5,-108"/>
<text text-anchor="middle" x="140.5" y="-93.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">lb</text>
</g>
<!-- proc~getcurrent_u->lb -->
<g id="proc~~getcurrent_u~~CallsGraph_edge1" class="edge"><title>proc~getcurrent_u->lb</title>
<path fill="none" stroke="#000000" d="M67.7993,-66.0355C79.1497,-70.779 92.2978,-76.2737 104.211,-81.2525"/>
<polygon fill="#000000" stroke="#000000" points="102.867,-84.4839 113.443,-85.1105 105.566,-78.0252 102.867,-84.4839"/>
</g>
<!-- ub -->
<g id="proc~~getcurrent_u~~CallsGraph_node3" class="node"><title>ub</title>
<polygon fill="#777777" stroke="#777777" points="167.5,-66 113.5,-66 113.5,-42 167.5,-42 167.5,-66"/>
<text text-anchor="middle" x="140.5" y="-51.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">ub</text>
</g>
<!-- proc~getcurrent_u->ub -->
<g id="proc~~getcurrent_u~~CallsGraph_edge2" class="edge"><title>proc~getcurrent_u->ub</title>
<path fill="none" stroke="#000000" d="M76.137,-54C85.059,-54 94.574,-54 103.446,-54"/>
<polygon fill="#000000" stroke="#000000" points="103.491,-57.5001 113.491,-54 103.491,-50.5001 103.491,-57.5001"/>
</g>
<!-- spectrum -->
<g id="proc~~getcurrent_u~~CallsGraph_node4" class="node"><title>spectrum</title>
<polygon fill="#777777" stroke="#777777" points="169,-24 112,-24 112,-0 169,-0 169,-24"/>
<text text-anchor="middle" x="140.5" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">spectrum</text>
</g>
<!-- proc~getcurrent_u->spectrum -->
<g id="proc~~getcurrent_u~~CallsGraph_edge3" class="edge"><title>proc~getcurrent_u->spectrum</title>
<path fill="none" stroke="#000000" d="M67.7993,-41.9645C78.5842,-37.4573 90.9921,-32.272 102.422,-27.4954"/>
<polygon fill="#000000" stroke="#000000" points="103.858,-30.6884 111.735,-23.6031 101.159,-24.2297 103.858,-30.6884"/>
</g>
</g>
</svg>
</div>
<div><a type="button" class="graph-help" data-toggle="modal" href="#graph-help-text">Help</a></div>
<div class="modal fade" id="graph-help-text" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="-graph-help-label">Graph Key</h4>
</div>
<div class="modal-body">
<p>Nodes of different colours represent the following: </p>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: Graph Key Pages: 1 -->
<svg width="560pt" height="32pt"
viewBox="0.00 0.00 559.50 32.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 28)">
<title>Graph Key</title>
<polygon fill="white" stroke="none" points="-4,4 -4,-28 555.5,-28 555.5,4 -4,4"/>
<!-- Subroutine -->
<g id="node1" class="node"><title>Subroutine</title>
<polygon fill="#d9534f" stroke="#d9534f" points="64,-24 0,-24 0,-0 64,-0 64,-24"/>
<text text-anchor="middle" x="32" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Subroutine</text>
</g>
<!-- Function -->
<g id="node2" class="node"><title>Function</title>
<polygon fill="#d94e8f" stroke="#d94e8f" points="136,-24 82,-24 82,-0 136,-0 136,-24"/>
<text text-anchor="middle" x="109" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Function</text>
</g>
<!-- Interface -->
<g id="node3" class="node"><title>Interface</title>
<polygon fill="#a7506f" stroke="#a7506f" points="209.5,-24 154.5,-24 154.5,-0 209.5,-0 209.5,-24"/>
<text text-anchor="middle" x="182" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Interface</text>
</g>
<!-- Unknown Procedure Type -->
<g id="node4" class="node"><title>Unknown Procedure Type</title>
<polygon fill="#777777" stroke="#777777" points="364,-24 228,-24 228,-0 364,-0 364,-24"/>
<text text-anchor="middle" x="296" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Unknown Procedure Type</text>
</g>
<!-- Program -->
<g id="node5" class="node"><title>Program</title>
<polygon fill="#f0ad4e" stroke="#f0ad4e" points="436,-24 382,-24 382,-0 436,-0 436,-24"/>
<text text-anchor="middle" x="409" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Program</text>
</g>
<!-- This Page's Entity -->
<g id="node6" class="node"><title>This Page's Entity</title>
<polygon fill="none" stroke="black" points="551.5,-24 454.5,-24 454.5,-0 551.5,-0 551.5,-24"/>
<text text-anchor="middle" x="503" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50">This Page's Entity</text>
</g>
</g>
</svg>
<p>Solid arrows point from a procedure to one which it calls. Dashed
arrows point from an interface to procedures which implement that interface.
This could include the module procedures in a generic interface or the
implementation in a submodule of an interface in a parent module.
</p>
</div>
</div>
</div>
</div>
<br>
<section class="visible-xs visible-sm hidden-md">
<div class="panel panel-primary">
<div class="panel-heading text-left"><h3 class="panel-title">Source Code</h3></div>
<div class="list-group">
<a class="list-group-item" href="../proc/getcurrent_u.html#src">getCurrent_u</a>
</div>
</div>
</section>
<br class="visible-xs visible-sm hidden-md">
<section>
<h2><span class="anchor" id="src"></span>Source Code</h2>
<div class="highlight"><pre><span></span><span class="k">pure function </span><span class="n">getCurrent_u</span><span class="p">(</span><span class="n">self</span><span class="p">)</span> <span class="k">result</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="c">!! Returns the 3-d array with values of Eulerian velocity (mean current) in </span>
<span class="c">!! x-direction [m/s].</span>
<span class="c">!!</span>
<span class="c">!! Note: this implementation assumes that all u and v velocity arrays in </span>
<span class="c">!! the domain instance are of same length in depth, such that the resulting</span>
<span class="c">!! u and v arrays are regular 3-d arrays.</span>
<span class="k">class</span><span class="p">(</span><span class="n">domain_type</span><span class="p">),</span><span class="k">intent</span><span class="p">(</span><span class="n">in</span><span class="p">)</span> <span class="kd">::</span> <span class="n">self</span>
<span class="c">!! Domain instance</span>
<span class="kt">real</span><span class="p">(</span><span class="nb">kind</span><span class="o">=</span><span class="n">rk</span><span class="p">),</span><span class="k">dimension</span><span class="p">(:,:,:),</span><span class="k">allocatable</span> <span class="kd">::</span> <span class="n">u</span>
<span class="c">!! Eulerian u-velocity [m/s]</span>
<span class="kt">integer</span><span class="p">(</span><span class="nb">kind</span><span class="o">=</span><span class="n">ik</span><span class="p">)</span> <span class="kd">::</span> <span class="n">i</span><span class="p">,</span><span class="n">j</span>
<span class="kt">integer</span><span class="p">(</span><span class="nb">kind</span><span class="o">=</span><span class="n">ik</span><span class="p">)</span> <span class="kd">::</span> <span class="n">kdm</span>
<span class="k">associate</span><span class="p">(</span><span class="n">lb</span> <span class="o">=></span> <span class="n">self</span> <span class="p">%</span> <span class="n">lb</span><span class="p">,</span><span class="n">ub</span> <span class="o">=></span> <span class="n">self</span> <span class="p">%</span> <span class="n">ub</span><span class="p">)</span>
<span class="n">kdm</span> <span class="o">=</span> <span class="n">size</span><span class="p">(</span><span class="n">self</span> <span class="p">%</span> <span class="n">spectrum</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span> <span class="p">%</span> <span class="n">getCurrent_u</span><span class="p">())</span>
<span class="k">allocate</span><span class="p">(</span><span class="n">u</span><span class="p">(</span><span class="n">lb</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span><span class="n">ub</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span><span class="n">lb</span><span class="p">(</span><span class="mi">2</span><span class="p">):</span><span class="n">ub</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span><span class="n">kdm</span><span class="p">))</span>
<span class="k">do </span><span class="n">concurrent</span><span class="p">(</span><span class="n">i</span><span class="o">=</span><span class="n">lb</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span><span class="n">ub</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span><span class="n">j</span><span class="o">=</span><span class="n">lb</span><span class="p">(</span><span class="mi">2</span><span class="p">):</span><span class="n">ub</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="n">u</span><span class="p">(</span><span class="n">i</span><span class="p">,</span><span class="n">j</span><span class="p">,:)</span> <span class="o">=</span> <span class="n">self</span> <span class="p">%</span> <span class="n">spectrum</span><span class="p">(</span><span class="n">i</span><span class="p">,</span><span class="n">j</span><span class="p">)</span> <span class="p">%</span> <span class="n">getCurrent_u</span><span class="p">()</span>
<span class="n">enddo</span>
<span class="n">endassociate</span>
<span class="n">endfunction</span> <span class="n">getCurrent_u</span>
</pre></div>
</section>
<br>
</div>
</div>
<section class="visible-xs visible-sm hidden-md">
<hr>
<div class="panel panel-default">
<div class="panel-heading text-left"><h3 class="panel-title"><a data-toggle="collapse" href="#allprocs-1">All Procedures</a></h3></div>
<div id="allprocs-1" class="panel-collapse collapse">
<div class="list-group">
<a class="list-group-item" href="../proc/advect1drank1.html">advect1dRank1</a>
<a class="list-group-item" href="../proc/advect1drank2.html">advect1dRank2</a>
<a class="list-group-item" href="../proc/advect2drank2.html">advect2dRank2</a>
<a class="list-group-item" href="../interface/advectcentered2ndorder.html">advectCentered2ndOrder</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank0.html">advectCentered2ndOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank1.html">advectCentered2ndOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank2.html">advectCentered2ndOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank0.html">advectCentered2ndOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank1.html">advectCentered2ndOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank2.html">advectCentered2ndOrder2dRank2</a>
<a class="list-group-item" href="../interface/advectupwind1storder.html">advectUpwind1stOrder</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank0.html">advectUpwind1stOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank1.html">advectUpwind1stOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank2.html">advectUpwind1stOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank0.html">advectUpwind1stOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank1.html">advectUpwind1stOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank2.html">advectUpwind1stOrder2dRank2</a>
<a class="list-group-item" href="../proc/assign_array_1d.html">assign_array_1d</a>
<a class="list-group-item" href="../proc/assign_array_2d.html">assign_array_2d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_1d.html">assign_spectrum_array_1d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_2d.html">assign_spectrum_array_2d</a>
<a class="list-group-item" href="../interface/backward_euler.html">backward_euler</a>
<a class="list-group-item" href="../proc/backward_euler_domain.html">backward_euler_domain</a>
<a class="list-group-item" href="../proc/backward_euler_spectrum.html">backward_euler_spectrum</a>
<a class="list-group-item" href="../proc/constructor.html">constructor</a>
<a class="list-group-item" href="../proc/constructor%7E2.html">constructor</a>
<a class="list-group-item" href="../proc/constructor_1d.html">constructor_1d</a>
<a class="list-group-item" href="../proc/constructor_2d.html">constructor_2d</a>
<a class="list-group-item" href="../interface/diff.html">diff</a>
<a class="list-group-item" href="../proc/diff_1d.html">diff_1d</a>
<a class="list-group-item" href="../proc/diff_2d.html">diff_2d</a>
<a class="list-group-item" href="../interface/diff_periodic.html">diff_periodic</a>
<a class="list-group-item" href="../proc/diff_periodic_1d.html">diff_periodic_1d</a>
<a class="list-group-item" href="../proc/diff_periodic_2d.html">diff_periodic_2d</a>
<a class="list-group-item" href="../proc/domain_add_domain.html">domain_add_domain</a>
<a class="list-group-item" href="../proc/domain_add_real.html">domain_add_real</a>
<a class="list-group-item" href="../proc/domain_div_domain.html">domain_div_domain</a>
<a class="list-group-item" href="../proc/domain_div_real.html">domain_div_real</a>
<a class="list-group-item" href="../proc/domain_mult_domain.html">domain_mult_domain</a>
<a class="list-group-item" href="../proc/domain_mult_real.html">domain_mult_real</a>
<a class="list-group-item" href="../proc/domain_sub_domain.html">domain_sub_domain</a>
<a class="list-group-item" href="../proc/domain_sub_real.html">domain_sub_real</a>
<a class="list-group-item" href="../interface/domain_type.html">domain_type</a>
<a class="list-group-item" href="../proc/domain_unary_minus.html">domain_unary_minus</a>
<a class="list-group-item" href="../proc/donelanhamiltonhui.html">donelanHamiltonHui</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspectrum.html">donelanHamiltonHuiDirectionalSpectrum</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspreading.html">donelanHamiltonHuiDirectionalSpreading</a>
<a class="list-group-item" href="../proc/elevation.html">elevation</a>
<a class="list-group-item" href="../proc/eq.html">eq</a>
<a class="list-group-item" href="../proc/eq%7E2.html">eq</a>
<a class="list-group-item" href="../interface/exact_exponential.html">exact_exponential</a>
<a class="list-group-item" href="../proc/exact_exponential_domain.html">exact_exponential_domain</a>
<a class="list-group-item" href="../proc/exact_exponential_spectrum.html">exact_exponential_spectrum</a>
<a class="list-group-item" href="../interface/forward_euler.html">forward_euler</a>
<a class="list-group-item" href="../proc/forward_euler_domain.html">forward_euler_domain</a>
<a class="list-group-item" href="../proc/forward_euler_spectrum.html">forward_euler_spectrum</a>
<a class="list-group-item" href="../proc/frequencymoment.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/frequencymoment%7E2.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/ge.html">ge</a>
<a class="list-group-item" href="../proc/getairdensity.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getairdensity%7E2.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getamplitude.html">getAmplitude</a>
<a class="list-group-item" href="../proc/getaxisx.html">getAxisX</a>
<a class="list-group-item" href="../proc/getaxisy.html">getAxisY</a>
<a class="list-group-item" href="../proc/getcurrent_u.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_u%7E2.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_v.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getcurrent_v%7E2.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getdepth.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepth%7E2.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepthlevels.html">getDepthLevels</a>
<a class="list-group-item" href="../proc/getdirections.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections%7E2.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections2d.html">getDirections2d</a>
<a class="list-group-item" href="../proc/getelevation.html">getElevation</a>
<a class="list-group-item" href="../proc/getelevation%7E2.html">getElevation</a>
<a class="list-group-item" href="../proc/getfrequency.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency%7E2.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency2d.html">getFrequency2d</a>
<a class="list-group-item" href="../proc/getgravity.html">getGravity</a>
<a class="list-group-item" href="../proc/getgravity%7E2.html">getGravity</a>
<a class="list-group-item" href="../proc/getgrid.html">getGrid</a>
<a class="list-group-item" href="../proc/getgridrotation.html">getGridRotation</a>
<a class="list-group-item" href="../proc/getgridspacingx.html">getGridSpacingX</a>
<a class="list-group-item" href="../proc/getgridspacingxwithhalo.html">getGridSpacingXWithHalo</a>
<a class="list-group-item" href="../proc/getgridspacingy.html">getGridSpacingY</a>
<a class="list-group-item" href="../proc/getgridspacingywithhalo.html">getGridSpacingYWithHalo</a>
<a class="list-group-item" href="../proc/getgroupspeed.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed%7E2.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed2d.html">getGroupSpeed2d</a>
<a class="list-group-item" href="../proc/getlatitude.html">getLatitude</a>
<a class="list-group-item" href="../proc/getlongitude.html">getLongitude</a>
<a class="list-group-item" href="../proc/getlowerbounds.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getlowerbounds%7E2.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getphasespeed.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed%7E2.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed2d.html">getPhaseSpeed2d</a>
<a class="list-group-item" href="../proc/getspectrum.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrum%7E2.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrumarray.html">getSpectrumArray</a>
<a class="list-group-item" href="../proc/getsurfacetension.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getsurfacetension%7E2.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getupperbounds.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getupperbounds%7E2.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getwaterdensity.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaterdensity%7E2.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaveaction.html">getWaveAction</a>
<a class="list-group-item" href="../proc/getwavelength.html">getWavelength</a>
<a class="list-group-item" href="../proc/getwavenumber.html">getWavenumber</a>
<a class="list-group-item" href="../proc/getwavenumber2d.html">getWavenumber2d</a>
<a class="list-group-item" href="../proc/getwavenumberspacing.html">getWavenumberSpacing</a>
<a class="list-group-item" href="../proc/gravityclairaut.html">gravityClairaut</a>
<a class="list-group-item" href="../interface/grid_type.html">grid_type</a>
<a class="list-group-item" href="../proc/gt.html">gt</a>
<a class="list-group-item" href="../proc/horizontalacceleration.html">horizontalAcceleration</a>
<a class="list-group-item" href="../proc/horizontalvelocity.html">horizontalVelocity</a>
<a class="list-group-item" href="../interface/integrate.html">integrate</a>
<a class="list-group-item" href="../proc/integrate_domain.html">integrate_domain</a>
<a class="list-group-item" href="../proc/integrate_spectrum.html">integrate_spectrum</a>
<a class="list-group-item" href="../proc/isallocated.html">isAllocated</a>
<a class="list-group-item" href="../proc/isallocated%7E2.html">isAllocated</a>
<a class="list-group-item" href="../proc/ismonochromatic.html">isMonochromatic</a>
<a class="list-group-item" href="../proc/isomnidirectional.html">isOmnidirectional</a>
<a class="list-group-item" href="../proc/jonswap.html">jonswap</a>
<a class="list-group-item" href="../proc/jonswappeakfrequency.html">jonswapPeakFrequency</a>
<a class="list-group-item" href="../proc/le.html">le</a>
<a class="list-group-item" href="../proc/lt.html">lt</a>
<a class="list-group-item" href="../proc/meanperiod.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiod%7E2.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing%7E2.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meansquareslope.html">meanSquareSlope</a>
<a class="list-group-item" href="../proc/meansquareslopedirectional.html">meanSquareSlopeDirectional</a>
<a class="list-group-item" href="../proc/momentum_x.html">momentum_x</a>
<a class="list-group-item" href="../proc/momentum_y.html">momentum_y</a>
<a class="list-group-item" href="../proc/momentumflux_xx.html">momentumFlux_xx</a>
<a class="list-group-item" href="../proc/momentumflux_xy.html">momentumFlux_xy</a>
<a class="list-group-item" href="../proc/momentumflux_yy.html">momentumFlux_yy</a>
<a class="list-group-item" href="../proc/neq.html">neq</a>
<a class="list-group-item" href="../proc/neq%7E2.html">neq</a>
<a class="list-group-item" href="../proc/nondimensionaldepth.html">nondimensionalDepth</a>
<a class="list-group-item" href="../proc/nondimensionalenergy.html">nondimensionalEnergy</a>
<a class="list-group-item" href="../proc/nondimensionalfetch.html">nondimensionalFetch</a>
<a class="list-group-item" href="../proc/nondimensionalfrequency.html">nondimensionalFrequency</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_h1986.html">nondimensionalRoughness_H1986</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_s1974.html">nondimensionalRoughness_S1974</a>
<a class="list-group-item" href="../proc/nondimensionaltime.html">nondimensionalTime</a>
<a class="list-group-item" href="../proc/omnidirectionalspectrum.html">omnidirectionalSpectrum</a>
<a class="list-group-item" href="../interface/ones.html">ones</a>
<a class="list-group-item" href="../proc/ones_int.html">ones_int</a>
<a class="list-group-item" href="../proc/ones_real.html">ones_real</a>
<a class="list-group-item" href="../proc/peakedness.html">peakedness</a>
<a class="list-group-item" href="../proc/peakfrequency.html">peakFrequency</a>
<a class="list-group-item" href="../proc/peakfrequencydiscrete.html">peakFrequencyDiscrete</a>
<a class="list-group-item" href="../proc/phillips.html">phillips</a>
<a class="list-group-item" href="../proc/piersonmoskowitz.html">piersonMoskowitz</a>
<a class="list-group-item" href="../proc/piersonmoskowitzpeakfrequency.html">piersonMoskowitzPeakFrequency</a>
<a class="list-group-item" href="../proc/pressure.html">pressure</a>
<a class="list-group-item" href="../interface/range.html">range</a>
<a class="list-group-item" href="../proc/range_int.html">range_int</a>
<a class="list-group-item" href="../proc/range_real.html">range_real</a>
<a class="list-group-item" href="../proc/readjson.html">readJSON</a>
<a class="list-group-item" href="../proc/real2d_mult_spectrum.html">real2d_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_add_domain.html">real_add_domain</a>
<a class="list-group-item" href="../proc/real_add_spectrum.html">real_add_spectrum</a>
<a class="list-group-item" href="../proc/real_div_domain.html">real_div_domain</a>
<a class="list-group-item" href="../proc/real_div_spectrum.html">real_div_spectrum</a>
<a class="list-group-item" href="../proc/real_mult_domain.html">real_mult_domain</a>
<a class="list-group-item" href="../proc/real_mult_spectrum.html">real_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_sub_domain.html">real_sub_domain</a>
<a class="list-group-item" href="../proc/real_sub_spectrum.html">real_sub_spectrum</a>
<a class="list-group-item" href="../proc/saturationspectrum.html">saturationSpectrum</a>
<a class="list-group-item" href="../proc/sbf_dccm2012.html">sbf_DCCM2012</a>
<a class="list-group-item" href="../proc/sbf_jonswap.html">sbf_JONSWAP</a>
<a class="list-group-item" href="../proc/sds_dccm2012.html">sds_DCCM2012</a>
<a class="list-group-item" href="../proc/sdt_dccm2012.html">sdt_DCCM2012</a>
<a class="list-group-item" href="../proc/setairdensity.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setairdensity%7E2.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setcurrent1d.html">setCurrent1d</a>
<a class="list-group-item" href="../proc/setcurrent2d.html">setCurrent2d</a>
<a class="list-group-item" href="../proc/setdepth.html">setDepth</a>
<a class="list-group-item" href="../proc/setdepth%7E2.html">setDepth</a>
<a class="list-group-item" href="../proc/setelevation.html">setElevation</a>
<a class="list-group-item" href="../proc/setelevation%7E2.html">setElevation</a>
<a class="list-group-item" href="../proc/setgravity.html">setGravity</a>
<a class="list-group-item" href="../proc/setgravity%7E2.html">setGravity</a>
<a class="list-group-item" href="../proc/setspectrum1d.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum1d%7E2.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum2d.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrum2d%7E2.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d1d.html">setSpectrumArray1d1d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d2d.html">setSpectrumArray1d2d</a>
<a class="list-group-item" href="../proc/setspectrumarray2d2d.html">setSpectrumArray2d2d</a>
<a class="list-group-item" href="../proc/setsurfacetension.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setsurfacetension%7E2.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setwaterdensity.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/setwaterdensity%7E2.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/significantsurfaceorbitalvelocity.html">significantSurfaceOrbitalVelocity</a>
<a class="list-group-item" href="../proc/significantwaveheight.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/significantwaveheight%7E2.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/sin_dccm2012.html">sin_DCCM2012</a>
<a class="list-group-item" href="../proc/snl_dccm2012.html">snl_DCCM2012</a>
<a class="list-group-item" href="../proc/spectrum_add_real.html">spectrum_add_real</a>
<a class="list-group-item" href="../proc/spectrum_add_spectrum.html">spectrum_add_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_div_real.html">spectrum_div_real</a>
<a class="list-group-item" href="../proc/spectrum_div_spectrum.html">spectrum_div_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_mult_real.html">spectrum_mult_real</a>
<a class="list-group-item" href="../proc/spectrum_mult_real2d.html">spectrum_mult_real2d</a>
<a class="list-group-item" href="../proc/spectrum_mult_spectrum.html">spectrum_mult_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_sub_real.html">spectrum_sub_real</a>
<a class="list-group-item" href="../proc/spectrum_sub_spectrum.html">spectrum_sub_spectrum</a>
<a class="list-group-item" href="../interface/spectrum_type.html">spectrum_type</a>
<a class="list-group-item" href="../proc/spectrum_unary_minus.html">spectrum_unary_minus</a>
<a class="list-group-item" href="../proc/stokesdrift.html">stokesDrift</a>
<a class="list-group-item" href="../proc/stokesdrift2d.html">stokesDrift2d</a>
<a class="list-group-item" href="../interface/tile.html">tile</a>
<a class="list-group-item" href="../proc/tile_1d_int.html">tile_1d_int</a>
<a class="list-group-item" href="../proc/tile_1d_real.html">tile_1d_real</a>
<a class="list-group-item" href="../proc/tile_2d_int.html">tile_2d_int</a>
<a class="list-group-item" href="../proc/tile_2d_real.html">tile_2d_real</a>
<a class="list-group-item" href="../proc/tile_3d_int.html">tile_3d_int</a>
<a class="list-group-item" href="../proc/tile_3d_real.html">tile_3d_real</a>
<a class="list-group-item" href="../proc/ursellnumber.html">ursellNumber</a>
<a class="list-group-item" href="../proc/verticalacceleration.html">verticalAcceleration</a>
<a class="list-group-item" href="../proc/verticalvelocity.html">verticalVelocity</a>
<a class="list-group-item" href="../proc/waveage.html">waveAge</a>
<a class="list-group-item" href="../proc/wavenumber.html">wavenumber</a>
<a class="list-group-item" href="../proc/wavenumbermoment.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumbermoment%7E2.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumberspectrum.html">wavenumberSpectrum</a>
<a class="list-group-item" href="../proc/writejson.html">writeJSON</a>
<a class="list-group-item" href="../proc/writejson%7E2.html">writeJSON</a>
<a class="list-group-item" href="../interface/zeros.html">zeros</a>
<a class="list-group-item" href="../proc/zeros_int.html">zeros_int</a>
<a class="list-group-item" href="../proc/zeros_real.html">zeros_real</a>
</div>
</div>
</div>
</section>
<hr>
</div> <!-- /container -->
<footer>
<div class="container">
<div class="row">
<div class="col-xs-6 col-md-4"><p>© 2017 </p></div>
<div class="col-xs-6 col-md-4 col-md-push-4">
<p class="text-right">
Documentation generated by
<a href="https://github.com/cmacmackin/ford">FORD</a>
</p>
</div>
<div class="col-xs-12 col-md-4 col-md-pull-4"><p class="text-center"> wavy was developed by Wavebit Scientific LLC</p></div>
</div>
<br>
</div> <!-- /container -->
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
-->
<script src="../js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../js/ie10-viewport-bug-workaround.js"></script>
<!-- MathJax JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } },
jax: ['input/TeX','input/MathML','output/HTML-CSS'],
extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
'HTML-CSS': {
styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '#000000 ! important'} }
}
});
</script>
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html> | bsd-3-clause |
e02d96ec16/CumulusCI | cumulusci/tasks/salesforce/Deploy.py | 4641 | import base64
import os
import tempfile
import zipfile
from cumulusci.core.utils import process_bool_arg
from cumulusci.salesforce_api.metadata import ApiDeploy
from cumulusci.tasks.salesforce import BaseSalesforceMetadataApiTask
from cumulusci.utils import zip_clean_metaxml
from cumulusci.utils import zip_inject_namespace
from cumulusci.utils import zip_strip_namespace
from cumulusci.utils import zip_tokenize_namespace
class Deploy(BaseSalesforceMetadataApiTask):
api_class = ApiDeploy
task_options = {
'path': {
'description': 'The path to the metadata source to be deployed',
'required': True,
},
'unmanaged': {
'description': "If True, changes namespace_inject to replace tokens with a blank string",
},
'namespace_inject': {
'description': "If set, the namespace tokens in files and filenames are replaced with the namespace's prefix",
},
'namespace_strip': {
'description': "If set, all namespace prefixes for the namespace specified are stripped from files and filenames",
},
'namespace_tokenize': {
'description': "If set, all namespace prefixes for the namespace specified are replaced with tokens for use with namespace_inject",
},
'namespaced_org': {
'description': "If True, the tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___ will get replaced with the namespace. The default is false causing those tokens to get stripped and replaced with an empty string. Set this if deploying to a namespaced scratch org or packaging org.",
},
'clean_meta_xml': {
'description': "Defaults to True which strips the <packageVersions/> element from all meta.xml files. The packageVersion element gets added automatically by the target org and is set to whatever version is installed in the org. To disable this, set this option to False",
},
}
def _get_api(self, path=None):
if not path:
path = self.task_config.options__path
# Build the zip file
zip_file = tempfile.TemporaryFile()
zipf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
pwd = os.getcwd()
os.chdir(path)
for root, dirs, files in os.walk('.'):
for f in files:
self._write_zip_file(zipf, root, f)
zipf.close()
zipf_processed = self._process_zip_file(zipfile.ZipFile(zip_file))
zipf_processed.fp.seek(0)
package_zip = base64.b64encode(zipf_processed.fp.read())
os.chdir(pwd)
return self.api_class(self, package_zip, purge_on_delete=False)
def _process_zip_file(self, zipf):
zipf = self._process_namespace(zipf)
zipf = self._process_meta_xml(zipf)
return zipf
def _process_namespace(self, zipf):
if self.options.get('namespace_tokenize'):
self.logger.info(
'Tokenizing namespace prefix {}__'.format(
self.options['namespace_tokenize'],
)
)
zipf = zip_tokenize_namespace(zipf, self.options['namespace_tokenize'], logger=self.logger)
if self.options.get('namespace_inject'):
kwargs = {}
kwargs['managed'] = not process_bool_arg(self.options.get('unmanaged', True))
kwargs['namespaced_org'] = process_bool_arg(self.options.get('namespaced_org', False))
kwargs['logger'] = self.logger
if kwargs['managed']:
self.logger.info(
'Replacing namespace tokens from metadata with namespace prefix {}__'.format(
self.options['namespace_inject'],
)
)
else:
self.logger.info(
'Stripping namespace tokens from metadata for unmanaged deployment'
)
zipf = zip_inject_namespace(zipf, self.options['namespace_inject'], **kwargs)
if self.options.get('namespace_strip'):
zipf = zip_strip_namespace(zipf, self.options['namespace_strip'], logger=self.logger)
return zipf
def _process_meta_xml(self, zipf):
if not process_bool_arg(self.options.get('clean_meta_xml', True)):
return zipf
self.logger.info(
'Cleaning meta.xml files of packageVersion elements for deploy'
)
zipf = zip_clean_metaxml(zipf, logger=self.logger)
return zipf
def _write_zip_file(self, zipf, root, path):
zipf.write(os.path.join(root, path))
| bsd-3-clause |
adem-team/advanced | lukisongroup/purchasing/views/plan-term/review.php | 2360 | <?php
use kartik\helpers\Html;
use yii\widgets\DetailView;
use kartik\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\bootstrap\ActiveForm;
use kartik\tabs\TabsX;
use yii\helpers\Json;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\web\Request;
use kartik\daterange\DateRangePicker;
use yii\db\ActiveRecord;
use yii\data\ArrayDataProvider;
use lukisongroup\master\models\Customers;
use lukisongroup\master\models\Termcustomers;
use lukisongroup\master\models\Distributor;
use lukisongroup\hrd\models\Corp;
$this->sideCorp = 'ESM-Trading Terms'; /* Title Select Company pada header pasa sidemenu/menu samping kiri */
$this->sideMenu = 'esm_trading_term'; /* kd_menu untuk list menu pada sidemenu, get from table of database */
$this->title = Yii::t('app', 'Trading Terms ');
//print_r($model[0]);
//echo $model[0]->NmDis;
?>
<div class="content" >
<!-- HEADER !-->
<div class="row">
<div class="col-lg-12">
<!-- HEADER !-->
<div class="col-md-1" style="float:left;">
<?php echo Html::img('@web/upload/lukison.png', ['class' => 'pnjg', 'style'=>'width:100px;height:70px;']); ?>
</div>
<div class="col-md-9" style="padding-top:15px;">
<h3 class="text-center"><b> <?php echo 'TERM - '.ucwords($model[0]->NmCustomer) ?> </b></h3>
</div>
<div class="col-md-12">
<hr style="height:10px;margin-top: 1px; margin-bottom: 1px;color:#94cdf0">
</div>
<!-- DATA !-->
<?php
$contentData=$this->render('_reviewData',[
'model'=>$model,
'dataProvider'=>$dataProvider,
'dataProviderBudget'=>$dataProviderBudget
]);
$contentChart=$this->render('_reviewChart');
$items=[
[
'label'=>'<i class="fa fa-mortar-board fa-lg"></i> TERM DATA','content'=>$contentData,
// 'active'=>true,
'options' => ['id' => 'term-data'],
],
[
'label'=>'<i class="fa fa-bar-chart fa-lg"></i> TERM CHART','content'=>'',
'options' => ['id' => 'term-chart'],
]
];
echo TabsX::widget([
'id'=>'tab-term-plan',
'items'=>$items,
'position'=>TabsX::POS_ABOVE,
'encodeLabels'=>false
]);
?>
</div>
</div>
</div><!-- Body !--> | bsd-3-clause |
samwolf1982/timutparserolxdomria_yii2 | backend/views/olxstatistic/index.php | 919 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\OlxstatisticSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Olxstatistics';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="olxstatistic-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Olxstatistic', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'shorturl:url',
'fullurl:url',
'someelse',
'someelse2',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| bsd-3-clause |
JaneliaSciComp/osgpyplusplus | src/modules/osg/generated_code/Node.pypp.cpp | 49800 | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "wrap_referenced.h"
#include "node.pypp.hpp"
namespace bp = boost::python;
struct Node_wrapper : osg::Node, bp::wrapper< osg::Node > {
Node_wrapper( )
: osg::Node( )
, bp::wrapper< osg::Node >(){
// null constructor
}
virtual void accept( ::osg::NodeVisitor & nv ) {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(nv) );
else{
this->osg::Node::accept( boost::ref(nv) );
}
}
void default_accept( ::osg::NodeVisitor & nv ) {
osg::Node::accept( boost::ref(nv) );
}
virtual ::osg::Camera * asCamera( ) {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera * default_asCamera( ) {
return osg::Node::asCamera( );
}
virtual ::osg::Camera const * asCamera( ) const {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera const * default_asCamera( ) const {
return osg::Node::asCamera( );
}
virtual ::osg::Geode * asGeode( ) {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode * default_asGeode( ) {
return osg::Node::asGeode( );
}
virtual ::osg::Geode const * asGeode( ) const {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode const * default_asGeode( ) const {
return osg::Node::asGeode( );
}
virtual ::osg::Group * asGroup( ) {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group * default_asGroup( ) {
return osg::Node::asGroup( );
}
virtual ::osg::Group const * asGroup( ) const {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group const * default_asGroup( ) const {
return osg::Node::asGroup( );
}
virtual ::osg::Switch * asSwitch( ) {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch * default_asSwitch( ) {
return osg::Node::asSwitch( );
}
virtual ::osg::Switch const * asSwitch( ) const {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch const * default_asSwitch( ) const {
return osg::Node::asSwitch( );
}
virtual ::osg::Transform * asTransform( ) {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform * default_asTransform( ) {
return osg::Node::asTransform( );
}
virtual ::osg::Transform const * asTransform( ) const {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform const * default_asTransform( ) const {
return osg::Node::asTransform( );
}
virtual void ascend( ::osg::NodeVisitor & nv ) {
if( bp::override func_ascend = this->get_override( "ascend" ) )
func_ascend( boost::ref(nv) );
else{
this->osg::Node::ascend( boost::ref(nv) );
}
}
void default_ascend( ::osg::NodeVisitor & nv ) {
osg::Node::ascend( boost::ref(nv) );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::Node::className( );
}
}
char const * default_className( ) const {
return osg::Node::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::Node::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::Node::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::Node::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::Node::cloneType( );
}
virtual ::osg::BoundingSphere computeBound( ) const {
if( bp::override func_computeBound = this->get_override( "computeBound" ) )
return func_computeBound( );
else{
return this->osg::Node::computeBound( );
}
}
::osg::BoundingSphere default_computeBound( ) const {
return osg::Node::computeBound( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::Node::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::Node::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::Node::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::Node::libraryName( );
}
virtual void resizeGLObjectBuffers( unsigned int arg0 ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( arg0 );
else{
this->osg::Node::resizeGLObjectBuffers( arg0 );
}
}
void default_resizeGLObjectBuffers( unsigned int arg0 ) {
osg::Node::resizeGLObjectBuffers( arg0 );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Node::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Node::setThreadSafeRefUnref( threadSafe );
}
virtual void traverse( ::osg::NodeVisitor & arg0 ) {
if( bp::override func_traverse = this->get_override( "traverse" ) )
func_traverse( boost::ref(arg0) );
else{
this->osg::Node::traverse( boost::ref(arg0) );
}
}
void default_traverse( ::osg::NodeVisitor & arg0 ) {
osg::Node::traverse( boost::ref(arg0) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
void register_Node_class(){
{ //::osg::Node
typedef bp::class_< Node_wrapper, bp::bases< osg::Object >, osg::ref_ptr< ::osg::Node >, boost::noncopyable > Node_exposer_t;
Node_exposer_t Node_exposer = Node_exposer_t( "Node", "\n Base class for all internal nodes in the scene graph.\n Provides interface for most common node operations (Composite Pattern).\n", bp::no_init );
bp::scope Node_scope( Node_exposer );
Node_exposer.def( bp::init< >("\n Construct a node.\n Initialize the parent list to empty, node name to and\n bounding sphere dirty flag to true.\n") );
{ //::osg::Node::accept
typedef void ( ::osg::Node::*accept_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_accept_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"accept"
, accept_function_type(&::osg::Node::accept)
, default_accept_function_type(&Node_wrapper::default_accept)
, ( bp::arg("nv") ) );
}
{ //::osg::Node::addCullCallback
typedef void ( ::osg::Node::*addCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addCullCallback"
, addCullCallback_function_type( &::osg::Node::addCullCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the cull callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::addDescription
typedef void ( ::osg::Node::*addDescription_function_type)( ::std::string const & ) ;
Node_exposer.def(
"addDescription"
, addDescription_function_type( &::osg::Node::addDescription )
, ( bp::arg("desc") )
, " Add a description string to the node." );
}
{ //::osg::Node::addEventCallback
typedef void ( ::osg::Node::*addEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addEventCallback"
, addEventCallback_function_type( &::osg::Node::addEventCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the event callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::addUpdateCallback
typedef void ( ::osg::Node::*addUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addUpdateCallback"
, addUpdateCallback_function_type( &::osg::Node::addUpdateCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the update callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera * ( ::osg::Node::*asCamera_function_type)( ) ;
typedef ::osg::Camera * ( Node_wrapper::*default_asCamera_function_type)( ) ;
Node_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&Node_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera const * ( ::osg::Node::*asCamera_function_type)( ) const;
typedef ::osg::Camera const * ( Node_wrapper::*default_asCamera_function_type)( ) const;
Node_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&Node_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode * ( ::osg::Node::*asGeode_function_type)( ) ;
typedef ::osg::Geode * ( Node_wrapper::*default_asGeode_function_type)( ) ;
Node_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&Node_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode const * ( ::osg::Node::*asGeode_function_type)( ) const;
typedef ::osg::Geode const * ( Node_wrapper::*default_asGeode_function_type)( ) const;
Node_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&Node_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGroup
typedef ::osg::Group * ( ::osg::Node::*asGroup_function_type)( ) ;
typedef ::osg::Group * ( Node_wrapper::*default_asGroup_function_type)( ) ;
Node_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Node::asGroup)
, default_asGroup_function_type(&Node_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGroup
typedef ::osg::Group const * ( ::osg::Node::*asGroup_function_type)( ) const;
typedef ::osg::Group const * ( Node_wrapper::*default_asGroup_function_type)( ) const;
Node_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Node::asGroup)
, default_asGroup_function_type(&Node_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch * ( ::osg::Node::*asSwitch_function_type)( ) ;
typedef ::osg::Switch * ( Node_wrapper::*default_asSwitch_function_type)( ) ;
Node_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&Node_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch const * ( ::osg::Node::*asSwitch_function_type)( ) const;
typedef ::osg::Switch const * ( Node_wrapper::*default_asSwitch_function_type)( ) const;
Node_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&Node_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform * ( ::osg::Node::*asTransform_function_type)( ) ;
typedef ::osg::Transform * ( Node_wrapper::*default_asTransform_function_type)( ) ;
Node_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&Node_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform const * ( ::osg::Node::*asTransform_function_type)( ) const;
typedef ::osg::Transform const * ( Node_wrapper::*default_asTransform_function_type)( ) const;
Node_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&Node_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::ascend
typedef void ( ::osg::Node::*ascend_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_ascend_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"ascend"
, ascend_function_type(&::osg::Node::ascend)
, default_ascend_function_type(&Node_wrapper::default_ascend)
, ( bp::arg("nv") ) );
}
{ //::osg::Node::className
typedef char const * ( ::osg::Node::*className_function_type)( ) const;
typedef char const * ( Node_wrapper::*default_className_function_type)( ) const;
Node_exposer.def(
"className"
, className_function_type(&::osg::Node::className)
, default_className_function_type(&Node_wrapper::default_className) );
}
{ //::osg::Node::clone
typedef ::osg::Object * ( ::osg::Node::*clone_function_type)( ::osg::CopyOp const & ) const;
typedef ::osg::Object * ( Node_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const;
Node_exposer.def(
"clone"
, clone_function_type(&::osg::Node::clone)
, default_clone_function_type(&Node_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::Node::cloneType
typedef ::osg::Object * ( ::osg::Node::*cloneType_function_type)( ) const;
typedef ::osg::Object * ( Node_wrapper::*default_cloneType_function_type)( ) const;
Node_exposer.def(
"cloneType"
, cloneType_function_type(&::osg::Node::cloneType)
, default_cloneType_function_type(&Node_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::Node::computeBound
typedef ::osg::BoundingSphere ( ::osg::Node::*computeBound_function_type)( ) const;
typedef ::osg::BoundingSphere ( Node_wrapper::*default_computeBound_function_type)( ) const;
Node_exposer.def(
"computeBound"
, computeBound_function_type(&::osg::Node::computeBound)
, default_computeBound_function_type(&Node_wrapper::default_computeBound) );
}
{ //::osg::Node::containsOccluderNodes
typedef bool ( ::osg::Node::*containsOccluderNodes_function_type)( ) const;
Node_exposer.def(
"containsOccluderNodes"
, containsOccluderNodes_function_type( &::osg::Node::containsOccluderNodes )
, " return true if this node is an OccluderNode or the subgraph below this node are OccluderNodes." );
}
{ //::osg::Node::dirtyBound
typedef void ( ::osg::Node::*dirtyBound_function_type)( ) ;
Node_exposer.def(
"dirtyBound"
, dirtyBound_function_type( &::osg::Node::dirtyBound )
, " Mark this nodes bounding sphere dirty.\n Forcing it to be computed on the next call to getBound()." );
}
{ //::osg::Node::getBound
typedef ::osg::BoundingSphere const & ( ::osg::Node::*getBound_function_type)( ) const;
Node_exposer.def(
"getBound"
, getBound_function_type( &::osg::Node::getBound )
, bp::return_internal_reference< >()
, " Get the bounding sphere of node.\n Using lazy evaluation computes the bounding sphere if it is dirty." );
}
{ //::osg::Node::getComputeBoundingSphereCallback
typedef ::osg::Node::ComputeBoundingSphereCallback * ( ::osg::Node::*getComputeBoundingSphereCallback_function_type)( ) ;
Node_exposer.def(
"getComputeBoundingSphereCallback"
, getComputeBoundingSphereCallback_function_type( &::osg::Node::getComputeBoundingSphereCallback )
, bp::return_internal_reference< >()
, " Get the compute bound callback." );
}
{ //::osg::Node::getComputeBoundingSphereCallback
typedef ::osg::Node::ComputeBoundingSphereCallback const * ( ::osg::Node::*getComputeBoundingSphereCallback_function_type)( ) const;
Node_exposer.def(
"getComputeBoundingSphereCallback"
, getComputeBoundingSphereCallback_function_type( &::osg::Node::getComputeBoundingSphereCallback )
, bp::return_internal_reference< >()
, " Get the const compute bound callback." );
}
{ //::osg::Node::getCullCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getCullCallback_function_type)( ) ;
Node_exposer.def(
"getCullCallback"
, getCullCallback_function_type( &::osg::Node::getCullCallback )
, bp::return_internal_reference< >()
, " Get cull node callback, called during cull traversal." );
}
{ //::osg::Node::getCullCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getCullCallback_function_type)( ) const;
Node_exposer.def(
"getCullCallback"
, getCullCallback_function_type( &::osg::Node::getCullCallback )
, bp::return_internal_reference< >()
, " Get const cull node callback, called during cull traversal." );
}
{ //::osg::Node::getCullingActive
typedef bool ( ::osg::Node::*getCullingActive_function_type)( ) const;
Node_exposer.def(
"getCullingActive"
, getCullingActive_function_type( &::osg::Node::getCullingActive )
, " Get the view frustum/small feature _cullingActive flag for this node. Used as a guide\n to the cull traversal." );
}
{ //::osg::Node::getDescription
typedef ::std::string const & ( ::osg::Node::*getDescription_function_type)( unsigned int ) const;
Node_exposer.def(
"getDescription"
, getDescription_function_type( &::osg::Node::getDescription )
, ( bp::arg("i") )
, bp::return_value_policy< bp::copy_const_reference >()
, " Get a single const description of the const node." );
}
{ //::osg::Node::getDescription
typedef ::std::string & ( ::osg::Node::*getDescription_function_type)( unsigned int ) ;
Node_exposer.def(
"getDescription"
, getDescription_function_type( &::osg::Node::getDescription )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Get a single description of the node." );
}
{ //::osg::Node::getDescriptions
typedef ::std::vector< std::string > & ( ::osg::Node::*getDescriptions_function_type)( ) ;
Node_exposer.def(
"getDescriptions"
, getDescriptions_function_type( &::osg::Node::getDescriptions )
, bp::return_internal_reference< >()
, " Get the description list of the node." );
}
{ //::osg::Node::getDescriptions
typedef ::std::vector< std::string > const & ( ::osg::Node::*getDescriptions_function_type)( ) const;
Node_exposer.def(
"getDescriptions"
, getDescriptions_function_type( &::osg::Node::getDescriptions )
, bp::return_internal_reference< >()
, " Get the const description list of the const node." );
}
{ //::osg::Node::getEventCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getEventCallback_function_type)( ) ;
Node_exposer.def(
"getEventCallback"
, getEventCallback_function_type( &::osg::Node::getEventCallback )
, bp::return_internal_reference< >()
, " Get event node callback, called during event traversal." );
}
{ //::osg::Node::getEventCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getEventCallback_function_type)( ) const;
Node_exposer.def(
"getEventCallback"
, getEventCallback_function_type( &::osg::Node::getEventCallback )
, bp::return_internal_reference< >()
, " Get const event node callback, called during event traversal." );
}
{ //::osg::Node::getInitialBound
typedef ::osg::BoundingSphere const & ( ::osg::Node::*getInitialBound_function_type)( ) const;
Node_exposer.def(
"getInitialBound"
, getInitialBound_function_type( &::osg::Node::getInitialBound )
, bp::return_internal_reference< >()
, " Set the initial bounding volume to use when computing the overall bounding volume." );
}
{ //::osg::Node::getNodeMask
typedef unsigned int ( ::osg::Node::*getNodeMask_function_type)( ) const;
Node_exposer.def(
"getNodeMask"
, getNodeMask_function_type( &::osg::Node::getNodeMask )
, " Get the node Mask." );
}
{ //::osg::Node::getNumChildrenRequiringEventTraversal
typedef unsigned int ( ::osg::Node::*getNumChildrenRequiringEventTraversal_function_type)( ) const;
Node_exposer.def(
"getNumChildrenRequiringEventTraversal"
, getNumChildrenRequiringEventTraversal_function_type( &::osg::Node::getNumChildrenRequiringEventTraversal )
, " Get the number of Children of this node which require Event traversal,\n since they have an Event Callback attached to them or their children." );
}
{ //::osg::Node::getNumChildrenRequiringUpdateTraversal
typedef unsigned int ( ::osg::Node::*getNumChildrenRequiringUpdateTraversal_function_type)( ) const;
Node_exposer.def(
"getNumChildrenRequiringUpdateTraversal"
, getNumChildrenRequiringUpdateTraversal_function_type( &::osg::Node::getNumChildrenRequiringUpdateTraversal )
, " Get the number of Children of this node which require Update traversal,\n since they have an Update Callback attached to them or their children." );
}
{ //::osg::Node::getNumChildrenWithCullingDisabled
typedef unsigned int ( ::osg::Node::*getNumChildrenWithCullingDisabled_function_type)( ) const;
Node_exposer.def(
"getNumChildrenWithCullingDisabled"
, getNumChildrenWithCullingDisabled_function_type( &::osg::Node::getNumChildrenWithCullingDisabled )
, " Get the number of Children of this node which have culling disabled." );
}
{ //::osg::Node::getNumChildrenWithOccluderNodes
typedef unsigned int ( ::osg::Node::*getNumChildrenWithOccluderNodes_function_type)( ) const;
Node_exposer.def(
"getNumChildrenWithOccluderNodes"
, getNumChildrenWithOccluderNodes_function_type( &::osg::Node::getNumChildrenWithOccluderNodes )
, " Get the number of Children of this node which are or have OccluderNodes." );
}
{ //::osg::Node::getNumDescriptions
typedef unsigned int ( ::osg::Node::*getNumDescriptions_function_type)( ) const;
Node_exposer.def(
"getNumDescriptions"
, getNumDescriptions_function_type( &::osg::Node::getNumDescriptions )
, " Get the number of descriptions of the node." );
}
{ //::osg::Node::getNumParents
typedef unsigned int ( ::osg::Node::*getNumParents_function_type)( ) const;
Node_exposer.def(
"getNumParents"
, getNumParents_function_type( &::osg::Node::getNumParents )
, " Get the number of parents of node.\n Return: the number of parents of this node." );
}
{ //::osg::Node::getOrCreateStateSet
typedef ::osg::StateSet * ( ::osg::Node::*getOrCreateStateSet_function_type)( ) ;
Node_exposer.def(
"getOrCreateStateSet"
, getOrCreateStateSet_function_type( &::osg::Node::getOrCreateStateSet )
, bp::return_internal_reference< >()
, " return the nodes StateSet, if one does not already exist create it\n set the node and return the newly created StateSet. This ensures\n that a valid StateSet is always returned and can be used directly." );
}
{ //::osg::Node::getParent
typedef ::osg::Group * ( ::osg::Node::*getParent_function_type)( unsigned int ) ;
Node_exposer.def(
"getParent"
, getParent_function_type( &::osg::Node::getParent )
, ( bp::arg("i") )
, bp::return_internal_reference< >() );
}
{ //::osg::Node::getParent
typedef ::osg::Group const * ( ::osg::Node::*getParent_function_type)( unsigned int ) const;
Node_exposer.def(
"getParent"
, getParent_function_type( &::osg::Node::getParent )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Get a single const parent of node.\n @param i: index of the parent to get.\n Return: the parent i." );
}
{ //::osg::Node::getParentalNodePaths
typedef ::osg::NodePathList ( ::osg::Node::*getParentalNodePaths_function_type)( ::osg::Node * ) const;
Node_exposer.def(
"getParentalNodePaths"
, getParentalNodePaths_function_type( &::osg::Node::getParentalNodePaths )
, ( bp::arg("haltTraversalAtNode")=bp::object() )
, " Get the list of node paths parent paths.\n The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node." );
}
{ //::osg::Node::getParents
typedef ::std::vector< osg::Group* > const & ( ::osg::Node::*getParents_function_type)( ) const;
Node_exposer.def(
"getParents"
, getParents_function_type( &::osg::Node::getParents )
, bp::return_internal_reference< >()
, " Get the parent list of node." );
}
{ //::osg::Node::getParents
typedef ::std::vector< osg::Group* > ( ::osg::Node::*getParents_function_type)( ) ;
Node_exposer.def(
"getParents"
, getParents_function_type( &::osg::Node::getParents )
, " Get the a copy of parent list of node. A copy is returned to\n prevent modification of the parent list." );
}
{ //::osg::Node::getStateSet
typedef ::osg::StateSet * ( ::osg::Node::*getStateSet_function_type)( ) ;
Node_exposer.def(
"getStateSet"
, getStateSet_function_type( &::osg::Node::getStateSet )
, bp::return_internal_reference< >()
, " Return the nodes StateSet. returns NULL if a stateset is not attached." );
}
{ //::osg::Node::getStateSet
typedef ::osg::StateSet const * ( ::osg::Node::*getStateSet_function_type)( ) const;
Node_exposer.def(
"getStateSet"
, getStateSet_function_type( &::osg::Node::getStateSet )
, bp::return_internal_reference< >()
, " Return the nodes const StateSet. Returns NULL if a stateset is not attached." );
}
{ //::osg::Node::getUpdateCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getUpdateCallback_function_type)( ) ;
Node_exposer.def(
"getUpdateCallback"
, getUpdateCallback_function_type( &::osg::Node::getUpdateCallback )
, bp::return_internal_reference< >()
, " Get update node callback, called during update traversal." );
}
{ //::osg::Node::getUpdateCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getUpdateCallback_function_type)( ) const;
Node_exposer.def(
"getUpdateCallback"
, getUpdateCallback_function_type( &::osg::Node::getUpdateCallback )
, bp::return_internal_reference< >()
, " Get const update node callback, called during update traversal." );
}
{ //::osg::Node::getWorldMatrices
typedef ::osg::MatrixList ( ::osg::Node::*getWorldMatrices_function_type)( ::osg::Node const * ) const;
Node_exposer.def(
"getWorldMatrices"
, getWorldMatrices_function_type( &::osg::Node::getWorldMatrices )
, ( bp::arg("haltTraversalAtNode")=bp::object() )
, " Get the list of matrices that transform this node from local coordinates to world coordinates.\n The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node." );
}
{ //::osg::Node::isCullingActive
typedef bool ( ::osg::Node::*isCullingActive_function_type)( ) const;
Node_exposer.def(
"isCullingActive"
, isCullingActive_function_type( &::osg::Node::isCullingActive )
, " Return true if this node can be culled by view frustum, occlusion or small feature culling during the cull traversal.\n Note, returns true only if no children have culling disabled, and the local _cullingActive flag is true." );
}
{ //::osg::Node::isSameKindAs
typedef bool ( ::osg::Node::*isSameKindAs_function_type)( ::osg::Object const * ) const;
typedef bool ( Node_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const;
Node_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osg::Node::isSameKindAs)
, default_isSameKindAs_function_type(&Node_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osg::Node::libraryName
typedef char const * ( ::osg::Node::*libraryName_function_type)( ) const;
typedef char const * ( Node_wrapper::*default_libraryName_function_type)( ) const;
Node_exposer.def(
"libraryName"
, libraryName_function_type(&::osg::Node::libraryName)
, default_libraryName_function_type(&Node_wrapper::default_libraryName) );
}
{ //::osg::Node::removeCullCallback
typedef void ( ::osg::Node::*removeCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeCullCallback"
, removeCullCallback_function_type( &::osg::Node::removeCullCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::removeEventCallback
typedef void ( ::osg::Node::*removeEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeEventCallback"
, removeEventCallback_function_type( &::osg::Node::removeEventCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::removeUpdateCallback
typedef void ( ::osg::Node::*removeUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeUpdateCallback"
, removeUpdateCallback_function_type( &::osg::Node::removeUpdateCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::resizeGLObjectBuffers
typedef void ( ::osg::Node::*resizeGLObjectBuffers_function_type)( unsigned int ) ;
typedef void ( Node_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ;
Node_exposer.def(
"resizeGLObjectBuffers"
, resizeGLObjectBuffers_function_type(&::osg::Node::resizeGLObjectBuffers)
, default_resizeGLObjectBuffers_function_type(&Node_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("arg0") ) );
}
{ //::osg::Node::setComputeBoundingSphereCallback
typedef void ( ::osg::Node::*setComputeBoundingSphereCallback_function_type)( ::osg::Node::ComputeBoundingSphereCallback * ) ;
Node_exposer.def(
"setComputeBoundingSphereCallback"
, setComputeBoundingSphereCallback_function_type( &::osg::Node::setComputeBoundingSphereCallback )
, ( bp::arg("callback") )
, " Set the compute bound callback to override the default computeBound." );
}
{ //::osg::Node::setCullCallback
typedef void ( ::osg::Node::*setCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setCullCallback"
, setCullCallback_function_type( &::osg::Node::setCullCallback )
, ( bp::arg("nc") )
, " Set cull node callback, called during cull traversal." );
}
{ //::osg::Node::setCullingActive
typedef void ( ::osg::Node::*setCullingActive_function_type)( bool ) ;
Node_exposer.def(
"setCullingActive"
, setCullingActive_function_type( &::osg::Node::setCullingActive )
, ( bp::arg("active") )
, " Set the view frustum/small feature culling of this node to be active or inactive.\n The default value is true for _cullingActive. Used as a guide\n to the cull traversal." );
}
{ //::osg::Node::setDescriptions
typedef void ( ::osg::Node::*setDescriptions_function_type)( ::std::vector< std::string > const & ) ;
Node_exposer.def(
"setDescriptions"
, setDescriptions_function_type( &::osg::Node::setDescriptions )
, ( bp::arg("descriptions") )
, " Set the list of string descriptions." );
}
{ //::osg::Node::setEventCallback
typedef void ( ::osg::Node::*setEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setEventCallback"
, setEventCallback_function_type( &::osg::Node::setEventCallback )
, ( bp::arg("nc") )
, " Set event node callback, called during event traversal." );
}
{ //::osg::Node::setInitialBound
typedef void ( ::osg::Node::*setInitialBound_function_type)( ::osg::BoundingSphere const & ) ;
Node_exposer.def(
"setInitialBound"
, setInitialBound_function_type( &::osg::Node::setInitialBound )
, ( bp::arg("bsphere") )
, " Set the initial bounding volume to use when computing the overall bounding volume." );
}
{ //::osg::Node::setNodeMask
typedef void ( ::osg::Node::*setNodeMask_function_type)( unsigned int ) ;
Node_exposer.def(
"setNodeMask"
, setNodeMask_function_type( &::osg::Node::setNodeMask )
, ( bp::arg("nm") )
, " Set the node mask." );
}
{ //::osg::Node::setStateSet
typedef void ( ::osg::Node::*setStateSet_function_type)( ::osg::StateSet * ) ;
Node_exposer.def(
"setStateSet"
, setStateSet_function_type( &::osg::Node::setStateSet )
, ( bp::arg("stateset") )
, " Set the nodes StateSet." );
}
{ //::osg::Node::setThreadSafeRefUnref
typedef void ( ::osg::Node::*setThreadSafeRefUnref_function_type)( bool ) ;
typedef void ( Node_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ;
Node_exposer.def(
"setThreadSafeRefUnref"
, setThreadSafeRefUnref_function_type(&::osg::Node::setThreadSafeRefUnref)
, default_setThreadSafeRefUnref_function_type(&Node_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) );
}
{ //::osg::Node::setUpdateCallback
typedef void ( ::osg::Node::*setUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setUpdateCallback"
, setUpdateCallback_function_type( &::osg::Node::setUpdateCallback )
, ( bp::arg("nc") )
, " Set update node callback, called during update traversal." );
}
{ //::osg::Node::traverse
typedef void ( ::osg::Node::*traverse_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_traverse_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"traverse"
, traverse_function_type(&::osg::Node::traverse)
, default_traverse_function_type(&Node_wrapper::default_traverse)
, ( bp::arg("arg0") ) );
}
{ //::osg::Object::computeDataVariance
typedef void ( ::osg::Object::*computeDataVariance_function_type)( ) ;
typedef void ( Node_wrapper::*default_computeDataVariance_function_type)( ) ;
Node_exposer.def(
"computeDataVariance"
, computeDataVariance_function_type(&::osg::Object::computeDataVariance)
, default_computeDataVariance_function_type(&Node_wrapper::default_computeDataVariance) );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)( ) ;
typedef ::osg::Referenced * ( Node_wrapper::*default_getUserData_function_type)( ) ;
Node_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&Node_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)( ) const;
typedef ::osg::Referenced const * ( Node_wrapper::*default_getUserData_function_type)( ) const;
Node_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&Node_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ;
typedef void ( Node_wrapper::*default_setName_function_type)( ::std::string const & ) ;
Node_exposer.def(
"setName"
, setName_function_type(&::osg::Object::setName)
, default_setName_function_type(&Node_wrapper::default_setName)
, ( bp::arg("name") ) );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( char const * ) ;
Node_exposer.def(
"setName"
, setName_function_type( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." );
}
{ //::osg::Object::setUserData
typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ;
typedef void ( Node_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ;
Node_exposer.def(
"setUserData"
, setUserData_function_type(&::osg::Object::setUserData)
, default_setUserData_function_type(&Node_wrapper::default_setUserData)
, ( bp::arg("obj") ) );
}
{ //property "stateSet"[fget=::osg::Node::getOrCreateStateSet, fset=::osg::Node::setStateSet]
typedef ::osg::StateSet * ( ::osg::Node::*fget)( ) ;
typedef void ( ::osg::Node::*fset)( ::osg::StateSet * ) ;
Node_exposer.add_property(
"stateSet"
, bp::make_function(
fget( &::osg::Node::getOrCreateStateSet )
, bp::return_internal_reference< >() )
, fset( &::osg::Node::setStateSet ) );
}
}
}
| bsd-3-clause |
leesab/irods | iRODS/lib/api/include/chkObjPermAndStat.hpp | 1734 | /*** Copyright (c), The Unregents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* chkObjPermAndStat.h
*/
#ifndef CHK_OBJ_PERM_AND_STAT_HPP
#define CHK_OBJ_PERM_AND_STAT_HPP
/* This is Object File I/O type API call */
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
#include "dataObjInpOut.hpp"
/* definition for flags */
#define CHK_COLL_FOR_BUNDLE_OPR 0x1
#
typedef struct {
char objPath[MAX_NAME_LEN];
char permission[NAME_LEN];
int flags;
int status;
keyValPair_t condInput;
} chkObjPermAndStat_t;
#define ChkObjPermAndStat_PI "str objPath[MAX_NAME_LEN]; str permission[NAME_LEN]; int flags; int status; struct KeyValPair_PI;"
#if defined(RODS_SERVER)
#define RS_CHK_OBJ_PERM_AND_STAT rsChkObjPermAndStat
/* prototype for the server handler */
int
rsChkObjPermAndStat( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
int
_rsChkObjPermAndStat( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
int
chkCollForBundleOpr( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
#else
#define RS_CHK_OBJ_PERM_AND_STAT NULL
#endif
/* prototype for the client call */
int
rcChkObjPermAndStat( rcComm_t *conn, chkObjPermAndStat_t *chkObjPermAndStatInp );
/* rcChkObjPermAndStat - Unregister a iRODS dataObject.
* Input -
* rcComm_t *conn - The client connection handle.
* chkObjPermAndStat_t *chkObjPermAndStatInp - the dataObjInfo to unregister
*
* OutPut -
* int status - status of the operation.
*/
#endif /* CHK_OBJ_PERM_AND_STAT_H */
| bsd-3-clause |
quantmind/pulsar | pulsar/apps/data/__init__.py | 496 | from .store import (
Command, Store, RemoteStore, PubSub, PubSubClient,
parse_store_url, create_store, register_store, data_stores,
NoSuchStore
)
from .channels import Channels
from . import redis # noqa
from .pulsards.startds import start_store
__all__ = [
'Command',
'Store',
'RemoteStore',
'PubSub',
'PubSubClient',
'parse_store_url',
'create_store',
'register_store',
'data_stores',
'NoSuchStore',
'start_store',
'Channels'
]
| bsd-3-clause |
raisedadead/FreeCodeCamp | client/src/components/helpers/link.tsx | 742 | import { Link as GatsbyLink } from 'gatsby';
import React from 'react';
interface LinkProps {
children?: React.ReactNode;
className?: string;
external?: boolean;
sameTab?: boolean;
state?: Record<string, unknown>;
to: string;
}
const Link = ({
children,
to,
external,
sameTab,
...other
}: LinkProps): JSX.Element => {
if (!external && /^\/(?!\/)/.test(to)) {
return (
<GatsbyLink to={to} {...other}>
{children}
</GatsbyLink>
);
} else if (sameTab && external) {
return (
<a href={to} {...other}>
{children}
</a>
);
}
return (
<a href={to} {...other} rel='noopener noreferrer' target='_blank'>
{children}
</a>
);
};
export default Link;
| bsd-3-clause |
JeanWolf/yii-doc-center | themes/jyk/info.html | 2629 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>礼品兑换</title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<meta name="format-detection" content="telephone=no" />
<meta name="format-detection" content="email=no" />
<link rel="stylesheet" href="./weui.min.css" />
<link rel="stylesheet" href="./example.css" />
</head>
<body>
<div class="container" id="container">
<div class="panel">
<div class="hd">
<img src="./gift.jpg" alt="your gift" style="width:100%;height:auto;" />
</div>
<div class="bd">
<div class="weui_cells_title">
<p>兑换成功</p>
<p>请填写收货地址信息</p>
</div>
<div class="weui_cells weui_cells_form">
<div class="weui_cell">
<div class="weui_cell_hd"><label class="weui_label">姓名</label></div>
<div class="weui_cell_bd weui_cell_primary">
<input class="weui_input" type="text" placeholder=""/>
</div>
</div>
<div class="weui_cell">
<div class="weui_cell_hd"><label class="weui_label">电话</label></div>
<div class="weui_cell_bd weui_cell_primary">
<input class="weui_input" type="text" placeholder=""/>
</div>
</div>
<div class="weui_cell">
<div class="weui_cell_hd"><label class="weui_label">地址</label></div>
<div class="weui_cell_bd weui_cell_primary">
<input class="weui_input" type="text" placeholder=""/>
</div>
</div>
<div class="weui_cell weui_vcode">
<div class="weui_cell_hd"><label class="weui_label">验证码</label></div>
<div class="weui_cell_bd weui_cell_primary">
<input class="weui_input" type="number" placeholder=""/>
</div>
<div class="weui_cell_ft" style="font-size: inherit;">
<i class="weui_icon_info_circle" id="ckCode"> 4321</i>
</div>
</div>
</div>
<div class="weui_btn_area">
<a class="weui_btn weui_btn_primary" href="./success.html" id="showTooltips">提交</a>
</div>
</div>
</div>
</div>
</body>
</html> | bsd-3-clause |
taojang/haskell-programming-book-exercise | src/ch29/Vigenere.hs | 1735 | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Char
import qualified Data.Map as M
import Data.Traversable (sequenceA)
import Control.Monad.Fix
import Control.Applicative ((<|>), liftA2)
import Control.Monad
import System.Environment (getArgs)
import System.Console.GetOpt
import System.IO
import System.Exit
data Args = Encrypt | Decrypt | Key String
deriving (Show, Eq, Ord)
tokey Encrypt = "e"
tokey Decrypt = "d"
tokey (Key _) = "k"
-- Perform encryption or decryption, depending on f.
crypt f key = map toLetter . zipWith f (cycle key)
where toLetter = chr . (+) (ord 'A')
-- Encrypt or decrypt one letter.
enc k c = (ord k + ord c) `mod` 26
dec k c = (ord c - ord k) `mod` 26
-- Given a key, encrypt or decrypt an input string.
encrypt = crypt enc
decrypt = crypt dec
-- Convert a string to have only upper case letters.
convert = map toUpper . filter isLetter
flags = [ Option ['e'] [] (NoArg Encrypt) "encryption"
, Option ['d'] [] (NoArg Decrypt) "decription"
, Option ['k'] [] (ReqArg Key "KEY") "key"
]
main :: IO ()
main = do
args <- getArgs
let (opts, _, _) = getOpt Permute flags args
let opts' = M.fromList $ fmap (\a -> (tokey a, a)) opts
let lookupOpts = flip M.lookup opts'
input <- getInput
run (lookupOpts "d" <|> lookupOpts "e") (lookupOpts "k") input
where
getInput = do
c <- hGetChar stdin
if c == '\n'
then return []
else (c:) <$> getInput
-- getInput = getLine
run (Just Encrypt) (Just (Key key)) input = putStrLn $ encrypt key input
run (Just Decrypt) (Just (Key key)) input = putStrLn $ decrypt key input
run _ _ _ = die "please use this software correctly."
| bsd-3-clause |
CIT-VSB-TUO/ResBill | resbill/src/main/java/cz/vsb/resbill/web/contracts/ContractPersonEditController.java | 7614 | package cz.vsb.resbill.web.contracts;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import cz.vsb.resbill.criteria.ContractPersonCriteria;
import cz.vsb.resbill.criteria.PersonCriteria;
import cz.vsb.resbill.criteria.PersonCriteria.OrderBy;
import cz.vsb.resbill.dto.ContractPersonEditDTO;
import cz.vsb.resbill.exception.ContractPersonServiceException;
import cz.vsb.resbill.model.ContractPerson;
import cz.vsb.resbill.model.Person;
import cz.vsb.resbill.service.ContractPersonService;
import cz.vsb.resbill.service.PersonService;
import cz.vsb.resbill.util.WebUtils;
/**
* A controller for handling requests for/from contracts/contractPersonEdit.html page template.
*
* @author HAL191
*
*/
@Controller
@RequestMapping("/contracts/persons/edit")
@SessionAttributes("contractPersonEditDTO")
public class ContractPersonEditController extends AbstractContractController {
private static final Logger log = LoggerFactory.getLogger(ContractPersonEditController.class);
private static final String CONTRACT_PERSON_EDIT_DTO_MODEL_KEY = "contractPersonEditDTO";
@Inject
private ContractPersonService contractPersonService;
@Inject
private PersonService personService;
@InitBinder
public void initBinder(WebDataBinder binder, Locale locale) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
@ModelAttribute("persons")
public List<Person> getPersons() {
try {
PersonCriteria criteria = new PersonCriteria();
criteria.setOrderBy(OrderBy.NAME);
return personService.findPersons(criteria, null, null);
} catch (Exception e) {
log.error("Cannot load persons", e);
return null;
}
}
private void loadContractPersonEditDTO(Integer personId, Integer contractId, ModelMap model) {
if (log.isDebugEnabled()) {
log.debug("Requested person.id=" + personId);
}
ContractPersonEditDTO cpEditDTO = null;
try {
if (personId != null) {
ContractPersonCriteria cpCriteria = new ContractPersonCriteria();
cpCriteria.setContractId(contractId);
cpCriteria.setPersonId(personId);
List<ContractPerson> cps = contractPersonService.findContractPersons(cpCriteria, null, Integer.valueOf(1));
cpEditDTO = new ContractPersonEditDTO(DataAccessUtils.singleResult(cps));
} else {
ContractPerson ct = new ContractPerson();
if (contractId != null) {
ct.setContract(contractService.findContract(contractId));
}
cpEditDTO = new ContractPersonEditDTO(ct);
}
model.addAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, cpEditDTO);
} catch (Exception e) {
log.error("Cannot load contract person with person.id: " + personId, e);
model.addAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, cpEditDTO);
WebUtils.addGlobalError(model, CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, "error.load.contract.person");
}
if (log.isDebugEnabled()) {
log.debug("Loaded contractPersonEditDTO: " + cpEditDTO);
}
}
/**
* Handles all GET requests. Binds loaded {@link ContractPersonEditDTO} entity with the key "contractPersonEditDTO" into a model.
*
* @param contractPersonId
* key of a {@link ContractPersonEditDTO} to view/edit
* @param model
* @return
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public String view(@RequestParam(value = "personId", required = false) Integer personId, @RequestParam(value = CONTRACT_ID_PARAM_KEY, required = false) Integer contractId, ModelMap model) {
loadContractPersonEditDTO(personId, contractId, model);
return "contracts/contractPersonEdit";
}
/**
* Handles POST requests for saving edited {@link ContractPersonEditDTO} instance.
*
* @param contractPersonEditDTO
* @param bindingResult
* @return
*/
@RequestMapping(value = "", method = RequestMethod.POST, params = "save")
public String save(@Valid @ModelAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY) ContractPersonEditDTO contractPersonEditDTO, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (log.isDebugEnabled()) {
log.debug("ContractPersonEditDTO to save: " + contractPersonEditDTO);
}
if (!bindingResult.hasErrors()) {
try {
ContractPerson ct = contractPersonEditDTO.getContractPerson();
if (ct.getId() == null) {
ct.setPerson(personService.findPerson(contractPersonEditDTO.getPersonId()));
}
ct = contractPersonService.saveContractPerson(ct);
if (log.isDebugEnabled()) {
log.debug("Saved contract person: " + ct);
}
redirectAttributes.addAttribute(CONTRACT_ID_PARAM_KEY, ct.getContract().getId());
return "redirect:/contracts/overview";
} catch (ContractPersonServiceException e) {
switch (e.getReason()) {
case NONUNIQUE_CONTRACT_PERSON:
bindingResult.reject("error.save.contract.person.nonunique");
break;
case CONTRACT_PERSON_MODIFICATION:
bindingResult.reject("error.save.contract.person.modified");
break;
default:
log.warn("Unsupported reason: " + e);
bindingResult.reject("error.save.contract.person");
break;
}
} catch (Exception e) {
log.error("Cannot save ContractPersonEditDTO: " + contractPersonEditDTO, e);
bindingResult.reject("error.save.contract.person");
}
} else {
bindingResult.reject("error.save.contract.person.validation");
}
return "contracts/contractPersonEdit";
}
/**
* Handle POST requests for deleting {@link ContractPersonEditDTO} instance.
*
* @param contractPersonEditDTO
* @param bindingResult
* @return
*/
@RequestMapping(value = "", method = RequestMethod.POST, params = "delete")
public String delete(@ModelAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY) ContractPersonEditDTO contractPersonEditDTO, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (log.isDebugEnabled()) {
log.debug("ContractPersonEditDTO to delete: " + contractPersonEditDTO);
}
try {
ContractPerson ct = contractPersonService.deleteContractPerson(contractPersonEditDTO.getContractPerson().getId());
if (log.isDebugEnabled()) {
log.debug("Deleted ContractPerson: " + ct);
}
redirectAttributes.addAttribute(CONTRACT_ID_PARAM_KEY, ct.getContract().getId());
return "redirect:/contracts/overview";
} catch (ContractPersonServiceException e) {
log.warn("Unsupported cause: " + e);
bindingResult.reject("error.delete.contract.person");
} catch (Exception e) {
log.error("Cannot delete ContractPersonEditDTO: " + contractPersonEditDTO, e);
bindingResult.reject("error.delete.contract.person");
}
return "contracts/contractPersonEdit";
}
}
| bsd-3-clause |
ekmett/ghc | compiler/main/DynFlags.hs | 154957 | -------------------------------------------------------------------------------
--
-- | Dynamic flags
--
-- Most flags are dynamic flags, which means they can change from compilation
-- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
-- session can be using different dynamic flags. Dynamic flags can also be set
-- at the prompt in GHCi.
--
-- (c) The University of Glasgow 2005
--
-------------------------------------------------------------------------------
{-# OPTIONS -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
module DynFlags (
-- * Dynamic flags and associated configuration types
DumpFlag(..),
GeneralFlag(..),
WarningFlag(..),
ExtensionFlag(..),
Language(..),
PlatformConstants(..),
FatalMessager, LogAction, FlushOut(..), FlushErr(..),
ProfAuto(..),
glasgowExtsFlags,
dopt, dopt_set, dopt_unset,
gopt, gopt_set, gopt_unset,
wopt, wopt_set, wopt_unset,
xopt, xopt_set, xopt_unset,
lang_set,
whenGeneratingDynamicToo, ifGeneratingDynamicToo,
whenCannotGenerateDynamicToo,
dynamicTooMkDynamicDynFlags,
DynFlags(..),
HasDynFlags(..), ContainsDynFlags(..),
RtsOptsEnabled(..),
HscTarget(..), isObjectTarget, defaultObjectTarget,
targetRetainsAllBindings,
GhcMode(..), isOneShot,
GhcLink(..), isNoLink,
PackageFlag(..),
PkgConfRef(..),
Option(..), showOpt,
DynLibLoader(..),
fFlags, fWarningFlags, fLangFlags, xFlags,
dynFlagDependencies,
tablesNextToCode, mkTablesNextToCode,
printOutputForUser, printInfoForUser,
Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
wayGeneralFlags, wayUnsetGeneralFlags,
-- ** Safe Haskell
SafeHaskellMode(..),
safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
packageTrustOn,
safeDirectImpsReq, safeImplicitImpsReq,
unsafeFlags,
-- ** System tool settings and locations
Settings(..),
targetPlatform,
ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
extraGccViaCFlags, systemPackageConfig,
pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc,
opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
opt_windres, opt_lo, opt_lc,
-- ** Manipulating DynFlags
defaultDynFlags, -- Settings -> DynFlags
defaultWays,
interpWays,
initDynFlags, -- DynFlags -> IO DynFlags
defaultFatalMessager,
defaultLogAction,
defaultLogActionHPrintDoc,
defaultLogActionHPutStrDoc,
defaultFlushOut,
defaultFlushErr,
getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
getVerbFlags,
updOptLevel,
setTmpDir,
setPackageName,
-- ** Parsing DynFlags
parseDynamicFlagsCmdLine,
parseDynamicFilePragma,
parseDynamicFlagsFull,
-- ** Available DynFlags
allFlags,
flagsAll,
flagsDynamic,
flagsPackage,
supportedLanguagesAndExtensions,
languageExtensions,
-- ** DynFlags C compiler options
picCCOpts, picPOpts,
-- * Configuration of the stg-to-stg passes
StgToDo(..),
getStgToDo,
-- * Compiler configuration suitable for display to the user
compilerInfo,
#ifdef GHCI
-- Only in stage 2 can we be sure that the RTS
-- exposes the appropriate runtime boolean
rtsIsProfiled,
#endif
#include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
bLOCK_SIZE_W,
wORD_SIZE_IN_BITS,
tAG_MASK,
mAX_PTR_TAG,
tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
-- * SSE and AVX
isSseEnabled,
isSse2Enabled,
isSse4_2Enabled,
isAvxEnabled,
isAvx2Enabled,
isAvx512cdEnabled,
isAvx512erEnabled,
isAvx512fEnabled,
isAvx512pfEnabled,
-- * Linker information
LinkerInfo(..),
) where
#include "HsVersions.h"
import Platform
import PlatformConstants
import Module
import PackageConfig
import {-# SOURCE #-} Hooks
import {-# SOURCE #-} PrelNames ( mAIN )
import {-# SOURCE #-} Packages (PackageState)
import DriverPhases ( Phase(..), phaseInputExt )
import Config
import CmdLineParser
import Constants
import Panic
import Util
import Maybes ( orElse )
import MonadUtils
import qualified Pretty
import SrcLoc
import FastString
import Outputable
#ifdef GHCI
import Foreign.C ( CInt(..) )
#endif
import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
import System.IO.Unsafe ( unsafePerformIO )
import Data.IORef
import Control.Monad
import Data.Bits
import Data.Char
import Data.Int
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word
import System.FilePath
import System.IO
import System.IO.Error
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import GHC.Foreign (withCString, peekCString)
-- -----------------------------------------------------------------------------
-- DynFlags
data DumpFlag
-- debugging flags
= Opt_D_dump_cmm
| Opt_D_dump_cmm_raw
-- All of the cmm subflags (there are a lot!) Automatically
-- enabled if you run -ddump-cmm
| Opt_D_dump_cmm_cfg
| Opt_D_dump_cmm_cbe
| Opt_D_dump_cmm_proc
| Opt_D_dump_cmm_sink
| Opt_D_dump_cmm_sp
| Opt_D_dump_cmm_procmap
| Opt_D_dump_cmm_split
| Opt_D_dump_cmm_info
| Opt_D_dump_cmm_cps
-- end cmm subflags
| Opt_D_dump_asm
| Opt_D_dump_asm_native
| Opt_D_dump_asm_liveness
| Opt_D_dump_asm_regalloc
| Opt_D_dump_asm_regalloc_stages
| Opt_D_dump_asm_conflicts
| Opt_D_dump_asm_stats
| Opt_D_dump_asm_expanded
| Opt_D_dump_llvm
| Opt_D_dump_core_stats
| Opt_D_dump_deriv
| Opt_D_dump_ds
| Opt_D_dump_foreign
| Opt_D_dump_inlinings
| Opt_D_dump_rule_firings
| Opt_D_dump_rule_rewrites
| Opt_D_dump_simpl_trace
| Opt_D_dump_occur_anal
| Opt_D_dump_parsed
| Opt_D_dump_rn
| Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
| Opt_D_dump_simpl
| Opt_D_dump_simpl_iterations
| Opt_D_dump_simpl_phases
| Opt_D_dump_spec
| Opt_D_dump_prep
| Opt_D_dump_stg
| Opt_D_dump_stranal
| Opt_D_dump_tc
| Opt_D_dump_types
| Opt_D_dump_rules
| Opt_D_dump_cse
| Opt_D_dump_worker_wrapper
| Opt_D_dump_rn_trace
| Opt_D_dump_rn_stats
| Opt_D_dump_opt_cmm
| Opt_D_dump_simpl_stats
| Opt_D_dump_cs_trace -- Constraint solver in type checker
| Opt_D_dump_tc_trace
| Opt_D_dump_if_trace
| Opt_D_dump_vt_trace
| Opt_D_dump_splices
| Opt_D_dump_BCOs
| Opt_D_dump_vect
| Opt_D_dump_ticked
| Opt_D_dump_rtti
| Opt_D_source_stats
| Opt_D_verbose_stg2stg
| Opt_D_dump_hi
| Opt_D_dump_hi_diffs
| Opt_D_dump_mod_cycles
| Opt_D_dump_view_pattern_commoning
| Opt_D_verbose_core2core
deriving (Eq, Show, Enum)
-- | Enumerates the simple on-or-off dynamic flags
data GeneralFlag
= Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
| Opt_D_faststring_stats
| Opt_D_dump_minimal_imports
| Opt_DoCoreLinting
| Opt_DoStgLinting
| Opt_DoCmmLinting
| Opt_DoAsmLinting
| Opt_NoLlvmMangler -- hidden flag
| Opt_WarnIsError -- -Werror; makes warnings fatal
| Opt_PrintExplicitForalls
-- optimisation opts
| Opt_Strictness
| Opt_LateDmdAnal
| Opt_KillAbsence
| Opt_KillOneShot
| Opt_FullLaziness
| Opt_FloatIn
| Opt_Specialise
| Opt_StaticArgumentTransformation
| Opt_CSE
| Opt_LiberateCase
| Opt_SpecConstr
| Opt_DoLambdaEtaExpansion
| Opt_IgnoreAsserts
| Opt_DoEtaReduction
| Opt_CaseMerge
| Opt_UnboxStrictFields
| Opt_UnboxSmallStrictFields
| Opt_DictsCheap
| Opt_EnableRewriteRules -- Apply rewrite rules during simplification
| Opt_Vectorise
| Opt_VectorisationAvoidance
| Opt_RegsGraph -- do graph coloring register allocation
| Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
| Opt_PedanticBottoms -- Be picky about how we treat bottom
| Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
| Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag)
| Opt_IrrefutableTuples
| Opt_CmmSink
| Opt_CmmElimCommonBlocks
| Opt_OmitYields
| Opt_SimpleListLiterals
| Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
| Opt_DictsStrict -- be strict in argument dictionaries
| Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
| Opt_Loopification -- See Note [Self-recursive tail calls]
-- Interface files
| Opt_IgnoreInterfacePragmas
| Opt_OmitInterfacePragmas
| Opt_ExposeAllUnfoldings
-- profiling opts
| Opt_AutoSccsOnIndividualCafs
| Opt_ProfCountEntries
-- misc opts
| Opt_Pp
| Opt_ForceRecomp
| Opt_ExcessPrecision
| Opt_EagerBlackHoling
| Opt_NoHsMain
| Opt_SplitObjs
| Opt_StgStats
| Opt_HideAllPackages
| Opt_PrintBindResult
| Opt_Haddock
| Opt_HaddockOptions
| Opt_Hpc_No_Auto
| Opt_BreakOnException
| Opt_BreakOnError
| Opt_PrintEvldWithShow
| Opt_PrintBindContents
| Opt_GenManifest
| Opt_EmbedManifest
| Opt_EmitExternalCore
| Opt_SharedImplib
| Opt_BuildingCabalPackage
| Opt_IgnoreDotGhci
| Opt_GhciSandbox
| Opt_GhciHistory
| Opt_HelpfulErrors
| Opt_DeferTypeErrors
| Opt_Parallel
| Opt_GranMacros
| Opt_PIC
| Opt_SccProfilingOn
| Opt_Ticky
| Opt_Ticky_Allocd
| Opt_Ticky_LNE
| Opt_Ticky_Dyn_Thunk
| Opt_Static
| Opt_RPath
| Opt_RelativeDynlibPaths
| Opt_Hpc
| Opt_FlatCache
-- PreInlining is on by default. The option is there just to see how
-- bad things get if you turn it off!
| Opt_SimplPreInlining
-- output style opts
| Opt_ErrorSpans -- Include full span info in error messages,
-- instead of just the start position.
| Opt_PprCaseAsLet
-- Suppress all coercions, them replacing with '...'
| Opt_SuppressCoercions
| Opt_SuppressVarKinds
-- Suppress module id prefixes on variables.
| Opt_SuppressModulePrefixes
-- Suppress type applications.
| Opt_SuppressTypeApplications
-- Suppress info such as arity and unfoldings on identifiers.
| Opt_SuppressIdInfo
-- Suppress separate type signatures in core, but leave types on
-- lambda bound vars
| Opt_SuppressTypeSignatures
-- Suppress unique ids on variables.
-- Except for uniques, as some simplifier phases introduce new
-- variables that have otherwise identical names.
| Opt_SuppressUniques
-- temporary flags
| Opt_RunCPS
| Opt_RunCPSZ
| Opt_AutoLinkPackages
| Opt_ImplicitImportQualified
-- keeping stuff
| Opt_KeepHiDiffs
| Opt_KeepHcFiles
| Opt_KeepSFiles
| Opt_KeepTmpFiles
| Opt_KeepRawTokenStream
| Opt_KeepLlvmFiles
| Opt_BuildDynamicToo
-- safe haskell flags
| Opt_DistrustAllPackages
| Opt_PackageTrust
deriving (Eq, Show, Enum)
data WarningFlag =
Opt_WarnDuplicateExports
| Opt_WarnDuplicateConstraints
| Opt_WarnHiShadows
| Opt_WarnImplicitPrelude
| Opt_WarnIncompletePatterns
| Opt_WarnIncompleteUniPatterns
| Opt_WarnIncompletePatternsRecUpd
| Opt_WarnOverflowedLiterals
| Opt_WarnEmptyEnumerations
| Opt_WarnMissingFields
| Opt_WarnMissingImportList
| Opt_WarnMissingMethods
| Opt_WarnMissingSigs
| Opt_WarnMissingLocalSigs
| Opt_WarnNameShadowing
| Opt_WarnOverlappingPatterns
| Opt_WarnTypeDefaults
| Opt_WarnMonomorphism
| Opt_WarnUnusedBinds
| Opt_WarnUnusedImports
| Opt_WarnUnusedMatches
| Opt_WarnWarningsDeprecations
| Opt_WarnDeprecatedFlags
| Opt_WarnAMP
| Opt_WarnDodgyExports
| Opt_WarnDodgyImports
| Opt_WarnOrphans
| Opt_WarnAutoOrphans
| Opt_WarnIdentities
| Opt_WarnTabs
| Opt_WarnUnrecognisedPragmas
| Opt_WarnDodgyForeignImports
| Opt_WarnLazyUnliftedBindings
| Opt_WarnUnusedDoBind
| Opt_WarnWrongDoBind
| Opt_WarnAlternativeLayoutRuleTransitional
| Opt_WarnUnsafe
| Opt_WarnSafe
| Opt_WarnPointlessPragmas
| Opt_WarnUnsupportedCallingConventions
| Opt_WarnUnsupportedLlvmVersion
| Opt_WarnInlineRuleShadowing
deriving (Eq, Show, Enum)
data Language = Haskell98 | Haskell2010
deriving Enum
-- | The various Safe Haskell modes
data SafeHaskellMode
= Sf_None
| Sf_Unsafe
| Sf_Trustworthy
| Sf_Safe
| Sf_SafeInferred
deriving (Eq)
instance Show SafeHaskellMode where
show Sf_None = "None"
show Sf_Unsafe = "Unsafe"
show Sf_Trustworthy = "Trustworthy"
show Sf_Safe = "Safe"
show Sf_SafeInferred = "Safe-Inferred"
instance Outputable SafeHaskellMode where
ppr = text . show
data ExtensionFlag
= Opt_Cpp
| Opt_OverlappingInstances
| Opt_UndecidableInstances
| Opt_IncoherentInstances
| Opt_MonomorphismRestriction
| Opt_MonoPatBinds
| Opt_MonoLocalBinds
| Opt_RelaxedPolyRec -- Deprecated
| Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
| Opt_ForeignFunctionInterface
| Opt_UnliftedFFITypes
| Opt_InterruptibleFFI
| Opt_CApiFFI
| Opt_GHCForeignImportPrim
| Opt_JavaScriptFFI
| Opt_ParallelArrays -- Syntactic support for parallel arrays
| Opt_Arrows -- Arrow-notation syntax
| Opt_TemplateHaskell
| Opt_QuasiQuotes
| Opt_ImplicitParams
| Opt_ImplicitPrelude
| Opt_ScopedTypeVariables
| Opt_AllowAmbiguousTypes
| Opt_UnboxedTuples
| Opt_BangPatterns
| Opt_TypeFamilies
| Opt_OverloadedStrings
| Opt_OverloadedLists
| Opt_NumDecimals
| Opt_DisambiguateRecordFields
| Opt_RecordWildCards
| Opt_RecordPuns
| Opt_ViewPatterns
| Opt_GADTs
| Opt_GADTSyntax
| Opt_NPlusKPatterns
| Opt_DoAndIfThenElse
| Opt_RebindableSyntax
| Opt_ConstraintKinds
| Opt_PolyKinds -- Kind polymorphism
| Opt_DataKinds -- Datatype promotion
| Opt_InstanceSigs
| Opt_StandaloneDeriving
| Opt_DeriveDataTypeable
| Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
| Opt_DeriveFunctor
| Opt_DeriveTraversable
| Opt_DeriveFoldable
| Opt_DeriveGeneric -- Allow deriving Generic/1
| Opt_DefaultSignatures -- Allow extra signatures for defmeths
| Opt_TypeSynonymInstances
| Opt_FlexibleContexts
| Opt_FlexibleInstances
| Opt_ConstrainedClassMethods
| Opt_MultiParamTypeClasses
| Opt_NullaryTypeClasses
| Opt_FunctionalDependencies
| Opt_UnicodeSyntax
| Opt_ExistentialQuantification
| Opt_MagicHash
| Opt_EmptyDataDecls
| Opt_KindSignatures
| Opt_RoleAnnotations
| Opt_ParallelListComp
| Opt_TransformListComp
| Opt_MonadComprehensions
| Opt_GeneralizedNewtypeDeriving
| Opt_RecursiveDo
| Opt_PostfixOperators
| Opt_TupleSections
| Opt_PatternGuards
| Opt_LiberalTypeSynonyms
| Opt_RankNTypes
| Opt_ImpredicativeTypes
| Opt_TypeOperators
| Opt_ExplicitNamespaces
| Opt_PackageImports
| Opt_ExplicitForAll
| Opt_AlternativeLayoutRule
| Opt_AlternativeLayoutRuleTransitional
| Opt_DatatypeContexts
| Opt_NondecreasingIndentation
| Opt_RelaxedLayout
| Opt_TraditionalRecordSyntax
| Opt_LambdaCase
| Opt_MultiWayIf
| Opt_TypeHoles
| Opt_NegativeLiterals
| Opt_EmptyCase
deriving (Eq, Enum, Show)
-- | Contains not only a collection of 'GeneralFlag's but also a plethora of
-- information relating to the compilation of a single file or GHC session
data DynFlags = DynFlags {
ghcMode :: GhcMode,
ghcLink :: GhcLink,
hscTarget :: HscTarget,
settings :: Settings,
verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
optLevel :: Int, -- ^ Optimisation level
simplPhases :: Int, -- ^ Number of simplifier phases
maxSimplIterations :: Int, -- ^ Max simplifier iterations
shouldDumpSimplPhase :: Maybe String,
ruleCheck :: Maybe String,
strictnessBefore :: [Int], -- ^ Additional demand analysis
parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
-- in --make mode, where Nothing ==> compile as
-- many in parallel as there are CPUs.
maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
-- to show in type error messages
simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
-- Not optional; otherwise ForceSpecConstr can diverge.
liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
-- See CoreMonad.FloatOutSwitches
historySize :: Int,
cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
importPaths :: [FilePath],
mainModIs :: Module,
mainFunIs :: Maybe String,
ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
thisPackage :: PackageId, -- ^ name of package currently being compiled
-- ways
ways :: [Way], -- ^ Way flags from the command line
buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
rtsBuildTag :: String, -- ^ The RTS \"way\"
-- For object splitting
splitInfo :: Maybe (String,Int),
-- paths etc.
objectDir :: Maybe String,
dylibInstallName :: Maybe String,
hiDir :: Maybe String,
stubDir :: Maybe String,
dumpDir :: Maybe String,
objectSuf :: String,
hcSuf :: String,
hiSuf :: String,
canGenerateDynamicToo :: IORef Bool,
dynObjectSuf :: String,
dynHiSuf :: String,
-- Packages.isDllName needs to know whether a call is within a
-- single DLL or not. Normally it does this by seeing if the call
-- is to the same package, but for the ghc package, we split the
-- package between 2 DLLs. The dllSplit tells us which sets of
-- modules are in which package.
dllSplitFile :: Maybe FilePath,
dllSplit :: Maybe [Set String],
outputFile :: Maybe String,
dynOutputFile :: Maybe String,
outputHi :: Maybe String,
dynLibLoader :: DynLibLoader,
-- | This is set by 'DriverPipeline.runPipeline' based on where
-- its output is going.
dumpPrefix :: Maybe FilePath,
-- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
-- Set by @-ddump-file-prefix@
dumpPrefixForce :: Maybe FilePath,
ldInputs :: [Option],
includePaths :: [String],
libraryPaths :: [String],
frameworkPaths :: [String], -- used on darwin only
cmdlineFrameworks :: [String], -- ditto
rtsOpts :: Maybe String,
rtsOptsEnabled :: RtsOptsEnabled,
hpcDir :: String, -- ^ Path to store the .mix files
-- Plugins
pluginModNames :: [ModuleName],
pluginModNameOpts :: [(ModuleName,String)],
-- GHC API hooks
hooks :: Hooks,
-- For ghc -M
depMakefile :: FilePath,
depIncludePkgDeps :: Bool,
depExcludeMods :: [ModuleName],
depSuffixes :: [String],
-- Package flags
extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
-- ^ The @-package-db@ flags given on the command line, in the order
-- they appeared.
packageFlags :: [PackageFlag],
-- ^ The @-package@ and @-hide-package@ flags from the command-line
-- Package state
-- NB. do not modify this field, it is calculated by
-- Packages.initPackages and Packages.updatePackages.
pkgDatabase :: Maybe [PackageConfig],
pkgState :: PackageState,
-- Temporary files
-- These have to be IORefs, because the defaultCleanupHandler needs to
-- know what to clean when an exception happens
filesToClean :: IORef [FilePath],
dirsToClean :: IORef (Map FilePath FilePath),
filesToNotIntermediateClean :: IORef [FilePath],
-- The next available suffix to uniquely name a temp file, updated atomically
nextTempSuffix :: IORef Int,
-- Names of files which were generated from -ddump-to-file; used to
-- track which ones we need to truncate because it's our first run
-- through
generatedDumps :: IORef (Set FilePath),
-- hsc dynamic flags
dumpFlags :: IntSet,
generalFlags :: IntSet,
warningFlags :: IntSet,
-- Don't change this without updating extensionFlags:
language :: Maybe Language,
-- | Safe Haskell mode
safeHaskell :: SafeHaskellMode,
-- We store the location of where some extension and flags were turned on so
-- we can produce accurate error messages when Safe Haskell fails due to
-- them.
thOnLoc :: SrcSpan,
newDerivOnLoc :: SrcSpan,
pkgTrustOnLoc :: SrcSpan,
warnSafeOnLoc :: SrcSpan,
warnUnsafeOnLoc :: SrcSpan,
-- Don't change this without updating extensionFlags:
extensions :: [OnOff ExtensionFlag],
-- extensionFlags should always be equal to
-- flattenExtensionFlags language extensions
extensionFlags :: IntSet,
-- Unfolding control
-- See Note [Discounts and thresholds] in CoreUnfold
ufCreationThreshold :: Int,
ufUseThreshold :: Int,
ufFunAppDiscount :: Int,
ufDictDiscount :: Int,
ufKeenessFactor :: Float,
ufDearOp :: Int,
maxWorkerArgs :: Int,
ghciHistSize :: Int,
-- | MsgDoc output action: use "ErrUtils" instead of this if you can
log_action :: LogAction,
flushOut :: FlushOut,
flushErr :: FlushErr,
haddockOptions :: Maybe String,
ghciScripts :: [String],
-- Output style options
pprUserLength :: Int,
pprCols :: Int,
traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
useUnicodeQuotes :: Bool,
-- | what kind of {-# SCC #-} to add automatically
profAuto :: ProfAuto,
interactivePrint :: Maybe String,
llvmVersion :: IORef Int,
nextWrapperNum :: IORef (ModuleEnv Int),
-- | Machine dependant flags (-m<blah> stuff)
sseVersion :: Maybe (Int, Int), -- (major, minor)
avx :: Bool,
avx2 :: Bool,
avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
avx512f :: Bool, -- Enable AVX-512 instructions.
avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
-- | Run-time linker information (what options we need, etc.)
rtldFlags :: IORef (Maybe LinkerInfo)
}
class HasDynFlags m where
getDynFlags :: m DynFlags
class ContainsDynFlags t where
extractDynFlags :: t -> DynFlags
replaceDynFlags :: t -> DynFlags -> t
data ProfAuto
= NoProfAuto -- ^ no SCC annotations added
| ProfAutoAll -- ^ top-level and nested functions are annotated
| ProfAutoTop -- ^ top-level functions annotated only
| ProfAutoExports -- ^ exported functions annotated only
| ProfAutoCalls -- ^ annotate call-sites
deriving (Enum)
data Settings = Settings {
sTargetPlatform :: Platform, -- Filled in by SysTools
sGhcUsagePath :: FilePath, -- Filled in by SysTools
sGhciUsagePath :: FilePath, -- ditto
sTopDir :: FilePath,
sTmpDir :: String, -- no trailing '/'
-- You shouldn't need to look things up in rawSettings directly.
-- They should have their own fields instead.
sRawSettings :: [(String, String)],
sExtraGccViaCFlags :: [String],
sSystemPackageConfig :: FilePath,
sLdSupportsCompactUnwind :: Bool,
sLdSupportsBuildId :: Bool,
sLdSupportsFilelist :: Bool,
sLdIsGnuLd :: Bool,
-- commands for particular phases
sPgm_L :: String,
sPgm_P :: (String,[Option]),
sPgm_F :: String,
sPgm_c :: (String,[Option]),
sPgm_s :: (String,[Option]),
sPgm_a :: (String,[Option]),
sPgm_l :: (String,[Option]),
sPgm_dll :: (String,[Option]),
sPgm_T :: String,
sPgm_sysman :: String,
sPgm_windres :: String,
sPgm_libtool :: String,
sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
-- options for particular phases
sOpt_L :: [String],
sOpt_P :: [String],
sOpt_F :: [String],
sOpt_c :: [String],
sOpt_a :: [String],
sOpt_l :: [String],
sOpt_windres :: [String],
sOpt_lo :: [String], -- LLVM: llvm optimiser
sOpt_lc :: [String], -- LLVM: llc static compiler
sPlatformConstants :: PlatformConstants
}
targetPlatform :: DynFlags -> Platform
targetPlatform dflags = sTargetPlatform (settings dflags)
ghcUsagePath :: DynFlags -> FilePath
ghcUsagePath dflags = sGhcUsagePath (settings dflags)
ghciUsagePath :: DynFlags -> FilePath
ghciUsagePath dflags = sGhciUsagePath (settings dflags)
topDir :: DynFlags -> FilePath
topDir dflags = sTopDir (settings dflags)
tmpDir :: DynFlags -> String
tmpDir dflags = sTmpDir (settings dflags)
rawSettings :: DynFlags -> [(String, String)]
rawSettings dflags = sRawSettings (settings dflags)
extraGccViaCFlags :: DynFlags -> [String]
extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
systemPackageConfig :: DynFlags -> FilePath
systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
pgm_L :: DynFlags -> String
pgm_L dflags = sPgm_L (settings dflags)
pgm_P :: DynFlags -> (String,[Option])
pgm_P dflags = sPgm_P (settings dflags)
pgm_F :: DynFlags -> String
pgm_F dflags = sPgm_F (settings dflags)
pgm_c :: DynFlags -> (String,[Option])
pgm_c dflags = sPgm_c (settings dflags)
pgm_s :: DynFlags -> (String,[Option])
pgm_s dflags = sPgm_s (settings dflags)
pgm_a :: DynFlags -> (String,[Option])
pgm_a dflags = sPgm_a (settings dflags)
pgm_l :: DynFlags -> (String,[Option])
pgm_l dflags = sPgm_l (settings dflags)
pgm_dll :: DynFlags -> (String,[Option])
pgm_dll dflags = sPgm_dll (settings dflags)
pgm_T :: DynFlags -> String
pgm_T dflags = sPgm_T (settings dflags)
pgm_sysman :: DynFlags -> String
pgm_sysman dflags = sPgm_sysman (settings dflags)
pgm_windres :: DynFlags -> String
pgm_windres dflags = sPgm_windres (settings dflags)
pgm_libtool :: DynFlags -> String
pgm_libtool dflags = sPgm_libtool (settings dflags)
pgm_lo :: DynFlags -> (String,[Option])
pgm_lo dflags = sPgm_lo (settings dflags)
pgm_lc :: DynFlags -> (String,[Option])
pgm_lc dflags = sPgm_lc (settings dflags)
opt_L :: DynFlags -> [String]
opt_L dflags = sOpt_L (settings dflags)
opt_P :: DynFlags -> [String]
opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
++ sOpt_P (settings dflags)
opt_F :: DynFlags -> [String]
opt_F dflags = sOpt_F (settings dflags)
opt_c :: DynFlags -> [String]
opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
++ sOpt_c (settings dflags)
opt_a :: DynFlags -> [String]
opt_a dflags = sOpt_a (settings dflags)
opt_l :: DynFlags -> [String]
opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
++ sOpt_l (settings dflags)
opt_windres :: DynFlags -> [String]
opt_windres dflags = sOpt_windres (settings dflags)
opt_lo :: DynFlags -> [String]
opt_lo dflags = sOpt_lo (settings dflags)
opt_lc :: DynFlags -> [String]
opt_lc dflags = sOpt_lc (settings dflags)
-- | The target code type of the compilation (if any).
--
-- Whenever you change the target, also make sure to set 'ghcLink' to
-- something sensible.
--
-- 'HscNothing' can be used to avoid generating any output, however, note
-- that:
--
-- * If a program uses Template Haskell the typechecker may try to run code
-- from an imported module. This will fail if no code has been generated
-- for this module. You can use 'GHC.needsTemplateHaskell' to detect
-- whether this might be the case and choose to either switch to a
-- different target or avoid typechecking such modules. (The latter may be
-- preferable for security reasons.)
--
data HscTarget
= HscC -- ^ Generate C code.
| HscAsm -- ^ Generate assembly using the native code generator.
| HscLlvm -- ^ Generate assembly using the llvm code generator.
| HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
| HscNothing -- ^ Don't generate any code. See notes above.
deriving (Eq, Show)
-- | Will this target result in an object file on the disk?
isObjectTarget :: HscTarget -> Bool
isObjectTarget HscC = True
isObjectTarget HscAsm = True
isObjectTarget HscLlvm = True
isObjectTarget _ = False
-- | Does this target retain *all* top-level bindings for a module,
-- rather than just the exported bindings, in the TypeEnv and compiled
-- code (if any)? In interpreted mode we do this, so that GHCi can
-- call functions inside a module. In HscNothing mode we also do it,
-- so that Haddock can get access to the GlobalRdrEnv for a module
-- after typechecking it.
targetRetainsAllBindings :: HscTarget -> Bool
targetRetainsAllBindings HscInterpreted = True
targetRetainsAllBindings HscNothing = True
targetRetainsAllBindings _ = False
-- | The 'GhcMode' tells us whether we're doing multi-module
-- compilation (controlled via the "GHC" API) or one-shot
-- (single-module) compilation. This makes a difference primarily to
-- the "Finder": in one-shot mode we look for interface files for
-- imported modules, but in multi-module mode we look for source files
-- in order to check whether they need to be recompiled.
data GhcMode
= CompManager -- ^ @\-\-make@, GHCi, etc.
| OneShot -- ^ @ghc -c Foo.hs@
| MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
deriving Eq
instance Outputable GhcMode where
ppr CompManager = ptext (sLit "CompManager")
ppr OneShot = ptext (sLit "OneShot")
ppr MkDepend = ptext (sLit "MkDepend")
isOneShot :: GhcMode -> Bool
isOneShot OneShot = True
isOneShot _other = False
-- | What to do in the link step, if there is one.
data GhcLink
= NoLink -- ^ Don't link at all
| LinkBinary -- ^ Link object code into a binary
| LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
-- bytecode and object code).
| LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
| LinkStaticLib -- ^ Link objects into a static lib
deriving (Eq, Show)
isNoLink :: GhcLink -> Bool
isNoLink NoLink = True
isNoLink _ = False
data PackageFlag
= ExposePackage String
| ExposePackageId String
| HidePackage String
| IgnorePackage String
| TrustPackage String
| DistrustPackage String
deriving (Eq, Show)
defaultHscTarget :: Platform -> HscTarget
defaultHscTarget = defaultObjectTarget
-- | The 'HscTarget' value corresponding to the default way to create
-- object files on the current platform.
defaultObjectTarget :: Platform -> HscTarget
defaultObjectTarget platform
| platformUnregisterised platform = HscC
| cGhcWithNativeCodeGen == "YES" = HscAsm
| otherwise = HscLlvm
tablesNextToCode :: DynFlags -> Bool
tablesNextToCode dflags
= mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
-- Determines whether we will be compiling
-- info tables that reside just before the entry code, or with an
-- indirection to the entry code. See TABLES_NEXT_TO_CODE in
-- includes/rts/storage/InfoTables.h.
mkTablesNextToCode :: Bool -> Bool
mkTablesNextToCode unregisterised
= not unregisterised && cGhcEnableTablesNextToCode == "YES"
data DynLibLoader
= Deployable
| SystemDependent
deriving Eq
data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
deriving (Show)
-----------------------------------------------------------------------------
-- Ways
-- The central concept of a "way" is that all objects in a given
-- program must be compiled in the same "way". Certain options change
-- parameters of the virtual machine, eg. profiling adds an extra word
-- to the object header, so profiling objects cannot be linked with
-- non-profiling objects.
-- After parsing the command-line options, we determine which "way" we
-- are building - this might be a combination way, eg. profiling+threaded.
-- We then find the "build-tag" associated with this way, and this
-- becomes the suffix used to find .hi files and libraries used in
-- this compilation.
data Way
= WayCustom String -- for GHC API clients building custom variants
| WayThreaded
| WayDebug
| WayProf
| WayEventLog
| WayPar
| WayGran
| WayNDP
| WayDyn
deriving (Eq, Ord, Show)
allowed_combination :: [Way] -> Bool
allowed_combination way = and [ x `allowedWith` y
| x <- way, y <- way, x < y ]
where
-- Note ordering in these tests: the left argument is
-- <= the right argument, according to the Ord instance
-- on Way above.
-- dyn is allowed with everything
_ `allowedWith` WayDyn = True
WayDyn `allowedWith` _ = True
-- debug is allowed with everything
_ `allowedWith` WayDebug = True
WayDebug `allowedWith` _ = True
(WayCustom {}) `allowedWith` _ = True
WayProf `allowedWith` WayNDP = True
WayThreaded `allowedWith` WayProf = True
WayThreaded `allowedWith` WayEventLog = True
_ `allowedWith` _ = False
mkBuildTag :: [Way] -> String
mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
wayTag :: Way -> String
wayTag (WayCustom xs) = xs
wayTag WayThreaded = "thr"
wayTag WayDebug = "debug"
wayTag WayDyn = "dyn"
wayTag WayProf = "p"
wayTag WayEventLog = "l"
wayTag WayPar = "mp"
wayTag WayGran = "mg"
wayTag WayNDP = "ndp"
wayRTSOnly :: Way -> Bool
wayRTSOnly (WayCustom {}) = False
wayRTSOnly WayThreaded = True
wayRTSOnly WayDebug = True
wayRTSOnly WayDyn = False
wayRTSOnly WayProf = False
wayRTSOnly WayEventLog = True
wayRTSOnly WayPar = False
wayRTSOnly WayGran = False
wayRTSOnly WayNDP = False
wayDesc :: Way -> String
wayDesc (WayCustom xs) = xs
wayDesc WayThreaded = "Threaded"
wayDesc WayDebug = "Debug"
wayDesc WayDyn = "Dynamic"
wayDesc WayProf = "Profiling"
wayDesc WayEventLog = "RTS Event Logging"
wayDesc WayPar = "Parallel"
wayDesc WayGran = "GranSim"
wayDesc WayNDP = "Nested data parallelism"
-- Turn these flags on when enabling this way
wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayGeneralFlags _ (WayCustom {}) = []
wayGeneralFlags _ WayThreaded = []
wayGeneralFlags _ WayDebug = []
wayGeneralFlags _ WayDyn = [Opt_PIC]
wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
wayGeneralFlags _ WayEventLog = []
wayGeneralFlags _ WayPar = [Opt_Parallel]
wayGeneralFlags _ WayGran = [Opt_GranMacros]
wayGeneralFlags _ WayNDP = []
-- Turn these flags off when enabling this way
wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayUnsetGeneralFlags _ (WayCustom {}) = []
wayUnsetGeneralFlags _ WayThreaded = []
wayUnsetGeneralFlags _ WayDebug = []
wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
-- when we're going to be dynamically
-- linking. Plus it breaks compilation
-- on OSX x86.
Opt_SplitObjs]
wayUnsetGeneralFlags _ WayProf = []
wayUnsetGeneralFlags _ WayEventLog = []
wayUnsetGeneralFlags _ WayPar = []
wayUnsetGeneralFlags _ WayGran = []
wayUnsetGeneralFlags _ WayNDP = []
wayExtras :: Platform -> Way -> DynFlags -> DynFlags
wayExtras _ (WayCustom {}) dflags = dflags
wayExtras _ WayThreaded dflags = dflags
wayExtras _ WayDebug dflags = dflags
wayExtras _ WayDyn dflags = dflags
wayExtras _ WayProf dflags = dflags
wayExtras _ WayEventLog dflags = dflags
wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
wayExtras _ WayGran dflags = exposePackage' "concurrent" dflags
wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays
$ setGeneralFlag' Opt_Vectorise dflags
wayOptc :: Platform -> Way -> [String]
wayOptc _ (WayCustom {}) = []
wayOptc platform WayThreaded = case platformOS platform of
OSOpenBSD -> ["-pthread"]
OSNetBSD -> ["-pthread"]
_ -> []
wayOptc _ WayDebug = []
wayOptc _ WayDyn = []
wayOptc _ WayProf = ["-DPROFILING"]
wayOptc _ WayEventLog = ["-DTRACING"]
wayOptc _ WayPar = ["-DPAR", "-w"]
wayOptc _ WayGran = ["-DGRAN"]
wayOptc _ WayNDP = []
wayOptl :: Platform -> Way -> [String]
wayOptl _ (WayCustom {}) = []
wayOptl platform WayThreaded =
case platformOS platform of
-- FreeBSD's default threading library is the KSE-based M:N libpthread,
-- which GHC has some problems with. It's currently not clear whether
-- the problems are our fault or theirs, but it seems that using the
-- alternative 1:1 threading library libthr works around it:
OSFreeBSD -> ["-lthr"]
OSSolaris2 -> ["-lrt"]
OSOpenBSD -> ["-pthread"]
OSNetBSD -> ["-pthread"]
_ -> []
wayOptl _ WayDebug = []
wayOptl _ WayDyn = []
wayOptl _ WayProf = []
wayOptl _ WayEventLog = []
wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
"-lpvm3",
"-lgpvm3"]
wayOptl _ WayGran = []
wayOptl _ WayNDP = []
wayOptP :: Platform -> Way -> [String]
wayOptP _ (WayCustom {}) = []
wayOptP _ WayThreaded = []
wayOptP _ WayDebug = []
wayOptP _ WayDyn = []
wayOptP _ WayProf = ["-DPROFILING"]
wayOptP _ WayEventLog = ["-DTRACING"]
wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
wayOptP _ WayGran = ["-D__GRANSIM__"]
wayOptP _ WayNDP = []
whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenCannotGenerateDynamicToo dflags f
= ifCannotGenerateDynamicToo dflags f (return ())
ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifCannotGenerateDynamicToo dflags f g
= generateDynamicTooConditional dflags g f g
generateDynamicTooConditional :: MonadIO m
=> DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
= if gopt Opt_BuildDynamicToo dflags
then do let ref = canGenerateDynamicToo dflags
b <- liftIO $ readIORef ref
if b then canGen else cannotGen
else notTryingToGen
dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
dynamicTooMkDynamicDynFlags dflags0
= let dflags1 = addWay' WayDyn dflags0
dflags2 = dflags1 {
outputFile = dynOutputFile dflags1,
hiSuf = dynHiSuf dflags1,
objectSuf = dynObjectSuf dflags1
}
dflags3 = updateWays dflags2
dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
in dflags4
-----------------------------------------------------------------------------
-- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags dflags = do
let -- We can't build with dynamic-too on Windows, as labels before
-- the fork point are different depending on whether we are
-- building dynamically or not.
platformCanGenerateDynamicToo
= platformOS (targetPlatform dflags) /= OSMinGW32
refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
refNextTempSuffix <- newIORef 0
refFilesToClean <- newIORef []
refDirsToClean <- newIORef Map.empty
refFilesToNotIntermediateClean <- newIORef []
refGeneratedDumps <- newIORef Set.empty
refLlvmVersion <- newIORef 28
refRtldFlags <- newIORef Nothing
wrapperNum <- newIORef emptyModuleEnv
canUseUnicodeQuotes <- do let enc = localeEncoding
str = "‛’"
(withCString enc str $ \cstr ->
do str' <- peekCString enc cstr
return (str == str'))
`catchIOError` \_ -> return False
return dflags{
canGenerateDynamicToo = refCanGenerateDynamicToo,
nextTempSuffix = refNextTempSuffix,
filesToClean = refFilesToClean,
dirsToClean = refDirsToClean,
filesToNotIntermediateClean = refFilesToNotIntermediateClean,
generatedDumps = refGeneratedDumps,
llvmVersion = refLlvmVersion,
nextWrapperNum = wrapperNum,
useUnicodeQuotes = canUseUnicodeQuotes,
rtldFlags = refRtldFlags
}
-- | The normal 'DynFlags'. Note that they is not suitable for use in this form
-- and must be fully initialized by 'GHC.newSession' first.
defaultDynFlags :: Settings -> DynFlags
defaultDynFlags mySettings =
DynFlags {
ghcMode = CompManager,
ghcLink = LinkBinary,
hscTarget = defaultHscTarget (sTargetPlatform mySettings),
verbosity = 0,
optLevel = 0,
simplPhases = 2,
maxSimplIterations = 4,
shouldDumpSimplPhase = Nothing,
ruleCheck = Nothing,
maxRelevantBinds = Just 6,
simplTickFactor = 100,
specConstrThreshold = Just 2000,
specConstrCount = Just 3,
specConstrRecursive = 3,
liberateCaseThreshold = Just 2000,
floatLamArgs = Just 0, -- Default: float only if no fvs
historySize = 20,
strictnessBefore = [],
parMakeCount = Just 1,
cmdlineHcIncludes = [],
importPaths = ["."],
mainModIs = mAIN,
mainFunIs = Nothing,
ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
thisPackage = mainPackageId,
objectDir = Nothing,
dylibInstallName = Nothing,
hiDir = Nothing,
stubDir = Nothing,
dumpDir = Nothing,
objectSuf = phaseInputExt StopLn,
hcSuf = phaseInputExt HCc,
hiSuf = "hi",
canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
dynHiSuf = "dyn_hi",
dllSplitFile = Nothing,
dllSplit = Nothing,
pluginModNames = [],
pluginModNameOpts = [],
hooks = emptyHooks,
outputFile = Nothing,
dynOutputFile = Nothing,
outputHi = Nothing,
dynLibLoader = SystemDependent,
dumpPrefix = Nothing,
dumpPrefixForce = Nothing,
ldInputs = [],
includePaths = [],
libraryPaths = [],
frameworkPaths = [],
cmdlineFrameworks = [],
rtsOpts = Nothing,
rtsOptsEnabled = RtsOptsSafeOnly,
hpcDir = ".hpc",
extraPkgConfs = id,
packageFlags = [],
pkgDatabase = Nothing,
pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
ways = defaultWays mySettings,
buildTag = mkBuildTag (defaultWays mySettings),
rtsBuildTag = mkBuildTag (defaultWays mySettings),
splitInfo = Nothing,
settings = mySettings,
-- ghc -M values
depMakefile = "Makefile",
depIncludePkgDeps = False,
depExcludeMods = [],
depSuffixes = [],
-- end of ghc -M values
nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
filesToClean = panic "defaultDynFlags: No filesToClean",
dirsToClean = panic "defaultDynFlags: No dirsToClean",
filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
generatedDumps = panic "defaultDynFlags: No generatedDumps",
haddockOptions = Nothing,
dumpFlags = IntSet.empty,
generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
warningFlags = IntSet.fromList (map fromEnum standardWarnings),
ghciScripts = [],
language = Nothing,
safeHaskell = Sf_SafeInferred,
thOnLoc = noSrcSpan,
newDerivOnLoc = noSrcSpan,
pkgTrustOnLoc = noSrcSpan,
warnSafeOnLoc = noSrcSpan,
warnUnsafeOnLoc = noSrcSpan,
extensions = [],
extensionFlags = flattenExtensionFlags Nothing [],
-- The ufCreationThreshold threshold must be reasonably high to
-- take account of possible discounts.
-- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
-- into Csg.calc (The unfolding for sqr never makes it into the
-- interface file.)
ufCreationThreshold = 750,
ufUseThreshold = 60,
ufFunAppDiscount = 60,
-- Be fairly keen to inline a fuction if that means
-- we'll be able to pick the right method from a dictionary
ufDictDiscount = 30,
ufKeenessFactor = 1.5,
ufDearOp = 40,
maxWorkerArgs = 10,
ghciHistSize = 50, -- keep a log of length 50 by default
log_action = defaultLogAction,
flushOut = defaultFlushOut,
flushErr = defaultFlushErr,
pprUserLength = 5,
pprCols = 100,
useUnicodeQuotes = False,
traceLevel = 1,
profAuto = NoProfAuto,
llvmVersion = panic "defaultDynFlags: No llvmVersion",
interactivePrint = Nothing,
nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
sseVersion = Nothing,
avx = False,
avx2 = False,
avx512cd = False,
avx512er = False,
avx512f = False,
avx512pf = False,
rtldFlags = panic "defaultDynFlags: no rtldFlags"
}
defaultWays :: Settings -> [Way]
defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
then [WayDyn]
else []
interpWays :: [Way]
interpWays = if cDYNAMIC_GHC_PROGRAMS
then [WayDyn]
else []
--------------------------------------------------------------------------
type FatalMessager = String -> IO ()
type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
defaultFatalMessager :: FatalMessager
defaultFatalMessager = hPutStrLn stderr
defaultLogAction :: LogAction
defaultLogAction dflags severity srcSpan style msg
= case severity of
SevOutput -> printSDoc msg style
SevDump -> printSDoc (msg $$ blankLine) style
SevInteractive -> putStrSDoc msg style
SevInfo -> printErrs msg style
SevFatal -> printErrs msg style
_ -> do hPutChar stderr '\n'
printErrs (mkLocMessage severity srcSpan msg) style
-- careful (#2302): printErrs prints in UTF-8,
-- whereas converting to string first and using
-- hPutStr would just emit the low 8 bits of
-- each unicode char.
where printSDoc = defaultLogActionHPrintDoc dflags stdout
printErrs = defaultLogActionHPrintDoc dflags stderr
putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc dflags h d sty
= do let doc = runSDoc d (initSDocContext dflags sty)
Pretty.printDoc Pretty.PageMode (pprCols dflags) h doc
hFlush h
defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc dflags h d sty
= do let doc = runSDoc d (initSDocContext dflags sty)
hPutStr h (Pretty.render doc)
hFlush h
newtype FlushOut = FlushOut (IO ())
defaultFlushOut :: FlushOut
defaultFlushOut = FlushOut $ hFlush stdout
newtype FlushErr = FlushErr (IO ())
defaultFlushErr :: FlushErr
defaultFlushErr = FlushErr $ hFlush stderr
printOutputForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
printOutputForUser = printSevForUser SevOutput
printInfoForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
printInfoForUser = printSevForUser SevInfo
printSevForUser :: Severity -> DynFlags -> PrintUnqualified -> SDoc -> IO ()
printSevForUser sev dflags unqual doc
= log_action dflags dflags sev noSrcSpan (mkUserStyle unqual AllTheWay) doc
{-
Note [Verbosity levels]
~~~~~~~~~~~~~~~~~~~~~~~
0 | print errors & warnings only
1 | minimal verbosity: print "compiling M ... done." for each module.
2 | equivalent to -dshow-passes
3 | equivalent to existing "ghc -v"
4 | "ghc -v -ddump-most"
5 | "ghc -v -ddump-all"
-}
data OnOff a = On a
| Off a
-- OnOffs accumulate in reverse order, so we use foldr in order to
-- process them in the right order
flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
flattenExtensionFlags ml = foldr f defaultExtensionFlags
where f (On f) flags = IntSet.insert (fromEnum f) flags
f (Off f) flags = IntSet.delete (fromEnum f) flags
defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
languageExtensions :: Maybe Language -> [ExtensionFlag]
languageExtensions Nothing
-- Nothing => the default case
= Opt_NondecreasingIndentation -- This has been on by default for some time
: delete Opt_DatatypeContexts -- The Haskell' committee decided to
-- remove datatype contexts from the
-- language:
-- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
(languageExtensions (Just Haskell2010))
-- NB: MonoPatBinds is no longer the default
languageExtensions (Just Haskell98)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_NPlusKPatterns,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_NondecreasingIndentation
-- strictly speaking non-standard, but we always had this
-- on implicitly before the option was added in 7.1, and
-- turning it off breaks code, so we're keeping it on for
-- backwards compatibility. Cabal uses -XHaskell98 by
-- default unless you specify another language.
]
languageExtensions (Just Haskell2010)
= [Opt_ImplicitPrelude,
Opt_MonomorphismRestriction,
Opt_DatatypeContexts,
Opt_TraditionalRecordSyntax,
Opt_EmptyDataDecls,
Opt_ForeignFunctionInterface,
Opt_PatternGuards,
Opt_DoAndIfThenElse,
Opt_RelaxedPolyRec]
-- | Test whether a 'DumpFlag' is set
dopt :: DumpFlag -> DynFlags -> Bool
dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
|| (verbosity dflags >= 4 && enableIfVerbose f)
where enableIfVerbose Opt_D_dump_tc_trace = False
enableIfVerbose Opt_D_dump_rn_trace = False
enableIfVerbose Opt_D_dump_cs_trace = False
enableIfVerbose Opt_D_dump_if_trace = False
enableIfVerbose Opt_D_dump_vt_trace = False
enableIfVerbose Opt_D_dump_tc = False
enableIfVerbose Opt_D_dump_rn = False
enableIfVerbose Opt_D_dump_rn_stats = False
enableIfVerbose Opt_D_dump_hi_diffs = False
enableIfVerbose Opt_D_verbose_core2core = False
enableIfVerbose Opt_D_verbose_stg2stg = False
enableIfVerbose Opt_D_dump_splices = False
enableIfVerbose Opt_D_dump_rule_firings = False
enableIfVerbose Opt_D_dump_rule_rewrites = False
enableIfVerbose Opt_D_dump_simpl_trace = False
enableIfVerbose Opt_D_dump_rtti = False
enableIfVerbose Opt_D_dump_inlinings = False
enableIfVerbose Opt_D_dump_core_stats = False
enableIfVerbose Opt_D_dump_asm_stats = False
enableIfVerbose Opt_D_dump_types = False
enableIfVerbose Opt_D_dump_simpl_iterations = False
enableIfVerbose Opt_D_dump_ticked = False
enableIfVerbose Opt_D_dump_view_pattern_commoning = False
enableIfVerbose Opt_D_dump_mod_cycles = False
enableIfVerbose _ = True
-- | Set a 'DumpFlag'
dopt_set :: DynFlags -> DumpFlag -> DynFlags
dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
-- | Unset a 'DumpFlag'
dopt_unset :: DynFlags -> DumpFlag -> DynFlags
dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
-- | Test whether a 'GeneralFlag' is set
gopt :: GeneralFlag -> DynFlags -> Bool
gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
-- | Set a 'GeneralFlag'
gopt_set :: DynFlags -> GeneralFlag -> DynFlags
gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
-- | Unset a 'GeneralFlag'
gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
-- | Test whether a 'WarningFlag' is set
wopt :: WarningFlag -> DynFlags -> Bool
wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
-- | Set a 'WarningFlag'
wopt_set :: DynFlags -> WarningFlag -> DynFlags
wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
-- | Unset a 'WarningFlag'
wopt_unset :: DynFlags -> WarningFlag -> DynFlags
wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
-- | Test whether a 'ExtensionFlag' is set
xopt :: ExtensionFlag -> DynFlags -> Bool
xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
-- | Set a 'ExtensionFlag'
xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
xopt_set dfs f
= let onoffs = On f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
-- | Unset a 'ExtensionFlag'
xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
xopt_unset dfs f
= let onoffs = Off f : extensions dfs
in dfs { extensions = onoffs,
extensionFlags = flattenExtensionFlags (language dfs) onoffs }
lang_set :: DynFlags -> Maybe Language -> DynFlags
lang_set dflags lang =
dflags {
language = lang,
extensionFlags = flattenExtensionFlags lang (extensions dflags)
}
-- | Set the Haskell language standard to use
setLanguage :: Language -> DynP ()
setLanguage l = upd (`lang_set` Just l)
-- | Some modules have dependencies on others through the DynFlags rather than textual imports
dynFlagDependencies :: DynFlags -> [ModuleName]
dynFlagDependencies = pluginModNames
-- | Is the -fpackage-trust mode on
packageTrustOn :: DynFlags -> Bool
packageTrustOn = gopt Opt_PackageTrust
-- | Is Safe Haskell on in some way (including inference mode)
safeHaskellOn :: DynFlags -> Bool
safeHaskellOn dflags = safeHaskell dflags /= Sf_None
-- | Is the Safe Haskell safe language in use
safeLanguageOn :: DynFlags -> Bool
safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
-- | Is the Safe Haskell safe inference mode active
safeInferOn :: DynFlags -> Bool
safeInferOn dflags = safeHaskell dflags == Sf_SafeInferred
-- | Test if Safe Imports are on in some form
safeImportsOn :: DynFlags -> Bool
safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
safeHaskell dflags == Sf_Trustworthy ||
safeHaskell dflags == Sf_Safe
-- | Set a 'Safe Haskell' flag
setSafeHaskell :: SafeHaskellMode -> DynP ()
setSafeHaskell s = updM f
where f dfs = do
let sf = safeHaskell dfs
safeM <- combineSafeFlags sf s
return $ dfs { safeHaskell = safeM }
-- | Are all direct imports required to be safe for this Safe Haskell mode?
-- Direct imports are when the code explicitly imports a module
safeDirectImpsReq :: DynFlags -> Bool
safeDirectImpsReq d = safeLanguageOn d
-- | Are all implicit imports required to be safe for this Safe Haskell mode?
-- Implicit imports are things in the prelude. e.g System.IO when print is used.
safeImplicitImpsReq :: DynFlags -> Bool
safeImplicitImpsReq d = safeLanguageOn d
-- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
-- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
-- want to export this functionality from the module but do want to export the
-- type constructors.
combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags a b | a == Sf_SafeInferred = return b
| b == Sf_SafeInferred = return a
| a == Sf_None = return b
| b == Sf_None = return a
| a == b = return a
| otherwise = addErr errm >> return (panic errm)
where errm = "Incompatible Safe Haskell flags! ("
++ show a ++ ", " ++ show b ++ ")"
-- | A list of unsafe flags under Safe Haskell. Tuple elements are:
-- * name of the flag
-- * function to get srcspan that enabled the flag
-- * function to test if the flag is on
-- * function to turn the flag off
unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
xopt Opt_GeneralizedNewtypeDeriving,
flip xopt_unset Opt_GeneralizedNewtypeDeriving),
("-XTemplateHaskell", thOnLoc,
xopt Opt_TemplateHaskell,
flip xopt_unset Opt_TemplateHaskell)]
-- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
-> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
-> [a] -- ^ Correctly ordered extracted options
getOpts dflags opts = reverse (opts dflags)
-- We add to the options from the front, so we need to reverse the list
-- | Gets the verbosity flag for the current verbosity level. This is fed to
-- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
getVerbFlags :: DynFlags -> [String]
getVerbFlags dflags
| verbosity dflags >= 4 = ["-v"]
| otherwise = []
setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
setDynObjectSuf, setDynHiSuf,
setDylibInstallName,
setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
setPgmP, addOptl, addOptc, addOptP,
addCmdlineFramework, addHaddockOpts, addGhciScript,
setInteractivePrint
:: String -> DynFlags -> DynFlags
setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
:: Maybe String -> DynFlags -> DynFlags
setObjectDir f d = d{ objectDir = Just f}
setHiDir f d = d{ hiDir = Just f}
setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
-- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
-- \#included from the .hc file when compiling via C (i.e. unregisterised
-- builds).
setDumpDir f d = d{ dumpDir = Just f}
setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
setDylibInstallName f d = d{ dylibInstallName = Just f}
setObjectSuf f d = d{ objectSuf = f}
setDynObjectSuf f d = d{ dynObjectSuf = f}
setHiSuf f d = d{ hiSuf = f}
setDynHiSuf f d = d{ dynHiSuf = f}
setHcSuf f d = d{ hcSuf = f}
setOutputFile f d = d{ outputFile = f}
setDynOutputFile f d = d{ dynOutputFile = f}
setOutputHi f d = d{ outputHi = f}
addPluginModuleName :: String -> DynFlags -> DynFlags
addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
addPluginModuleNameOption :: String -> DynFlags -> DynFlags
addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
where (m, rest) = break (== ':') optflag
option = case rest of
[] -> "" -- should probably signal an error
(_:plug_opt) -> plug_opt -- ignore the ':' from break
parseDynLibLoaderMode f d =
case splitAt 8 f of
("deploy", "") -> d{ dynLibLoader = Deployable }
("sysdep", "") -> d{ dynLibLoader = SystemDependent }
_ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
setDumpPrefixForce f d = d { dumpPrefixForce = f}
-- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
-- Config.hs should really use Option.
setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
setDepMakefile :: FilePath -> DynFlags -> DynFlags
setDepMakefile f d = d { depMakefile = deOptDep f }
setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
addDepExcludeMod :: String -> DynFlags -> DynFlags
addDepExcludeMod m d
= d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
addDepSuffix :: FilePath -> DynFlags -> DynFlags
addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
-- XXX Legacy code:
-- We used to use "-optdep-flag -optdeparg", so for legacy applications
-- we need to strip the "-optdep" off of the arg
deOptDep :: String -> String
deOptDep x = case stripPrefix "-optdep" x of
Just rest -> rest
Nothing -> x
addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
addHaddockOpts f d = d{ haddockOptions = Just f}
addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
setInteractivePrint f d = d{ interactivePrint = Just f}
-- -----------------------------------------------------------------------------
-- Command-line options
-- | When invoking external tools as part of the compilation pipeline, we
-- pass these a sequence of options on the command-line. Rather than
-- just using a list of Strings, we use a type that allows us to distinguish
-- between filepaths and 'other stuff'. The reason for this is that
-- this type gives us a handle on transforming filenames, and filenames only,
-- to whatever format they're expected to be on a particular platform.
data Option
= FileOption -- an entry that _contains_ filename(s) / filepaths.
String -- a non-filepath prefix that shouldn't be
-- transformed (e.g., "/out=")
String -- the filepath/filename portion
| Option String
deriving ( Eq )
showOpt :: Option -> String
showOpt (FileOption pre f) = pre ++ f
showOpt (Option s) = s
-----------------------------------------------------------------------------
-- Setting the optimisation level
updOptLevel :: Int -> DynFlags -> DynFlags
-- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
updOptLevel n dfs
= dfs2{ optLevel = final_n }
where
final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
dfs1 = foldr (flip gopt_unset) dfs remove_gopts
dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
-- -----------------------------------------------------------------------------
-- StgToDo: abstraction of stg-to-stg passes to run.
data StgToDo
= StgDoMassageForProfiling -- should be (next to) last
-- There's also setStgVarInfo, but its absolute "lastness"
-- is so critical that it is hardwired in (no flag).
| D_stg_stats
getStgToDo :: DynFlags -> [StgToDo]
getStgToDo dflags
= todo2
where
stg_stats = gopt Opt_StgStats dflags
todo1 = if stg_stats then [D_stg_stats] else []
todo2 | WayProf `elem` ways dflags
= StgDoMassageForProfiling : todo1
| otherwise
= todo1
{- **********************************************************************
%* *
DynFlags parser
%* *
%********************************************************************* -}
-- -----------------------------------------------------------------------------
-- Parsing the dynamic flags.
-- | Parse dynamic flags from a list of command line arguments. Returns the
-- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
-- Throws a 'UsageError' if errors occurred during parsing (such as unknown
-- flags or missing arguments).
parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
-- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
-- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
-- Used to parse flags set in a modules pragma.
parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
-- ^ Updated 'DynFlags', left-over arguments, and
-- list of warnings.
parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
-- | Parses the dynamically set flags for GHC. This is the most general form of
-- the dynamic flag parser that the other methods simply wrap. It allows
-- saying which flags are valid flags and indicating if we are parsing
-- arguments from the command line or from a file pragma.
parseDynamicFlagsFull :: MonadIO m
=> [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
-> Bool -- ^ are the arguments from the command line?
-> DynFlags -- ^ current dynamic flags
-> [Located String] -- ^ arguments to parse
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
-- XXX Legacy support code
-- We used to accept things like
-- optdep-f -optdepdepend
-- optdep-f -optdep depend
-- optdep -f -optdepdepend
-- optdep -f -optdep depend
-- but the spaces trip up proper argument handling. So get rid of them.
let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
f (x : xs) = x : f xs
f xs = xs
args' = f args
let ((leftover, errs, warns), dflags1)
= runCmdLine (processArgs activeFlags args') dflags0
when (not (null errs)) $ liftIO $
throwGhcExceptionIO $ errorsToGhcException errs
-- check for disabled flags in safe haskell
let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
dflags3 = updateWays dflags2
theWays = ways dflags3
unless (allowed_combination theWays) $ liftIO $
throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
intercalate "/" (map wayDesc theWays)))
whenGeneratingDynamicToo dflags3 $
unless (isJust (outputFile dflags3) == isJust (dynOutputFile dflags3)) $
liftIO $ throwGhcExceptionIO $ CmdLineError
"With -dynamic-too, must give -dyno iff giving -o"
let (dflags4, consistency_warnings) = makeDynFlagsConsistent dflags3
dflags5 <- case dllSplitFile dflags4 of
Nothing -> return (dflags4 { dllSplit = Nothing })
Just f ->
case dllSplit dflags4 of
Just _ ->
-- If dllSplit is out of date then it would have
-- been set to Nothing. As it's a Just, it must be
-- up-to-date.
return dflags4
Nothing ->
do xs <- liftIO $ readFile f
let ss = map (Set.fromList . words) (lines xs)
return $ dflags4 { dllSplit = Just ss }
liftIO $ setUnsafeGlobalDynFlags dflags5
return (dflags5, leftover, consistency_warnings ++ sh_warns ++ warns)
updateWays :: DynFlags -> DynFlags
updateWays dflags
= let theWays = sort $ nub $ ways dflags
f = if WayDyn `elem` theWays then unSetGeneralFlag'
else setGeneralFlag'
in f Opt_Static
$ dflags {
ways = theWays,
buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
rtsBuildTag = mkBuildTag theWays
}
-- | Check (and potentially disable) any extensions that aren't allowed
-- in safe mode.
--
-- The bool is to indicate if we are parsing command line flags (false means
-- file pragma). This allows us to generate better warnings.
safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags)
= (dflags, [])
-- safe or safe-infer ON
safeFlagCheck cmdl dflags =
case safeLanguageOn dflags of
True -> (dflags', warns)
-- throw error if -fpackage-trust by itself with no safe haskell flag
False | not cmdl && packageTrustOn dflags
-> (gopt_unset dflags' Opt_PackageTrust,
[L (pkgTrustOnLoc dflags') $
"-fpackage-trust ignored;" ++
" must be specified with a Safe Haskell flag"]
)
False | null warns && safeInfOk
-> (dflags', [])
| otherwise
-> (dflags' { safeHaskell = Sf_None }, [])
-- Have we inferred Unsafe?
-- See Note [HscMain . Safe Haskell Inference]
where
-- TODO: Can we do better than this for inference?
safeInfOk = not $ xopt Opt_OverlappingInstances dflags
(dflags', warns) = foldl check_method (dflags, []) unsafeFlags
check_method (df, warns) (str,loc,test,fix)
| test df = (apFix fix df, warns ++ safeFailure (loc dflags) str)
| otherwise = (df, warns)
apFix f = if safeInferOn dflags then id else f
safeFailure loc str
= [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str]
{- **********************************************************************
%* *
DynFlags specifications
%* *
%********************************************************************* -}
-- | All dynamic flags option strings. These are the user facing strings for
-- enabling and disabling options.
allFlags :: [String]
allFlags = map ('-':) $
[ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
map ("fno-"++) fflags ++
map ("f"++) fflags ++
map ("X"++) supportedExtensions
where ok (PrefixPred _ _) = False
ok _ = True
fflags = fflags0 ++ fflags1 ++ fflags2
fflags0 = [ name | (name, _, _) <- fFlags ]
fflags1 = [ name | (name, _, _) <- fWarningFlags ]
fflags2 = [ name | (name, _, _) <- fLangFlags ]
{-
- Below we export user facing symbols for GHC dynamic flags for use with the
- GHC API.
-}
-- All dynamic flags present in GHC.
flagsAll :: [Flag (CmdLineP DynFlags)]
flagsAll = package_flags ++ dynamic_flags
-- All dynamic flags, minus package flags, present in GHC.
flagsDynamic :: [Flag (CmdLineP DynFlags)]
flagsDynamic = dynamic_flags
-- ALl package flags present in GHC.
flagsPackage :: [Flag (CmdLineP DynFlags)]
flagsPackage = package_flags
--------------- The main flags themselves ------------------
dynamic_flags :: [Flag (CmdLineP DynFlags)]
dynamic_flags = [
Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
, Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
, Flag "F" (NoArg (setGeneralFlag Opt_Pp))
, Flag "#include"
(HasArg (\s -> do addCmdlineHCInclude s
addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
, Flag "v" (OptIntSuffix setVerbosity)
, Flag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n})))
------- ways --------------------------------------------------------
, Flag "prof" (NoArg (addWay WayProf))
, Flag "eventlog" (NoArg (addWay WayEventLog))
, Flag "parallel" (NoArg (addWay WayPar))
, Flag "gransim" (NoArg (addWay WayGran))
, Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
, Flag "debug" (NoArg (addWay WayDebug))
, Flag "ndp" (NoArg (addWay WayNDP))
, Flag "threaded" (NoArg (addWay WayThreaded))
, Flag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
-- -ticky enables ticky-ticky code generation, and also implies -debug which
-- is required to get the RTS ticky support.
----- Linker --------------------------------------------------------
, Flag "static" (NoArg removeWayDyn)
, Flag "dynamic" (NoArg (addWay WayDyn))
-- ignored for compat w/ gcc:
, Flag "rdynamic" (NoArg (return ()))
, Flag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
------- Specific phases --------------------------------------------
-- need to appear before -pgmL to be parsed as LLVM flags.
, Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
, Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
, Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
, Flag "pgmP" (hasArg setPgmP)
, Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
, Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
, Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
, Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
, Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
, Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
, Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
, Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
, Flag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
-- need to appear before -optl/-opta to be parsed as LLVM flags.
, Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
, Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
, Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
, Flag "optP" (hasArg addOptP)
, Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
, Flag "optc" (hasArg addOptc)
, Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
, Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
, Flag "optl" (hasArg addOptl)
, Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
, Flag "split-objs"
(NoArg (if can_split
then setGeneralFlag Opt_SplitObjs
else addWarn "ignoring -fsplit-objs"))
-------- ghc -M -----------------------------------------------------
, Flag "dep-suffix" (hasArg addDepSuffix)
, Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
, Flag "dep-makefile" (hasArg setDepMakefile)
, Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
, Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
, Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
, Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
, Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
, Flag "exclude-module" (hasArg addDepExcludeMod)
, Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
, Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
-------- Linking ----------------------------------------------------
, Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
, Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
, Flag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib }))
, Flag "dynload" (hasArg parseDynLibLoaderMode)
, Flag "dylib-install-name" (hasArg setDylibInstallName)
-- -dll-split is an internal flag, used only during the GHC build
, Flag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
------- Libraries ---------------------------------------------------
, Flag "L" (Prefix addLibraryPath)
, Flag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
------- Frameworks --------------------------------------------------
-- -framework-path should really be -F ...
, Flag "framework-path" (HasArg addFrameworkPath)
, Flag "framework" (hasArg addCmdlineFramework)
------- Output Redirection ------------------------------------------
, Flag "odir" (hasArg setObjectDir)
, Flag "o" (sepArg (setOutputFile . Just))
, Flag "dyno" (sepArg (setDynOutputFile . Just))
, Flag "ohi" (hasArg (setOutputHi . Just ))
, Flag "osuf" (hasArg setObjectSuf)
, Flag "dynosuf" (hasArg setDynObjectSuf)
, Flag "hcsuf" (hasArg setHcSuf)
, Flag "hisuf" (hasArg setHiSuf)
, Flag "dynhisuf" (hasArg setDynHiSuf)
, Flag "hidir" (hasArg setHiDir)
, Flag "tmpdir" (hasArg setTmpDir)
, Flag "stubdir" (hasArg setStubDir)
, Flag "dumpdir" (hasArg setDumpDir)
, Flag "outputdir" (hasArg setOutputDir)
, Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
, Flag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
------- Keeping temporary files -------------------------------------
-- These can be singular (think ghc -c) or plural (think ghc --make)
, Flag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
, Flag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
, Flag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
, Flag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
, Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
, Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
, Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
setGeneralFlag Opt_KeepLlvmFiles))
, Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
setGeneralFlag Opt_KeepLlvmFiles))
-- This only makes sense as plural
, Flag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
------- Miscellaneous ----------------------------------------------
, Flag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
, Flag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
, Flag "with-rtsopts" (HasArg setRtsOpts)
, Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
, Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
, Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
, Flag "main-is" (SepArg setMainIs)
, Flag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
, Flag "haddock-opts" (hasArg addHaddockOpts)
, Flag "hpcdir" (SepArg setOptHpcDir)
, Flag "ghci-script" (hasArg addGhciScript)
, Flag "interactive-print" (hasArg setInteractivePrint)
, Flag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
, Flag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
, Flag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
------- recompilation checker --------------------------------------
, Flag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
deprecate "Use -fno-force-recomp instead"))
, Flag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
deprecate "Use -fforce-recomp instead"))
------ HsCpp opts ---------------------------------------------------
, Flag "D" (AnySuffix (upd . addOptP))
, Flag "U" (AnySuffix (upd . addOptP))
------- Include/Import Paths ----------------------------------------
, Flag "I" (Prefix addIncludePath)
, Flag "i" (OptPrefix addImportPath)
------ Output style options -----------------------------------------
, Flag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
, Flag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
, Flag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
-- Suppress all that is suppressable in core dumps.
-- Except for uniques, as some simplifier phases introduce new varibles that
-- have otherwise identical names.
, Flag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions
setGeneralFlag Opt_SuppressVarKinds
setGeneralFlag Opt_SuppressModulePrefixes
setGeneralFlag Opt_SuppressTypeApplications
setGeneralFlag Opt_SuppressIdInfo
setGeneralFlag Opt_SuppressTypeSignatures)
------ Debugging ----------------------------------------------------
, Flag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
, Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
, Flag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
, Flag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
, Flag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
, Flag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
, Flag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink)
, Flag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
, Flag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
, Flag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
, Flag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
, Flag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
, Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
, Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
, Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
, Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
, Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
, Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
, Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
, Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
, Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
, Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
setDumpFlag' Opt_D_dump_llvm))
, Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
, Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
, Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
, Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
, Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
, Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
, Flag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
, Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
, Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
, Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
, Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
, Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
, Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
, Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
, Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
, Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
, Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
, Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
, Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
, Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
, Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
, Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
, Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
, Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
, Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
, Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
, Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
, Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
, Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
, Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
, Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
, Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
, Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
, Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
, Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
setVerboseCore2Core))
, Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
, Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
, Flag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
, Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
, Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
, Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
, Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
, Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
, Flag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
, Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
, Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
, Flag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting))
, Flag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting))
, Flag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting))
, Flag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting))
, Flag "dshow-passes" (NoArg (do forceRecompile
setVerbosity $ Just 2))
, Flag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats))
, Flag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
------ Machine dependant (-m<blah>) stuff ---------------------------
, Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
, Flag "msse" (versionSuffix (\maj min d -> d{ sseVersion = Just (maj, min) }))
, Flag "mavx" (noArg (\d -> d{ avx = True }))
, Flag "mavx2" (noArg (\d -> d{ avx2 = True }))
, Flag "mavx512cd" (noArg (\d -> d{ avx512cd = True }))
, Flag "mavx512er" (noArg (\d -> d{ avx512er = True }))
, Flag "mavx512f" (noArg (\d -> d{ avx512f = True }))
, Flag "mavx512pf" (noArg (\d -> d{ avx512pf = True }))
------ Warning opts -------------------------------------------------
, Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
, Flag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
, Flag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
, Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
, Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
deprecate "Use -w instead"))
, Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
------ Plugin flags ------------------------------------------------
, Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
, Flag "fplugin" (hasArg addPluginModuleName)
------ Optimisation flags ------------------------------------------
, Flag "O" (noArgM (setOptLevel 1))
, Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
setOptLevel 0 dflags))
, Flag "Odph" (noArgM setDPHOpt)
, Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
-- If the number is missing, use 1
, Flag "fmax-relevant-binds" (intSuffix (\n d -> d{ maxRelevantBinds = Just n }))
, Flag "fno-max-relevant-binds" (noArg (\d -> d{ maxRelevantBinds = Nothing }))
, Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
, Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
, Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
, Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
, Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
, Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
, Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
, Flag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n }))
, Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
, Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
, Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
, Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
, Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
, Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
, Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
, Flag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
, Flag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n}))
, Flag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n}))
, Flag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n}))
, Flag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n}))
, Flag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n}))
, Flag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
, Flag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
------ Profiling ----------------------------------------------------
-- OLD profiling flags
, Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
, Flag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
, Flag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
-- NEW profiling flags
, Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
, Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
, Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
, Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
, Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
------ Compiler flags -----------------------------------------------
, Flag "fasm" (NoArg (setObjTarget HscAsm))
, Flag "fvia-c" (NoArg
(addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
, Flag "fvia-C" (NoArg
(addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
, Flag "fllvm" (NoArg (setObjTarget HscLlvm))
, Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
setTarget HscNothing))
, Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
, Flag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
, Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
, Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
------ Safe Haskell flags -------------------------------------------
, Flag "fpackage-trust" (NoArg setPackageTrust)
, Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None))
, Flag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
, Flag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
]
++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
++ map (mkFlag turnOn "X" setLanguage) languageFlags
++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
, Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
package_flags :: [Flag (CmdLineP DynFlags)]
package_flags = [
------- Packages ----------------------------------------------------
Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
, Flag "clear-package-db" (NoArg clearPkgConf)
, Flag "no-global-package-db" (NoArg removeGlobalPkgConf)
, Flag "no-user-package-db" (NoArg removeUserPkgConf)
, Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
, Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
-- backwards compat with GHC<=7.4 :
, Flag "package-conf" (HasArg $ \path -> do
addPkgConfRef (PkgConfFile path)
deprecate "Use -package-db instead")
, Flag "no-user-package-conf" (NoArg $ do
removeUserPkgConf
deprecate "Use -no-user-package-db instead")
, Flag "package-name" (hasArg setPackageName)
, Flag "package-id" (HasArg exposePackageId)
, Flag "package" (HasArg exposePackage)
, Flag "hide-package" (HasArg hidePackage)
, Flag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
, Flag "ignore-package" (HasArg ignorePackage)
, Flag "syslib" (HasArg (\s -> do exposePackage s
deprecate "Use -package instead"))
, Flag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages))
, Flag "trust" (HasArg trustPackage)
, Flag "distrust" (HasArg distrustPackage)
]
type TurnOnFlag = Bool -- True <=> we are turning the flag on
-- False <=> we are turning the flag off
turnOn :: TurnOnFlag; turnOn = True
turnOff :: TurnOnFlag; turnOff = False
type FlagSpec flag
= ( String -- Flag in string form
, flag -- Flag in internal form
, TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
-- Typically, emit a warning or error
mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
-> String -- ^ The flag prefix
-> (flag -> DynP ()) -- ^ What to do when the flag is found
-> FlagSpec flag -- ^ Specification of this particular flag
-> Flag (CmdLineP DynFlags)
mkFlag turn_on flagPrefix f (name, flag, extra_action)
= Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
deprecatedForExtension lang turn_on
= deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
where
flag | turn_on = lang
| otherwise = "No"++lang
useInstead :: String -> TurnOnFlag -> DynP ()
useInstead flag turn_on
= deprecate ("Use -f" ++ no ++ flag ++ " instead")
where
no = if turn_on then "" else "no-"
nop :: TurnOnFlag -> DynP ()
nop _ = return ()
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fWarningFlags :: [FlagSpec WarningFlag]
fWarningFlags = [
( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
( "warn-overflowed-literals", Opt_WarnOverflowedLiterals, nop ),
( "warn-empty-enumerations", Opt_WarnEmptyEnumerations, nop ),
( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
( "warn-duplicate-constraints", Opt_WarnDuplicateConstraints, nop ),
( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
( "warn-missing-fields", Opt_WarnMissingFields, nop ),
( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
( "warn-amp", Opt_WarnAMP, nop ),
( "warn-orphans", Opt_WarnOrphans, nop ),
( "warn-identities", Opt_WarnIdentities, nop ),
( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
( "warn-tabs", Opt_WarnTabs, nop ),
( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ),
( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
( "warn-safe", Opt_WarnSafe, setWarnSafe ),
( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ),
( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ),
( "warn-inline-rule-shadowing", Opt_WarnInlineRuleShadowing, nop ),
( "warn-unsupported-llvm-version", Opt_WarnUnsupportedLlvmVersion, nop ) ]
-- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
negatableFlags :: [FlagSpec GeneralFlag]
negatableFlags = [
( "ignore-dot-ghci", Opt_IgnoreDotGhci, nop ) ]
-- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
dFlags :: [FlagSpec GeneralFlag]
dFlags = [
( "suppress-coercions", Opt_SuppressCoercions, nop),
( "suppress-var-kinds", Opt_SuppressVarKinds, nop),
( "suppress-module-prefixes", Opt_SuppressModulePrefixes, nop),
( "suppress-type-applications", Opt_SuppressTypeApplications, nop),
( "suppress-idinfo", Opt_SuppressIdInfo, nop),
( "suppress-type-signatures", Opt_SuppressTypeSignatures, nop),
( "suppress-uniques", Opt_SuppressUniques, nop),
( "ppr-case-as-let", Opt_PprCaseAsLet, nop)]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fFlags :: [FlagSpec GeneralFlag]
fFlags = [
( "error-spans", Opt_ErrorSpans, nop ),
( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
( "strictness", Opt_Strictness, nop ),
( "late-dmd-anal", Opt_LateDmdAnal, nop ),
( "specialise", Opt_Specialise, nop ),
( "float-in", Opt_FloatIn, nop ),
( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
( "full-laziness", Opt_FullLaziness, nop ),
( "liberate-case", Opt_LiberateCase, nop ),
( "spec-constr", Opt_SpecConstr, nop ),
( "cse", Opt_CSE, nop ),
( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
( "ignore-asserts", Opt_IgnoreAsserts, nop ),
( "do-eta-reduction", Opt_DoEtaReduction, nop ),
( "case-merge", Opt_CaseMerge, nop ),
( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
( "unbox-small-strict-fields", Opt_UnboxSmallStrictFields, nop ),
( "dicts-cheap", Opt_DictsCheap, nop ),
( "excess-precision", Opt_ExcessPrecision, nop ),
( "eager-blackholing", Opt_EagerBlackHoling, nop ),
( "print-bind-result", Opt_PrintBindResult, nop ),
( "force-recomp", Opt_ForceRecomp, nop ),
( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
( "break-on-exception", Opt_BreakOnException, nop ),
( "break-on-error", Opt_BreakOnError, nop ),
( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
( "print-bind-contents", Opt_PrintBindContents, nop ),
( "run-cps", Opt_RunCPS, nop ),
( "run-cpsz", Opt_RunCPSZ, nop ),
( "vectorise", Opt_Vectorise, nop ),
( "vectorisation-avoidance", Opt_VectorisationAvoidance, nop ),
( "regs-graph", Opt_RegsGraph, nop ),
( "regs-iterative", Opt_RegsIterative, nop ),
( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag
( "llvm-pass-vectors-in-regs", Opt_LlvmPassVectorsInRegisters, nop), -- hidden flag
( "irrefutable-tuples", Opt_IrrefutableTuples, nop ),
( "cmm-sink", Opt_CmmSink, nop ),
( "cmm-elim-common-blocks", Opt_CmmElimCommonBlocks, nop ),
( "omit-yields", Opt_OmitYields, nop ),
( "simple-list-literals", Opt_SimpleListLiterals, nop ),
( "fun-to-thunk", Opt_FunToThunk, nop ),
( "gen-manifest", Opt_GenManifest, nop ),
( "embed-manifest", Opt_EmbedManifest, nop ),
( "ext-core", Opt_EmitExternalCore, nop ),
( "shared-implib", Opt_SharedImplib, nop ),
( "ghci-sandbox", Opt_GhciSandbox, nop ),
( "ghci-history", Opt_GhciHistory, nop ),
( "helpful-errors", Opt_HelpfulErrors, nop ),
( "defer-type-errors", Opt_DeferTypeErrors, nop ),
( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
( "prof-count-entries", Opt_ProfCountEntries, nop ),
( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop ),
( "hpc", Opt_Hpc, nop ),
( "pre-inlining", Opt_SimplPreInlining, nop ),
( "flat-cache", Opt_FlatCache, nop ),
( "use-rpaths", Opt_RPath, nop ),
( "kill-absence", Opt_KillAbsence, nop),
( "kill-one-shot", Opt_KillOneShot, nop),
( "dicts-strict", Opt_DictsStrict, nop ),
( "dmd-tx-dict-sel", Opt_DmdTxDictSel, nop ),
( "loopification", Opt_Loopification, nop )
]
-- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
fLangFlags :: [FlagSpec ExtensionFlag]
fLangFlags = [
( "th", Opt_TemplateHaskell,
\on -> deprecatedForExtension "TemplateHaskell" on
>> checkTemplateHaskellOk on ),
( "fi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "ffi", Opt_ForeignFunctionInterface,
deprecatedForExtension "ForeignFunctionInterface" ),
( "arrows", Opt_Arrows,
deprecatedForExtension "Arrows" ),
( "implicit-prelude", Opt_ImplicitPrelude,
deprecatedForExtension "ImplicitPrelude" ),
( "bang-patterns", Opt_BangPatterns,
deprecatedForExtension "BangPatterns" ),
( "monomorphism-restriction", Opt_MonomorphismRestriction,
deprecatedForExtension "MonomorphismRestriction" ),
( "mono-pat-binds", Opt_MonoPatBinds,
deprecatedForExtension "MonoPatBinds" ),
( "extended-default-rules", Opt_ExtendedDefaultRules,
deprecatedForExtension "ExtendedDefaultRules" ),
( "implicit-params", Opt_ImplicitParams,
deprecatedForExtension "ImplicitParams" ),
( "scoped-type-variables", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "parr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "PArr", Opt_ParallelArrays,
deprecatedForExtension "ParallelArrays" ),
( "allow-overlapping-instances", Opt_OverlappingInstances,
deprecatedForExtension "OverlappingInstances" ),
( "allow-undecidable-instances", Opt_UndecidableInstances,
deprecatedForExtension "UndecidableInstances" ),
( "allow-incoherent-instances", Opt_IncoherentInstances,
deprecatedForExtension "IncoherentInstances" )
]
supportedLanguages :: [String]
supportedLanguages = [ name | (name, _, _) <- languageFlags ]
supportedLanguageOverlays :: [String]
supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
supportedExtensions :: [String]
supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
supportedLanguagesAndExtensions :: [String]
supportedLanguagesAndExtensions =
supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
languageFlags :: [FlagSpec Language]
languageFlags = [
( "Haskell98", Haskell98, nop ),
( "Haskell2010", Haskell2010, nop )
]
-- | These -X<blah> flags cannot be reversed with -XNo<blah>
-- They are used to place hard requirements on what GHC Haskell language
-- features can be used.
safeHaskellFlags :: [FlagSpec SafeHaskellMode]
safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
where mkF flag = (show flag, flag, nop)
-- | These -X<blah> flags can all be reversed with -XNo<blah>
xFlags :: [FlagSpec ExtensionFlag]
xFlags = [
( "CPP", Opt_Cpp, nop ),
( "PostfixOperators", Opt_PostfixOperators, nop ),
( "TupleSections", Opt_TupleSections, nop ),
( "PatternGuards", Opt_PatternGuards, nop ),
( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
( "MagicHash", Opt_MagicHash, nop ),
( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
( "KindSignatures", Opt_KindSignatures, nop ),
( "RoleAnnotations", Opt_RoleAnnotations, nop ),
( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
( "ParallelListComp", Opt_ParallelListComp, nop ),
( "TransformListComp", Opt_TransformListComp, nop ),
( "MonadComprehensions", Opt_MonadComprehensions, nop),
( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
( "CApiFFI", Opt_CApiFFI, nop ),
( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
( "JavaScriptFFI", Opt_JavaScriptFFI, nop ),
( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
( "PolymorphicComponents", Opt_RankNTypes, nop),
( "Rank2Types", Opt_RankNTypes, nop),
( "RankNTypes", Opt_RankNTypes, nop ),
( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
( "TypeOperators", Opt_TypeOperators, nop ),
( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ),
( "RecursiveDo", Opt_RecursiveDo, nop ), -- Enables 'mdo' and 'rec'
( "DoRec", Opt_RecursiveDo,
deprecatedForExtension "RecursiveDo" ),
( "Arrows", Opt_Arrows, nop ),
( "ParallelArrays", Opt_ParallelArrays, nop ),
( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
( "QuasiQuotes", Opt_QuasiQuotes, nop ),
( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
( "RecordWildCards", Opt_RecordWildCards, nop ),
( "NamedFieldPuns", Opt_RecordPuns, nop ),
( "RecordPuns", Opt_RecordPuns,
deprecatedForExtension "NamedFieldPuns" ),
( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
( "OverloadedStrings", Opt_OverloadedStrings, nop ),
( "NumDecimals", Opt_NumDecimals, nop),
( "OverloadedLists", Opt_OverloadedLists, nop),
( "GADTs", Opt_GADTs, nop ),
( "GADTSyntax", Opt_GADTSyntax, nop ),
( "ViewPatterns", Opt_ViewPatterns, nop ),
( "TypeFamilies", Opt_TypeFamilies, nop ),
( "BangPatterns", Opt_BangPatterns, nop ),
( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
( "RebindableSyntax", Opt_RebindableSyntax, nop ),
( "ConstraintKinds", Opt_ConstraintKinds, nop ),
( "PolyKinds", Opt_PolyKinds, nop ),
( "DataKinds", Opt_DataKinds, nop ),
( "InstanceSigs", Opt_InstanceSigs, nop ),
( "MonoPatBinds", Opt_MonoPatBinds,
\ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
( "ExplicitForAll", Opt_ExplicitForAll, nop ),
( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
( "DatatypeContexts", Opt_DatatypeContexts,
\ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
( "RelaxedLayout", Opt_RelaxedLayout, nop ),
( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
( "LambdaCase", Opt_LambdaCase, nop ),
( "MultiWayIf", Opt_MultiWayIf, nop ),
( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
( "RelaxedPolyRec", Opt_RelaxedPolyRec,
\ turn_on -> unless turn_on
$ deprecate "You can't turn off RelaxedPolyRec any more" ),
( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
( "ImplicitParams", Opt_ImplicitParams, nop ),
( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
( "AllowAmbiguousTypes", Opt_AllowAmbiguousTypes, nop),
( "PatternSignatures", Opt_ScopedTypeVariables,
deprecatedForExtension "ScopedTypeVariables" ),
( "UnboxedTuples", Opt_UnboxedTuples, nop ),
( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
( "AutoDeriveTypeable", Opt_AutoDeriveTypeable, nop ),
( "DeriveFunctor", Opt_DeriveFunctor, nop ),
( "DeriveTraversable", Opt_DeriveTraversable, nop ),
( "DeriveFoldable", Opt_DeriveFoldable, nop ),
( "DeriveGeneric", Opt_DeriveGeneric, nop ),
( "DefaultSignatures", Opt_DefaultSignatures, nop ),
( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
( "FlexibleContexts", Opt_FlexibleContexts, nop ),
( "FlexibleInstances", Opt_FlexibleInstances, nop ),
( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
( "NullaryTypeClasses", Opt_NullaryTypeClasses, nop ),
( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
( "OverlappingInstances", Opt_OverlappingInstances, nop ),
( "UndecidableInstances", Opt_UndecidableInstances, nop ),
( "IncoherentInstances", Opt_IncoherentInstances, nop ),
( "PackageImports", Opt_PackageImports, nop ),
( "TypeHoles", Opt_TypeHoles, nop ),
( "NegativeLiterals", Opt_NegativeLiterals, nop ),
( "EmptyCase", Opt_EmptyCase, nop )
]
defaultFlags :: Settings -> [GeneralFlag]
defaultFlags settings
= [ Opt_AutoLinkPackages,
Opt_SharedImplib,
Opt_OmitYields,
Opt_GenManifest,
Opt_EmbedManifest,
Opt_PrintBindContents,
Opt_GhciSandbox,
Opt_GhciHistory,
Opt_HelpfulErrors,
Opt_ProfCountEntries,
Opt_SimplPreInlining,
Opt_FlatCache,
Opt_RPath
]
++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
-- The default -O0 options
++ default_PIC platform
++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
then wayGeneralFlags platform WayDyn
else [])
where platform = sTargetPlatform settings
default_PIC :: Platform -> [GeneralFlag]
default_PIC platform =
case (platformOS platform, platformArch platform) of
(OSDarwin, ArchX86_64) -> [Opt_PIC]
_ -> []
impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
impliedFlags
= [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
, (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
, (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
, (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
, (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
, (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
, (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
, (Opt_GADTs, turnOn, Opt_GADTSyntax)
, (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
, (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
, (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
-- AutoDeriveTypeable is not very useful without DeriveDataTypeable
, (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
-- We turn this on so that we can export associated type
-- type synonyms in subordinates (e.g. MyClass(type AssocType))
, (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
, (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
, (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
-- Record wild-cards implies field disambiguation
-- Otherwise if you write (C {..}) you may well get
-- stuff like " 'a' not in scope ", which is a bit silly
-- if the compiler has just filled in field 'a' of constructor 'C'
, (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
, (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
-- An implicit parameter constraint, `?x::Int`, is desugared into
-- `IP "x" Int`, which requires a flexible context/instance.
, (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts)
, (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances)
, (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI)
]
optLevelFlags :: [([Int], GeneralFlag)]
optLevelFlags
= [ ([0], Opt_IgnoreInterfacePragmas)
, ([0], Opt_OmitInterfacePragmas)
, ([1,2], Opt_IgnoreAsserts)
, ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
-- in PrelRules
, ([1,2], Opt_DoEtaReduction)
, ([1,2], Opt_CaseMerge)
, ([1,2], Opt_Strictness)
, ([1,2], Opt_CSE)
, ([1,2], Opt_FullLaziness)
, ([1,2], Opt_Specialise)
, ([1,2], Opt_FloatIn)
, ([1,2], Opt_UnboxSmallStrictFields)
, ([2], Opt_LiberateCase)
, ([2], Opt_SpecConstr)
-- XXX disabled, see #7192
-- , ([2], Opt_RegsGraph)
, ([0,1,2], Opt_LlvmTBAA)
, ([1,2], Opt_CmmSink)
, ([1,2], Opt_CmmElimCommonBlocks)
, ([0,1,2], Opt_DmdTxDictSel)
-- , ([2], Opt_StaticArgumentTransformation)
-- Max writes: I think it's probably best not to enable SAT with -O2 for the
-- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
-- several improvements to the heuristics, and I'm concerned that without
-- those changes SAT will interfere with some attempts to write "high
-- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
-- this year. In particular, the version in HEAD lacks the tail call
-- criterion, so many things that look like reasonable loops will be
-- turned into functions with extra (unneccesary) thunk creation.
, ([0,1,2], Opt_DoLambdaEtaExpansion)
-- This one is important for a tiresome reason:
-- we want to make sure that the bindings for data
-- constructors are eta-expanded. This is probably
-- a good thing anyway, but it seems fragile.
, ([0,1,2], Opt_VectorisationAvoidance)
]
-- -----------------------------------------------------------------------------
-- Standard sets of warning options
standardWarnings :: [WarningFlag]
standardWarnings
= [ Opt_WarnOverlappingPatterns,
Opt_WarnWarningsDeprecations,
Opt_WarnDeprecatedFlags,
Opt_WarnAMP,
Opt_WarnUnrecognisedPragmas,
Opt_WarnPointlessPragmas,
Opt_WarnDuplicateConstraints,
Opt_WarnDuplicateExports,
Opt_WarnOverflowedLiterals,
Opt_WarnEmptyEnumerations,
Opt_WarnMissingFields,
Opt_WarnMissingMethods,
Opt_WarnLazyUnliftedBindings,
Opt_WarnWrongDoBind,
Opt_WarnUnsupportedCallingConventions,
Opt_WarnDodgyForeignImports,
Opt_WarnInlineRuleShadowing,
Opt_WarnAlternativeLayoutRuleTransitional,
Opt_WarnUnsupportedLlvmVersion
]
minusWOpts :: [WarningFlag]
-- Things you get with -W
minusWOpts
= standardWarnings ++
[ Opt_WarnUnusedBinds,
Opt_WarnUnusedMatches,
Opt_WarnUnusedImports,
Opt_WarnIncompletePatterns,
Opt_WarnDodgyExports,
Opt_WarnDodgyImports
]
minusWallOpts :: [WarningFlag]
-- Things you get with -Wall
minusWallOpts
= minusWOpts ++
[ Opt_WarnTypeDefaults,
Opt_WarnNameShadowing,
Opt_WarnMissingSigs,
Opt_WarnHiShadows,
Opt_WarnOrphans,
Opt_WarnUnusedDoBind
]
enableGlasgowExts :: DynP ()
enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
mapM_ setExtensionFlag glasgowExtsFlags
disableGlasgowExts :: DynP ()
disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
mapM_ unSetExtensionFlag glasgowExtsFlags
glasgowExtsFlags :: [ExtensionFlag]
glasgowExtsFlags = [
Opt_ForeignFunctionInterface
, Opt_UnliftedFFITypes
, Opt_ImplicitParams
, Opt_ScopedTypeVariables
, Opt_UnboxedTuples
, Opt_TypeSynonymInstances
, Opt_StandaloneDeriving
, Opt_DeriveDataTypeable
, Opt_DeriveFunctor
, Opt_DeriveFoldable
, Opt_DeriveTraversable
, Opt_DeriveGeneric
, Opt_FlexibleContexts
, Opt_FlexibleInstances
, Opt_ConstrainedClassMethods
, Opt_MultiParamTypeClasses
, Opt_FunctionalDependencies
, Opt_MagicHash
, Opt_ExistentialQuantification
, Opt_UnicodeSyntax
, Opt_PostfixOperators
, Opt_PatternGuards
, Opt_LiberalTypeSynonyms
, Opt_RankNTypes
, Opt_TypeOperators
, Opt_ExplicitNamespaces
, Opt_RecursiveDo
, Opt_ParallelListComp
, Opt_EmptyDataDecls
, Opt_KindSignatures
, Opt_GeneralizedNewtypeDeriving ]
#ifdef GHCI
-- Consult the RTS to find whether GHC itself has been built profiled
-- If so, you can't use Template Haskell
foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
rtsIsProfiled :: Bool
rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
#endif
setWarnSafe :: Bool -> DynP ()
setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
setWarnSafe False = return ()
setWarnUnsafe :: Bool -> DynP ()
setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
setWarnUnsafe False = return ()
setPackageTrust :: DynP ()
setPackageTrust = do
setGeneralFlag Opt_PackageTrust
l <- getCurLoc
upd $ \d -> d { pkgTrustOnLoc = l }
setGenDeriving :: TurnOnFlag -> DynP ()
setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
setGenDeriving False = return ()
checkTemplateHaskellOk :: TurnOnFlag -> DynP ()
#ifdef GHCI
checkTemplateHaskellOk turn_on
| turn_on && rtsIsProfiled
= addErr "You can't use Template Haskell with a profiled compiler"
| otherwise
= getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
#else
-- In stage 1 we don't know that the RTS has rts_isProfiled,
-- so we simply say "ok". It doesn't matter because TH isn't
-- available in stage 1 anyway.
checkTemplateHaskellOk _ = return ()
#endif
{- **********************************************************************
%* *
DynFlags constructors
%* *
%********************************************************************* -}
type DynP = EwM (CmdLineP DynFlags)
upd :: (DynFlags -> DynFlags) -> DynP ()
upd f = liftEwM (do dflags <- getCmdLineState
putCmdLineState $! f dflags)
updM :: (DynFlags -> DynP DynFlags) -> DynP ()
updM f = do dflags <- liftEwM getCmdLineState
dflags' <- f dflags
liftEwM $ putCmdLineState $! dflags'
--------------- Constructor functions for OptKind -----------------
noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
noArg fn = NoArg (upd fn)
noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
noArgM fn = NoArg (updM fn)
noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
hasArg fn = HasArg (upd . fn)
hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
deprecate deprec)
sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
sepArg fn = SepArg (upd . fn)
intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
intSuffix fn = IntSuffix (\n -> upd (fn n))
floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
floatSuffix fn = FloatSuffix (\n -> upd (fn n))
optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
-> OptKind (CmdLineP DynFlags)
optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
versionSuffix :: (Int -> Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
versionSuffix fn = VersionSuffix (\maj min -> upd (fn maj min))
setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
--------------------------
addWay :: Way -> DynP ()
addWay w = upd (addWay' w)
addWay' :: Way -> DynFlags -> DynFlags
addWay' w dflags0 = let platform = targetPlatform dflags0
dflags1 = dflags0 { ways = w : ways dflags0 }
dflags2 = wayExtras platform w dflags1
dflags3 = foldr setGeneralFlag' dflags2
(wayGeneralFlags platform w)
dflags4 = foldr unSetGeneralFlag' dflags3
(wayUnsetGeneralFlags platform w)
in dflags4
removeWayDyn :: DynP ()
removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
--------------------------
setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
setGeneralFlag f = upd (setGeneralFlag' f)
unSetGeneralFlag f = upd (unSetGeneralFlag' f)
setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
setGeneralFlag' f dflags = gopt_set dflags f
unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
unSetGeneralFlag' f dflags = gopt_unset dflags f
--------------------------
setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
setWarningFlag f = upd (\dfs -> wopt_set dfs f)
unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
--------------------------
setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
setExtensionFlag f = upd (setExtensionFlag' f)
unSetExtensionFlag f = upd (unSetExtensionFlag' f)
setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
where
deps = [ if turn_on then setExtensionFlag' d
else unSetExtensionFlag' d
| (f', turn_on, d) <- impliedFlags, f' == f ]
-- When you set f, set the ones it implies
-- NB: use setExtensionFlag recursively, in case the implied flags
-- implies further flags
unSetExtensionFlag' f dflags = xopt_unset dflags f
-- When you un-set f, however, we don't un-set the things it implies
-- (except for -fno-glasgow-exts, which is treated specially)
--------------------------
alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
alterSettings f dflags = dflags { settings = f (settings dflags) }
--------------------------
setDumpFlag' :: DumpFlag -> DynP ()
setDumpFlag' dump_flag
= do upd (\dfs -> dopt_set dfs dump_flag)
when want_recomp forceRecompile
where -- Certain dumpy-things are really interested in what's going
-- on during recompilation checking, so in those cases we
-- don't want to turn it off.
want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
Opt_D_dump_hi_diffs]
forceRecompile :: DynP ()
-- Whenver we -ddump, force recompilation (by switching off the
-- recompilation checker), else you don't see the dump! However,
-- don't switch it off in --make mode, else *everything* gets
-- recompiled which probably isn't what you want
forceRecompile = do dfs <- liftEwM getCmdLineState
when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
where
force_recomp dfs = isOneShot (ghcMode dfs)
setVerboseCore2Core :: DynP ()
setVerboseCore2Core = do setDumpFlag' Opt_D_verbose_core2core
upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
setDumpSimplPhases :: String -> DynP ()
setDumpSimplPhases s = do forceRecompile
upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
where
spec = case s of { ('=' : s') -> s'; _ -> s }
setVerbosity :: Maybe Int -> DynP ()
setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
addCmdlineHCInclude :: String -> DynP ()
addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
data PkgConfRef
= GlobalPkgConf
| UserPkgConf
| PkgConfFile FilePath
addPkgConfRef :: PkgConfRef -> DynP ()
addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
removeUserPkgConf :: DynP ()
removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
where
isNotUser UserPkgConf = False
isNotUser _ = True
removeGlobalPkgConf :: DynP ()
removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
where
isNotGlobal GlobalPkgConf = False
isNotGlobal _ = True
clearPkgConf :: DynP ()
clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
exposePackage, exposePackageId, hidePackage, ignorePackage,
trustPackage, distrustPackage :: String -> DynP ()
exposePackage p = upd (exposePackage' p)
exposePackageId p =
upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
hidePackage p =
upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
ignorePackage p =
upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
distrustPackage p = exposePackage p >>
upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
exposePackage' :: String -> DynFlags -> DynFlags
exposePackage' p dflags
= dflags { packageFlags = ExposePackage p : packageFlags dflags }
setPackageName :: String -> DynFlags -> DynFlags
setPackageName p s = s{ thisPackage = stringToPackageId p }
-- If we're linking a binary, then only targets that produce object
-- code are allowed (requests for other target types are ignored).
setTarget :: HscTarget -> DynP ()
setTarget l = setTargetWithPlatform (const l)
setTargetWithPlatform :: (Platform -> HscTarget) -> DynP ()
setTargetWithPlatform f = upd set
where
set dfs = let l = f (targetPlatform dfs)
in if ghcLink dfs /= LinkBinary || isObjectTarget l
then dfs{ hscTarget = l }
else dfs
-- Changes the target only if we're compiling object code. This is
-- used by -fasm and -fllvm, which switch from one to the other, but
-- not from bytecode to object-code. The idea is that -fasm/-fllvm
-- can be safely used in an OPTIONS_GHC pragma.
setObjTarget :: HscTarget -> DynP ()
setObjTarget l = updM set
where
set dflags
| isObjectTarget (hscTarget dflags)
= return $ dflags { hscTarget = l }
| otherwise = return dflags
setOptLevel :: Int -> DynFlags -> DynP DynFlags
setOptLevel n dflags
| hscTarget dflags == HscInterpreted && n > 0
= do addWarn "-O conflicts with --interactive; -O ignored."
return dflags
| otherwise
= return (updOptLevel n dflags)
-- -Odph is equivalent to
--
-- -O2 optimise as much as possible
-- -fmax-simplifier-iterations20 this is necessary sometimes
-- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
--
setDPHOpt :: DynFlags -> DynP DynFlags
setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
, simplPhases = 3
})
setMainIs :: String -> DynP ()
setMainIs arg
| not (null main_fn) && isLower (head main_fn)
-- The arg looked like "Foo.Bar.baz"
= upd $ \d -> d{ mainFunIs = Just main_fn,
mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
| isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
= upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
| otherwise -- The arg looked like "baz"
= upd $ \d -> d{ mainFunIs = Just arg }
where
(main_mod, main_fn) = splitLongestPrefix arg (== '.')
addLdInputs :: Option -> DynFlags -> DynFlags
addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]}
-----------------------------------------------------------------------------
-- Paths & Libraries
addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
-- -i on its own deletes the import paths
addImportPath "" = upd (\s -> s{importPaths = []})
addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
addLibraryPath p =
upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
addIncludePath p =
upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
addFrameworkPath p =
upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
#ifndef mingw32_TARGET_OS
split_marker :: Char
split_marker = ':' -- not configurable (ToDo)
#endif
splitPathList :: String -> [String]
splitPathList s = filter notNull (splitUp s)
-- empty paths are ignored: there might be a trailing
-- ':' in the initial list, for example. Empty paths can
-- cause confusion when they are translated into -I options
-- for passing to gcc.
where
#ifndef mingw32_TARGET_OS
splitUp xs = split split_marker xs
#else
-- Windows: 'hybrid' support for DOS-style paths in directory lists.
--
-- That is, if "foo:bar:baz" is used, this interpreted as
-- consisting of three entries, 'foo', 'bar', 'baz'.
-- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
-- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
--
-- Notice that no attempt is made to fully replace the 'standard'
-- split marker ':' with the Windows / DOS one, ';'. The reason being
-- that this will cause too much breakage for users & ':' will
-- work fine even with DOS paths, if you're not insisting on being silly.
-- So, use either.
splitUp [] = []
splitUp (x:':':div:xs) | div `elem` dir_markers
= ((x:':':div:p): splitUp rs)
where
(p,rs) = findNextPath xs
-- we used to check for existence of the path here, but that
-- required the IO monad to be threaded through the command-line
-- parser which is quite inconvenient. The
splitUp xs = cons p (splitUp rs)
where
(p,rs) = findNextPath xs
cons "" xs = xs
cons x xs = x:xs
-- will be called either when we've consumed nought or the
-- "<Drive>:/" part of a DOS path, so splitting is just a Q of
-- finding the next split marker.
findNextPath xs =
case break (`elem` split_markers) xs of
(p, _:ds) -> (p, ds)
(p, xs) -> (p, xs)
split_markers :: [Char]
split_markers = [':', ';']
dir_markers :: [Char]
dir_markers = ['/', '\\']
#endif
-- -----------------------------------------------------------------------------
-- tmpDir, where we store temporary files.
setTmpDir :: FilePath -> DynFlags -> DynFlags
setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
-- we used to fix /cygdrive/c/.. on Windows, but this doesn't
-- seem necessary now --SDM 7/2/2008
-----------------------------------------------------------------------------
-- RTS opts
setRtsOpts :: String -> DynP ()
setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
-----------------------------------------------------------------------------
-- Hpc stuff
setOptHpcDir :: String -> DynP ()
setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
-----------------------------------------------------------------------------
-- Via-C compilation stuff
-- There are some options that we need to pass to gcc when compiling
-- Haskell code via C, but are only supported by recent versions of
-- gcc. The configure script decides which of these options we need,
-- and puts them in the "settings" file in $topdir. The advantage of
-- having these in a separate file is that the file can be created at
-- install-time depending on the available gcc version, and even
-- re-generated later if gcc is upgraded.
--
-- The options below are not dependent on the version of gcc, only the
-- platform.
picCCOpts :: DynFlags -> [String]
picCCOpts dflags
= case platformOS (targetPlatform dflags) of
OSDarwin
-- Apple prefers to do things the other way round.
-- PIC is on by default.
-- -mdynamic-no-pic:
-- Turn off PIC code generation.
-- -fno-common:
-- Don't generate "common" symbols - these are unwanted
-- in dynamic libraries.
| gopt Opt_PIC dflags -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
| otherwise -> ["-mdynamic-no-pic"]
OSMinGW32 -- no -fPIC for Windows
| gopt Opt_PIC dflags -> ["-U __PIC__", "-D__PIC__"]
| otherwise -> []
_
-- we need -fPIC for C files when we are compiling with -dynamic,
-- otherwise things like stub.c files don't get compiled
-- correctly. They need to reference data in the Haskell
-- objects, but can't without -fPIC. See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
| gopt Opt_PIC dflags || not (gopt Opt_Static dflags) ->
["-fPIC", "-U __PIC__", "-D__PIC__"]
| otherwise -> []
picPOpts :: DynFlags -> [String]
picPOpts dflags
| gopt Opt_PIC dflags = ["-U __PIC__", "-D__PIC__"]
| otherwise = []
-- -----------------------------------------------------------------------------
-- Splitting
can_split :: Bool
can_split = cSupportsSplitObjs == "YES"
-- -----------------------------------------------------------------------------
-- Compiler Info
compilerInfo :: DynFlags -> [(String, String)]
compilerInfo dflags
= -- We always make "Project name" be first to keep parsing in
-- other languages simple, i.e. when looking for other fields,
-- you don't have to worry whether there is a leading '[' or not
("Project name", cProjectName)
-- Next come the settings, so anything else can be overridden
-- in the settings file (as "lookup" uses the first match for the
-- key)
: rawSettings dflags
++ [("Project version", cProjectVersion),
("Booter version", cBooterVersion),
("Stage", cStage),
("Build platform", cBuildPlatformString),
("Host platform", cHostPlatformString),
("Target platform", cTargetPlatformString),
("Have interpreter", cGhcWithInterpreter),
("Object splitting supported", cSupportsSplitObjs),
("Have native code generator", cGhcWithNativeCodeGen),
("Support SMP", cGhcWithSMP),
("Tables next to code", cGhcEnableTablesNextToCode),
("RTS ways", cGhcRTSWays),
("Support dynamic-too", "YES"),
("Support parallel --make", "YES"),
("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags
then "YES" else "NO"),
("GHC Dynamic", if cDYNAMIC_GHC_PROGRAMS
then "YES" else "NO"),
("Leading underscore", cLeadingUnderscore),
("Debug on", show debugIsOn),
("LibDir", topDir dflags),
("Global Package DB", systemPackageConfig dflags)
]
#include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs"
bLOCK_SIZE_W :: DynFlags -> Int
bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags
wORD_SIZE_IN_BITS :: DynFlags -> Int
wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8
tAG_MASK :: DynFlags -> Int
tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1
mAX_PTR_TAG :: DynFlags -> Int
mAX_PTR_TAG = tAG_MASK
-- Might be worth caching these in targetPlatform?
tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer
tARGET_MIN_INT dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (minBound :: Int32)
8 -> toInteger (minBound :: Int64)
w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w)
tARGET_MAX_INT dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (maxBound :: Int32)
8 -> toInteger (maxBound :: Int64)
w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w)
tARGET_MAX_WORD dflags
= case platformWordSize (targetPlatform dflags) of
4 -> toInteger (maxBound :: Word32)
8 -> toInteger (maxBound :: Word64)
w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w)
-- Whenever makeDynFlagsConsistent does anything, it starts over, to
-- ensure that a later change doesn't invalidate an earlier check.
-- Be careful not to introduce potential loops!
makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String])
makeDynFlagsConsistent dflags
| hscTarget dflags == HscC &&
not (platformUnregisterised (targetPlatform dflags))
= if cGhcWithNativeCodeGen == "YES"
then let dflags' = dflags { hscTarget = HscAsm }
warn = "Compiler not unregisterised, so using native code generator rather than compiling via C"
in loop dflags' warn
else let dflags' = dflags { hscTarget = HscLlvm }
warn = "Compiler not unregisterised, so using LLVM rather than compiling via C"
in loop dflags' warn
| hscTarget dflags == HscAsm &&
platformUnregisterised (targetPlatform dflags)
= loop (dflags { hscTarget = HscC })
"Compiler unregisterised, so compiling via C"
| hscTarget dflags == HscAsm &&
cGhcWithNativeCodeGen /= "YES"
= let dflags' = dflags { hscTarget = HscLlvm }
warn = "No native code generator, so using LLVM"
in loop dflags' warn
| hscTarget dflags == HscLlvm &&
not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
not ((isARM arch) && (os == OSLinux)) &&
(not (gopt Opt_Static dflags) || gopt Opt_PIC dflags)
= if cGhcWithNativeCodeGen == "YES"
then let dflags' = dflags { hscTarget = HscAsm }
warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform"
in loop dflags' warn
else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform"
| os == OSDarwin &&
arch == ArchX86_64 &&
not (gopt Opt_PIC dflags)
= loop (gopt_set dflags Opt_PIC)
"Enabling -fPIC as it is always on for this platform"
| otherwise = (dflags, [])
where loc = mkGeneralSrcSpan (fsLit "when making flags consistent")
loop updated_dflags warning
= case makeDynFlagsConsistent updated_dflags of
(dflags', ws) -> (dflags', L loc warning : ws)
platform = targetPlatform dflags
arch = platformArch platform
os = platformOS platform
--------------------------------------------------------------------------
-- Do not use unsafeGlobalDynFlags!
--
-- unsafeGlobalDynFlags is a hack, necessary because we need to be able
-- to show SDocs when tracing, but we don't always have DynFlags
-- available.
--
-- Do not use it if you can help it. You may get the wrong value!
GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags)
unsafeGlobalDynFlags :: DynFlags
unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags
setUnsafeGlobalDynFlags :: DynFlags -> IO ()
setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags
-- -----------------------------------------------------------------------------
-- SSE and AVX
-- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to
-- check if SSE is enabled, we might have x86-64 imply the -msse2
-- flag.
isSseEnabled :: DynFlags -> Bool
isSseEnabled dflags = case platformArch (targetPlatform dflags) of
ArchX86_64 -> True
ArchX86 -> sseVersion dflags >= Just (1,0)
_ -> False
isSse2Enabled :: DynFlags -> Bool
isSse2Enabled dflags = case platformArch (targetPlatform dflags) of
ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be
-- possible to make it optional, but we'd need to
-- fix at least the foreign call code where the
-- calling convention specifies the use of xmm regs,
-- and possibly other places.
True
ArchX86 -> sseVersion dflags >= Just (2,0)
_ -> False
isSse4_2Enabled :: DynFlags -> Bool
isSse4_2Enabled dflags = sseVersion dflags >= Just (4,2)
isAvxEnabled :: DynFlags -> Bool
isAvxEnabled dflags = avx dflags || avx2 dflags || avx512f dflags
isAvx2Enabled :: DynFlags -> Bool
isAvx2Enabled dflags = avx2 dflags || avx512f dflags
isAvx512cdEnabled :: DynFlags -> Bool
isAvx512cdEnabled dflags = avx512cd dflags
isAvx512erEnabled :: DynFlags -> Bool
isAvx512erEnabled dflags = avx512er dflags
isAvx512fEnabled :: DynFlags -> Bool
isAvx512fEnabled dflags = avx512f dflags
isAvx512pfEnabled :: DynFlags -> Bool
isAvx512pfEnabled dflags = avx512pf dflags
-- -----------------------------------------------------------------------------
-- Linker information
-- LinkerInfo contains any extra options needed by the system linker.
data LinkerInfo
= GnuLD [Option]
| GnuGold [Option]
| DarwinLD [Option]
| UnknownLD
deriving Eq
| bsd-3-clause |
tonnerre/dockerfiles | db/postgresql/pg_config.sh | 6331 | #!/bin/sh
#
# Copyright (c) 2017, Caoimhe Chaos <[email protected]>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * 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.
#
# * Neither the name of Ancient Solutions nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
POSTGRESQL_VERSION="9.4"
if [ x"$POSTGRESQL_MASTER" = x"" ]
then
echo "Error: POSTGRESQL_MASTER is not set." 1>&2
exit 1
fi
if [ ! -f /secrets/pg_syncpw ]
then
echo "Error: No PostgreSQL sync password in /secrets/pg_syncpw" 1>&2
exit 1
fi
pw="$(cat /secrets/pg_syncpw)"
/usr/bin/pg_basebackup -D "/var/lib/postgresql/${POSTGRESQL_VERSION}/main" \
-RP -d "host=${POSTGRESQL_MASTER} port=5432 user=replicator password=${pw} sslmode=require"
# Access
/usr/bin/pg_conftool -- set listen_addresses '*'
/usr/bin/pg_conftool -- set ssl_prefer_server_ciphers on
/usr/bin/pg_conftool -- set ssl_ciphers 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH'
/usr/bin/pg_conftool -- set ssl_renegotiation_limit 512MB
/usr/bin/pg_conftool -- set password_encryption on
/usr/bin/pg_conftool -- set db_user_namespace off
# Tuning paramaters
/usr/bin/pg_conftool -- set shared_buffers 480MB
/usr/bin/pg_conftool -- set temp_buffers 8MB
/usr/bin/pg_conftool -- set max_prepared_transactions 64
/usr/bin/pg_conftool -- set work_mem 10MB
/usr/bin/pg_conftool -- set maintenance_work_mem 120MB
/usr/bin/pg_conftool -- set max_stack_depth 2MB
/usr/bin/pg_conftool -- set dynamic_shared_memory_type posix
/usr/bin/pg_conftool -- set full_page_writes on
/usr/bin/pg_conftool -- set wal_buffers 4MB
/usr/bin/pg_conftool -- set wal_writer_delay 200ms
# Query tuning
/usr/bin/pg_conftool -- set enable_bitmapscan on
/usr/bin/pg_conftool -- set enable_hashagg on
/usr/bin/pg_conftool -- set enable_hashjoin on
/usr/bin/pg_conftool -- set enable_material on
/usr/bin/pg_conftool -- set enable_mergejoin on
/usr/bin/pg_conftool -- set enable_nestloop on
/usr/bin/pg_conftool -- set enable_seqscan on
/usr/bin/pg_conftool -- set enable_sort on
/usr/bin/pg_conftool -- set enable_tidscan on
/usr/bin/pg_conftool -- set default_statistics_target 10
/usr/bin/pg_conftool -- set constraint_exclusion off
/usr/bin/pg_conftool -- set cursor_tuple_fraction 0.1
/usr/bin/pg_conftool -- set from_collapse_limit 8
/usr/bin/pg_conftool -- set join_collapse_limit 8
/usr/bin/pg_conftool -- set geqo on
/usr/bin/pg_conftool -- set geqo_threshold 12
/usr/bin/pg_conftool -- set geqo_effort 5
/usr/bin/pg_conftool -- set geqo_pool_size 0
/usr/bin/pg_conftool -- set geqo_generations 0
/usr/bin/pg_conftool -- set geqo_selection_bias 2.0
/usr/bin/pg_conftool -- set geqo_seed 0.0
# Vacuuming
/usr/bin/pg_conftool -- set autovacuum on
/usr/bin/pg_conftool -- set track_activities on
/usr/bin/pg_conftool -- set track_counts on
/usr/bin/pg_conftool -- set track_io_timing on
/usr/bin/pg_conftool -- set track_functions none
/usr/bin/pg_conftool -- set track_activity_query_size 1024
/usr/bin/pg_conftool -- set log_autovacuum_min_duration 120000
/usr/bin/pg_conftool -- set autovacuum_max_workers 3
/usr/bin/pg_conftool -- set autovacuum_naptime 1min
/usr/bin/pg_conftool -- set autovacuum_vacuum_threshold 50
/usr/bin/pg_conftool -- set autovacuum_analyze_threshold 50
/usr/bin/pg_conftool -- set autovacuum_vacuum_scale_factor 0.2
/usr/bin/pg_conftool -- set autovacuum_analyze_scale_factor 0.1
/usr/bin/pg_conftool -- set autovacuum_freeze_max_age 200000000
/usr/bin/pg_conftool -- set autovacuum_multixact_freeze_max_age 400000000
/usr/bin/pg_conftool -- set autovacuum_vacuum_cost_delay 20ms
/usr/bin/pg_conftool -- set autovacuum_vacuum_cost_limit -1
# Replication
/usr/bin/pg_conftool -- set hot_standby on
/usr/bin/pg_conftool -- set hot_standby_feedback on
/usr/bin/pg_conftool -- set wal_level hot_standby
/usr/bin/pg_conftool -- set max_wal_senders 5
/usr/bin/pg_conftool -- set wal_keep_segments 8
/usr/bin/pg_conftool -- set checkpoint_segments 8
/usr/bin/pg_conftool -- set checkpoint_completion_target 0.7
# Logging
/usr/bin/pg_conftool -- set log_destination stderr
/usr/bin/pg_conftool -- set log_parser_stats off
/usr/bin/pg_conftool -- set log_planner_stats off
/usr/bin/pg_conftool -- set log_executor_stats off
/usr/bin/pg_conftool -- set log_statement_stats off
/usr/bin/pg_conftool -- set update_process_title on
# Locale
/usr/bin/pg_conftool -- set lc_messages en_US.UTF-8
/usr/bin/pg_conftool -- set lc_monetary en_US.UTF-8
/usr/bin/pg_conftool -- set lc_numeric en_US.UTF-8
/usr/bin/pg_conftool -- set lc_time en_US.UTF-8
# Secret configuration
# TODO(caoimhe): generate hba config from etcd on demand.
/usr/bin/pg_conftool -- set ssl_cert_file /secrets/postgresql.crt
/usr/bin/pg_conftool -- set ssl_key_file /secrets/postgresql.key
/usr/bin/pg_conftool -- set hba_file /secrets/postgresql.hba.conf
/usr/bin/pg_conftool -- set ident_file /secrets/postgresql.ident.conf
exec "/usr/lib/postgresql/${POSTGRESQL_VERSION}/bin/postmaster" "-D" "/var/lib/postgresql/${POSTGRESQL_VERSION}/main" "-c" "config_file=/etc/postgresql/${POSTGRESQL_VERSION}/main/postgresql.conf"
| bsd-3-clause |
egeor/libxsmm | src/template/libxsmm_dnn_convolution_winograd_backward_nhwc_custom_input_trans_alpha6.tpl.c | 6328 | /******************************************************************************
** Copyright (c) 2016-2018, Intel Corporation **
** 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. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "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 THE COPYRIGHT **
** HOLDER 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. **
******************************************************************************/
/* Kunal Banerjee (Intel Corp.)
******************************************************************************/
int total_tiles = handle->cwino_bwd.itiles*handle->cwino_bwd.jtiles;
LIBXSMM_VLA_DECL(4, const float, input, inp, handle->ofwp, handle->blocksofm, TDVLEN);
LIBXSMM_VLA_DECL(5, float, output, tinp, ALPHA, handle->blocksofm*handle->cwino_bwd.bimg, total_tiles, TDVLEN);
LIBXSMM_VLA_DECL(4, float, Iw, Iwp, ALPHA, ALPHA, TDVLEN);
float I[ALPHA][ALPHA][TDVLEN];
unsigned int ti, tj;
int i, j, k;
int xdim, ydim;
const int l_pad = (handle->desc.W - handle->ofw)/2 + 1;
const int t_pad = (handle->desc.H - handle->ofh)/2 + 1;
float T[6][6][TDVLEN];
float t0[TDVLEN];
float t1[TDVLEN];
float t2[TDVLEN];
float t3[TDVLEN];
float t4[TDVLEN];
float t5[TDVLEN];
for (tj = 0; tj < handle->cwino_bwd.jtiles; tj++) {
for (ti = 0; ti < handle->cwino_bwd.itiles; ti++) {
for (j = 0; j < ALPHA; j++) {
ydim = tj*(ALPHA - 2) + j - t_pad;
if ((ydim < 0) || (ydim >= handle->ofh)) {
for (i = 0; i < ALPHA; i++) {
LIBXSMM_PRAGMA_SIMD
for (k = 0; k < TDVLEN; k++) {
I[j][i][k] = 0.0f;
}
}
} else {
for (i = 0; i < ALPHA; i++) {
xdim = ti*(ALPHA - 2) + i - l_pad;
if ((xdim < 0) || (xdim >= handle->ofw)) {
LIBXSMM_PRAGMA_SIMD
for (k = 0; k < TDVLEN; k++) {
I[j][i][k] = 0.0f;
}
} else {
LIBXSMM_PRAGMA_SIMD
for (k = 0; k < TDVLEN; k++) {
I[j][i][k] = LIBXSMM_VLA_ACCESS(4, input, ydim, xdim, 0, k, handle->ofwp, handle->blocksofm, TDVLEN);
}
}
}
}
}
/*trans_I_4x4_3x3(ALPHA, TDVLEN, Iw[tj*handle->cwino_bwd.itiles + ti], I);*/
/* inline code start */
for (i = 0; i < 6; i++) {
LIBXSMM_PRAGMA_SIMD
for (j = 0; j < TDVLEN; j++) {
t0[j] = I[4][i][j] - 4.0f*I[2][i][j];
t1[j] = I[3][i][j] - 4.0f*I[1][i][j];
t2[j] = I[4][i][j] - I[2][i][j];
t3[j] = I[3][i][j] - I[1][i][j];
t4[j] = I[4][i][j] - 5.0f*I[2][i][j];
t5[j] = I[5][i][j] - 5.0f*I[3][i][j];
T[0][i][j] = t4[j] + 4.0f*I[0][i][j];
T[1][i][j] = t0[j] + t1[j];
T[2][i][j] = t0[j] - t1[j];
T[3][i][j] = t2[j] + 2.0f*t3[j];
T[4][i][j] = t2[j] - 2.0f*t3[j];
T[5][i][j] = t5[j] + 4.0f*I[1][i][j];
}
}
for (i = 0; i < 6; i++) {
LIBXSMM_PRAGMA_SIMD
for (j = 0; j < TDVLEN; j++) {
t0[j] = T[i][4][j] - 4.0f*T[i][2][j];
t1[j] = T[i][3][j] - 4.0f*T[i][1][j];
t2[j] = T[i][4][j] - T[i][2][j];
t3[j] = T[i][3][j] - T[i][1][j];
t4[j] = T[i][4][j] - 5.0f*T[i][2][j];
t5[j] = T[i][5][j] - 5.0f*T[i][3][j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 0, j, ALPHA, ALPHA, TDVLEN) = t4[j] + 4.0f*T[i][0][j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 1, j, ALPHA, ALPHA, TDVLEN) = t0[j] + t1[j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 2, j, ALPHA, ALPHA, TDVLEN) = t0[j] - t1[j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 3, j, ALPHA, ALPHA, TDVLEN) = t2[j] + 2.0f*t3[j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 4, j, ALPHA, ALPHA, TDVLEN) = t2[j] - 2.0f*t3[j];
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, i, 5, j, ALPHA, ALPHA, TDVLEN) = t5[j] + 4.0f*T[i][1][j];
}
}
/* inline code end */
}
}
for (j = 0; j < ALPHA; j++) {
for (i = 0; i < ALPHA; i++) {
for (tj = 0; tj < handle->cwino_bwd.jtiles; tj++) {
for (ti = 0; ti < handle->cwino_bwd.itiles; ti++) {
LIBXSMM_PRAGMA_SIMD
for (k = 0; k < TDVLEN; k++) {
LIBXSMM_VLA_ACCESS(5, output, j, i, 0, tj*handle->cwino_bwd.itiles + ti, k, ALPHA, handle->blocksofm*handle->cwino_bwd.bimg, total_tiles, TDVLEN) =
LIBXSMM_VLA_ACCESS(4, Iw, tj*handle->cwino_bwd.itiles + ti, j, i, k, ALPHA, ALPHA, TDVLEN);
}
}
}
}
}
| bsd-3-clause |
Phortran/SicurezzaInformatica | ApkSSL_Tester/libs/soot/doc/soot/jimple/toolkits/annotation/logic/class-use/LoopFinder.html | 6077 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Jan 22 14:18:59 CET 2012 -->
<TITLE>
Uses of Class soot.jimple.toolkits.annotation.logic.LoopFinder (Soot API)
</TITLE>
<META NAME="date" CONTENT="2012-01-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class soot.jimple.toolkits.annotation.logic.LoopFinder (Soot API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../soot/jimple/toolkits/annotation/logic/LoopFinder.html" title="class in soot.jimple.toolkits.annotation.logic"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?soot/jimple/toolkits/annotation/logic//class-useLoopFinder.html" target="_top"><B>FRAMES</B></A>
<A HREF="LoopFinder.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>soot.jimple.toolkits.annotation.logic.LoopFinder</B></H2>
</CENTER>
No usage of soot.jimple.toolkits.annotation.logic.LoopFinder
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../soot/jimple/toolkits/annotation/logic/LoopFinder.html" title="class in soot.jimple.toolkits.annotation.logic"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?soot/jimple/toolkits/annotation/logic//class-useLoopFinder.html" target="_top"><B>FRAMES</B></A>
<A HREF="LoopFinder.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| bsd-3-clause |
ferdianap/eris | visor/include/visor/MPEG7FexLib_src_OpenCV22/AddressLib/nhood.h | 10076 | /*
* nhood.h
*
* nhood provides the kernel for intra, fifo and lifo addrssing functions
* and performs the complex pixel load/store mechanisms implemented
* by pointer arithmetics
*
*/
/****** CopyRightBegin *******************************************************/
/* */
/* Copyright (C) 1996 TU-Muenchen LIS All Rights Reserved. */
/* */
/****** CopyRightEnd *********************************************************/
/*****************************************************************************/
/* CREATED BY : S. Herrmann 26/2/96 */
/* TU Muenchen-LIS */
/* based on : MPEG-4 Momusys VM Data structure */
/*****************************************************************************/
/**** LISSCCSInfo ************************************************************/
/* Filename : $RCSfile: nhood.h,v $
Version : Revision: 1.12
Last Edit: Date: 2003/10/23 14:31:02
Released : %D% %T% */
/**** LISSCCSInfo ************************************************************/
/*
///////////////////////////////////////////////////////////////////////////////
//
// This software module was originally developed by
//
// S. Herrmann TU-Munich, Institute for Integrated Circuits
// (contributing organizations names)
//
// in the course of development of the MPEG-7 Experimentation Model.
//
// This software module is an implementation of a part of one or more MPEG-7
// Experimentation Model tools as specified by the MPEG-7 Requirements.
//
// ISO/IEC gives users of MPEG-7 free license to this software module or
// modifications thereof for use in hardware or software products claiming
// conformance to MPEG-7.
//
// Those intending to use this software module in hardware or software products
// are advised that its use may infringe existing patents. The original
// developer of this software module and his/her company, the subsequent
// editors and their companies, and ISO/IEC have no liability for use of this
// software module or modifications thereof in an implementation.
//
// Copyright is not released for non MPEG-7 conforming products. The
// organizations named above retain full right to use the code for their own
// purpose, assign or donate the code to a third party and inhibit third parties
// from using the code for non MPEG-7 conforming products.
//
// Copyright (c) 1998-1999.
//
// This notice must be included in all copies or derivative works.
//
// Applicable File Name: nhood.h
//
*/
#ifndef _NHOOD_
#define _NHOOD_
/******* INCLUDES ************************************************************/
#include <visor/MPEG7FexLib_src_OpenCV22/AddressLib/momusys.h>
#include <visor/MPEG7FexLib_src_OpenCV22/AddressLib/address.h>
/******* DEFINES *************************************************************/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/* Treat naming conflict of MoMuSys and ImageMagick*/
#ifndef _MYMOMUSYS_
#ifndef _NAMECONFICTDEFS_
#define _NAMECONFICTDEFS_
#define MomImageType ImageType
#define MomImageData ImageData
#define MomImage Image
#define MomVopExtend VopExtend
#define MomVop Vop
#define momvop vop
#endif
#endif
/******* MAKROS *************************************************************/
/******* TYPES ***************************************************************/
struct size_conv_struct
{
char repeatx;
char strepx;
char stepx;
char repeaty;
char strepy;
char stepy;
};
typedef struct size_conv_struct TSizeConv;
struct nhood_struct
{
MomImage *_n_marker; /* pointer to markerfield*/
TCoor _n_inwidth,_n_inheight; /* input image size*/
/* matrix size*/
char _n_xblksize; /* matrix x radius without centrer*/
char _n_yblksize; /* matrix y radius without centrer*/
char _n_xblkstart; /* top line of matrix*/
char _n_yblkstart; /* left line of matrix*/
char _n_xblkstop; /* buttom line of matrix*/
char _n_yblkstop; /* right line of matrix*/
char _n_xblkdelta; /* preload line x delta*/
char _n_yblkdelta; /* preload line y delta*/
/*replacment values*/
TChan _n_amaska;
TChan _n_ymaska;
TChan _n_umaska;
TChan _n_vmaska;
TChan _n_axmaska;
TChan _n_amasko;
TChan _n_ymasko;
TChan _n_umasko;
TChan _n_vmasko;
TChan _n_axmasko;
/* MomImageType _n_iatype;
MomImageType _n_iytype;
MomImageType _n_iutype;
MomImageType _n_ivtype;*/
char _n_inchanels; /* corrected flags of input channels*/
char _n_reschanels; /* corrected flags of result channels*/
char _n_scanmode; /* corrected scanmode for conectivity*/
char _n_mintern; /* flag for internally controlled marker field*/
char error; /* error indicator*/
/* Interface from addressing methodes to neighborhood*/
TPixel matrix[25]; /* input matrix register*/
TPixel result; /* output result vector*/
/* position counters*/
TCoor width,height; /* reuslt image size*/
TCoor _n_cntx,_n_cnty; /* curent pixel position in result frame*/
TCoor _n_stx,_n_sty; /* curent pixel position of startmark*/
TCoor _n_maxx,_n_maxy; /* maximumpositions of processingwindow*/
TCoor _n_icntx,_n_icnty; /* curent pixel position in input frame*/
char _n_irepeatx,_n_irepeaty;/* subsampling of inputvalues*/
char _n_istepx,_n_istepy;/* subsampling of resultvalues*/
char _n_irepcntx,_n_irepcnty;
/* repeated times of imput position*/
char _n_stirepcntx,_n_stirepcnty;
/* initial values of repeat counters*/
char _n_firstx,_n_firsty; /* first pixel in step raster*/
/*incrementer values for pointer shifts*/
short _n_iaes,_n_iyes,_n_iues,_n_ives; /*element sizes*/
short _n_raes,_n_ryes,_n_rues,_n_rves;
short _n_ias,_n_iys,_n_ius,_n_ivs,_n_ms,_n_axs; /*horizontal step size*/
short _n_ras,_n_rys,_n_rus,_n_rvs;
TCoor _n_ials,_n_iyls,_n_iuls,_n_ivls,_n_mls,_n_axls; /*vertoical step size*/
TCoor _n_rals,_n_ryls,_n_ruls,_n_rvls;
/* references to read-write functions*/
TChan(*_n_iaget)(MomImageData data);
TChan(*_n_iyget)(MomImageData data);
TChan(*_n_iuget)(MomImageData data);
TChan(*_n_ivget)(MomImageData data);
TChan(*_n_axget)(MomImageData data);
TChan(*_n_mget) (MomImageData data);
TChan(*_n_raget)(MomImageData data);
TChan(*_n_ryget)(MomImageData data);
TChan(*_n_ruget)(MomImageData data);
TChan(*_n_rvget)(MomImageData data);
void (*_n_iaset)(MomImageData data,TChan value);
void (*_n_iyset)(MomImageData data,TChan value);
void (*_n_iuset)(MomImageData data,TChan value);
void (*_n_ivset)(MomImageData data,TChan value);
void (*_n_axset)(MomImageData data,TChan value);
void (*_n_mset) (MomImageData data,TChan value);
void (*_n_raset)(MomImageData data,TChan value);
void (*_n_ryset)(MomImageData data,TChan value);
void (*_n_ruset)(MomImageData data,TChan value);
void (*_n_rvset)(MomImageData data,TChan value);
MomImageType _n_ratype,_n_rytype,_n_rutype,_n_rvtype,_n_mtype,_n_axtype;
/* pointer to pixel positions*/
MomImageData _n_ia,_n_iy,_n_iu,_n_iv,_n_m,_n_,_n_ax;
/* input pixel positions in memory*/
MomImageData _n_ra,_n_ry,_n_ru,_n_rv;
/* outout pixel position in memory*/
MomImageData stia,stiy,stiu,stiv,stm,stax; /* line start positions */
MomImageData stra,stry,stru,strv; /* in memory*/
MomImageData fstia,fstiy,fstiu,fstiv,fstm,fstax; /* frame start positions*/
MomImageData fstra,fstry,fstru,fstrv; /* in memory*/
};
typedef struct nhood_struct TNhood;
/******* VARIABLES ***********************************************************/
/*extern TNhood regs;*/
extern TSizeConv size1to1;
extern TSizeConv uphv1TO2;
extern TSizeConv uph1TO2;
extern TSizeConv upv1TO2;
extern TSizeConv downhv2TO1;
extern TSizeConv downv2TO1;
extern TSizeConv downh2TO1;
extern short _typesize[5];
extern char dirtopos[8];
/******* FUNCTIONS ***********************************************************/
void ConstructNhood(TNhood *nhood,MomVop *result, MomVop *in,
MomImage *aux,MomImage *marker,int usemarker,
char reschanels,char inchanels,char connect,
char scanmode,
TChan ahold,TChan yhold,TChan uhold,TChan vhold,
TChan axhold,TCoor winx,TCoor winy,TCoor resposx,
TCoor resposy,TCoor inposx,TCoor inposy,
TSizeConv inconv);
void DestructNhood(TNhood *nhood);
int CheckError(TNhood *nhood);
/* for fifo_area*/
void Goto(TNhood *nhood,TCoor dx,TCoor dy); /* ref not moved*/
void Preload4(TNhood *nhood,TCoor dx,TCoor dy); /* ref not moved*/
void Preload8(TNhood *nhood,TCoor dx,TCoor dy); /* ref not moved*/
void MUpdate(TNhood *nhood,char dir); /* write marker for
process on queue
out*/
void UpdatePos(TNhood *nhood,char dir); /* for process on queue in*/
/*for rec_area*/
void Shift(TNhood *nhood,char dir);
void LoadIfUnload3X3(TNhood *nhood,short regpos);
/* for intra*/
void Preload(TNhood *nhood);
void PreloadSub(TNhood *nhood);
void ShiftUpLineLoad(TNhood *nhood);
void ShiftDownLineLoad(TNhood *nhood);
void ShiftLeftLineLoad(TNhood *nhood);
void ShiftRightLineLoad(TNhood *nhood);
void ShiftUpSubLineLoad(TNhood *nhood);
void ShiftDownSubLineLoad(TNhood *nhood);
void ShiftLeftSubLineLoad(TNhood *nhood);
void ShiftRightSubLineLoad(TNhood *nhood);
void addlib_stop_here(char *message,int doexit, int exitcode);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif
| bsd-3-clause |
GKBelmonte/SoundPlayer | Blaze.SoundPlayer/WaveProviders/SimpleSoundProvider.cs | 1241 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using Blaze.SoundPlayer.Sounds;
namespace Blaze.SoundPlayer.WaveProviders
{
internal class SimpleSoundProvider : WaveProvider32, ISoundProvider
{
int sample;
SimpleSound mSound;
public SimpleSoundProvider(SimpleSound sound)
{
mSound = sound;
AmplitudeMultiplier = 1;// WaveProviderCommon.DefaultAmplitude;
}
public int Resolution
{
get;
private set;
}
public float Frequency
{
get;
set;
}
public float AmplitudeMultiplier
{
get;
set;
}
public override int Read(float[] buffer, int offset, int sampleCount)
{
int sampleRate = WaveFormat.SampleRate;
for (int n = 0; n < sampleCount; n++)
{
buffer[n + offset] = (AmplitudeMultiplier * mSound.Get(sampleRate, sample, Frequency));
sample++;
}
return sampleCount;
}
}
}
| bsd-3-clause |
ShadowLordAlpha/TWL | src/main/java/de/matthiasmann/twl/textarea/TextAreaModel.java | 8925 | /*
* Copyright (c) 2008-2013, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT OWNER 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.
*/
package de.matthiasmann.twl.textarea;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Data model for the TextArea widget.
*
* @author Matthias Mann
*/
public interface TextAreaModel extends Iterable<TextAreaModel.Element> {
public enum HAlignment {
LEFT, RIGHT, CENTER, JUSTIFY
}
public enum Display {
INLINE, BLOCK
}
public enum VAlignment {
TOP, MIDDLE, BOTTOM, FILL
}
public enum Clear {
NONE, LEFT, RIGHT, BOTH
}
public enum FloatPosition {
NONE, LEFT, RIGHT
}
public abstract class Element {
private Style style;
protected Element(Style style) {
notNull(style, "style");
this.style = style;
}
/**
* Returns the style associated with this element
*
* @return the style associated with this element
*/
public Style getStyle() {
return style;
}
/**
* Replaces the style associated with this element. This method does not
* cause the model callback to be fired.
*
* @param style
* the new style. Must not be null.
*/
public void setStyle(Style style) {
notNull(style, "style");
this.style = style;
}
static void notNull(Object o, String name) {
if (o == null) {
throw new NullPointerException(name);
}
}
}
public class LineBreakElement extends Element {
public LineBreakElement(Style style) {
super(style);
}
};
public class TextElement extends Element {
private String text;
public TextElement(Style style, String text) {
super(style);
notNull(text, "text");
this.text = text;
}
/**
* Returns ths text.
*
* @return the text.
*/
public String getText() {
return text;
}
/**
* Replaces the text of this element. This method does not cause the
* model callback to be fired.
*
* @param text
* the new text. Must not be null.
*/
public void setText(String text) {
notNull(text, "text");
this.text = text;
}
}
public class ImageElement extends Element {
private final String imageName;
private final String tooltip;
public ImageElement(Style style, String imageName, String tooltip) {
super(style);
this.imageName = imageName;
this.tooltip = tooltip;
}
public ImageElement(Style style, String imageName) {
this(style, imageName, null);
}
/**
* Returns the image name for this image element.
*
* @return the image name for this image element.
*/
public String getImageName() {
return imageName;
}
/**
* Returns the tooltip or null for this image.
*
* @return the tooltip or null for this image. Can be null.
*/
public String getToolTip() {
return tooltip;
}
}
public class WidgetElement extends Element {
private final String widgetName;
private final String widgetParam;
public WidgetElement(Style style, String widgetName, String widgetParam) {
super(style);
this.widgetName = widgetName;
this.widgetParam = widgetParam;
}
public String getWidgetName() {
return widgetName;
}
public String getWidgetParam() {
return widgetParam;
}
}
public class ContainerElement extends Element implements Iterable<Element> {
protected final ArrayList<Element> children;
public ContainerElement(Style style) {
super(style);
this.children = new ArrayList<Element>();
}
public Iterator<Element> iterator() {
return children.iterator();
}
public Element getElement(int index) {
return children.get(index);
}
public int getNumElements() {
return children.size();
}
public void add(Element element) {
this.children.add(element);
}
}
public class ParagraphElement extends ContainerElement {
public ParagraphElement(Style style) {
super(style);
}
}
public class LinkElement extends ContainerElement {
private String href;
public LinkElement(Style style, String href) {
super(style);
this.href = href;
}
/**
* Returns the href of the link.
*
* @return the href of the link. Can be null.
*/
public String getHREF() {
return href;
}
/**
* Replaces the href of this link. This method does not cause the model
* callback to be fired.
*
* @param href
* the new href of the link, can be null.
*/
public void setHREF(String href) {
this.href = href;
}
}
/**
* A list item in an unordered list
*/
public class ListElement extends ContainerElement {
public ListElement(Style style) {
super(style);
}
}
/**
* An ordered list. All contained elements are treated as list items.
*/
public class OrderedListElement extends ContainerElement {
private final int start;
public OrderedListElement(Style style, int start) {
super(style);
this.start = start;
}
public int getStart() {
return start;
}
}
public class BlockElement extends ContainerElement {
public BlockElement(Style style) {
super(style);
}
}
public class TableCellElement extends ContainerElement {
private final int colspan;
public TableCellElement(Style style) {
this(style, 1);
}
public TableCellElement(Style style, int colspan) {
super(style);
this.colspan = colspan;
}
public int getColspan() {
return colspan;
}
}
public class TableElement extends Element {
private final int numColumns;
private final int numRows;
private final int cellSpacing;
private final int cellPadding;
private final TableCellElement[] cells;
private final Style[] rowStyles;
public TableElement(Style style, int numColumns, int numRows,
int cellSpacing, int cellPadding) {
super(style);
if (numColumns < 0) {
throw new IllegalArgumentException("numColumns");
}
if (numRows < 0) {
throw new IllegalArgumentException("numRows");
}
this.numColumns = numColumns;
this.numRows = numRows;
this.cellSpacing = cellSpacing;
this.cellPadding = cellPadding;
this.cells = new TableCellElement[numRows * numColumns];
this.rowStyles = new Style[numRows];
}
public int getNumColumns() {
return numColumns;
}
public int getNumRows() {
return numRows;
}
public int getCellPadding() {
return cellPadding;
}
public int getCellSpacing() {
return cellSpacing;
}
public TableCellElement getCell(int row, int column) {
if (column < 0 || column >= numColumns) {
throw new IndexOutOfBoundsException("column");
}
if (row < 0 || row >= numRows) {
throw new IndexOutOfBoundsException("row");
}
return cells[row * numColumns + column];
}
public Style getRowStyle(int row) {
return rowStyles[row];
}
public void setCell(int row, int column, TableCellElement cell) {
if (column < 0 || column >= numColumns) {
throw new IndexOutOfBoundsException("column");
}
if (row < 0 || row >= numRows) {
throw new IndexOutOfBoundsException("row");
}
cells[row * numColumns + column] = cell;
}
public void setRowStyle(int row, Style style) {
rowStyles[row] = style;
}
}
/**
* Adds a model change callback which is called when the model is modified.
*
* @param cb
* the callback - must not be null.
*/
public void addCallback(Runnable cb);
/**
* Removes the specific callback.
*
* @param cb
* the callback that should be removed.
*/
public void removeCallback(Runnable cb);
}
| bsd-3-clause |
edunetcat/edunetcatweb2 | frontend/web/css/panell.css | 5351 | body {
background-color: #f8f8f8;
}
#wrapper {
width: 100%;
}
#page-wrapper {
padding: 0 15px;
min-height: 568px;
background-color: #fff;
}
@media(min-width:768px) {
#page-wrapper {
position: inherit;
margin: 0 0 0 250px;
padding: 0 30px;
border-left: 1px solid #e7e7e7;
}
}
.navbar-top-links {
margin-right: 0;
}
.navbar-top-links li {
display: inline-block;
}
.navbar-top-links li:last-child {
margin-right: 15px;
}
.navbar-top-links li a {
padding: 15px;
min-height: 50px;
}
.navbar-top-links .dropdown-menu li {
display: block;
}
.navbar-top-links .dropdown-menu li:last-child {
margin-right: 0;
}
.navbar-top-links .dropdown-menu li a {
padding: 3px 20px;
min-height: 0;
}
.navbar-top-links .dropdown-menu li a div {
white-space: normal;
}
.navbar-top-links .dropdown-messages,
.navbar-top-links .dropdown-tasks,
.navbar-top-links .dropdown-alerts {
width: 310px;
min-width: 0;
}
.navbar-top-links .dropdown-messages {
margin-left: 5px;
}
.navbar-top-links .dropdown-tasks {
margin-left: -59px;
}
.navbar-top-links .dropdown-alerts {
margin-left: -123px;
}
.navbar-top-links .dropdown-user {
right: 0;
left: auto;
}
.sidebar .sidebar-nav.navbar-collapse {
padding-right: 0;
padding-left: 0;
}
.sidebar .sidebar-search {
padding: 15px;
}
.sidebar ul li {
border-bottom: 1px solid #e7e7e7;
}
.sidebar ul li a.active {
background-color: #eee;
}
.sidebar .arrow {
float: right;
}
.sidebar .fa.arrow:before {
content: "\f104";
}
.sidebar .active>a>.fa.arrow:before {
content: "\f107";
}
.sidebar .nav-second-level li,
.sidebar .nav-third-level li {
border-bottom: 0!important;
}
.sidebar .nav-second-level li a {
padding-left: 37px;
}
.sidebar .nav-third-level li a {
padding-left: 52px;
}
@media(min-width:768px) {
.sidebar {
z-index: 1;
position: absolute;
width: 250px;
margin-top: 51px;
}
.navbar-top-links .dropdown-messages,
.navbar-top-links .dropdown-tasks,
.navbar-top-links .dropdown-alerts {
margin-left: auto;
}
}
.btn-outline {
color: inherit;
background-color: transparent;
transition: all .5s;
}
.btn-primary.btn-outline {
color: #428bca;
}
.btn-success.btn-outline {
color: #5cb85c;
}
.btn-info.btn-outline {
color: #5bc0de;
}
.btn-warning.btn-outline {
color: #f0ad4e;
}
.btn-danger.btn-outline {
color: #d9534f;
}
.btn-primary.btn-outline:hover,
.btn-success.btn-outline:hover,
.btn-info.btn-outline:hover,
.btn-warning.btn-outline:hover,
.btn-danger.btn-outline:hover {
color: #fff;
}
.chat {
margin: 0;
padding: 0;
list-style: none;
}
.chat li {
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px dotted #999;
}
.chat li.left .chat-body {
margin-left: 60px;
}
.chat li.right .chat-body {
margin-right: 60px;
}
.chat li .chat-body p {
margin: 0;
}
.panel .slidedown .glyphicon,
.chat .glyphicon {
margin-right: 5px;
}
.chat-panel .panel-body {
height: 350px;
overflow-y: scroll;
}
.flot-chart {
display: block;
height: 400px;
}
.flot-chart-content {
width: 100%;
height: 100%;
}
.dataTables_wrapper {
position: relative;
clear: both;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
background: 0 0;
}
table.dataTable thead .sorting_asc:after {
content: "\f0de";
float: right;
font-family: fontawesome;
}
table.dataTable thead .sorting_desc:after {
content: "\f0dd";
float: right;
font-family: fontawesome;
}
table.dataTable thead .sorting:after {
content: "\f0dc";
float: right;
font-family: fontawesome;
color: rgba(50,50,50,.5);
}
.btn-circle {
width: 30px;
height: 30px;
padding: 6px 0;
border-radius: 15px;
text-align: center;
font-size: 12px;
line-height: 1.428571429;
}
.btn-circle.btn-lg {
width: 50px;
height: 50px;
padding: 10px 16px;
border-radius: 25px;
font-size: 18px;
line-height: 1.33;
}
.btn-circle.btn-xl {
width: 70px;
height: 70px;
padding: 10px 16px;
border-radius: 35px;
font-size: 24px;
line-height: 1.33;
}
.show-grid [class^=col-] {
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #ddd;
background-color: #eee!important;
}
.show-grid {
margin: 15px 0;
}
.huge {
font-size: 40px;
}
.panel-green {
border-color: #5cb85c;
}
.panel-green .panel-heading {
border-color: #5cb85c;
color: #fff;
background-color: #5cb85c;
}
.panel-green a {
color: #5cb85c;
}
.panel-green a:hover {
color: #3d8b3d;
}
.panel-red {
border-color: #d9534f;
}
.panel-red .panel-heading {
border-color: #d9534f;
color: #fff;
background-color: #d9534f;
}
.panel-red a {
color: #d9534f;
}
.panel-red a:hover {
color: #b52b27;
}
.panel-yellow {
border-color: #f0ad4e;
}
.panel-yellow .panel-heading {
border-color: #f0ad4e;
color: #fff;
background-color: #f0ad4e;
}
.panel-yellow a {
color: #f0ad4e;
}
.panel-yellow a:hover {
color: #df8a13;
} | bsd-3-clause |
nickmeharry/django-mysql | tests/testapp/management/commands/test_dbparams.py | 3738 | # -*- coding:utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from unittest import mock, skipIf
import django
import pytest
from django.core.management import CommandError, call_command
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase
from django.utils.six.moves import StringIO
# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module
command_connections = 'django_mysql.management.commands.dbparams.connections'
sqlite = ConnectionHandler({
'default': {'ENGINE': 'django.db.backends.sqlite3'}
})
full_db = ConnectionHandler({'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'ausername',
'PASSWORD': 'apassword',
'HOST': 'ahost.example.com',
'PORT': '12345',
'OPTIONS': {
'read_default_file': '/tmp/defaults.cnf',
'ssl': {'ca': '/tmp/mysql.cert'}
}
}})
socket_db = ConnectionHandler({'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/etc/mydb.sock',
}})
class DBParamsTests(SimpleTestCase):
@skipIf(django.VERSION[:2] >= (1, 10),
'argument parsing uses a fixed single argument in Django 1.10+')
def test_invalid_number_of_databases(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', 'default', 'default', skip_checks=True)
assert "more than one connection" in str(excinfo.value)
def test_invalid_database(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', 'nonexistent', skip_checks=True)
assert "does not exist" in str(excinfo.value)
def test_invalid_both(self):
with pytest.raises(CommandError):
call_command('dbparams', dsn=True, mysql=True, skip_checks=True)
@mock.patch(command_connections, sqlite)
def test_invalid_not_mysql(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', skip_checks=True)
assert "not a MySQL database connection" in str(excinfo.value)
@mock.patch(command_connections, full_db)
def test_mysql_full(self):
out = StringIO()
call_command('dbparams', stdout=out, skip_checks=True)
output = out.getvalue()
assert (
output ==
"--defaults-file=/tmp/defaults.cnf --user=ausername "
"--password=apassword --host=ahost.example.com --port=12345 "
"--ssl-ca=/tmp/mysql.cert mydatabase"
)
@mock.patch(command_connections, socket_db)
def test_mysql_socket(self):
out = StringIO()
call_command('dbparams', stdout=out, skip_checks=True)
output = out.getvalue()
assert output == "--socket=/etc/mydb.sock"
@mock.patch(command_connections, full_db)
def test_dsn_full(self):
out = StringIO()
err = StringIO()
call_command('dbparams', 'default', dsn=True,
stdout=out, stderr=err, skip_checks=True)
output = out.getvalue()
assert (
output ==
"F=/tmp/defaults.cnf,u=ausername,p=apassword,h=ahost.example.com,"
"P=12345,D=mydatabase"
)
errors = err.getvalue()
assert "SSL params can't be" in errors
@mock.patch(command_connections, socket_db)
def test_dsn_socket(self):
out = StringIO()
err = StringIO()
call_command('dbparams', dsn=True,
stdout=out, stderr=err, skip_checks=True)
output = out.getvalue()
assert output == 'S=/etc/mydb.sock'
errors = err.getvalue()
assert errors == ""
| bsd-3-clause |
GarenGoh/yii | components/countryService.php | 1552 | <?php
namespace app\components;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Country;
/**
* countryService represents the model behind the search form about `app\models\Country`.
*/
class countryService extends Country
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['code', 'name'], 'safe'],
[['population'], 'integer'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Country::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'population' => $this->population,
]);
$query->andFilterWhere(['like', 'code', $this->code])
->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
| bsd-3-clause |
zadean/pl-sql-BaseX | tcp_examples/example.sql | 317 | -- example.sql
set serverout on
declare
v_sess utl_tcp.connection;
v_inpt varchar2(4000);
v_outp clob;
begin
v_sess := basex_client.open_session('localhost', 1984, 'admin', 'admin');
dbms_output.put_line(basex_client.bx_execute(v_sess, 'info'));
basex_client.close_session(v_sess);
end;
/
| bsd-3-clause |
VampireMe/admin-9939-com | tests/Common_Test.php | 634 | <?php
/**
* @version 0.0.0.1
*/
function callback($callback) {
$callback();
}
//输出: This is a anonymous function.<br />\n
//这里是直接定义一个匿名函数进行传递, 在以往的版本中, 这是不可用的.
//现在, 这种语法非常舒服, 和javascript语法基本一致, 之所以说基本呢, 需要继续向下看
//结论: 一个舒服的语法必然会受欢迎的.
$obj = (object) "Hello, everyone";
$callback = function () use ($obj) {
print "This is a closure use object, msg is: {$obj->scalar}. <br />\n";
};
$obj = (object) "Hello, everybody";
callback($callback);
echo $obj->toString();
| bsd-3-clause |
Swappsco/portal | config/settings/common.py | 9483 | # -*- coding: utf-8 -*-
"""
Django settings for djangocali-portal project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_literals
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)
APPS_DIR = ROOT_DIR.path('djangocali-portal')
env = environ.Env()
environ.Env.read_env()
# APP CONFIGURATION
# ------------------------------------------------------------------------------
DJANGO_APPS = (
# Default Django apps:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Useful template tags:
# 'django.contrib.humanize',
# Admin
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'crispy_forms', # Form layouts
'allauth', # registration
'allauth.account', # registration
'allauth.socialaccount', # registration
)
# Apps specific for this project go here.
LOCAL_APPS = (
'djangocali-portal.users', # custom users app
# Your stuff: custom apps go here
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# MIDDLEWARE CONFIGURATION
# ------------------------------------------------------------------------------
MIDDLEWARE_CLASSES = (
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# MIGRATIONS CONFIGURATION
# ------------------------------------------------------------------------------
MIGRATION_MODULES = {
'sites': 'djangocali-portal.contrib.sites.migrations'
}
# DEBUG
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# FIXTURE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
str(APPS_DIR.path('fixtures')),
)
# EMAIL CONFIGURATION
# ------------------------------------------------------------------------------
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
# MANAGER CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
("""djangocali""", '[email protected]'),
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
'default': env.db("DATABASE_URL", default="postgres:///djangocali-portal"),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
# GENERAL CONFIGURATION
# ------------------------------------------------------------------------------
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'UTC'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
'DIRS': [
str(APPS_DIR.path('templates')),
],
'OPTIONS': {
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
'debug': DEBUG,
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
# Your stuff: custom template context processors go here
],
},
},
]
# See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# STATIC FILE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
str(APPS_DIR.path('static')),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# MEDIA CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR('media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# URL Configuration
# ------------------------------------------------------------------------------
ROOT_URLCONF = 'config.urls'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
# AUTHENTICATION CONFIGURATION
# ------------------------------------------------------------------------------
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
# Some really nice defaults
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Custom user app defaults
# Select the correct user model
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
# SLUGLIFIER
AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'
# LOGGING CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
########## CELERY
INSTALLED_APPS += ('djangocali-portal.taskapp.celery.CeleryConfig',)
# if you are not using the django database broker (e.g. rabbitmq, redis, memcached), you can remove the next line.
INSTALLED_APPS += ('kombu.transport.django',)
BROKER_URL = env("CELERY_BROKER_URL", default='django://')
########## END CELERY
# Your common stuff: Below this line define 3rd party library settings
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.