repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
gtarnaras/packer-builder-arm-image | pkg/builder/step_copy_image.go | package builder
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/solo-io/packer-builder-arm-image/pkg/image"
"github.com/solo-io/packer-builder-arm-image/pkg/utils"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
type stepCopyImage struct {
FromKey, ResultKey string
ImageOpener image.ImageOpener
ui packer.Ui
}
func (s *stepCopyImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
fromFile := state.Get(s.FromKey).(string)
config := state.Get("config").(*Config)
s.ui = state.Get("ui").(packer.Ui)
s.ui.Say("Copying source image.")
outputDir := filepath.Dir(config.OutputFile)
imageName := filepath.Base(config.OutputFile)
err := s.copy(ctx, state, fromFile, outputDir, imageName)
if err != nil {
s.ui.Error(fmt.Sprintf("%v", err))
return multistep.ActionHalt
}
state.Put(s.ResultKey, config.OutputFile)
return multistep.ActionContinue
}
func (s *stepCopyImage) Cleanup(state multistep.StateBag) {
}
func (s *stepCopyImage) copy_progress(ctx context.Context, state multistep.StateBag, dst io.Writer, src image.Image) error {
ui := state.Get("ui").(packer.Ui)
ctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
defer close(done)
go func() {
defer cancel()
for {
select {
case <-time.After(time.Second):
if _, ok := state.GetOk(multistep.StateCancelled); ok {
ui.Say("Interrupt received. Cancelling copy...")
break
}
case <-done:
return
}
}
}()
_, err := utils.CopyWithProgress(ctx, ui, dst, src)
return err
}
func (s *stepCopyImage) copy(ctx context.Context, state multistep.StateBag, src, dir, filename string) error {
srcf, err := s.ImageOpener.Open(src)
if err != nil {
return err
}
defer srcf.Close()
err = os.MkdirAll(dir, 0755)
if err != nil {
return err
}
dstf, err := os.Create(filepath.Join(dir, filename))
if err != nil {
return err
}
defer dstf.Close()
err = s.copy_progress(ctx, state, dstf, srcf)
if err != nil {
return err
}
return nil
}
|
mkjanda/IAT-Server | iat-webapp/src/main/java/net/iatsoftware/iat/repositories/ClientExceptionRepository.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.iatsoftware.iat.repositories;
/**
*
* @author michael
*/
import net.iatsoftware.iat.entities.ClientExceptionReport;
public interface ClientExceptionRepository extends GenericRepository<Long, ClientExceptionReport> {
}
|
wt1187982580/javaBook-src | mybatisBook/src/main/java/com/huifer/mybatis/pojo/Dept.java | <filename>mybatisBook/src/main/java/com/huifer/mybatis/pojo/Dept.java
package com.huifer.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* 描述:
*
* @author huifer
* @date 2019-02-21
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
private Long id;
private String dname;
private String loc;
/**
* 职员集合
*/
private List<Employee> empList;
}
|
llabake/Hello-Books | server/routes/userRoute.js | <filename>server/routes/userRoute.js<gh_stars>1-10
import UserController from '../controllers/v1/userController';
import Authentication from '../middlewares/authenticationMiddleware';
const userRoute = (app) => {
/**
* @swagger
* definition:
* User:
* properties:
* username:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* password:
* type: string
* email:
* type: string
* example: {
* username: smith,
* firstName: William,
* lastName: Smith,
* password: <PASSWORD>,
* email: <EMAIL>
* }
* SignInData:
* properties:
* username:
* type: string
* password:
* type: string
* example: {
* username: smith,
* password: <PASSWORD>
* }
* Profile:
* properties:
* id:
* type: integer
* image:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* EditProfileResponse:
* properties:
* userId:
* type: integer
* image:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* role:
* type: string
* EditProfile:
* properties:
* userId:
* type: integer
* image:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* role:
* type: string
* example: {
* firstName: smithed,
* lastName: William
* }
*
* /api/v1/users/signup:
* post:
* tags:
* - User Functionality
* summary: Signs user up
* description: Adds/Creates a new user
* produces:
* - application/json
* consumes:
* - application/json
* parameters:
* - name: user
* description: User Object
* in: body
* required: true
* schema:
* $ref: '#/definitions/User'
* responses:
* 201:
* description: Successfully created
* example: {
* message: Your Signup was successful smith,
* user: {
* id: 8,
* username: smith,
* email: <EMAIL>
* },
* token: <KEY>
* }
* 400:
* description: Incomplete parameters or type
* example: {
* username: username is required
* }
* 409:
* description: User with username or email already exist
* 500:
* description: Internal Server Error
*/
app.post('/api/v1/users/signup', UserController.signUp);
/**
* @swagger
* /api/v1/users/signin:
* post:
* tags:
* - User Functionality
* summary: Logs user in
* description: authenticates a user in the database
* produces:
* - application/json
* consumes:
* - application/json
* parameters:
* - name: user
* description: User Object
* in: body
* required: true
* schema:
* $ref: '#/definitions/SignInData'
* responses:
* 200:
* description: Successfully logged in
* example: {
* message: Welcome smith, you're logged in,
* token: <KEY>
* }
* 401:
* description: Unauthorized- Incomplete parameters or type
* example: {
* success: false,
* message: Authentication failed. Incorrect credentials.
* }
* 500:
* description: Internal Server Error
*/
app.post('/api/v1/users/signin', UserController.signIn);
/**
* @swagger
* /api/v1/users/signout:
* post:
* tags:
* - User Functionality
* summary: Logs user out
* description: Log out user
* produces:
* - application/json
* parameters:
* - name: authorization
* in: header
* type: string
* required: true
* responses:
* 200:
* description: Successfully log out user
* example: {
* message: You have successfully logged out smith
* }
*/
app.post(
'/api/v1/users/signout',
Authentication.authMiddleware, UserController.signOut
);
/**
* @swagger
* /api/v1/users/signup/validate:
* get:
* tags:
* - User Functionality
* summary: Validates username or email existence
* description: Checks if user exists
* produces:
* - application/json
* parameters:
* - name: username
* description: username to validate existence
* in: query
* type: string
* - name: email
* description: email to validate existence
* in: query
* type: email
* responses:
* 200:
* description: Successfully found no user with parameter
* example: {
* message: Username is valid | Email is valid
* }
* 400:
* description: User parameter already exists
* example: {
* message: Username already taken | Email already taken | Email or Username expected in query,
* }
* 500:
* description: Internal Server Error
*/
app.get(
'/api/v1/users/signup/validate', UserController.checkUserExist
)
/**
* @swagger
* /api/v1/users/profile:
* put:
* tags:
* - User Functionality
* summary: Modify Profile
* description: Edits user's profile
* produces:
* - application/json
* parameters:
* - name: authorization
* description: an authentication header
* type: string
* in: header
* required: true
* - name: user
* description:
* in: body
* required: true
* schema:
* $ref: '#/definitions/EditProfile'
* responses:
* 200:
* description: Successfully modified user profile
* schema:
* type: object
* properties:
* profile:
* $ref: '#/definitions/EditProfileResponse'
* message: Profile modified successfully
* 500:
* description: Internal Server Error
* 400:
* description: Invalid credentials
* example: {
* firstName: firstName is required
* }
*/
app.put(
'/api/v1/users/profile', Authentication.authMiddleware, UserController.editUserProfile
)
/**
* @swagger
* /api/v1/users/profile:
* get:
* tags:
* - User Functionality
* summary: User Profile
* description: Gets user profile
* produces:
* - application/json
* parameters:
* - name: authorization
* description: an authentication header
* type: string
* in: header
* required: true
* responses:
* 200:
* description: Successfully retrieved user profile
* schema:
* type: object
* properties:
* profile:
* $ref: '#/definitions/Profile'
* message: Profile retrieved successfully
* 400:
* description: Internal Server Error
*/
app.get(
'/api/v1/users/profile', Authentication.authMiddleware, UserController.getUserProfile)
};
export default userRoute;
|
neonkingfr/ccv | lib/nnc/cmd/convolution/cpu_opt/_ccv_nnc_conv_cpu_gemm.c | <filename>lib/nnc/cmd/convolution/cpu_opt/_ccv_nnc_conv_cpu_gemm.c
#include "ccv.h"
#include "ccv_internal.h"
#include "nnc/ccv_nnc.h"
#include "nnc/ccv_nnc_easy.h"
#include "nnc/ccv_nnc_internal.h"
#include "../_ccv_nnc_conv_cpu_opt.h"
int _ccv_nnc_conv_forw_gemm_cpu_opt(const ccv_nnc_tensor_view_t* const a, const ccv_nnc_tensor_t* const w, const ccv_nnc_tensor_t* const bias, const ccv_nnc_hint_t hint, ccv_nnc_tensor_view_t* const b)
{
assert(!CCV_IS_TENSOR_VIEW(a));
assert(!CCV_IS_TENSOR_VIEW(w));
assert(!bias || !CCV_IS_TENSOR_VIEW(bias));
assert(!CCV_IS_TENSOR_VIEW(b));
const int a_nd = ccv_nnc_tensor_nd(a->info.dim);
assert(a_nd == CCV_NNC_MAX_DIM + 1 || a_nd == CCV_NNC_MAX_DIM + 2);
const int* adim = (a_nd == CCV_NNC_MAX_DIM + 1) ? a->info.dim : a->info.dim + 1;
const int b_nd = ccv_nnc_tensor_nd(b->info.dim);
assert(b_nd == CCV_NNC_MAX_DIM + 1 || b_nd == CCV_NNC_MAX_DIM + 2);
const int* bdim = (b_nd == CCV_NNC_MAX_DIM + 1) ? b->info.dim : b->info.dim + 1;
assert(hint.border.begin[0] == 0 && hint.border.begin[1] == 0);
assert(hint.border.end[0] == 0 && hint.border.end[1] == 0);
assert(adim[0] == bdim[0]);
assert(adim[1] == bdim[1]);
assert(hint.stride.dim[0] <= 1 && hint.stride.dim[1] <= 1);
ccv_dense_matrix_t am = ccv_dense_matrix(adim[0] * adim[1], adim[2], CCV_32F | CCV_C1, a->data.u8, 0);
ccv_dense_matrix_t bm = ccv_dense_matrix(bdim[0] * bdim[1], bdim[2], CCV_32F | CCV_C1, b->data.u8, 0);
// copy bias into each row.
int i;
if (bias)
for (i = 0; i < bm.rows; i++)
memcpy(bm.data.f32 + i * bdim[2], bias->data.f32, sizeof(float) * bdim[2]);
ccv_dense_matrix_t* dbm = &bm;
ccv_dense_matrix_t wm = ccv_dense_matrix(bdim[2], adim[2], CCV_32F | CCV_C1, w->data.u8, 0);
if (bias)
ccv_gemm(&am, &wm, 1, dbm, 1, CCV_B_TRANSPOSE, (ccv_matrix_t**)&dbm, 0); // supply b as matrix C is allowed
else
ccv_gemm(&am, &wm, 1, 0, 0, CCV_B_TRANSPOSE, (ccv_matrix_t**)&dbm, 0); // supply b as matrix C is allowed
return CCV_NNC_EXEC_SUCCESS;
}
|
ford442/openmpt | common/FileReader.h | /*
* FileReader.h
* ------------
* Purpose: A basic class for transparent reading of memory-based files.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#pragma once
#include "openmpt/all/BuildSettings.hpp"
#include "mpt/io_read/filecursor.hpp"
#include "mpt/io_read/filecursor_filename_traits.hpp"
#include "mpt/io_read/filecursor_traits_filedata.hpp"
#include "mpt/io_read/filecursor_traits_memory.hpp"
#include "mpt/io_read/filereader.hpp"
#include "openmpt/base/Types.hpp"
#include "mptPathString.h"
#include "mptStringBuffer.h"
#include <algorithm>
#include <array>
#include <limits>
#include <optional>
#include <string>
#include <vector>
#include <cstring>
#include "FileReaderFwd.h"
OPENMPT_NAMESPACE_BEGIN
namespace FileReaderExt
{
// Read a string of length srcSize into fixed-length char array destBuffer using a given read mode.
// The file cursor is advanced by "srcSize" bytes.
// Returns true if at least one byte could be read or 0 bytes were requested.
template<mpt::String::ReadWriteMode mode, size_t destSize, typename TFileCursor>
bool ReadString(TFileCursor &f, char (&destBuffer)[destSize], const typename TFileCursor::pos_type srcSize)
{
typename TFileCursor::PinnedView source = f.ReadPinnedView(srcSize); // Make sure the string is cached properly.
typename TFileCursor::pos_type realSrcSize = source.size(); // In case fewer bytes are available
mpt::String::WriteAutoBuf(destBuffer) = mpt::String::ReadBuf(mode, mpt::byte_cast<const char*>(source.data()), realSrcSize);
return (realSrcSize > 0 || srcSize == 0);
}
// Read a string of length srcSize into a std::string dest using a given read mode.
// The file cursor is advanced by "srcSize" bytes.
// Returns true if at least one character could be read or 0 characters were requested.
template<mpt::String::ReadWriteMode mode, typename TFileCursor>
bool ReadString(TFileCursor &f, std::string &dest, const typename TFileCursor::pos_type srcSize)
{
dest.clear();
typename TFileCursor::PinnedView source = f.ReadPinnedView(srcSize); // Make sure the string is cached properly.
typename TFileCursor::pos_type realSrcSize = source.size(); // In case fewer bytes are available
dest = mpt::String::ReadBuf(mode, mpt::byte_cast<const char*>(source.data()), realSrcSize);
return (realSrcSize > 0 || srcSize == 0);
}
// Read a string of length srcSize into a mpt::charbuf dest using a given read mode.
// The file cursor is advanced by "srcSize" bytes.
// Returns true if at least one character could be read or 0 characters were requested.
template<mpt::String::ReadWriteMode mode, std::size_t len, typename TFileCursor>
bool ReadString(TFileCursor &f, mpt::charbuf<len> &dest, const typename TFileCursor::pos_type srcSize)
{
typename TFileCursor::PinnedView source = f.ReadPinnedView(srcSize); // Make sure the string is cached properly.
typename TFileCursor::pos_type realSrcSize = source.size(); // In case fewer bytes are available
dest = mpt::String::ReadBuf(mode, mpt::byte_cast<const char*>(source.data()), realSrcSize);
return (realSrcSize > 0 || srcSize == 0);
}
// Read a charset encoded string of length srcSize into a mpt::ustring dest using a given read mode.
// The file cursor is advanced by "srcSize" bytes.
// Returns true if at least one character could be read or 0 characters were requested.
template<mpt::String::ReadWriteMode mode, typename TFileCursor>
bool ReadString(TFileCursor &f, mpt::ustring &dest, mpt::Charset charset, const typename TFileCursor::pos_type srcSize)
{
dest.clear();
typename TFileCursor::PinnedView source = f.ReadPinnedView(srcSize); // Make sure the string is cached properly.
typename TFileCursor::pos_type realSrcSize = source.size(); // In case fewer bytes are available
dest = mpt::ToUnicode(charset, mpt::String::ReadBuf(mode, mpt::byte_cast<const char*>(source.data()), realSrcSize));
return (realSrcSize > 0 || srcSize == 0);
}
// Read a string with a preprended length field of type Tsize (must be a packed<*,*> type) into a std::string dest using a given read mode.
// The file cursor is advanced by the string length.
// Returns true if the size field could be read and at least one character could be read or 0 characters were requested.
template<typename Tsize, mpt::String::ReadWriteMode mode, size_t destSize, typename TFileCursor>
bool ReadSizedString(TFileCursor &f, char (&destBuffer)[destSize], const typename TFileCursor::pos_type maxLength = std::numeric_limits<typename TFileCursor::pos_type>::max())
{
mpt::packed<typename Tsize::base_type, typename Tsize::endian_type> srcSize; // Enforce usage of a packed type by ensuring that the passed type has the required typedefs
if(!mpt::IO::FileReader::Read(f, srcSize))
{
return false;
}
return FileReaderExt::ReadString<mode>(f, destBuffer, std::min(static_cast<typename TFileCursor::pos_type>(srcSize), maxLength));
}
// Read a string with a preprended length field of type Tsize (must be a packed<*,*> type) into a std::string dest using a given read mode.
// The file cursor is advanced by the string length.
// Returns true if the size field could be read and at least one character could be read or 0 characters were requested.
template<typename Tsize, mpt::String::ReadWriteMode mode, typename TFileCursor>
bool ReadSizedString(TFileCursor &f, std::string &dest, const typename TFileCursor::pos_type maxLength = std::numeric_limits<typename TFileCursor::pos_type>::max())
{
mpt::packed<typename Tsize::base_type, typename Tsize::endian_type> srcSize; // Enforce usage of a packed type by ensuring that the passed type has the required typedefs
if(!mpt::IO::FileReader::Read(f, srcSize))
{
return false;
}
return FileReaderExt::ReadString<mode>(f, dest, std::min(static_cast<typename TFileCursor::pos_type>(srcSize), maxLength));
}
// Read a string with a preprended length field of type Tsize (must be a packed<*,*> type) into a mpt::charbuf dest using a given read mode.
// The file cursor is advanced by the string length.
// Returns true if the size field could be read and at least one character could be read or 0 characters were requested.
template<typename Tsize, mpt::String::ReadWriteMode mode, std::size_t len, typename TFileCursor>
bool ReadSizedString(TFileCursor &f, mpt::charbuf<len> &dest, const typename TFileCursor::pos_type maxLength = std::numeric_limits<typename TFileCursor::pos_type>::max())
{
mpt::packed<typename Tsize::base_type, typename Tsize::endian_type> srcSize; // Enforce usage of a packed type by ensuring that the passed type has the required typedefs
if(!mpt::IO::FileReader::Read(f, srcSize))
{
return false;
}
return FileReaderExt::ReadString<mode>(f, dest, std::min(static_cast<typename TFileCursor::pos_type>(srcSize), maxLength));
}
} // namespace FileReaderExt
namespace detail {
template <typename Ttraits, typename Tfilenametraits>
using FileCursor = mpt::IO::FileCursor<Ttraits, Tfilenametraits>;
template <typename Ttraits, typename Tfilenametraits>
class FileReader
: public FileCursor<Ttraits, Tfilenametraits>
{
private:
using traits_type = Ttraits;
using filename_traits_type = Tfilenametraits;
public:
using pos_type = typename traits_type::pos_type;
using off_t = pos_type;
using data_type = typename traits_type::data_type;
using ref_data_type = typename traits_type::ref_data_type;
using shared_data_type = typename traits_type::shared_data_type;
using value_data_type = typename traits_type::value_data_type;
using shared_filename_type = typename filename_traits_type::shared_filename_type;
public:
// Initialize invalid file reader object.
FileReader()
{
return;
}
FileReader(const FileCursor<Ttraits, Tfilenametraits> &other)
: FileCursor<Ttraits, Tfilenametraits>(other)
{
return;
}
FileReader(FileCursor<Ttraits, Tfilenametraits> &&other)
: FileCursor<Ttraits, Tfilenametraits>(std::move(other))
{
return;
}
// Initialize file reader object with pointer to data and data length.
template <typename Tbyte>
explicit FileReader(mpt::span<Tbyte> bytedata, shared_filename_type filename = shared_filename_type{})
: FileCursor<Ttraits, Tfilenametraits>(bytedata, std::move(filename))
{
return;
}
// Initialize file reader object based on an existing file reader object window.
explicit FileReader(value_data_type other, shared_filename_type filename = shared_filename_type{})
: FileCursor<Ttraits, Tfilenametraits>(std::move(other), std::move(filename))
{
return;
}
public:
template <typename T>
bool Read(T &target)
{
return mpt::IO::FileReader::Read(*this, target);
}
template <typename T>
T ReadIntLE()
{
return mpt::IO::FileReader::ReadIntLE<T>(*this);
}
template <typename T>
T ReadIntBE()
{
return mpt::IO::FileReader::ReadIntLE<T>(*this);
}
template <typename T>
T ReadTruncatedIntLE(pos_type size)
{
return mpt::IO::FileReader::ReadTruncatedIntLE<T>(*this, size);
}
template <typename T>
T ReadSizedIntLE(pos_type size)
{
return mpt::IO::FileReader::ReadSizedIntLE<T>(*this, size);
}
uint32 ReadUint32LE()
{
return mpt::IO::FileReader::ReadUint32LE(*this);
}
uint32 ReadUint32BE()
{
return mpt::IO::FileReader::ReadUint32BE(*this);
}
int32 ReadInt32LE()
{
return mpt::IO::FileReader::ReadInt32LE(*this);
}
int32 ReadInt32BE()
{
return mpt::IO::FileReader::ReadInt32BE(*this);
}
uint32 ReadUint24LE()
{
return mpt::IO::FileReader::ReadUint24LE(*this);
}
uint32 ReadUint24BE()
{
return mpt::IO::FileReader::ReadUint24BE(*this);
}
uint16 ReadUint16LE()
{
return mpt::IO::FileReader::ReadUint16LE(*this);
}
uint16 ReadUint16BE()
{
return mpt::IO::FileReader::ReadUint16BE(*this);
}
int16 ReadInt16LE()
{
return mpt::IO::FileReader::ReadInt16LE(*this);
}
int16 ReadInt16BE()
{
return mpt::IO::FileReader::ReadInt16BE(*this);
}
char ReadChar()
{
return mpt::IO::FileReader::ReadChar(*this);
}
uint8 ReadUint8()
{
return mpt::IO::FileReader::ReadUint8(*this);
}
int8 ReadInt8()
{
return mpt::IO::FileReader::ReadInt8(*this);
}
float ReadFloatLE()
{
return mpt::IO::FileReader::ReadFloatLE(*this);
}
float ReadFloatBE()
{
return mpt::IO::FileReader::ReadFloatBE(*this);
}
double ReadDoubleLE()
{
return mpt::IO::FileReader::ReadDoubleLE(*this);
}
double ReadDoubleBE()
{
return mpt::IO::FileReader::ReadDoubleBE(*this);
}
template <typename T>
bool ReadStruct(T &target)
{
return mpt::IO::FileReader::ReadStruct(*this, target);
}
template <typename T>
size_t ReadStructPartial(T &target, size_t partialSize = sizeof(T))
{
return mpt::IO::FileReader::ReadStructPartial(*this, target, partialSize);
}
bool ReadNullString(std::string &dest, const pos_type maxLength = std::numeric_limits<pos_type>::max())
{
return mpt::IO::FileReader::ReadNullString(*this, dest, maxLength);
}
bool ReadLine(std::string &dest, const pos_type maxLength = std::numeric_limits<pos_type>::max())
{
return mpt::IO::FileReader::ReadLine(*this, dest, maxLength);
}
template<typename T, std::size_t destSize>
bool ReadArray(T (&destArray)[destSize])
{
return mpt::IO::FileReader::ReadArray(*this, destArray);
}
template<typename T, std::size_t destSize>
bool ReadArray(std::array<T, destSize> &destArray)
{
return mpt::IO::FileReader::ReadArray(*this, destArray);
}
template <typename T, std::size_t destSize>
std::array<T, destSize> ReadArray()
{
return mpt::IO::FileReader::ReadArray<T, destSize>(*this);
}
template<typename T>
bool ReadVector(std::vector<T> &destVector, size_t destSize)
{
return mpt::IO::FileReader::ReadVector(*this, destVector, destSize);
}
template<size_t N>
bool ReadMagic(const char (&magic)[N])
{
return mpt::IO::FileReader::ReadMagic(*this, magic);
}
template<typename T>
bool ReadVarInt(T &target)
{
return mpt::IO::FileReader::ReadVarInt(*this, target);
}
template <typename T>
using Item = mpt::IO::FileReader::Chunk<T, FileReader>;
template <typename T>
using ChunkList = mpt::IO::FileReader::ChunkList<T, FileReader>;
template<typename T>
Item<T> ReadNextChunk(off_t alignment)
{
return mpt::IO::FileReader::ReadNextChunk<T, FileReader>(*this, alignment);
}
template<typename T>
ChunkList<T> ReadChunks(off_t alignment)
{
return mpt::IO::FileReader::ReadChunks<T, FileReader>(*this, alignment);
}
template<typename T>
ChunkList<T> ReadChunksUntil(off_t alignment, decltype(T().GetID()) stopAtID)
{
return mpt::IO::FileReader::ReadChunksUntil<T, FileReader>(*this, alignment, stopAtID);
}
template<mpt::String::ReadWriteMode mode, size_t destSize>
bool ReadString(char (&destBuffer)[destSize], const pos_type srcSize)
{
return FileReaderExt::ReadString<mode>(*this, destBuffer, srcSize);
}
template<mpt::String::ReadWriteMode mode>
bool ReadString(std::string &dest, const pos_type srcSize)
{
return FileReaderExt::ReadString<mode>(*this, dest, srcSize);
}
template<mpt::String::ReadWriteMode mode, std::size_t len>
bool ReadString(mpt::charbuf<len> &dest, const pos_type srcSize)
{
return FileReaderExt::ReadString<mode>(*this, dest, srcSize);
}
template<mpt::String::ReadWriteMode mode>
bool ReadString(mpt::ustring &dest, mpt::Charset charset, const pos_type srcSize)
{
return FileReaderExt::ReadString<mode>(*this, dest, charset, srcSize);
}
template<typename Tsize, mpt::String::ReadWriteMode mode, size_t destSize>
bool ReadSizedString(char (&destBuffer)[destSize], const pos_type maxLength = std::numeric_limits<pos_type>::max())
{
return FileReaderExt::ReadSizedString<Tsize, mode>(*this, destBuffer, maxLength);
}
template<typename Tsize, mpt::String::ReadWriteMode mode>
bool ReadSizedString(std::string &dest, const pos_type maxLength = std::numeric_limits<pos_type>::max())
{
return FileReaderExt::ReadSizedString<Tsize, mode>(*this, dest, maxLength);
}
template<typename Tsize, mpt::String::ReadWriteMode mode, std::size_t len>
bool ReadSizedString(mpt::charbuf<len> &dest, const pos_type maxLength = std::numeric_limits<pos_type>::max())
{
return FileReaderExt::ReadSizedString<Tsize, mode, len>(*this, dest, maxLength);
}
};
} // namespace detail
using FileCursor = detail::FileCursor<mpt::IO::FileCursorTraitsFileData, mpt::IO::FileCursorFilenameTraits<mpt::PathString>>;
using FileReader = detail::FileReader<mpt::IO::FileCursorTraitsFileData, mpt::IO::FileCursorFilenameTraits<mpt::PathString>>;
using ChunkReader = FileReader;
using MemoryFileCursor = detail::FileCursor<mpt::IO::FileCursorTraitsMemory, mpt::IO::FileCursorFilenameTraitsNone>;
using MemoryFileReader = detail::FileReader<mpt::IO::FileCursorTraitsMemory, mpt::IO::FileCursorFilenameTraitsNone>;
OPENMPT_NAMESPACE_END
|
diegohfacchinetti/ExemploReactRedux | frontend/node_modules/redux-multi/test/index.js | <gh_stars>0
/**
* Imports
*/
import test from 'tape'
import multi from '../src'
/**
* Tests
*/
test('should work', ({plan, pass, end}) => {
plan(2)
multi({dispatch: () => pass('pass')})(() => {})([1, 2])
})
|
14ms/Minecraft-Disclosed-Source-Modifications | Scov 030121/Scov/value/util/BooleanParser.java | <gh_stars>1-10
package Scov.value.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public final class BooleanParser {
private static final Map<String, Boolean> PARSE;
static {
PARSE = new HashMap<String, Boolean>() {
{
this.put("enable", true);
this.put("true", true);
this.put("on", true);
this.put("1", true);
this.put("disable", false);
this.put("false", false);
this.put("off", false);
this.put("0", false);
}
};
}
public static Optional<Boolean> parse(final String input) {
return Optional.ofNullable(BooleanParser.PARSE.get(input.toLowerCase()));
}
} |
leonardoamurca/tompero | src/pages/Recipe.js | <filename>src/pages/Recipe.js
import React, { useState, useEffect } from "react";
import { request } from "../utils/request";
import styles from "./Recipe.module.css";
import { recipes } from "../mocks/recipes";
import Loading from "../components/Loading";
function Recipe(props) {
const [loading, setLoading] = useState(false);
const [recipe, setRecipe] = useState(null);
useEffect(() => {
async function fetchRecipe() {
setLoading(true);
const res = await request(`recipes/${props.match.params.id}`);
if (res) {
const user = await request(`users/${res.user_id}`);
setRecipe({
author: { id: user.id, name: user.name },
image:
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fres.cloudinary.com%2Fmundo%2Fimage%2Fupload%2Fc_crop%2Cf_auto%2Cg_north_west%2Ch_3228%2Cq_auto%2Cw_6123%2Cx_0%2Cy_426%2Fv1564406376%2Flasagna_gf1zpi.jpg&f=1&nofb=1",
...res,
});
}
setLoading(false);
}
fetchRecipe();
}, []);
{
return (
recipe && (
<div className={styles.Container}>
<img width="600px" src={recipe.image} alt={recipe.name} />
<div className={styles.ContentContainer}>
<div className={styles.Header}>
<h1>{recipe.name}</h1>
<p className={styles.Author}>
por <a href={`#${recipe.author.id}`}>{recipe.author.name}</a>
</p>
</div>
<div className={styles.Ingredients}>
<h2>Ingredientes</h2>
<ul>
{recipe.ingredients.split(";").map((ingredient) => (
<li>{ingredient}</li>
))}
</ul>
</div>
<div className={styles.Directions}>
<h2>Modo de Preparo</h2>
<ol>
{recipe.directions.split(";").map((direction) => (
<li>{direction}</li>
))}
</ol>
</div>
</div>
{loading && <Loading />}
{recipe && recipe.length === 0 && (
<h1>Não há receitas cadastradas</h1>
)}
</div>
)
);
}
}
export default Recipe;
|
guhilling/cdi-tes | cdi-test-core/src/test/java/de/hilling/junit/cdi/scope/context/AbstractScopeContextTest.java | <filename>cdi-test-core/src/test/java/de/hilling/junit/cdi/scope/context/AbstractScopeContextTest.java
package de.hilling.junit.cdi.scope.context;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import de.hilling.junit.cdi.CdiTestJunitExtension;
import de.hilling.junit.cdi.ContextControlWrapper;
import de.hilling.junit.cdi.scopedbeans.RequestScopedBean;
import de.hilling.junit.cdi.scopedbeans.ScopedBean;
import de.hilling.junit.cdi.scopedbeans.TestScopedBean;
import de.hilling.junit.cdi.scopedbeans.TestSuiteScopedBean;
@ExtendWith(CdiTestJunitExtension.class)
class AbstractScopeContextTest {
private static Map<Type, UUID> uuidMap;
@BeforeAll
private static void reset() {
uuidMap = new HashMap<>();
}
@Test
void resolveInvocationTargetManagerA() {
assertAllTypes();
}
@Test
void resolveInvocationTargetManagerB() {
assertAllTypes();
}
void assertAllTypes() {
resolveOrAssert(TestSuiteScopedBean.class, Assertions::assertEquals);
resolveOrAssert(TestScopedBean.class, Assertions::assertNotEquals);
resolveOrAssert(RequestScopedBean.class, Assertions::assertNotEquals);
}
private <T extends ScopedBean> void resolveOrAssert(Class<T> type, BiConsumer<UUID, UUID> assertion) {
ContextControlWrapper controlWrapper = ContextControlWrapper.getInstance();
final T resolvedObject = controlWrapper.getContextualReference(type);
if (!uuidMap.containsKey(type)) {
uuidMap.put(type, resolvedObject.getUuid());
} else {
assertion.accept(uuidMap.get(type), resolvedObject.getUuid());
}
}
} |
larsw/rya | test/rdf/src/main/java/org/apache/rya/streams/kafka/RdfTestUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.rya.streams.kafka;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.MultiProjection;
import org.eclipse.rdf4j.query.algebra.Projection;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.ParsedQuery;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
/**
* A set of utility functions that are useful when writing tests RDF functions.
*/
@DefaultAnnotation(NonNull.class)
public final class RdfTestUtil {
private RdfTestUtil() { }
/**
* Fetch the {@link StatementPattern} from a SPARQL string.
*
* @param sparql - A SPARQL query that contains only a single Statement Pattern. (not null)
* @return The {@link StatementPattern} that was in the query, if it could be found. Otherwise {@code null}
* @throws Exception The statement pattern could not be found in the parsed SPARQL query.
*/
public static @Nullable StatementPattern getSp(final String sparql) throws Exception {
requireNonNull(sparql);
final AtomicReference<StatementPattern> statementPattern = new AtomicReference<>();
final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
parsed.getTupleExpr().visitChildren(new AbstractQueryModelVisitor<Exception>() {
@Override
public void meet(final StatementPattern node) throws Exception {
statementPattern.set(node);
}
});
return statementPattern.get();
}
/**
* Get the first {@link Projection} node from a SPARQL query.
*
* @param sparql - The query that contains a single Projection node.
* @return The first {@link Projection} that is encountered.
* @throws Exception The query could not be parsed.
*/
public static @Nullable Projection getProjection(final String sparql) throws Exception {
requireNonNull(sparql);
final AtomicReference<Projection> projection = new AtomicReference<>();
final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
@Override
public void meet(final Projection node) throws Exception {
projection.set(node);
}
});
return projection.get();
}
/**
* Get the first {@link MultiProjection} node from a SPARQL query.
*
* @param sparql - The query that contains a single Projection node.
* @return The first {@link MultiProjection} that is encountered.
* @throws Exception The query could not be parsed.
*/
public static @Nullable MultiProjection getMultiProjection(final String sparql) throws Exception {
requireNonNull(sparql);
final AtomicReference<MultiProjection> multiProjection = new AtomicReference<>();
final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
@Override
public void meet(final MultiProjection node) throws Exception {
multiProjection.set(node);
}
});
return multiProjection.get();
}
/**
* Get the first {@link Filter} node from a SPARQL query.
*
* @param sparql - The query that contains a single Projection node.
* @return The first {@link Filter} that is encountered.
* @throws Exception The query could not be parsed.
*/
public static @Nullable Filter getFilter(final String sparql) throws Exception {
requireNonNull(sparql);
final AtomicReference<Filter> filter = new AtomicReference<>();
final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
@Override
public void meet(final Filter node) throws Exception {
filter.set(node);
}
});
return filter.get();
}
} |
nulllaborg/51duino | cores/STC8/wiring.h | <gh_stars>1-10
/*
wiring.h
Modified 2 February 2018 for mcs51 by huaweiwx
*/
#ifndef _WIRING_H_
#define _WIRING_H_
#ifndef USE_SYSTICK
#define USE_SYSTICK 1
#endif
#if CORE_STCYn > 1
#define T1MS (65536L-F_CPU/1000) //1ms timer calculation method in 1T mode
#elif CORE_STCYn == 1
#define T1MS (65536L-F_CPU/12/1000) //1ms timer calculation method in 12T mode
#else
#error NOT STC core or CORE_STCYn undef!
#endif
#define TH0_INIT (T1MS >> 8)
#define TL0_INIT (T1MS & 0xff)
void delay_loop(unsigned char cnt);
#if USE_SYSTICK
unsigned long millis();
unsigned long micros();
void delay(unsigned int ms);
void delayMicroseconds(unsigned int us);
#else
void delay10us(unsigned int us);
void delay(unsigned int ms);
#define delayMicroseconds(us) if(us>10){delay10us(us/10);}else{delay_loop(us);}
#endif //USE_SYSTICK
#endif //_WIRING_H_
|
LazaroRaul/rextporter | src/client/client_catcher.go | package client
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/simelo/rextporter/src/cache"
)
// CatcherCreator have info to create catcher client
type CatcherCreator struct {
Cache cache.Cache
ClientFactory CacheableFactory
}
// CreateClient create a catcher client
func (cc CatcherCreator) CreateClient() (cl Client, err error) {
var ccl CacheableClient
if ccl, err = cc.ClientFactory.CreateClient(); err != nil {
return ccl, err
}
return Catcher{cache: cc.Cache, dataKey: ccl.DataPath(), clientFactory: cc.ClientFactory}, nil
}
// Catcher have a client and a cache to save time loading data
type Catcher struct {
cache cache.Cache
dataKey string
clientFactory CacheableFactory
}
// GetData return the data, can be from local cache or making the original request
func (cl Catcher) GetData(metricsCollector chan<- prometheus.Metric) (body []byte, err error) {
if body, err = cl.cache.Get(cl.dataKey); err == nil {
return body, err
}
cl.cache.Lock()
defer cl.cache.Unlock()
if body, err = cl.cache.Get(cl.dataKey); err == nil {
return body, err
}
var ccl CacheableClient
if ccl, err = cl.clientFactory.CreateClient(); err != nil {
return nil, err
}
if body, err = ccl.GetData(metricsCollector); err == nil {
cl.cache.Set(cl.dataKey, body)
}
return body, err
}
|
borosboyo/timechamp | src/main/java/hu/bme/aut/timechamp/repository/TodoRepository.java | <gh_stars>1-10
package hu.bme.aut.timechamp.repository;
import hu.bme.aut.timechamp.model.Todo;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
public interface TodoRepository extends JpaRepository<Todo, Long> {
List<Todo> findByName(String name);
@EntityGraph(attributePaths = "app_user.todos")
@Query("SELECT t FROM Todo t")
List<Todo> findAllWithAppUserTodos();
@EntityGraph(attributePaths = "event.todos")
@Query("SELECT t FROM Todo t")
List<Todo> findAllWithEventTodos();
Todo findById(long id);
@Modifying
@Transactional
int removeById(long id);
}
|
mateusdeap/natalie | spec/core/array/pack/g_spec.rb | <gh_stars>100-1000
# skip-test
require_relative '../../../spec_helper'
require_relative '../fixtures/classes'
require_relative 'shared/basic'
require_relative 'shared/numeric_basic'
require_relative 'shared/float'
describe "Array#pack with format 'G'" do
it_behaves_like :array_pack_basic, 'G'
it_behaves_like :array_pack_basic_float, 'G'
it_behaves_like :array_pack_arguments, 'G'
it_behaves_like :array_pack_no_platform, 'G'
it_behaves_like :array_pack_numeric_basic, 'G'
it_behaves_like :array_pack_float, 'G'
it_behaves_like :array_pack_double_be, 'G'
end
describe "Array#pack with format 'g'" do
it_behaves_like :array_pack_basic, 'g'
it_behaves_like :array_pack_basic_float, 'g'
it_behaves_like :array_pack_arguments, 'g'
it_behaves_like :array_pack_no_platform, 'g'
it_behaves_like :array_pack_numeric_basic, 'g'
it_behaves_like :array_pack_float, 'g'
it_behaves_like :array_pack_float_be, 'g'
end
|
denney/carbon-devicemgt-master | components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.certificate.mgt.core.impl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.cms.CMSAbsentContent;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.Store;
import org.jscep.message.*;
import org.jscep.transaction.FailInfo;
import org.jscep.transaction.Nonce;
import org.jscep.transaction.TransactionId;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
import org.wso2.carbon.certificate.mgt.core.dto.CAStatus;
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException;
import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants;
import org.wso2.carbon.certificate.mgt.core.util.CommonUtil;
import org.wso2.carbon.certificate.mgt.core.util.Serializer;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.security.auth.x500.X500Principal;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public class CertificateGenerator {
private static final Log log = LogFactory.getLog(CertificateGenerator.class);
public static String getCommonName(X509Certificate requestCertificate) {
String distinguishedName = requestCertificate.getSubjectDN().getName();
if (distinguishedName != null && !distinguishedName.isEmpty()) {
String[] dnSplits = distinguishedName.split(",");
for (String dnSplit : dnSplits) {
if (dnSplit.contains("CN=")) {
String[] cnSplits = dnSplit.split("=");
if (cnSplits[1] != null) {
return cnSplits[1];
}
}
}
}
return null;
}
public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse)
throws CertificateManagementDAOException {
try {
if (certificateBytes != null) {
java.security.cert.Certificate x509Certificate =
(java.security.cert.Certificate) Serializer.deserialize(certificateBytes);
if (x509Certificate instanceof X509Certificate) {
X509Certificate certificate = (X509Certificate) x509Certificate;
certificateResponse.setNotAfter(certificate.getNotAfter().getTime());
certificateResponse.setNotBefore(certificate.getNotBefore().getTime());
certificateResponse.setCertificateserial(certificate.getSerialNumber());
certificateResponse.setIssuer(certificate.getIssuerDN().getName());
certificateResponse.setSubject(certificate.getSubjectDN().getName());
certificateResponse.setCertificateVersion(certificate.getVersion());
}
}
} catch (ClassNotFoundException | IOException e) {
String errorMsg = "Error while deserializing the certificate.";
throw new CertificateManagementDAOException(errorMsg, e);
}
}
public List<X509Certificate> getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException {
if (ca == null) {
throw new KeystoreException("CA certificate is mandatory");
}
if (ra == null) {
throw new KeystoreException("RA certificate is mandatory");
}
List<X509Certificate> certificateList = new ArrayList<X509Certificate>();
InputStream caInputStream = null;
InputStream raInputStream = null;
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
caInputStream = new ByteArrayInputStream(ca);
raInputStream = new ByteArrayInputStream(ra);
X509Certificate caCert = (X509Certificate) certificateFactory.generateCertificate(caInputStream);
X509Certificate raCert = (X509Certificate) certificateFactory.generateCertificate(raInputStream);
certificateList.add(caCert);
certificateList.add(raCert);
} catch (CertificateException e) {
String errorMsg = "Error occurred while fetching root certificates";
throw new KeystoreException(errorMsg, e);
} finally {
if (caInputStream != null) {
try {
caInputStream.close();
} catch (IOException e) {
log.error("Error occurred when closing CA input stream");
}
}
if (raInputStream != null) {
try {
raInputStream.close();
} catch (IOException e) {
log.error("Error occurred when closing RA input stream");
}
}
}
return certificateList;
}
public X509Certificate generateX509Certificate() throws KeystoreException {
CommonUtil commonUtil = new CommonUtil();
Date validityBeginDate = commonUtil.getValidityStartDate();
Date validityEndDate = commonUtil.getValidityEndDate();
Security.addProvider(new BouncyCastleProvider());
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
CertificateManagementConstants.RSA, CertificateManagementConstants.PROVIDER);
keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom());
KeyPair pair = keyPairGenerator.generateKeyPair();
X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL);
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
principal, CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate,
principal, pair.getPublic());
ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
.setProvider(CertificateManagementConstants.PROVIDER).build(
pair.getPrivate());
X509Certificate certificate = new JcaX509CertificateConverter()
.setProvider(CertificateManagementConstants.PROVIDER).getCertificate(
certificateBuilder.build(contentSigner));
// cert.checkValidity();
certificate.verify(certificate.getPublicKey());
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore =
new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificateToStore.setCertificate(certificate);
certificates.add(certificateToStore);
saveCertInKeyStore(certificates);
return certificate;
} catch (NoSuchAlgorithmException e) {
String errorMsg = "No such algorithm found when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (NoSuchProviderException e) {
String errorMsg = "No such provider found when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (OperatorCreationException e) {
String errorMsg = "Issue in operator creation when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (CertificateExpiredException e) {
String errorMsg = "Certificate expired after generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (CertificateNotYetValidException e) {
String errorMsg = "Certificate not yet valid when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) {
String errorMsg = "Certificate issue occurred when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (InvalidKeyException e) {
String errorMsg = "Invalid key used when generating certificate";
throw new KeystoreException(errorMsg, e);
} catch (SignatureException e) {
String errorMsg = "Signature related issue occurred when generating certificate";
throw new KeystoreException(errorMsg, e);
}
}
public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException {
try {
CMSSignedData signedData = new CMSSignedData(inputStream);
Store reqStore = signedData.getCertificates();
@SuppressWarnings("unchecked")
Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);
KeyStoreReader keyStoreReader = new KeyStoreReader();
PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey();
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate();
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
X509CertificateHolder holder = reqCerts.iterator().next();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
X509Certificate reqCert = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);
PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA);
PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder);
PkiMessage<?> pkiMessage = messageDecoder.decode(signedData);
Object msgData = pkiMessage.getMessageData();
Nonce senderNonce = Nonce.nextNonce();
TransactionId transId = pkiMessage.getTransactionId();
Nonce recipientNonce = pkiMessage.getSenderNonce();
CertRep certRep;
PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData;
X509Certificate generatedCert = generateCertificateFromCSR(
privateKeyCA, certRequest, certCA.getIssuerX500Principal().getName());
List<X509Certificate> issued = new ArrayList<X509Certificate>();
issued.add(generatedCert);
if (issued.size() == 0) {
certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
} else {
CMSSignedData messageData = getMessageData(issued);
certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
}
PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, CertificateManagementConstants.DES_EDE);
PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder);
CMSSignedData cmsSignedData = encoder.encode(certRep);
return cmsSignedData.getEncoded();
} catch (CertificateException e) {
String errorMsg = "Certificate issue occurred when generating getPKIMessage";
throw new KeystoreException(errorMsg, e);
} catch (MessageEncodingException e) {
String errorMsg = "Message encoding issue occurred when generating getPKIMessage";
throw new KeystoreException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Input output issue occurred when generating getPKIMessage";
throw new KeystoreException(errorMsg, e);
} catch (MessageDecodingException e) {
String errorMsg = "Message decoding issue occurred when generating getPKIMessage";
throw new KeystoreException(errorMsg, e);
} catch (CMSException e) {
String errorMsg = "CMS issue occurred when generating getPKIMessage";
throw new KeystoreException(errorMsg, e);
}
}
public boolean verifySignature(String headerSignature) throws KeystoreException {
Certificate certificate = extractCertificateFromSignature(headerSignature);
return (certificate != null);
}
public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException {
if (requestCertificate == null) {
throw new IllegalArgumentException("Certificate of which the signature needs to be validated cannot " +
"be null");
}
KeyStoreReader keyStoreReader = new KeyStoreReader();
CertificateResponse lookUpCertificate;
String commonNameExtracted = getCommonName(requestCertificate);
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
return lookUpCertificate;
}
public CertificateResponse verifyCertificateDN(String distinguishedName) throws KeystoreException {
CertificateResponse lookUpCertificate = null;
KeyStoreReader keyStoreReader = new KeyStoreReader();
if (distinguishedName != null && !distinguishedName.isEmpty()) {
String[] dnSplits = distinguishedName.split("/CN=");
if (dnSplits != null) {
String commonNameExtracted = dnSplits[dnSplits.length - 1];
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
}
}
return lookUpCertificate;
}
public X509Certificate pemToX509Certificate(String pem)
throws KeystoreException {
InputStream inputStream = null;
X509Certificate x509Certificate = null;
try {
inputStream = new ByteArrayInputStream(Base64.decodeBase64(pem.getBytes()));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate) cf.generateCertificate(inputStream);
} catch (CertificateException e) {
String errorMsg = "Certificate issue occurred when generating converting PEM to x509Certificate";
log.error(errorMsg, e);
throw new KeystoreException(errorMsg, e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
log.error("Error closing Certificate input stream", e);
}
}
return x509Certificate;
}
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {
if (headerSignature == null || headerSignature.isEmpty()) {
return null;
}
try {
KeyStoreReader keyStoreReader = new KeyStoreReader();
CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes()));
Store reqStore = signedData.getCertificates();
@SuppressWarnings("unchecked")
Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);
if (reqCerts != null && reqCerts.size() > 0) {
CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
X509CertificateHolder holder = reqCerts.iterator().next();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
X509Certificate reqCert = (X509Certificate) certificateFactory.
generateCertificate(byteArrayInputStream);
if (reqCert != null && reqCert.getSerialNumber() != null) {
Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias(
reqCert.getSerialNumber().toString());
if (lookUpCertificate instanceof X509Certificate) {
return (X509Certificate) lookUpCertificate;
}
}
}
} catch (CMSException e) {
String errorMsg = "CMSException when decoding certificate signature";
throw new KeystoreException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "IOException when decoding certificate signature";
throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) {
String errorMsg = "CertificateException when decoding certificate signature";
throw new KeystoreException(errorMsg, e);
}
return null;
}
public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
PKCS10CertificationRequest request,
String issueSubject)
throws KeystoreException {
CommonUtil commonUtil = new CommonUtil();
Date validityBeginDate = commonUtil.getValidityStartDate();
Date validityEndDate = commonUtil.getValidityEndDate();
X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL);
//X500Name certSubject = request.getSubject();
Attribute attributes[] = request.getAttributes();
// if (certSubject == null) {
// certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
// } else {
// org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs();
//
// if (rdn == null || rdn.length == 0) {
// certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
// }
// }
RDN[] certUniqueIdRDN;
BigInteger certUniqueIdentifier;
// IMPORTANT: "Serial-Number" of the certificate used when creating it, is set as its "Alias" to save to
// keystore.
if (request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER).length != 0) {
// if certificate attribute "UNIQUE_IDENTIFIER" exists use its hash as the "Serial-Number" for the
// certificate.
certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER);
certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());
} else if (request.getSubject().getRDNs(BCStyle.SERIALNUMBER).length != 0) {
// else if certificate attribute "SERIAL_NUMBER" exists use its hash as the "Serial-Number" for the
// certificate.
certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.SERIALNUMBER);
certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());
} else {
// else get the BigInteger Value of the integer that is the current system-time in millis as the
// "Serial-Number".
certUniqueIdentifier = CommonUtil.generateSerialNumber();
}
X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
new X500Name(issueSubject), certUniqueIdentifier, validityBeginDate, validityEndDate, certSubject,
request.getSubjectPublicKeyInfo());
ContentSigner sigGen;
X509Certificate issuedCert;
try {
certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
if (attributes != null) {
ASN1Encodable extractedValue = getChallengePassword(attributes);
if (extractedValue != null) {
certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true,
extractedValue);
}
}
sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
.setProvider(CertificateManagementConstants.PROVIDER).build(privateKey);
issuedCert = new JcaX509CertificateConverter().setProvider(
CertificateManagementConstants.PROVIDER).getCertificate(
certificateBuilder.build(sigGen));
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate =
new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificate.setCertificate(issuedCert);
certificates.add(certificate);
saveCertInKeyStore(certificates);
} catch (CertIOException e) {
String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
throw new KeystoreException(errorMsg, e);
} catch (OperatorCreationException e) {
String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR";
throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) {
String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR";
throw new KeystoreException(errorMsg, e);
}
return issuedCert;
}
private ASN1Encodable getChallengePassword(Attribute[] attributes) {
for (Attribute attribute : attributes) {
if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attribute.getAttrType())) {
if (attribute.getAttrValues() != null && attribute.getAttrValues().size() > 0) {
return attribute.getAttrValues().getObjectAt(0);
}
}
}
return null;
}
private CMSSignedData getMessageData(final List<X509Certificate> certs) throws KeystoreException {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
JcaCertStore store;
try {
store = new JcaCertStore(certs);
generator.addCertificates(store);
return generator.generate(new CMSAbsentContent());
} catch (CertificateEncodingException e) {
String errorMsg = "Certificate encoding issue occurred when generating getMessageData";
throw new KeystoreException(errorMsg, e);
} catch (CMSException e) {
String errorMsg = "Message decoding issue occurred when generating getMessageData";
throw new KeystoreException(errorMsg, e);
}
}
// private PrivateKey getSignerKey(String signerPrivateKeyPath) throws KeystoreException {
//
// File file = new File(signerPrivateKeyPath);
// FileInputStream fis;
//
// try {
// fis = new FileInputStream(file);
// DataInputStream dis = new DataInputStream(fis);
// byte[] keyBytes = new byte[(int) file.length()];
// dis.readFully(keyBytes);
// dis.close();
//
// String temp = new String(keyBytes);
// String privateKeyPEM = temp.replace(
// CertificateManagementConstants.RSA_PRIVATE_KEY_BEGIN_TEXT, CertificateManagementConstants.EMPTY_TEXT);
// privateKeyPEM = privateKeyPEM
// .replace(CertificateManagementConstants.RSA_PRIVATE_KEY_END_TEXT, CertificateManagementConstants.EMPTY_TEXT);
//
// byte[] decoded = Base64.decodeBase64(privateKeyPEM);
// PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(decoded);
// KeyFactory keyFactory = KeyFactory.getInstance(CertificateManagementConstants.RSA);
//
// return keyFactory.generatePrivate(encodedKeySpec);
// } catch (FileNotFoundException e) {
// String errorMsg = "Private key file not found in getSignerKey";
// throw new KeystoreException(errorMsg, e);
// } catch (IOException e) {
// String errorMsg = "Input output issue in getSignerKey";
// throw new KeystoreException(errorMsg, e);
// } catch (NoSuchAlgorithmException e) {
// String errorMsg = "Algorithm not not found in getSignerKey";
// throw new KeystoreException(errorMsg, e);
// } catch (InvalidKeySpecException e) {
// String errorMsg = "Invalid key found in getSignerKey";
// throw new KeystoreException(errorMsg, e);
// }
// }
//
// private X509Certificate getSigner(String signerCertificatePath) throws KeystoreException {
//
// X509Certificate certificate;
// try {
// CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
// certificate = (X509Certificate) certificateFactory.generateCertificate(
// new FileInputStream(signerCertificatePath));
//
// return certificate;
// } catch (CertificateException e) {
// String errorMsg = "Certificate related issue occurred in getSigner";
// throw new KeystoreException(errorMsg, e);
// } catch (FileNotFoundException e) {
// String errorMsg = "Signer certificate path not found in getSigner";
// throw new KeystoreException(errorMsg, e);
// }
// }
public SCEPResponse getCACert() throws KeystoreException {
try {
SCEPResponse scepResponse = new SCEPResponse();
KeyStoreReader keyStoreReader = new KeyStoreReader();
byte[] caBytes = keyStoreReader.getCACertificate().getEncoded();
byte[] raBytes = keyStoreReader.getRACertificate().getEncoded();
final List<X509Certificate> certs = getRootCertificates(caBytes, raBytes);
byte[] bytes;
if (certs.size() == 0) {
scepResponse.setResultCriteria(CAStatus.CA_CERT_FAILED);
bytes = new byte[0];
} else if (certs.size() == 1) {
scepResponse.setResultCriteria(CAStatus.CA_CERT_RECEIVED);
bytes = certs.get(0).getEncoded();
} else {
scepResponse.setResultCriteria(CAStatus.CA_RA_CERT_RECEIVED);
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
JcaCertStore store = new JcaCertStore(certs);
generator.addCertificates(store);
CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
bytes = degenerateSd.getEncoded();
}
scepResponse.setEncodedResponse(bytes);
return scepResponse;
} catch (CertificateEncodingException e) {
String errorMsg = "Certificate encoding issue occurred in getCACert";
throw new KeystoreException(errorMsg, e);
} catch (CMSException e) {
String errorMsg = "CMS issue occurred in getCACert";
throw new KeystoreException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Input output issue occurred in getCACert";
throw new KeystoreException(errorMsg, e);
}
}
public void saveCertInKeyStore(List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificate)
throws KeystoreException {
if (certificate == null) {
return;
}
try {
CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO();
CertificateManagementDAOFactory.beginTransaction();
certificateDAO.addCertificate(certificate);
CertificateManagementDAOFactory.commitTransaction();
} catch (CertificateManagementDAOException e) {
String errorMsg = "Error occurred when saving the generated certificate";
CertificateManagementDAOFactory.rollbackTransaction();
throw new KeystoreException(errorMsg, e);
} catch (TransactionManagementException e) {
String errorMsg = "Error occurred when saving the generated certificate";
throw new KeystoreException(errorMsg, e);
}
}
public String extractChallengeToken(X509Certificate certificate) {
byte[] challengePassword = certificate.getExtensionValue(
PKCSObjectIdentifiers.pkcs_9_at_challengePassword.toString());
if (challengePassword != null) {
return new String(challengePassword);
}
return null;
}
// private ASN1Primitive toASN1Primitive(byte[] data) {
//
// ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
// ASN1InputStream inputStream = new ASN1InputStream(byteArrayInputStream);
//
// try {
// return inputStream.readObject();
// } catch (IOException e) {
// String errorMsg = "IOException occurred when converting binary array to ASN1Primitive";
// log.error(errorMsg, e);
// } finally {
// try {
// byteArrayInputStream.close();
// inputStream.close();
// } catch (IOException e) {
// String errorMsg = "IOException occurred when closing streams";
// log.error(errorMsg, e);
// }
// }
//
// return null;
// }
/**
* This method is used to retrieve signed certificate from certificate signing request.
*
* @param binarySecurityToken CSR that comes from the client as a String value.It is base 64 encoded request
* security token.
* @return Return signed certificate in X508Certificate type object.
* @throws KeystoreException
*/
public X509Certificate getSignedCertificateFromCSR(String binarySecurityToken)
throws KeystoreException {
byte[] byteArrayBst = DatatypeConverter.parseBase64Binary(binarySecurityToken);
PKCS10CertificationRequest certificationRequest;
KeyStoreReader keyStoreReader = new KeyStoreReader();
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
try {
certificationRequest = new PKCS10CertificationRequest(byteArrayBst);
} catch (IOException e) {
throw new KeystoreException("CSR cannot be recovered.", e);
}
return generateCertificateFromCSR(privateKeyCA, certificationRequest,
certCA.getIssuerX500Principal().getName());
}
} |
shgriffi/openshift-ansible | utils/src/ooinstall/ansible_plugins/facts_callback.py | <reponame>shgriffi/openshift-ansible<gh_stars>1-10
# TODO: Temporarily disabled due to importing old code into openshift-ansible
# repo. We will work on these over time.
# pylint: disable=bad-continuation,missing-docstring,no-self-use,invalid-name,no-value-for-parameter
import os
import yaml
from ansible.plugins.callback import CallbackBase
from ansible.parsing.yaml.dumper import AnsibleDumper
# ansible.compat.six goes away with Ansible 2.4
try:
from ansible.compat.six import u
except ImportError:
from ansible.module_utils.six import u
# pylint: disable=super-init-not-called
class CallbackModule(CallbackBase):
def __init__(self):
######################
# This is ugly stoopid. This should be updated in the following ways:
# 1) it should probably only be used for the
# openshift_facts.yml playbook, so maybe there's some way to check
# a variable that's set when that playbook is run?
try:
self.hosts_yaml_name = os.environ['OO_INSTALL_CALLBACK_FACTS_YAML']
except KeyError:
raise ValueError('The OO_INSTALL_CALLBACK_FACTS_YAML environment '
'variable must be set.')
self.hosts_yaml = os.open(self.hosts_yaml_name, os.O_CREAT |
os.O_WRONLY)
def v2_on_any(self, *args, **kwargs):
pass
def v2_runner_on_failed(self, res, ignore_errors=False):
pass
# pylint: disable=protected-access
def v2_runner_on_ok(self, res):
abridged_result = res._result.copy()
# Collect facts result from playbooks/byo/openshift_facts.yml
if 'result' in abridged_result:
facts = abridged_result['result']['ansible_facts']['openshift']
hosts_yaml = {}
hosts_yaml[res._host.get_name()] = facts
to_dump = u(yaml.dump(hosts_yaml,
allow_unicode=True,
default_flow_style=False,
Dumper=AnsibleDumper))
os.write(self.hosts_yaml, to_dump)
def v2_runner_on_skipped(self, res):
pass
def v2_runner_on_unreachable(self, res):
pass
def v2_runner_on_no_hosts(self, task):
pass
def v2_runner_on_async_poll(self, res):
pass
def v2_runner_on_async_ok(self, res):
pass
def v2_runner_on_async_failed(self, res):
pass
def v2_playbook_on_start(self, playbook):
pass
def v2_playbook_on_notify(self, res, handler):
pass
def v2_playbook_on_no_hosts_matched(self):
pass
def v2_playbook_on_no_hosts_remaining(self):
pass
def v2_playbook_on_task_start(self, name, is_conditional):
pass
# pylint: disable=too-many-arguments
def v2_playbook_on_vars_prompt(self, varname, private=True, prompt=None,
encrypt=None, confirm=False, salt_size=None, salt=None, default=None):
pass
def v2_playbook_on_setup(self):
pass
def v2_playbook_on_import_for_host(self, res, imported_file):
pass
def v2_playbook_on_not_import_for_host(self, res, missing_file):
pass
def v2_playbook_on_play_start(self, play):
pass
def v2_playbook_on_stats(self, stats):
pass
|
connectim/iOS | Connect/Client/Wallet/View/LMWalletViewCell.h | //
// LMWalletViewCell.h
// Connect
//
// Created by Edwin on 16/7/14.
// Copyright © 2016年 Connect. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface LMWalletViewCell : UIView
// wallet money
@property(nonatomic, strong) UILabel *walletAccout;
@end
|
MetaPhase-Consulting/State-TalentMAP | src/reducers/bureauPositionDetails/bureauPositionDetails.test.js | <gh_stars>1-10
import * as reducers from './bureauPositionDetails';
describe('assignment reducers', () => {
it('can set reducer BUREAU_POSITION_DETAILS_HAS_ERRORED', () => {
expect(reducers.bureauPositionDetailsHasErrored(false, { type: 'BUREAU_POSITION_DETAILS_HAS_ERRORED', hasErrored: true })).toBe(true);
});
it('can set reducer BUREAU_POSITION_DETAILS_IS_LOADING', () => {
expect(reducers.bureauPositionDetailsIsLoading(false, { type: 'BUREAU_POSITION_DETAILS_IS_LOADING', isLoading: true })).toBe(true);
});
it('can set reducer BUREAU_POSITION_DETAILS_FETCH_DATA_SUCCESS', () => {
expect(reducers.bureauPositionDetails(false, { type: 'BUREAU_POSITION_DETAILS_FETCH_DATA_SUCCESS', bureauPositionDetails: {} })).toEqual({});
});
});
|
masud-technope/ACER-Replication-Package-ASE2017 | corpus/class/eclipse.pde.ui/5270.java | /*******************************************************************************
* Copyright (c) 2008, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* <NAME> <<EMAIL>> - creation of this class
* Code 9 Corporation - ongoing enhancements
*******************************************************************************/
package org.eclipse.pde.internal.ui.parts;
import java.util.*;
import java.util.List;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.forms.widgets.FormToolkit;
public class ComboViewerPart {
private Control fCombo;
private ComboViewer fComboViewer;
private List<Object> fObjects;
/**
* The magic object used to deal with null content
*/
public static Object NULL_OBJECT = new Object();
public ComboViewerPart() {
}
public void createControl(Composite parent, FormToolkit toolkit, int style) {
if (toolkit.getBorderStyle() == SWT.BORDER) {
fCombo = new Combo(parent, style | SWT.BORDER);
fComboViewer = new ComboViewer((Combo) fCombo);
} else {
fCombo = new CCombo(parent, style | SWT.FLAT);
fComboViewer = new ComboViewer((CCombo) fCombo);
}
fObjects = new ArrayList();
fComboViewer.setLabelProvider(new LabelProvider());
fComboViewer.setContentProvider(ArrayContentProvider.getInstance());
fComboViewer.setInput(fObjects);
}
public Control getControl() {
return fCombo;
}
public void setEnabled(boolean enabled) {
fCombo.setEnabled(enabled);
}
public void refresh() {
fComboViewer.refresh();
}
public void addItem(Object item) {
fObjects.add((item == null) ? NULL_OBJECT : item);
refresh();
}
public void addItem(Object item, int index) {
fObjects.add(index, (item == null) ? NULL_OBJECT : item);
refresh();
}
public Collection<Object> getItems() {
return fObjects;
}
public void setItems(Object[] items) {
fObjects.clear();
for (int i = 0; i < items.length; i++) fObjects.add((items[i] == null) ? NULL_OBJECT : items[i]);
refresh();
}
public void setItems(Collection<?> items) {
fObjects.clear();
Iterator<?> it = items.iterator();
while (it.hasNext()) {
Object o = it.next();
fObjects.add((o == null) ? NULL_OBJECT : o);
}
refresh();
}
public void select(Object item) {
if (item != null)
fComboViewer.setSelection(new StructuredSelection(item));
else
fComboViewer.setSelection(null);
}
public void select(int index) {
if (index < fObjects.size())
select(fObjects.get(index));
}
public void setLabelProvider(IBaseLabelProvider labelProvider) {
fComboViewer.setLabelProvider(labelProvider);
}
public void setComparator(ViewerComparator comparator) {
fComboViewer.setComparator(comparator);
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
fComboViewer.addSelectionChangedListener(listener);
}
public Object getSelection() {
return ((IStructuredSelection) fComboViewer.getSelection()).getFirstElement();
}
}
|
mosxuqian/CodeCollection | Algorithm/HashTable/hashtableTest.c | <reponame>mosxuqian/CodeCollection
#include<stdio.h>
#include "hashtable.h"
int main()
{
hash_table_t *table = hash_table_new(MODE_COPY);
int i = 1;
int val = 100;
int val2 = 200;
int j = 2;
int x =0;
for (x=0;x<3000;x++)
{
// use the macro
HT_ADD(table, &j, &val);
// or use the function
//hash_table_add(table, &j, i, (void *) &val, sizeof(int));
val++;
j++;
}
hash_table_add(table, &j, i, (void *) &val2, 1);
j--; j--;
hash_table_remove(table, &j, i);
HT_REMOVE(table, &j);
if (hash_table_has_key(table, &j, i))
{
printf("Key found %d\n", j);
}
else
{
printf("Key NOT found %d\n", j);
}
val = -100;
val2 = -200;
j--;
int *value = NULL;
value = (int* ) HT_LOOKUP(table, &j);
void** keys = NULL;
size_t num = hash_table_get_keys(table, keys);
printf("found %d keys\n", (int)num);
printf("j -> %d \n", j);
if (value)
printf("value is %d\n", *value);
else
printf("*value is %p\n", value);
return 0;
}
|
BaiduFE/Tangram-base | test/baidu/dom/getComputedStyle.js | module("baidu.dom.getComputedStyle");
test("get style from style", function() {
if (ua.browser.ie) {
ok(true, "IE not supportted");
return;
}
expect(7);
var div = document.createElement('div');
var img = document.createElement('img');
document.body.appendChild(div);
div.appendChild(img);
div.id = 'div_id';
div.style.cssFloat = div.style.float = 'left';// opera下cssFloat生效
div.style.width = '100px';
div.style.height = '150px';
div.style.background = "#FFCC80";
div.style.color = "red";
img.style.display = 'block';
img.style.width = '10%';
img.style.height = '10%';
equal(baidu.dom.getComputedStyle(div, 'float'), 'left');
equal(baidu.dom.getComputedStyle(div, 'width'), '100px');
equal(baidu.dom.getComputedStyle(div, 'height'), '150px');
var color = baidu.dom.getComputedStyle(div, 'color').toLowerCase();
ok(color == '#ff0000' || color == 'red'
|| (/rgb\(255,\s?0,\s?0\)/.test(color)), 'color red');
equal(baidu.dom.getComputedStyle(img, 'display'), 'block');
equal(baidu.dom.getComputedStyle(img, 'width'), '10px');
equal(baidu.dom.getComputedStyle(img, 'height'), '15px');
document.body.removeChild(div);
});
/** css加载也需要时间 * */
test("get style from css file", function() {
if (ua.browser.ie) {
ok(true, "IE not supportted");
return;
}
expect(9);
stop();
var div = document.createElement('div');
var div1 = document.createElement('div');
var img = document.createElement('img');
var p = document.createElement('p');
var link = document.createElement('link');
document.body.appendChild(div);
document.body.appendChild(div1);
div.appendChild(p);
div.appendChild(img);
$(div).attr('className', "content");
$(div1).attr('className', 'content');
$(img).attr('className', 'content');
$(p).attr('className', 'pid');
ua.loadcss(upath + 'style.css', function() {
/** IE的float属性叫styleFloat,firefox则是cssFloat * */
equal(baidu.dom.getComputedStyle(div, 'float'), 'left');
equal(baidu.dom.getComputedStyle(div, 'width'), '200px');
var color = baidu.dom.getComputedStyle(div, 'color').toLowerCase();
ok(color == '#00ff00' || color == 'rgb(0,255,0)'
|| color == 'rgb(0, 255, 0)', 'color');
equal(baidu.dom.getComputedStyle(div, 'position'), 'relative');
/** IE的float属性叫styleFloat,firefox则是cssFloat */
equal(baidu.dom.getComputedStyle(img, 'float'), 'left');
equal(baidu.dom.getComputedStyle(img, 'display'), 'block');
equal(baidu.dom.getComputedStyle(img, 'left'), '50px');
equal(baidu.dom.getComputedStyle(img, 'width'), '200px');
equal(baidu.dom.getComputedStyle(p, 'font-size'), '14px');
document.body.removeChild(div);
document.body.removeChild(div1);
start();
}, "pid", "font-size", "14px");
});
test("get style from fixer", function() {
if (ua.browser.ie) {
ok(true, "IE not supportted");
return;
}
stop();
ua.importsrc('baidu.dom._styleFixer.opacity', function() {
var div = document.createElement('div');
document.body.appendChild(div);
var img = document.createElement('img');
div.appendChild(img);
equal(baidu.dom.getComputedStyle(img, 'opacity'), '1');
document.body.removeChild(div);
start();
}, 'baidu.dom._styleFixer.opacity', 'baidu.dom.getComputedStyle');
});
test("get empty style in IE", function() {
if (ua.browser.ie) {
stop();
var div = document.createElement('div');
div.style.width = '100px';
equal(baidu.dom.getComputedStyle(div, 'width'), '','empty style');
start();
}
}); |
johnjohndoe/pgem | vendor/extensions/meetups/db/seeds.rb | Refinery::I18n.frontend_locales.each do |lang|
I18n.locale = lang
Refinery::User.find_each do |user|
user.plugins.where(name: 'refinerycms-meetups').first_or_create!(
position: (user.plugins.maximum(:position) || -1) +1
)
end if defined?(Refinery::User)
Refinery::Page.where(link_url: (url = "/meetups")).first_or_create!(
title: 'Meetups',
deletable: false,
menu_match: "^#{url}(\/|\/.+?|)$"
) do |page|
Refinery::Pages.default_parts.each_with_index do |part, index|
page.parts.build title: part[:title], slug: part[:slug], body: nil, position: index
end
end if defined?(Refinery::Page)
end
|
taoyuc3/CS225 | potd/potd-q54/main.cpp | #include <iostream>
#include <vector>
#include "Primes.h"
int main() {
std::vector<int> * primes = genPrimes(1000);
std::cout << "2 has " << numSequences(primes,2) << " sequence(s)." << std::endl;
std::cout << "3 has " << numSequences(primes,3) << " sequence(s)." << std::endl;
std::cout << "17 has " << numSequences(primes,17) << " sequence(s)." << std::endl;
std::cout << "41 has " << numSequences(primes,41) << " sequence(s)." << std::endl;
return 0;
}
|
svenfuchs/adva_cms | engines/adva_photos/app/models/album.rb | <gh_stars>10-100
class Album < Section
has_many :photos, :foreign_key => 'section_id', :dependent => :destroy
has_many :sets, :class_name => 'Category', :foreign_key => 'section_id', :dependent => :destroy, :order => 'lft' do
def roots
find :all, :conditions => {:parent_id => nil}, :order => 'lft'
end
def update_paths!
paths = Hash[*roots.map { |r|
r.self_and_descendants.map { |n| [n.id, { 'path' => n.send(:build_path) }] } }.flatten]
update paths.keys, paths.values
end
end
has_option :photos_per_page, :default => 25
has_filter :tagged, :categorized,
:text => { :attributes => :title },
:state => { :states => [:published, :unpublished] }
if Rails.plugin?(:adva_safemode)
class Jail < Content::Jail
allow :sets, :photos
end
end
def self.content_type
'Photo'
end
end
|
hpc4cmb/tidas | src/libtidas/src/tidas_dict_getdata.cpp | <filename>src/libtidas/src/tidas_dict_getdata.cpp
// TImestream DAta Storage (TIDAS).
//
// Copyright (c) 2015-2019 by the parties listed in the AUTHORS file. All rights
// reserved. Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <tidas_internal.hpp>
#include <tidas_backend_getdata.hpp>
using namespace std;
using namespace tidas;
tidas::dict_backend_getdata::dict_backend_getdata() {}
tidas::dict_backend_getdata::~dict_backend_getdata() {}
tidas::dict_backend_getdata::dict_backend_getdata(dict_backend_getdata const & other) {}
dict_backend_getdata & tidas::dict_backend_getdata::operator=(
dict_backend_getdata const & other) {
if (this != &other) {}
return *this;
}
void tidas::dict_backend_getdata::read(backend_path const & loc, map <string,
string> & data,
map <string, data_type> & types) {
TIDAS_THROW("GetData backend not supported");
return;
}
void tidas::dict_backend_getdata::write(backend_path const & loc, map <string,
string> const & data, map <string,
data_type> const & types)
const {
TIDAS_THROW("GetData backend not supported");
return;
}
|
jamieguerrero/lucytumolo-gatsby | src/components/Modalities.js | import React from 'react'
import PropTypes from 'prop-types'
import { v4 } from 'uuid'
const Modalities = ({ modalities }) => (
<div>
{modalities.map(modality => (
<div>
{modality.name}
<img src={modality.image}/>
{modality.description}
</div>
))}
</div>
)
Modalities.propTypes = {
testimonials: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
image: PropTypes.string,
description: PropTypes.string,
})
),
}
export default Modalities
|
Quesar/gradle-mobile-plugin | src/main/java/lv/ctco/scm/mobile/utils/IosArtifactUtil.java | package lv.ctco.scm.mobile.utils;
import lv.ctco.scm.utils.file.FileUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class IosArtifactUtil {
private IosArtifactUtil() {}
public static void unpackIpaPayload(File sourceIpa, File payloadContainerDir) throws IOException {
if (payloadContainerDir.exists()) {
FileUtil.cleanDirectory(payloadContainerDir);
} else {
Files.createDirectories(payloadContainerDir.toPath());
}
ZipUtil.extractAll(sourceIpa, payloadContainerDir);
}
public static void repackIpaPayload(File payloadContainerDir, File targetIpa) throws IOException {
if (payloadContainerDir.exists()) {
ZipUtil.compressDirectory(payloadContainerDir, false, targetIpa);
} else {
throw new IOException("Payload '"+payloadContainerDir.getAbsolutePath()+"' was not found!");
}
}
public static File getPayloadApp(File payloadContainerDir) throws IOException {
File payloadDir = new File(payloadContainerDir, "Payload");
File[] files = payloadDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".app")) {
return file;
}
}
}
throw new IOException(".app directory not found in '"+payloadContainerDir.getAbsolutePath()+"'");
}
}
|
mateussouzaweb/compactor | os/fs.go | package os
import (
"bytes"
"io/fs"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
)
// Exist check if file or directory exists
func Exist(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
// Permissions retrieve permissions for file or directory
func Permissions(path string) (fs.FileMode, error) {
var perm fs.FileMode
info, err := os.Stat(path)
if err != nil {
return perm, err
}
perm = info.Mode().Perm()
return perm, nil
}
// Read retrieve content from file
func Read(file string) (string, error) {
content, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return string(content), nil
}
// ReadMany retrieve merged content from file list
func ReadMany(files []string) (string, error) {
buf := bytes.NewBuffer(nil)
for _, filepath := range files {
content, err := Read(filepath)
if err != nil {
return "", err
}
buf.WriteString(content)
}
return buf.String(), nil
}
// Write content on file
func Write(file string, content string, perm fs.FileMode) error {
err := ioutil.WriteFile(file, []byte(content), perm)
if err != nil {
return err
}
return nil
}
// Copy the origin file into destination
func Copy(origin string, destination string) error {
content, err := Read(origin)
if err != nil {
return err
}
perm, err := Permissions(origin)
if err != nil {
return err
}
err = Write(destination, content, perm)
return err
}
// Delete remove a file
func Delete(file string) error {
if Exist(file) {
return os.Remove(file)
}
return nil
}
// Move a file to destination
func Move(origin string, destination string) error {
return os.Rename(origin, destination)
}
// Rename a file name
func Rename(origin string, destination string) error {
return Move(origin, destination)
}
// Chmod apply permissions to file
func Chmod(file string, perm fs.FileMode) error {
return os.Chmod(file, perm)
}
// Chown apply user and group ownership to file
func Chown(file string, user int, group int) error {
return os.Chown(file, user, group)
}
// Return the clean directory path for file
func Dir(path string) string {
return filepath.Dir(path)
}
// Return the clean file name for path, with extension
func File(path string) string {
return filepath.Base(path)
}
// Return the clean file name for path, without extension
func Name(path string) string {
name := filepath.Base(path)
ext := filepath.Ext(path)
return strings.TrimSuffix(name, ext)
}
// Return the clean file extension, with dot
func Extension(file string) string {
return filepath.Ext(file)
}
// Info read and return file information: content, checksum and permissions
func Info(file string) (string, string, fs.FileMode) {
content, err := Read(file)
if err != nil {
content = ""
}
perm, err := Permissions(file)
if err != nil {
perm = fs.FileMode(0644)
}
checksum, err := Checksum(content)
if err != nil {
checksum = ""
}
return content, checksum, perm
}
// WalkCallback type
type WalkCallback func(path string) error
// Walk find files in path and process callback for every result
func Walk(root string, callback WalkCallback) error {
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
return callback(path)
})
return err
}
// List walks on path and return every found file
func List(root string) ([]string, error) {
var files []string
err := Walk(root, func(path string) error {
files = append(files, path)
return nil
})
return files, err
}
// Find retrieve files from path that exactly match names
func Find(root string, names []string) ([]string, error) {
var files []string
err := Walk(root, func(path string) error {
name := filepath.Base(path)
for _, item := range names {
if name == item {
files = append(files, path)
break
}
}
return nil
})
return files, err
}
// FindMatch retrieve files from path that match patterns
func FindMatch(root string, patterns []string) ([]string, error) {
var files []string
err := Walk(root, func(thePath string) error {
for _, pattern := range patterns {
file := strings.Replace(thePath, root, "", 1)
file = strings.TrimLeft(file, "/")
matched, err := path.Match(pattern, file)
if err != nil {
return err
}
if matched {
files = append(files, thePath)
break
}
}
return nil
})
return files, err
}
// EnsureDirectory makes sure directory exists from file path
func EnsureDirectory(file string) error {
path := filepath.Dir(file)
if !Exist(path) {
err := os.MkdirAll(path, 0775)
if err != nil {
return err
}
}
return nil
}
|
ysimonson/new_sanctuary_asylum | spec/factories/community_factory.rb | <filename>spec/factories/community_factory.rb
FactoryBot.define do
factory :community do
name { Faker::Address.unique.city }
slug { name.downcase.gsub(/[^a-z]/i, '') }
association :region
end
trait :primary do
primary { true }
end
end
|
netspeak/netspeak4-application-cpp | src/netspeak/value/sextuple_traits.hpp | <filename>src/netspeak/value/sextuple_traits.hpp<gh_stars>0
// quadruple_traits.hpp -*- C++ -*-
// Copyright (C) 2011-2013 <NAME>
#ifndef NETSPEAK_VALUE_SEXTUPLE_TRAITS_HPP
#define NETSPEAK_VALUE_SEXTUPLE_TRAITS_HPP
#include "netspeak/value/sextuple.hpp"
#include "netspeak/value/value_traits.hpp"
namespace netspeak {
namespace value {
// -----------------------------------------------------------------------------
// Partial specialization for value::sextuple<T1, T2, T3, T4, T5, T6>
// -----------------------------------------------------------------------------
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6>
struct value_traits<sextuple<T1, T2, T3, T4, T5, T6> > {
typedef sextuple<T1, T2, T3, T4, T5, T6> value_type;
typedef uint16_t io_size_type;
typedef value_traits<T1> T1Traits; // Compiles for arithmetic types only.
typedef value_traits<T2> T2Traits; // Compiles for arithmetic types only.
typedef value_traits<T3> T3Traits; // Compiles for arithmetic types only.
typedef value_traits<T4> T4Traits; // Compiles for arithmetic types only.
typedef value_traits<T5> T5Traits; // Compiles for arithmetic types only.
typedef value_traits<T6> T6Traits; // Compiles for arithmetic types only.
static inline size_t size_of(const value_type& sextuple) {
return T1Traits::size_of(sextuple.e1()) + T2Traits::size_of(sextuple.e2()) +
T3Traits::size_of(sextuple.e3()) + T4Traits::size_of(sextuple.e4()) +
T5Traits::size_of(sextuple.e5()) + T6Traits::size_of(sextuple.e6());
}
static inline char* copy_to(const value_type& sextuple, char* buffer) {
buffer = T1Traits::copy_to(sextuple.e1(), buffer);
buffer = T2Traits::copy_to(sextuple.e2(), buffer);
buffer = T3Traits::copy_to(sextuple.e3(), buffer);
buffer = T4Traits::copy_to(sextuple.e4(), buffer);
buffer = T5Traits::copy_to(sextuple.e5(), buffer);
return T6Traits::copy_to(sextuple.e6(), buffer);
}
static inline const char* copy_from(value_type& sextuple,
const char* buffer) {
buffer = T1Traits::copy_from(sextuple.e1(), buffer);
buffer = T2Traits::copy_from(sextuple.e2(), buffer);
buffer = T3Traits::copy_from(sextuple.e3(), buffer);
buffer = T4Traits::copy_from(sextuple.e4(), buffer);
buffer = T5Traits::copy_from(sextuple.e5(), buffer);
return T6Traits::copy_from(sextuple.e6(), buffer);
}
static inline bool write_to(const value_type& sextuple, FILE* file) {
return T1Traits::write_to(sextuple.e1(), file) &&
T2Traits::write_to(sextuple.e2(), file) &&
T3Traits::write_to(sextuple.e3(), file) &&
T4Traits::write_to(sextuple.e4(), file) &&
T5Traits::write_to(sextuple.e5(), file) &&
T6Traits::write_to(sextuple.e6(), file);
}
static inline bool read_from(value_type& sextuple, FILE* file) {
return T1Traits::read_from(sextuple.e1(), file) &&
T2Traits::read_from(sextuple.e2(), file) &&
T3Traits::read_from(sextuple.e3(), file) &&
T4Traits::read_from(sextuple.e4(), file) &&
T5Traits::read_from(sextuple.e5(), file) &&
T6Traits::read_from(sextuple.e6(), file);
}
static inline void print_to(const value_type& sextuple, std::ostream& os) {
T1Traits::print_to(sextuple.e1(), os);
os << tuple_element_separator;
T2Traits::print_to(sextuple.e2(), os);
os << tuple_element_separator;
T3Traits::print_to(sextuple.e3(), os);
os << tuple_element_separator;
T4Traits::print_to(sextuple.e4(), os);
os << tuple_element_separator;
T5Traits::print_to(sextuple.e5(), os);
os << tuple_element_separator;
T6Traits::print_to(sextuple.e6(), os);
}
static inline void println_to(const value_type& sextuple, std::ostream& os) {
print_to(sextuple, os);
os << '\n';
}
static inline void parse_from(value_type& sextuple, std::istream& is) {
T1Traits::parse_from(sextuple.e1(), is);
T2Traits::parse_from(sextuple.e2(), is);
T3Traits::parse_from(sextuple.e3(), is);
T4Traits::parse_from(sextuple.e4(), is);
T5Traits::parse_from(sextuple.e5(), is);
T6Traits::parse_from(sextuple.e6(), is);
}
static inline std::string type_name() {
return T1Traits::type_name() + T2Traits::type_name() +
T3Traits::type_name() + T4Traits::type_name() +
T5Traits::type_name() + T6Traits::type_name();
}
};
// -----------------------------------------------------------------------------
// Operators
// -----------------------------------------------------------------------------
template <typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6>
std::ostream& operator<<(std::ostream& os,
const sextuple<T1, T2, T3, T4, T5, T6>& value) {
if (os)
value_traits<sextuple<T1, T2, T3, T4, T5, T6> >::print_to(value, os);
return os;
}
} // namespace value
} // namespace netspeak
#endif // NETSPEAK_VALUE_SEXTUPLE_TRAITS_HPP
|
quanpands/wflow | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_python/value_scale_traits.cc | <gh_stars>0
#include "value_scale_traits.h"
namespace pcraster {
std::string const ValueScaleTraits<VS_B>::name("Boolean");
std::string const ValueScaleTraits<VS_L>::name("LDD");
std::string const ValueScaleTraits<VS_N>::name("Nominal");
std::string const ValueScaleTraits<VS_O>::name("Ordinal");
std::string const ValueScaleTraits<VS_S>::name("Scalar");
std::string const ValueScaleTraits<VS_D>::name("Directional");
ValueScaleTraits<VS_S>::Type const ValueScaleTraits<VS_S>::minimum = -FLT_MAX;
ValueScaleTraits<VS_S>::Type const ValueScaleTraits<VS_S>::maximum = FLT_MAX;
ValueScaleTraits<VS_D>::Type const ValueScaleTraits<VS_D>::minimum = -FLT_MAX;
ValueScaleTraits<VS_D>::Type const ValueScaleTraits<VS_D>::maximum = FLT_MAX;
} // namespace pcraster
|
Selvasundaram/gluster-ovirt | backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/DbUserDAODbFacadeImpl.java | <reponame>Selvasundaram/gluster-ovirt<gh_stars>1-10
package org.ovirt.engine.core.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.dal.dbbroker.CustomMapSqlParameterSource;
import org.ovirt.engine.core.dal.dbbroker.DbFacadeUtils;
import org.ovirt.engine.core.dal.dbbroker.user_sessions;
/**
* <code>DBUserDAODbFacadeImpl</code> provides an implementation of {@link DbUserDAO} with the previously developed
* {@link DbFacade} code.
*
*/
public class DbUserDAODbFacadeImpl extends BaseDAODbFacade implements DbUserDAO {
private class DbUserRowMapper implements ParameterizedRowMapper<DbUser> {
@Override
public DbUser mapRow(ResultSet rs, int rowNum) throws SQLException {
DbUser entity = new DbUser();
entity.setdepartment(rs.getString("department"));
entity.setdesktop_device(rs.getString("desktop_device"));
entity.setdomain(rs.getString("domain"));
entity.setemail(rs.getString("email"));
entity.setgroups(rs.getString("groups"));
entity.setname(rs.getString("name"));
entity.setnote(rs.getString("note"));
entity.setnote(rs.getString("note"));
entity.setrole(rs.getString("role"));
entity.setstatus(rs.getInt("status"));
entity.setsurname(rs.getString("surname"));
entity.setuser_icon_path(rs.getString("user_icon_path"));
entity.setuser_id(Guid.createGuidFromString(rs.getString("user_id")));
entity.setsession_count(rs.getInt("session_count"));
entity.setusername(rs.getString("username"));
entity.setLastAdminCheckStatus(rs.getBoolean("last_admin_check_status"));
entity.setGroupIds(rs.getString("group_ids"));
return entity;
}
}
private class DbUserMapSqlParameterSource extends
CustomMapSqlParameterSource {
public DbUserMapSqlParameterSource(DbUser user) {
super(dialect);
addValue("department", user.getdepartment());
addValue("desktop_device", user.getdesktop_device());
addValue("domain", user.getdomain());
addValue("email", user.getemail());
addValue("groups", user.getgroups());
addValue("name", user.getname());
addValue("note", user.getnote());
addValue("role", user.getrole());
addValue("status", user.getstatus());
addValue("surname", user.getsurname());
addValue("user_icon_path", user.getuser_icon_path());
addValue("user_id", user.getuser_id());
addValue("session_count", user.getsession_count());
addValue("username", user.getusername());
addValue("last_admin_check_status", user.getLastAdminCheckStatus());
addValue("group_ids", user.getGroupIds());
}
}
@Override
public DbUser get(Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("user_id", id);
return getCallsHandler().executeRead("GetUserByUserId", new DbUserRowMapper(), parameterSource);
}
@Override
public DbUser getByUsername(String username) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("username", username);
return getCallsHandler().executeRead("GetUserByUserName", new DbUserRowMapper(), parameterSource);
}
@SuppressWarnings("unchecked")
@Override
public List<DbUser> getAllForVm(Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("vm_guid", id);
return getCallsHandler().executeReadList("GetUsersByVmGuid", new DbUserRowMapper(),
parameterSource);
}
@SuppressWarnings("unchecked")
@Override
public List<DbUser> getAllTimeLeasedUsersForVm(int vmid) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("vm_pool_id", vmid);
return getCallsHandler().executeReadList("Gettime_leasedusers_by_vm_pool_id",
new DbUserRowMapper(),
parameterSource);
}
@Override
public List<DbUser> getAllWithQuery(String query) {
return new SimpleJdbcTemplate(jdbcTemplate).query(query,
new DbUserRowMapper());
}
@SuppressWarnings("unchecked")
@Override
public List<user_sessions> getAllUserSessions() {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource();
ParameterizedRowMapper<user_sessions> mapper = new ParameterizedRowMapper<user_sessions>() {
@Override
public user_sessions mapRow(ResultSet rs, int rowNum)
throws SQLException {
user_sessions entity = new user_sessions();
entity.setbrowser(rs.getString("browser"));
entity.setclient_type(rs.getString("client_type"));
entity.setlogin_time(DbFacadeUtils.fromDate(rs
.getTimestamp("login_time")));
entity.setos(rs.getString("os"));
entity.setsession_id(rs.getString("session_id"));
entity.setuser_id(Guid.createGuidFromString(rs
.getString("user_id")));
return entity;
}
};
return getCallsHandler().executeReadList("GetAllFromuser_sessions", mapper, parameterSource);
}
@SuppressWarnings("unchecked")
@Override
public List<DbUser> getAll() {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource();
return getCallsHandler().executeReadList("GetAllFromUsers", new DbUserRowMapper(),
parameterSource);
}
@Override
public void save(DbUser user) {
new SimpleJdbcCall(jdbcTemplate).withProcedureName("InsertUser").execute(new DbUserMapSqlParameterSource(user));
}
@Override
public void saveSession(user_sessions session) {
if (!StringHelper.EqOp(session.getsession_id(), "")) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("browser", session.getbrowser())
.addValue("client_type", session.getclient_type())
.addValue("login_time", session.getlogin_time())
.addValue("os", session.getos())
.addValue("session_id", session.getsession_id())
.addValue("user_id", session.getuser_id());
getCallsHandler().executeModification("Insertuser_sessions", parameterSource);
}
}
@Override
public void update(DbUser user) {
getCallsHandler().executeModification("UpdateUser", new DbUserMapSqlParameterSource(user));
}
@Override
public void remove(Guid id) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("user_id", id);
getCallsHandler().executeModification("DeleteUser", parameterSource);
}
@Override
public void removeUserSession(String sessionid, Guid userid) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource()
.addValue("session_id", sessionid).addValue("user_id", userid);
new SimpleJdbcCall(jdbcTemplate).withProcedureName("Deleteuser_sessions").execute(parameterSource);
}
@Override
public void removeUserSessions(Map<String, Guid> sessionmap) {
for (Map.Entry<String, Guid> entry : sessionmap.entrySet()) {
removeUserSession(entry.getKey(), entry.getValue());
}
}
@Override
public void removeAllSessions() {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource();
new SimpleJdbcCall(jdbcTemplate).withProcedureName("DeleteAlluser_sessions").execute(parameterSource);
}
}
|
sajalguptajft/cobbzilla-wizard | wizard-server/src/main/java/org/cobbzilla/wizard/dao/AbstractChildCRUDDAO.java | package org.cobbzilla.wizard.dao;
import org.cobbzilla.wizard.model.ChildEntity;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.cobbzilla.wizard.model.Identifiable.UUID;
public abstract class AbstractChildCRUDDAO<C extends ChildEntity, P> extends AbstractDAO<C> {
@Autowired protected SessionFactory sessionFactory;
private final Class<P> parentEntityClass;
public AbstractChildCRUDDAO(Class<P> parentEntityClass) {
this.parentEntityClass = parentEntityClass;
}
@Override public C findByUuid(String uuid) {
return uniqueResult(Restrictions.eq(UUID, uuid));
}
@Override public C findByUniqueField(String field, Object value) {
return uniqueResult(Restrictions.eq(field, value));
}
public List<C> findByParentUuid(String parentUuid) {
final String queryString = "from " + getEntityClass().getSimpleName() + " x where x." + parentEntityClass.getSimpleName().toLowerCase() + ".uuid=? order by x.ctime";
return (List<C>) getHibernateTemplate().find(queryString, parentUuid);
}
public Map<String, C> mapChildrenOfParentByUuid(String parentUuid) {
return mapChildrenOfParentByUuid(findByParentUuid(parentUuid));
}
public Map<String, C> mapChildrenOfParentByUuid(List<C> recordList) {
Map<String, C> records = new HashMap<>(recordList.size());
for (C record : recordList) {
records.put(record.getUuid(), record);
}
return records;
}
private P findParentByUuid(String parentId) {
return (P) uniqueResult(criteria(parentEntityClass).add(Restrictions.eq(UUID, parentId)));
}
public C create(String parentUuid, @Valid C child) {
P parent = findParentByUuid(parentUuid);
child.setParent(checkNotNull(parent));
return create(child);
}
@Override public C create(@Valid C child) {
child.beforeCreate();
child.setUuid((String) getHibernateTemplate().save(checkNotNull(child)));
return child;
}
@Override public C update(@Valid C child) {
getHibernateTemplate().update(checkNotNull(child));
return child;
}
@Override public void delete(String uuid) {
C found = get(checkNotNull(uuid));
if (found != null) {
getHibernateTemplate().delete(found);
}
}
}
|
DevGithub007/My_Codes | 295 C Questions/61.c | <filename>295 C Questions/61.c
#include<stdio.h>
main()
{
union d
{
unsigned int a:1;
unsigned int b:2;
unsigned :0;
unsigned int d:1;
unsigned int e:0;
};
union d aa;
aa.a=1;
aa.b=5;
printf("d.aa.a=%d d.aa.b=%d",aa.a,aa.b);
}
|
MystaraCorvus/Adventurer | RagnarokMod/src/main/java/Adventurer/patches/AdventurerEnum.java | <gh_stars>0
package Adventurer.patches;
import com.evacipated.cardcrawl.modthespire.lib.SpireEnum;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
public class AdventurerEnum
{
@SpireEnum
public static AbstractPlayer.PlayerClass ADVENTURER;
@SpireEnum
public static AbstractPlayer.PlayerClass THIEF;
@SpireEnum
public static AbstractPlayer.PlayerClass ACOLYTE;
@SpireEnum
public static AbstractPlayer.PlayerClass ARCHER;
@SpireEnum
public static AbstractPlayer.PlayerClass MAGICIAN;
@SpireEnum
public static AbstractPlayer.PlayerClass MERCHANT;
@SpireEnum
public static AbstractPlayer.PlayerClass SWORDSMAN;
}
|
rudderlabs/rudder-utils | utils/config-gen/node_modules/antd/lib/_util/reactNode.js | <filename>utils/config-gen/node_modules/antd/lib/_util/reactNode.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cloneElement = cloneElement;
var React = _interopRequireWildcard(require("react"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
// eslint-disable-next-line import/prefer-default-export
function cloneElement(element) {
if (!React.isValidElement(element)) return element;
for (var _len = arguments.length, restArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
restArgs[_key - 1] = arguments[_key];
}
return React.cloneElement.apply(React, [element].concat(restArgs));
}
//# sourceMappingURL=reactNode.js.map
|
e-gineer/edgr | core/core.go | package core
import (
"encoding/csv"
"encoding/xml"
"fmt"
"log"
"net/http"
"regexp"
"time"
"github.com/piquette/edgr/core/model"
"golang.org/x/net/html/charset"
)
var (
iexSymbolsURL = "https://api.iextrading.com/1.0/ref-data/symbols?format=csv"
secCompanyURL = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=%s&start=0&count=1&output=atom"
iexCompanyURL = "https://api.iextrading.com/1.0/stock/spy/company"
dirRegex = regexp.MustCompile(`<td><a href="(.*?)"><img`)
urlRegex = regexp.MustCompile(`.*<a href="(.*?)index.html"><img`)
)
// Filer models
// -----------------
// Company is a simple struct for a single company.
type Company struct {
Name string
Symbol string
}
// rssFeed is the feed obj.
type rssFeed struct {
Info secFilerInfo `xml:"company-info"`
}
type secFilerInfo struct {
CIK string `xml:"cik"`
SIC string `xml:"assigned-sic,omitempty"`
SICDesc string `xml:"assigned-sic-desc,omitempty"`
Name string `xml:"conformed-name"`
}
// Filer methods
// -----------------
// GetPublicCompanies returns a list of public companies.
func GetPublicCompanies() ([]Company, error) {
return GetPublicCompaniesWithHeaders(map[string]string{})
}
// GetPublicCompaniesWithHeaders returns a list of public companies, adding the given HTTP headers to the request.
func GetPublicCompaniesWithHeaders(headers map[string]string) ([]Company, error) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", iexSymbolsURL, nil)
if err != nil {
return []Company{}, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return []Company{}, err
}
defer resp.Body.Close()
r := csv.NewReader(resp.Body)
r.FieldsPerRecord = -1
table, err := r.ReadAll()
result := []Company{}
for _, row := range table {
sym := row[0]
nme := row[1]
if len(sym) > 5 || nme == "" {
continue
}
result = append(result, Company{
Symbol: sym,
Name: nme,
})
}
return result, nil
}
// GetFiler gets a single filer from the SEC website based on symbol.
func GetFiler(symbol string) (filer *model.Filer, err error) {
return GetFilerWithHeaders(symbol, map[string]string{})
}
// GetFilerWithHeaders gets a single filer from the SEC website based on symbol, adding the given HTTP headers to the request.
func GetFilerWithHeaders(symbol string, headers map[string]string) (filer *model.Filer, err error) {
// get the cik for each symbol.
// tedious process...
url := fmt.Sprintf(secCompanyURL, symbol)
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
var feed rssFeed
decoder := xml.NewDecoder(resp.Body)
decoder.CharsetReader = charset.NewReaderLabel
err = decoder.Decode(&feed)
if err != nil {
return
}
if feed.Info.CIK == "" {
err = fmt.Errorf("no cik found in response data")
return
}
if feed.Info.Name == "" {
err = fmt.Errorf("no name found in response data")
return
}
return &model.Filer{
CIK: feed.Info.CIK,
Symbol: symbol,
SIC: feed.Info.SIC,
SICDescription: feed.Info.SICDesc,
Name: feed.Info.Name,
}, nil
}
// Filings models
// -----------------
// SECFiling contains a single instance of an sec filing.
type SECFiling struct {
Filing *model.Filing
Docs []*model.Document
}
// Filings methods
// -----------------
// GetFilings gets a list of filings for a single CIK.
func GetFilings(cik, formtype, stoptime string) (filings []SECFiling, err error) {
var stop *time.Time
if stoptime != "" {
t, err := time.Parse("2006-01-02", stoptime)
if err != nil {
return filings, err
}
stop = &t
}
dirPage, err := getPage("https://www.sec.gov/Archives/edgar/data/"+cik, 2)
if err != nil {
return
}
urls := findListURLs(dirPage)
for _, u := range urls {
docsPage, getErr := getPage(u, 2)
if getErr != nil {
log.Println("couldnt find page:", getErr)
continue
}
idxURL := findIdxURL(docsPage)
if idxURL == "" {
log.Println("couldnt regex idx url")
continue
}
filing, buildErr := buildFiling(cik, idxURL)
if buildErr != nil {
log.Println(buildErr)
continue
}
if formtype != "" {
// check form type.
if filing.Filing.FormType != formtype {
continue
}
}
if stop != nil {
// check cutoff time.
if filing.Filing.EdgarTime.Before(*stop) {
return
}
}
// Do stuff with the filing...
filing.Filing.AllSymbols = []string{filing.Filing.Symbol}
fmt.Println(filing)
filings = append(filings, filing)
}
return
}
|
marcio55afr/sktime | sktime/datatypes/_alignment/__init__.py | <reponame>marcio55afr/sktime
# -*- coding: utf-8 -*-
"""Module exports: Alignment type checkers and mtype inference."""
from sktime.datatypes._alignment._check import check_dict as check_dict_Alignment
from sktime.datatypes._alignment._registry import (
MTYPE_LIST_ALIGNMENT,
MTYPE_REGISTER_ALIGNMENT,
)
__all__ = [
"check_dict_Alignment",
"MTYPE_LIST_ALIGNMENT",
"MTYPE_REGISTER_ALIGNMENT",
]
|
bijeshcnair/wavemaker-app-runtime | src/main/webapp/scripts/modules/widgets/grid/datagrid.js | <reponame>bijeshcnair/wavemaker-app-runtime
/*global $, window, angular, moment, WM, _, document, parseInt, navigator*/
/*jslint todo: true*/
/**
* JQuery Datagrid widget.
*/
'use strict';
$.widget('wm.datagrid', {
options: {
data: [],
statusMsg: '',
colDefs: [],
rowActions: [],
headerConfig: [],
sortInfo: {
'field': '',
'direction': ''
},
isMobile: false,
enableSort: true,
filtermode: '',
height: '100%',
showHeader: true,
selectFirstRow: false,
showRowIndex: false,
enableRowSelection: true,
enableColumnSelection: false,
rowNgClass: '',
multiselect: false,
filterNullRecords: true,
cssClassNames: {
'tableRow' : 'app-datagrid-row',
'headerCell' : 'app-datagrid-header-cell',
'groupHeaderCell' : 'app-datagrid-group-header-cell',
'tableCell' : 'app-datagrid-cell',
'grid' : '',
'gridDefault' : 'table',
'gridBody' : 'app-datagrid-body',
'deleteRow' : 'danger',
'ascIcon' : 'wi wi-long-arrow-up',
'descIcon' : 'wi wi-long-arrow-down',
'selectedColumn' : 'selected-column'
},
dataStates: {
'loading': 'Loading...',
'ready': '',
'error': 'An error occurred in loading the data.',
'nodata': 'No data found.'
},
loadingicon: '',
startRowIndex: 1,
editmode: '',
searchHandler: WM.noop,
sortHandler: function (sortInfo, e) {
/* Local sorting if server side sort handler is not provided. */
e.stopPropagation();
var data = $.extend(true, [], this.options.data);
this._setOption('data', _.orderBy(data, sortInfo.field, sortInfo.direction));
if ($.isFunction(this.options.afterSort)) {
this.options.afterSort(e);
}
}
},
customColumnDefs: {
'checkbox': {
'field' : 'checkbox',
'type' : 'custom',
'displayName' : '',
'sortable' : false,
'searchable' : false,
'resizable' : false,
'selectable' : false,
'readonly' : true,
'style' : 'width: 50px; text-align: center;',
'textAlignment' : 'center',
'isMultiSelectCol' : true,
'show' : true
},
'radio': {
'field' : 'radio',
'type' : 'custom',
'displayName' : '',
'sortable' : false,
'searchable' : false,
'resizable' : false,
'selectable' : false,
'readonly' : true,
'style' : 'width: 50px; text-align: center;',
'textAlignment' : 'center',
'show' : true
},
'rowIndex': {
'field' : 'rowIndex',
'type' : 'custom',
'displayName' : 'S. No.',
'sortable' : false,
'searchable' : false,
'selectable' : false,
'readonly' : true,
'style' : 'text-align: left;',
'textAlignment' : 'left',
'show' : true
}
},
CONSTANTS: {
'QUICK_EDIT' : 'quickedit',
'INLINE' : 'inline',
'FORM' : 'form',
'DIALOG' : 'dialog',
'SEARCH' : 'search',
'MULTI_COLUMN' : 'multicolumn'
},
Utils: {
random: function () {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
},
isDefined: function (value) {
return value !== undefined;
},
isObject: function (value) {
return value !== null && typeof value === 'object';
},
getObjectIndex: function (data, obj) {
var matchIndex = -1;
if (!Array.isArray(data)) {
return -1;
}
data.some(function (data, index) {
//todo: remove angular dependency.
if (angular.equals(data, obj)) {
matchIndex = index;
return true;
}
});
return matchIndex;
},
generateGuid: function () {
var random = this.random;
return random() + random() + '-' + random() + '-' + random() + '-' +
random() + '-' + random() + random() + random();
},
isValidHtml: function (htm) {
var validHtmlRegex = /<[a-z][\s\S]*>/i;
return validHtmlRegex.test(htm);
},
isMac: function () {
return navigator.platform.toUpperCase().indexOf('MAC') >= 0;
},
isDeleteKey: function (event) {
return (this.isMac() && event.which === 8) || event.which === 46;
}
},
_getColumnSortDirection: function (field) {
var sortInfo = this.options.sortInfo;
return field === sortInfo.field ? sortInfo.direction : '';
},
/*Based on the spacing property, add or remove classes*/
_toggleSpacingClasses: function (value) {
switch (value) {
case 'normal':
this.gridElement.removeClass('table-condensed');
this.gridHeaderElement.removeClass('table-condensed');
if (this.gridSearch) {
this.gridSearch.find('.form-group').removeClass('form-group-sm');
this.gridSearch.find('select').removeClass('input-sm');
this.gridSearch.find('.input-group').removeClass('input-group-sm');
}
break;
case 'condensed':
this.gridElement.addClass('table-condensed');
this.gridHeaderElement.addClass('table-condensed');
if (this.gridSearch) {
this.gridSearch.find('.form-group').addClass('form-group-sm');
this.gridSearch.find('select').addClass('input-sm');
this.gridSearch.find('.input-group').addClass('input-group-sm');
}
break;
}
},
//Method to calculate and get the column span of the header cells
_getColSpan: function (cols) {
var colSpan = 0,
self = this;
_.forEach(cols, function (col) {
var colDef;
if (col.isGroup) {
colSpan += self._getColSpan(col.columns);
} else {
colDef = _.find(self.preparedHeaderData, {'field': col.field});
//If show is false, don't increment the col span
colSpan = (!_.isUndefined(colDef.show) && !colDef.show) ? colSpan : colSpan + 1;
}
});
return colSpan;
},
//Method to set the column span of the header cells in the config
_setColSpan: function (config) {
var self = this;
_.forEach(config, function (col) {
if (col.isGroup) {
col.colspan = self._getColSpan(col.columns);
self.gridHeaderElement.find('th[data-col-group="' + col.field + '"]').attr('colspan', col.colspan);
self._setColSpan(col.columns);
}
});
},
/* Returns the table header template. */
_getHeaderTemplate: function () {
var $colgroup = $('<colgroup></colgroup>'),
$htm = $('<thead></thead>'),
isDefined = this.Utils.isDefined,
sortInfo = this.options.sortInfo,
sortField = sortInfo.field,
self = this,
rowTemplates = [],
headerConfig = this.options.headerConfig,
headerGroupClass = self.options.cssClassNames.groupHeaderCell,
$row;
function generateHeaderCell(value, index) {
var id = index,
field = value.field,
headerLabel = WM.isDefined(value.displayName) ? value.displayName : (field || ''),
titleLabel = headerLabel,
sortEnabled = self.options.enableSort && (_.isUndefined(value.show) || value.show) && (_.isUndefined(value.sortable) || value.sortable) && !value.widgetType,
headerClasses = self.options.cssClassNames.headerCell,
sortClass,
tl = '',
$th,
$col,
$sortSpan,
$sortIcon;
headerLabel = (!WM.isDefined(headerLabel) || headerLabel === '') ? ' ' : headerLabel; //If headername is empty, add an empty space
$col = $('<col/>');
if (value.style) {
$col.attr('style', value.style);
}
$colgroup.append($col);
/* thead */
if (isDefined(value.class)) {
headerClasses += ' ' + value.class;
}
if (value.selected) {
headerClasses += ' ' + self.options.cssClassNames.selectedColumn + ' ';
}
if (field === 'checkbox' || field === 'radio') {
headerClasses += ' grid-col-small';
}
tl += '<th';
if ((_.isUndefined(value.resizable) || value.resizable) && (_.isUndefined(value.show) || value.show)) { //If show is false, do not add the resize option
tl += ' data-col-resizable';
}
if (self.options.enableColumnSelection && (_.isUndefined(value.selectable) || value.selectable)) {
tl += ' data-col-selectable';
}
if (sortEnabled) {
tl += ' data-col-sortable';
}
tl += '></th>';
$th = $(tl);
$th.attr({
'data-col-id' : id,
'data-col-field' : field,
'title' : titleLabel,
'style' : 'text-align: ' + value.textAlignment
});
$th.addClass(headerClasses);
/* For custom columns, show display name if provided, else don't show any label. */
if (field === 'checkbox') {
$th.append('<input type="checkbox" />');
}
$th.append('<span class="header-data">' + headerLabel + '</span>');
if (sortEnabled) { //If sort info is present, show the sort icon for that column on grid render
$sortSpan = $('<span class="sort-buttons-container"></span>');
$sortIcon = $('<i class="sort-icon"></i>');
if (sortField && sortField === value.field && sortInfo.direction) {
sortClass = sortInfo.direction === 'asc' ? self.options.cssClassNames.ascIcon : self.options.cssClassNames.descIcon;
$sortSpan.addClass('active');
$sortIcon.addClass(sortClass + ' ' + sortInfo.direction);
}
$th.append($sortSpan.append($sortIcon));
}
return $th.get(0).outerHTML;
}
//Method to generate the header row based on the column group config
function generateRow(cols, i) {
var tl = '';
_.forEach(cols, function (col) {
var index,
value,
classes,
styles,
$groupTl;
if (col.columns && col.columns.length) {
//If columns is present, this is a group header cell.
$groupTl = $('<th></th>');
classes = headerGroupClass + ' ' + (col.class || '');
styles = 'text-align: ' + col.textAlignment + ';background-color: ' + (col.backgroundColor || '') + ';';
$groupTl.attr({
'data-col-group' : col.field,
'class' : classes,
'style' : styles,
'title' : col.displayName
});
$groupTl.append('<span class="header-data">' + col.displayName + '</span>');
tl += $groupTl.get(0).outerHTML;
generateRow(col.columns, (i + 1));
} else {
//For non group cells, fetch the relative field definition and generate the template
index = _.findIndex(self.preparedHeaderData, {'field': col.field});
value = self.preparedHeaderData[index];
if (value) {
tl += generateHeaderCell(value, index);
}
}
});
rowTemplates[i] = rowTemplates[i] || '';
rowTemplates[i] += tl;
}
//If header config is not present, this is a dynamic grid. Generate headers directly from field defs
if (_.isEmpty(headerConfig)) {
$row = $('<tr></tr>');
self.preparedHeaderData.forEach(function (value, index) {
$row.append(generateHeaderCell(value, index));
});
$htm.append($row);
} else {
generateRow(headerConfig, 0);
//Combine all the row templates to generate the header
$htm.append(_.reduce(rowTemplates, function (template, rowTl, index) {
var $rowTl = $(rowTl),
tl = '',
rowSpan = rowTemplates.length - index;
if (rowSpan > 1) {
$rowTl.closest('th.app-datagrid-header-cell').attr('rowspan', rowSpan);
}
$rowTl.each(function () {
tl += $(this).get(0).outerHTML;
});
return template + '<tr>' + tl + '</tr>';
}, ''));
}
return { 'colgroup' : $colgroup, 'header' : $htm };
},
/* Returns the seachbox template. */
_getSearchTemplate: function () {
var htm,
sel = '<select name="wm-datagrid" data-element="dgFilterValue" ' +
'class="form-control app-select">' +
'<option value="" selected>Select Field</option>',
searchLabel = (this.Utils.isDefined(this.options.searchLabel) &&
this.options.searchLabel.length) ? this.options.searchLabel : 'Search:';
this.options.colDefs.forEach(function (colDef, index) {
if (colDef.field !== 'none' && colDef.field !== 'rowOperations' && colDef.searchable) {
sel += '<option value="' + colDef.field +
'" data-coldef-index="' + index + '">' +
(colDef.displayName || colDef.field) + '</option>';
}
});
sel += '</select>';
htm =
'<form class="form-search form-inline" onsubmit="return false;"><div class="form-group">' +
'<input type="text" data-element="dgSearchText" class="form-control app-textbox" value="" placeholder="' + searchLabel + '" style="display: inline-block;"/>' +
'</div><div class="input-append input-group">' +
sel +
'<span class="input-group-addon"><button type="button" data-element="dgSearchButton" class="app-search-button" title="Search">' +
'<i class="wi wi-search"></i>' +
'</button></span>' +
'</div>' +
'</div></form>';
return htm;
},
/* Returns the tbody markup. */
_getGridTemplate: function () {
var self = this,
$tbody = $('<tbody class="' + this.options.cssClassNames.gridBody + '"></tbody>');
_.forEach(this.preparedData, function (row) {
$tbody.append(self._getRowTemplate(row));
});
return $tbody;
},
/* Returns the table row template. */
_getRowTemplate: function (row) {
var htm,
self = this,
gridOptions = self.options,
rowNgClass = gridOptions.rowNgClass,
rowNgClassExpr = rowNgClass ? 'ng-class="' + rowNgClass + '"' : '';
htm = this.preparedHeaderData.reduce(function (prev, current, colIndex) {
return prev + self._getColumnTemplate(row, colIndex, current);
}, '<tr tabindex="0" class="' + gridOptions.cssClassNames.tableRow + ' ' + (gridOptions.rowClass || '') + '" data-row-id="' + row.pk + '" ' + rowNgClassExpr + '>');
htm += '</tr>';
if (rowNgClass) {
return gridOptions.getCompiledTemplate(htm, row);
}
return htm;
},
_getRowActionsColumnDefIndex: function () {
var i, len = this.preparedHeaderData.length;
for (i = 0; i < len; i += 1) {
if (this.preparedHeaderData[i].field === 'rowOperations') {
return i;
}
}
return -1;
},
_getRowActionsColumnDef: function () {
var index = this._getRowActionsColumnDefIndex();
if (index !== -1) {
return this.preparedHeaderData[index];
}
return null;
},
/* Returns the checkbox template. */
_getCheckboxTemplate: function (row, isMultiSelectCol) {
var checked = row.checked ? ' checked' : '',
disabled = row.disabed ? ' disabled' : '',
chkBoxName = isMultiSelectCol ? 'gridMultiSelect' : '';
return '<input name="' + chkBoxName + '" type="checkbox"' + checked + disabled + '/>';
},
/* Returns the radio template. */
_getRadioTemplate: function (row) {
var checked = row.checked ? ' checked' : '',
disabled = row.disabed ? ' disabled' : '';
return '<input type="radio" name="" value=""' + checked + disabled + '/>';
},
/* Returns the table cell template. */
_getColumnTemplate: function (row, colId, colDef) {
var classes = this.options.cssClassNames.tableCell + ' ' + (colDef.class || ''),
ngClass = colDef.ngclass || '',
htm = '<td class="' + classes + '" data-col-id="' + colId + '" style="text-align: ' + colDef.textAlignment + ';"',
colExpression = colDef.customExpression,
ctId = row.pk + '-' + colId,
value,
isCellCompiled = false,
columnValue;
if (colDef.field) {
//setting the default value
columnValue = row[colDef.field];
}
value = _.get(row, colDef.field);
if (value) {
columnValue = value;
}
if (ngClass) {
isCellCompiled = true;
}
if (!colDef.formatpattern) {
if (colDef.type === 'date' && this.options.dateFormat) {
colDef.formatpattern = 'toDate';
colDef.datepattern = this.options.dateFormat;
} else if (colDef.type === 'time' && this.options.timeFormat) {
colDef.formatpattern = 'toDate';
colDef.datepattern = this.options.timeFormat;
} else if (colDef.type === 'datetime' && this.options.dateTimeFormat) {
colDef.formatpattern = 'toDate';
colDef.datepattern = this.options.dateTimeFormat;
}
}
/*constructing the expression based on the choosen format options*/
if (colDef.formatpattern && colDef.formatpattern !== "None" && !colExpression) {
switch (colDef.formatpattern) {
case 'toDate':
if (colDef.datepattern) {
if (colDef.type === 'datetime') {
columnValue = columnValue ? moment(columnValue).valueOf() : undefined;
}
colExpression = "{{'" + columnValue + "' | toDate:'" + colDef.datepattern + "'}}";
}
break;
case 'toCurrency':
if (colDef.currencypattern) {
colExpression = "{{'" + columnValue + "' | toCurrency:'" + colDef.currencypattern;
if (colDef.fractionsize) {
colExpression += "':'" + colDef.fractionsize + "'}}";
} else {
colExpression += "'}}";
}
}
break;
case 'numberToString':
if (colDef.fractionsize) {
colExpression = "{{'" + columnValue + "' | numberToString:'" + colDef.fractionsize + "'}}";
}
break;
case 'stringToNumber':
colExpression = "{{'" + columnValue + "' | stringToNumber}}";
break;
case 'timeFromNow':
colExpression = "{{'" + columnValue + "' | timeFromNow}}";
break;
case 'prefix':
if (colDef.prefix) {
colExpression = "{{'" + columnValue + "' | prefix:'" + colDef.prefix + "'}}";
}
break;
case 'suffix':
if (colDef.suffix) {
colExpression = "{{'" + columnValue + "' | suffix:'" + colDef.suffix + "'}}";
}
break;
}
htm += 'title="' + colExpression + '"';
}
if (colExpression) {
if (isCellCompiled) {
htm += '>';
} else {
htm += 'data-compiled-template="' + ctId + '">';
isCellCompiled = true;
}
htm += colExpression;
} else {
if (colDef.type !== 'custom') {
columnValue = row[colDef.field];
/* 1. Show "null" values as null if filterNullRecords is true, else show empty string.
* 2. Show "undefined" values as empty string. */
if ((this.options.filterNullRecords && columnValue === null) ||
_.isUndefined(columnValue)) {
columnValue = '';
}
htm += 'title="' + columnValue + '">';
htm += columnValue;
} else {
htm += '>';
switch (colDef.field) {
case 'checkbox':
htm += this._getCheckboxTemplate(row, colDef.isMultiSelectCol);
break;
case 'radio':
htm += this._getRadioTemplate(row);
break;
case 'rowOperations':
htm += '<span class="actions-column" data-identifier="actionButtons"></span>';
break;
case 'rowIndex':
htm += row.index;
break;
case 'none':
htm += '';
break;
default:
htm += (_.isUndefined(columnValue) || columnValue === null) ? '' : columnValue;
}
}
}
htm += '</td>';
if (ngClass) {
htm = $(htm).attr({
'data-ng-class': ngClass,
'data-compiled-template': ctId
})[0].outerHTML;
}
if (isCellCompiled) {
this.compiledCellTemplates[ctId] = this.options.getCompiledTemplate(htm, row, colDef, true) || '';
}
return htm;
},
//Get event related template for editable widget
_getEventTemplate: function (colDef) {
var events = _.filter(_.keys(colDef), function (key) {return _.startsWith(key, 'on'); }),
template = '';
_.forEach(events, function (eventName) {
template += ' ' + _.kebabCase(eventName) + '="' + colDef[eventName] + '" ';
});
return template;
},
_getEditableTemplate: function ($el, colDef, cellText, rowId, operation) {
var template,
formName,
checkedTmpl,
placeholder = _.isUndefined(colDef.placeholder) ? '' : colDef.placeholder,
dataValue = (WM.isDefined(cellText) && cellText !== null) ? cellText : undefined,
eventTemplate = this._getEventTemplate(colDef),
dataFieldName = ' data-field-name="' + colDef.field + '" ',
disabled = (operation !== 'new' && colDef.primaryKey && colDef.generator === 'assigned') ? true : colDef.disabled,//In edit mode, set disabled for assigned columns
disabledTl = disabled ? ' disabled="' + disabled + '" ' : '',
required = colDef.required ? ' required="' + colDef.required + '" ' : '',
properties = disabledTl + dataFieldName + eventTemplate + required,
index = colDef.index;
switch (colDef.editWidgetType) {
case 'select':
cellText = cellText || '';
template = '<wm-select ' + properties + (colDef.isDefinedData ? ' scopedataset="fullFieldDefs[' + index + '].dataset"' : 'dataset="' + colDef.dataset + '"') + ' datafield="' + colDef.datafield + '" displayfield="' + colDef.displayfield + '" placeholder="' + placeholder + '"></wm-select>';
break;
case 'autocomplete':
case 'typeahead':
$el.addClass('datetime-wrapper');
template = '<wm-search ' + properties + ' dataset="' + colDef.dataset + '" datafield="' + colDef.datafield + '" displaylabel="' + colDef.displaylabel + '" searchkey="' + colDef.searchkey + '" ' + (colDef.relatedfield ? ' relatedfield="' + colDef.relatedfield + '"' : '') + ' type="autocomplete" placeholder="' + placeholder + '"></wm-select>';
break;
case 'date':
$el.addClass('datetime-wrapper');
template = '<wm-date ' + properties + ' placeholder="' + placeholder + '"></wm-date>';
break;
case 'time':
$el.addClass('datetime-wrapper');
template = '<wm-time ' + properties + ' placeholder="' + placeholder + '"></wm-time>';
break;
case 'datetime':
$el.addClass('datetime-wrapper');
template = '<wm-datetime ' + properties + ' outputformat="yyyy-MM-ddTHH:mm:ss" placeholder="' + placeholder + '"></wm-datetime>';
break;
case 'timestamp':
$el.addClass('datetime-wrapper');
template = '<wm-datetime ' + properties + ' placeholder="' + placeholder + '"></wm-datetime>';
break;
case 'checkbox':
checkedTmpl = colDef.checkedvalue ? ' checkedvalue="' + colDef.checkedvalue + '" ' : '';
checkedTmpl += colDef.uncheckedvalue ? ' uncheckedvalue="' + colDef.uncheckedvalue + '" ' : '';
template = '<wm-checkbox ' + checkedTmpl + properties + '></wm-checkbox>';
break;
case 'number':
template = '<wm-text type="number" ' + properties + ' placeholder="' + placeholder + '"></wm-text>';
break;
case 'textarea':
cellText = cellText || '';
template = '<wm-textarea ' + properties + ' placeholder="' + placeholder + '"></wm-textarea>';
break;
case 'upload':
formName = colDef.field + '_' + rowId;
$el.attr('form-name', formName);
template = '<form name="' + formName + '"><input focus-target' + dataFieldName + 'class="file-upload" type="file" name="' + colDef.field + '"/></form>';
break;
default:
template = '<wm-text ' + properties + ' placeholder="' + placeholder + '"></wm-text>';
break;
}
if (WM.isDefined(dataValue)) {
template = $(template);
template.attr('datavalue', dataValue);
}
$el.addClass(colDef.editWidgetType + '-widget');
return this.options.getCompiledTemplate(template, this.preparedData[rowId] || {}, colDef);
},
setHeaderConfigForDefaultFields: function (name) {
if (_.isEmpty(this.options.headerConfig)) {
return;
}
var fieldName = this.customColumnDefs[name].field;
_.remove(this.options.headerConfig, {'field': fieldName});
this.options.headerConfig.unshift({'field': fieldName, 'isPredefined': true});
},
setDefaultColsData: function (header) {
//If columns are not present, do not add the default columns
if (_.isEmpty(this.preparedHeaderData)) {
return;
}
if (this.options.showRowIndex) {
if (header) {
this.preparedHeaderData.unshift(this.customColumnDefs.rowIndex);
}
this.setHeaderConfigForDefaultFields('rowIndex');
}
if (this.options.multiselect) {
if (header) {
this.preparedHeaderData.unshift(this.customColumnDefs.checkbox);
}
this.setHeaderConfigForDefaultFields('checkbox');
}
if (!this.options.multiselect && this.options.showRadioColumn) {
if (header) {
this.preparedHeaderData.unshift(this.customColumnDefs.radio);
}
this.setHeaderConfigForDefaultFields('radio');
}
},
/* Prepares the grid header data by adding custom column definitions if needed. */
_prepareHeaderData: function () {
this.preparedHeaderData = [];
$.extend(this.preparedHeaderData, this.options.colDefs);
this.setDefaultColsData(true);
},
/* Generates default column definitions from given data. */
_generateCustomColDefs: function () {
var colDefs = [],
generatedColDefs = {};
function generateColumnDef(key) {
if (!generatedColDefs[key]) {
var colDef = {
'type': 'string',
'field': key
};
colDefs.push(colDef);
generatedColDefs[key] = true;
}
}
this.options.data.forEach(function (item) {
_.keys(item).forEach(generateColumnDef);
});
this.options.colDefs = colDefs;
this._prepareHeaderData();
},
/* Prepares the grid data by adding a primary key to each row's data. */
_prepareData: function () {
var data = [],
colDefs = this.options.colDefs,
self = this,
isObject = this.Utils.isObject,
isDefined = this.Utils.isDefined;
if (!this.options.colDefs.length && this.options.data.length) {
this._generateCustomColDefs();
}
this.options.data.forEach(function (item, i) {
var rowData = $.extend(true, {}, item);
colDefs.forEach(function (colDef) {
if (!colDef.field) {
return;
}
var fields = colDef.field.split('.'),
text = item,
j,
len = fields.length,
key,
isArray;
for (j = 0; j < len; j++) {
key = fields[j];
isArray = undefined;
if (key.indexOf('[0]') !== -1) {
key = key.replace('[0]', '');
isArray = true;
}
if (isObject(text) && !isArray) {
text = _.get(text, key);
} else if (isArray) {
text = _.get(text, key + '[0]');
} else {
text = undefined;
break;
}
}
if (isDefined(text)) {
rowData[colDef.field] = text;
} else if (fields.length > 1 && _.has(item, colDef.field)) {
/* For case when coldef field name has ".", but data is in
* format [{'foo.bar': 'test'}], i.e. when the key value is
* not a nested object but a primitive value.
* (Ideally if coldef name has ".", for e.g. field name 'foo.bar',
* data should be [{'foo': {'bar': 'test'}})*/
rowData[colDef.field] = item[colDef.field];
}
});
/* Add a unique identifier for each row. */
rowData.index = self.options.startRowIndex + i;
rowData.pk = i;
data.push(rowData);
});
this.preparedData = data;
},
/* Select previously selected columns after refreshing grid data. */
_reselectColumns: function () {
var selectedColumns = [],
self = this;
//If enableColumnSelection is set to true, reselect the columns on data refresh
if (this.gridHeader && this.options.enableColumnSelection) {
selectedColumns = this.gridHeader.find('th.' + this.options.cssClassNames.selectedColumn);
//Call the column selection handler on each of the selected columns
if (selectedColumns.length) {
selectedColumns.each(function () {
self.columnSelectionHandler(undefined, $(this));
});
}
}
//reset select all checkbox.
if (this.options.multiselect) {
this.updateSelectAllCheckboxState();
}
},
/* Initializes the grid. */
_create: function () {
// Add all instance specific values here.
$.extend(this, {
dataStatus: {
'message': '',
'state': ''
},
preparedData: [],
preparedHeaderData: [],
dataStatusContainer: null,
gridContainer: null,
gridElement: null,
gridHeader: null,
gridBody: null,
gridSearch: null,
tableId: null,
searchObj: {
'field': '',
'value': '',
'event': null
},
compiledCellTemplates: {}
});
this._setStatus = _.debounce(function () {
this.__setStatus();
}, 100);
this._prepareHeaderData();
this._prepareData();
this._render();
},
_setGridEditMode: function (val) {
if ($.isFunction(this.options.setGridEditMode)) {
this.options.setGridEditMode(val);
}
},
/* Re-renders the whole grid. */
_refreshGrid: function () {
this._prepareHeaderData();
this._prepareData();
this._render();
this.addOrRemoveScroll();
this._setGridEditMode(false);
},
refreshGrid: function () {
window.clearTimeout(this.refreshGridTimeout);
this.refreshGridTimeout = window.setTimeout(this._refreshGrid.bind(this), 50);
},
/* Re-renders the table body. */
refreshGridData: function () {
this._prepareData();
this.gridBody.remove();
this._renderGrid();
this._reselectColumns();
this.addOrRemoveScroll();
this._setGridEditMode(false);
},
/* Inserts a new blank row in the table. */
addNewRow: function (skipFocus) {
var rowId = this.gridBody.find('tr:visible').length,
rowData = {},
$row;
if ($.isFunction(this.options.beforeRowInsert)) {
this.options.beforeRowInsert();
}
rowData.index = this.options.startRowIndex + rowId;
rowData.pk = rowId;
if (this.options.editmode !== this.CONSTANTS.FORM && this.options.editmode !== this.CONSTANTS.DIALOG) {
$row = $(this._getRowTemplate(rowData));
if (!this.preparedData.length) {
this.setStatus('ready', this.dataStatus.ready);
}
this.gridElement.find('tbody.app-datagrid-body').append($row);
this._appendRowActions($row, true, rowData);
this.attachEventHandlers($row);
this._findAndReplaceCompiledTemplates();
$row.trigger('click', [undefined, {action: 'edit', operation: 'new', skipFocus: skipFocus}]);
this.updateSelectAllCheckboxState();
this.addOrRemoveScroll();
this.setColGroupWidths();
}
},
/* Returns the selected rows in the table. */
getSelectedRows: function () {
this.getSelectedColumns();
var selectedRowsData = [],
self = this;
this.preparedData.forEach(function (data, i) {
if (data.selected) {
selectedRowsData.push(self.options.data[i]);
}
});
return selectedRowsData;
},
/* Sets the selected rows in the table. */
selectRows: function (rows) {
var self = this;
/*Deselect all the previous selected rows in the table*/
self.gridBody.find('tr').each(function (index) {
if (self.preparedData[index].selected) {
$(this).trigger('click', [$(this), {skipSingleCheck: true}]);
}
});
/*Select the given row. If rows is an array, loop through the array and set the row*/
if (_.isArray(rows)) {
_.forEach(rows, function (row) {
self.selectRow(row, true);
});
} else {
self.selectRow(rows, true);
}
},
/*Set the default widths for the colgroup*/
setColGroupWidths : function () {
var self = this,
headerCols = this.options.isMobile ? this.gridElement.find('col') : this.gridHeaderElement.find('col'),
bodyCols = this.gridElement.find('col'),
headerCells = this.options.showHeader ? this.gridContainer.find('th.app-datagrid-header-cell') : this.gridElement.find('tr.app-datagrid-row:first td'),
colLength = this.preparedHeaderData.length,
scrollLeft = this.gridElement.parent().prop('scrollLeft'); //Preserve the scroll left to keep the same scroll after setting width
if (!headerCols.length && !headerCells.length) {
return;
}
//Set the col spans for the header groups
this._setColSpan(this.options.headerConfig);
//First Hide or show the column based on the show property so that width is calculated correctly
headerCells.each(function () {
var id = Number($(this).attr('data-col-id')),
colDef = self.preparedHeaderData[id],
$headerCell = self.gridContainer.find('th[data-col-id="' + id + '"]'),
$tdCell = self.gridElement.find('td.app-datagrid-cell[data-col-id="' + id + '"]'),
definedWidth = colDef.width,
$headerCol = $(headerCols[id]),
$bodyCol = $(bodyCols[id]),
width;
if (!_.isUndefined(colDef.show) && !colDef.show) { //If show is false, set width to 0 to hide the column
//Hide the header and column if show is false
$headerCell.hide();
$tdCell.hide();
$headerCol.hide();
$bodyCol.hide();
} else {
$headerCell.show();
$tdCell.show();
$headerCol.show();
$bodyCol.show();
}
//If default width is set, reset the width so that correct width is set on reload
if ($headerCol.length && $headerCol[0].style.width === '90px') {
width = _.isUndefined(definedWidth) ? '' : definedWidth;
$headerCol.css('width', width);
$bodyCol.css('width', width);
}
});
//setting the header col width based on the content width
headerCells.each(function () {
var $header = $(this),
id = Number($header.attr('data-col-id')),
colDef = self.preparedHeaderData[id],
definedWidth = colDef.width,
width,
tempWidth,
$headerCol;
if (!_.isUndefined(colDef.show) && !colDef.show) { //If show is false, set width to 0 to hide the column
//Hide the header and column if show is false
width = 0;
} else {
if ($header.hasClass('grid-col-small')) { //For checkbox or radio, set width as 30
width = 50;
} else {
if (_.isUndefined(definedWidth) || definedWidth === '' || _.includes(definedWidth, '%')) {
$headerCol = $(headerCols[id]);
if ($headerCol.length) {
tempWidth = $headerCol[0].style.width;
if (tempWidth === '' || tempWidth === '0px' || tempWidth === '90px' || _.includes(tempWidth, '%')) { //If width is not 0px, width is already set. So, set the same width again
width = $header.width();
width = width > 90 ? ((colLength === id + 1) ? width - 17 : width) : 90; //columnSanity check to prevent width being too small and Last column, adjust for the scroll width
} else {
width = tempWidth;
}
}
} else {
width = definedWidth;
}
}
}
$(headerCols[id]).css('width', width);
$(bodyCols[id]).css('width', width);
});
this.gridElement.parent().prop('scrollLeft', scrollLeft);
},
/* Returns the selected columns in the table. */
getSelectedColumns: function () {
var selectedColsData = {},
headerData = [],
self = this,
multiSelectColIndex,
radioColIndex,
colIndex;
$.extend(headerData, this.preparedHeaderData);
if (this.options.multiselect) {
headerData.some(function (item, i) {
if (item.field === 'checkbox') {
multiSelectColIndex = i;
return true;
}
});
headerData.splice(multiSelectColIndex, 1);
} else if (this.options.showRadioColumn) {
headerData.some(function (item, i) {
if (item.field === 'radio') {
radioColIndex = i;
return true;
}
});
headerData.splice(radioColIndex, 1);
}
if (this.options.showRowIndex) {
headerData.some(function (item, i) {
if (item.field === 'rowIndex') {
colIndex = i;
return true;
}
});
headerData.splice(colIndex, 1);
}
headerData.forEach(function (colDef) {
var field = colDef.field;
if (colDef.selected) {
selectedColsData[field] = {
'colDef': colDef,
'colData': self.options.data.map(function (data) { return data[field]; })
};
}
});
return selectedColsData;
},
/* Sets the options for the grid. */
_setOption: function (key, value) {
this._super(key, value);
switch (key) {
case 'showHeader':
this._toggleHeader();
this._toggleSearch();
this.setColGroupWidths();
this.addOrRemoveScroll();
break;
case 'filtermode':
this._toggleSearch();
break;
case 'searchLabel':
if (this.gridSearch) {
this.gridSearch.find(
'[data-element="dgSearchText"]'
).attr('placeholder', value);
}
break;
case 'rowngclass':
case 'rowclass':
this.refreshGrid();
break;
case 'selectFirstRow':
this.selectFirstRow(value);
break;
case 'data':
this.refreshGridData();
break;
case 'dataStates':
if (this.dataStatus.state === 'nodata') {
this.setStatus('nodata', this.dataStatus.nodata);
} else if (this.dataStatus.state === 'loading') {
this.setStatus('loading');
}
break;
case 'loadingicon':
this.dataStatusContainer.find('i').removeClass().addClass(this.options.loadingicon);
break;
case 'multiselect': // Fallthrough
case 'showRadioColumn':
case 'colDefs':
case 'rowActions':
case 'filterNullRecords':
case 'showRowIndex':
this.refreshGrid();
break;
case 'cssClassNames':
var gridClass = this.options.cssClassNames.gridDefault + ' ' + this.options.cssClassNames.grid;
// Set grid class on table.
this.gridElement.attr('class', gridClass);
this.gridHeaderElement.attr('class', gridClass);
if (this.options.spacing === 'condensed') {
this._toggleSpacingClasses('condensed');
}
break;
case 'spacing':
this._toggleSpacingClasses(value);
break;
}
},
getOptions: function () {
return this.options;
},
/* Toggles the table header visibility. */
_toggleHeader: function () {
if (this.gridHeaderElement) {
this.gridHeaderElement.empty();
}
if (this.gridElement) {
this.gridElement.find('colgroup').remove();
this.gridElement.find('thead').remove();
}
this.setDefaultColsData();
if (this.options.showHeader) {
this._renderHeader();
}
},
/* Toggles the searchbox visibility. */
_toggleSearch: function () {
if (this.gridSearch) {
this.gridSearch.remove();
}
if (this.options.filtermode === this.CONSTANTS.SEARCH) {
this._renderSearch();
} else if (this.options.filtermode === this.CONSTANTS.MULTI_COLUMN) {
this._renderRowFilter();
this.setColGroupWidths();
}
},
_isCustomExpressionNonEditable: function (customTag, $el) {
var $input;
if (!customTag) {
return false;
}
//Check if expression is provided for custom tag.
if (_.includes(customTag, '{{') && _.includes(customTag, '}}')) {
//If user gives an invalid expression, return false
try {
if ($($el.html()).length) {
return true;
}
} catch (e) {
return false;
}
return false;
}
$input = $(customTag);
if ($input.length) { //If expression is html, return true
return true;
}
return false;
},
/* Marks the first row as selected. */
selectFirstRow: function (value, visible) {
var $row,
id;
//If visible flag is true, select the first visible row item
if (visible) {
this.__setStatus();
$row = this.gridElement.find('tBody tr:visible:first');
} else {
$row = this.gridElement.find('tBody tr:first');
}
id = $row.attr('data-row-id');
// Select the first row if it exists, i.e. it is not the first row being added.
if ($row.length && this.preparedData.length) {
this.preparedData[id].selected = !value;
$row.trigger('click');
}
},
/* Selects a row. */
selectRow: function (row, value) {
var rowIndex = angular.isNumber(row) ? row : this.Utils.getObjectIndex(this.options.data, row),
selector,
$row;
if (rowIndex !== -1) {
selector = 'tr[data-row-id=' + rowIndex + ']';
$row = this.gridBody.find(selector);
if ($row.length) {
this.preparedData[rowIndex].selected = !value;
}
$row.trigger('click');
}
},
/**
* deselect a row
*/
deselectRow: function (row) {
this.selectRow(row, false);
},
/* Toggles the table row selection. */
toggleRowSelection: function ($row, selected) {
if (!$row.length) {
return;
}
var rowId = $row.attr('data-row-id'),
$checkbox,
$radio;
if (!this.preparedData[rowId]) {
return;
}
this.preparedData[rowId].selected = selected;
if (selected) {
$row.addClass('active');
} else {
$row.removeClass('active');
}
if (this.options.showRadioColumn) {
$radio = $row.find('td input:radio:not(:disabled)');
$radio.prop('checked', selected);
this.preparedData[rowId].checked = selected;
}
if (this.options.multiselect) {
$checkbox = $row.find('td input[name="gridMultiSelect"]:checkbox:not(:disabled)');
$checkbox.prop('checked', selected);
this.preparedData[rowId].checked = selected;
this.updateSelectAllCheckboxState();
} else {
this._deselectPreviousSelection($row);
}
},
/* Checks the header checkbox if all table checkboxes are checked, else unchecks it. */
updateSelectAllCheckboxState: function () {
if (!this.options.showHeader) {
return;
}
//As rows visibility is checked, remove loading icon
this.__setStatus();
var $headerCheckbox = this.gridHeader.find('th.app-datagrid-header-cell input:checkbox'),
$tbody = this.gridElement.find('tbody'),
checkedItemsLength = $tbody.find('tr:visible input[name="gridMultiSelect"]:checkbox:checked').length,
visibleRowsLength = $tbody.find('tr:visible').length;
if (!visibleRowsLength) {
$headerCheckbox.prop('checked', false);
return;
}
if (checkedItemsLength === visibleRowsLength) {
$headerCheckbox.prop('checked', true);
} else {
$headerCheckbox.prop('checked', false);
}
},
/* Handles row selection. */
rowSelectionHandler: function (e, $row, options) {
options = options || {};
e.stopPropagation();
var rowId,
rowData,
data,
selected,
self = this,
action = options.action,
isQuickEdit = this.options.editmode === this.CONSTANTS.QUICK_EDIT;
function callRowSelectionEvents() {
if (selected && $.isFunction(self.options.onRowSelect)) {
self.options.onRowSelect(data, e);
}
if (!selected && $.isFunction(self.options.onRowDeselect)) {
self.options.onRowDeselect(data, e);
}
}
if (action || (isQuickEdit && $(e.target).hasClass('app-datagrid-cell'))) {
//In case of advanced edit, Edit the row on click of a row
options.action = options.action || 'edit';
this.toggleEditRow(e, options);
if (options.skipSelect) {
return;
}
}
$row = $row || $(e.target).closest('tr');
rowId = $row.attr('data-row-id');
rowData = this.preparedData[rowId];
data = this.options.data[rowId];
selected = (rowData && rowData.selected) || false;
if (!options.skipSingleCheck && (($row.hasClass('active') && !this.options.multiselect) || !rowData)) {
if (!isQuickEdit) { //For quick edit, row will be in edit mode. So,, no need to call events.
callRowSelectionEvents();
}
return;
}
selected = !selected;
this.toggleRowSelection($row, selected);
callRowSelectionEvents();
},
/*Handles the double click of the grid row*/
rowDblClickHandler: function (e, $row) {
e.stopPropagation();
$row = $row || $(e.target).closest('tr');
var rowData, rowId = $row.attr('data-row-id');
rowData = this.preparedData[rowId];
if (!rowData) {
return;
}
if ($.isFunction(this.options.onRowDblClick)) {
this.options.onRowDblClick(rowData, e);
}
},
headerClickHandler: function (e) {
var $th = $(e.target).closest('th.app-datagrid-header-cell'),
id = $th.attr('data-col-id');
this.options.onHeaderClick(this.preparedHeaderData[id], e);
},
/* Handles column selection. */
columnSelectionHandler: function (e, $headerCell) {
if (e) {
e.stopImmediatePropagation();
}
var $th = e ? $(e.target).closest('th.app-datagrid-header-cell') : $headerCell,
id = $th.attr('data-col-id'),
colDef = this.preparedHeaderData[id],
field = colDef.field,
selector = 'td[data-col-id="' + id + '"]',
$column = this.gridElement.find(selector),
selected = $column.data('selected') || false,
colInfo = {
colDef: colDef,
data: this.options.data.map(function (data) { return data[field]; }),
sortDirection: this._getColumnSortDirection(colDef.field)
},
selectedClass = this.options.cssClassNames.selectedColumn;
selected = !selected;
colDef.selected = selected;
$column.data('selected', selected);
if (selected) {
$column.addClass(selectedClass);
$th.addClass(selectedClass);
if ($.isFunction(this.options.onColumnSelect) && e) {
this.options.onColumnSelect(colInfo, e);
}
} else {
$column.removeClass(selectedClass);
$th.removeClass(selectedClass);
if ($.isFunction(this.options.onColumnDeselect) && e) {
/*TODO: Confirm what to send to the callback (coldef?).*/
this.options.onColumnDeselect(colInfo, e);
}
}
},
_getValue: function ($el) {
var type = $el.attr('type'),
text;
if (type === 'checkbox') {
text = $el.prop('checked').toString();
} else {
text = $el.val();
$el.text(WM.isDefined(text) ? text : '');
}
return text;
},
getTextValue: function ($el, colDef, fields) {
var text,
$ie = $el.find('input'),
dataValue,
$elScope;
text = this._getValue($ie, fields);
if (colDef.editWidgetType && colDef.editWidgetType !== 'upload') {
$elScope = $el.children().isolateScope();
if ($elScope) {
dataValue = $elScope.datavalue;
text = dataValue === '' ? undefined : dataValue; //Empty value is set from the grid cell. So, set it back to undefined.
}
}
if (colDef.type === 'timestamp' && (!colDef.editWidgetType || colDef.editWidgetType === 'text')) {
text = parseInt(text, 10);
}
return text;
},
isDataModified: function ($editableElements, rowData) {
var isDataChanged = false,
self = this;
function getEpoch(val) {
return val ? moment(val).valueOf() : val;
}
$editableElements.each(function () {
var $el = $(this),
colId = $el.attr('data-col-id'),
colDef = self.preparedHeaderData[colId],
fields = _.split(colDef.field, '.'),
text = self.getTextValue($el, colDef, fields),
originalData = _.get(rowData, colDef.field);
if (colDef.editWidgetType === 'upload') {
//For upload widget, check if any file is uploaded
isDataChanged = document.forms[$el.attr('form-name')][colDef.field].files.length > 0;
} else {
//If new value and old value are not defined, then data is not changed
if (!WM.isDefined(text) && (originalData === null || originalData === undefined)) {
isDataChanged = false;
} else {
//For datetime, compare the values in epoch format
if (colDef.editWidgetType === 'datetime') {
isDataChanged = !(getEpoch(originalData) === getEpoch(text));
} else {
isDataChanged = !(originalData == text);
}
}
}
if (isDataChanged) {
return !isDataChanged;
}
});
return isDataChanged;
},
disableActions: function (val) {
var $deleteBtns = this.gridBody.find('.delete-row-button'),
$editBtns = this.gridBody.find('.edit-row-button');
if (val) {
//Disable edit and delete actions while editing a row
$editBtns.addClass('disabled-action');
$deleteBtns.addClass('disabled-action');
} else {
$editBtns.removeClass('disabled-action');
$deleteBtns.removeClass('disabled-action');
}
},
//Function to the first input element in a row
setFocusOnElement: function (e, $el) {
var $firstEl,
$target = $(e.target);
//If focused directly on the cell, focus the input in the cell
if ($target.hasClass('app-datagrid-cell')) {
$firstEl = $target.find('input');
} else {
if (!$el) {
$el = $target.closest('tr').find('td.cell-editing');
}
$firstEl = $($el).first().find('input');
if (!$firstEl.length) {
$firstEl = $($el).first().find('textarea');
}
if (!$firstEl.length) {
$firstEl = $($el).first().find('select');
}
}
//Focus the fiest element
if ($firstEl.length) {
$firstEl.first().focus();
}
},
removeNewRow: function ($row) {
this.disableActions(false);
this._setGridEditMode(false);
$row.attr('data-removed', true);
$row.remove();
if (!this.preparedData.length) {
this.setStatus('nodata', this.dataStatus.nodata);
}
this.addOrRemoveScroll();
},
//Method to save a row which is in editable state
saveRow: function (callBack) {
this.gridBody.find('tr.row-editing').each(function () {
$(this).trigger('click', [undefined, {action: 'save', skipSelect: true, noMsg: true, success: callBack}]);
});
},
/* Toggles the edit state of a row. */
toggleEditRow: function (e, options) {
options = options || {};
if (e) {
e.stopPropagation();
}
var $row = options.$row || $(e.target).closest('tr'),
$originalElements = $row.find('td'),
$editButton = $row.find('.edit-row-button'),
$cancelButton = $row.find('.cancel-edit-row-button'),
$saveButton = $row.find('.save-edit-row-button'),
$deleteButton = $row.find('.delete-row-button'),
rowData = _.cloneDeep(this.options.data[$row.attr('data-row-id')]) || {},
self = this,
rowId = parseInt($row.attr('data-row-id'), 10),
action,
isNewRow,
$editableElements,
isDataChanged = false,
isValid,
$requiredEls,
advancedEdit = self.options.editmode === self.CONSTANTS.QUICK_EDIT;
if ($row.attr('data-removed') === 'true') {
//Even after removing row, focus out is triggered and edit is called. In this case, return here
return;
}
//Select the current edited row
if (options.selectRow) {
this.selectRow(rowData, true);
}
e = e || {};
e.data = e.data || {};
action = e.data.action || options.action;
if (action === 'edit') {
if (advancedEdit && self.gridBody.find('tr.row-editing').length) {
//In case of advanced edit, save the previous row
self.saveRow(function (skipFocus, error) {
self.editSuccessHandler(skipFocus, error, e, $row, true);
});
return;
}
$row.addClass('row-editing');
if ($.isFunction(this.options.beforeRowUpdate)) {
this.options.beforeRowUpdate(rowData, e);
}
if (self.options.editmode === self.CONSTANTS.FORM || self.options.editmode === self.CONSTANTS.DIALOG) {
return;
}
//For new operation, set the rowdata from the default values
if (options.operation === 'new') {
_.forEach(self.preparedHeaderData, function (colDef) {
rowData[colDef.field] = colDef.defaultvalue;
});
}
//Event for on before form render. User can update row data here.
if ($.isFunction(this.options.onBeforeFormRender)) {
isValid = this.options.onBeforeFormRender(rowData, e, options.operation || action);
if (isValid === false) {
return;
}
}
this._setGridEditMode(true);
this.disableActions(true);
$deleteButton.removeClass('disabled-action');
$originalElements.each(function () {
var $el = $(this),
cellText = $el.text(),
id = $el.attr('data-col-id'),
colDef = self.preparedHeaderData[id],
value,
editableTemplate;
if (!colDef.readonly) {
value = _.get(rowData, colDef.field);
editableTemplate = self._getEditableTemplate($el, colDef, value, rowId, options.operation);
if (!(colDef.customExpression || colDef.formatpattern)) {
$el.addClass('cell-editing').html(editableTemplate).data('originalText', cellText);
} else {
if (self._isCustomExpressionNonEditable(colDef.customExpression, $el)) {
$el.addClass('cell-editing editable-expression').data('originalValue', {'template': colDef.customExpression, 'rowData': _.cloneDeep(rowData), 'colDef': colDef});
}
$el.addClass('cell-editing editable-expression').html(editableTemplate).data('originalText', cellText);
}
if (colDef.required) {
$el.addClass('required-field form-group');
}
}
});
// Show editable row.
$editButton.addClass('hidden');
$cancelButton.removeClass('hidden');
$saveButton.removeClass('hidden');
$editableElements = $row.find('td.cell-editing');
$editableElements.on('click', function (e) {
e.stopPropagation();
});
if (!options.skipFocus && $editableElements) {
self.setFocusOnElement(e, $editableElements);
}
//Event for on before form render. User can access form widgets here.
if ($.isFunction(this.options.onFormRender)) {
this.options.onFormRender($row, e, options.operation || action);
}
} else {
$editableElements = $row.find('td.cell-editing');
isNewRow = rowId >= this.preparedData.length;
if (action === 'save') {
$requiredEls = $editableElements.find('.ng-invalid-required');
//If required fields are present and value is not filled, return here
if ($requiredEls.length > 0) {
$requiredEls.addClass('ng-touched');
if ($.isFunction(options.success)) {
options.success(false, true);
}
return;
}
if (isNewRow) {
isDataChanged = true;
} else {
isDataChanged = this.isDataModified($editableElements, rowData);
}
if (isDataChanged) {
$editableElements.each(function () {
var $el = $(this),
colId = $el.attr('data-col-id'),
colDef = self.preparedHeaderData[colId],
fields = _.split(colDef.field, '.'),
text;
text = self.getTextValue($el, colDef, fields);
if (fields.length === 1 && colDef.editWidgetType === 'upload') {
_.set(rowData, colDef.field, _.get(document.forms, [$el.attr('form-name'), colDef.field, 'files', 0]));
} else {
text = ((fields.length === 1 || isNewRow) && text === '') ? undefined : text; //Set empty values as undefined
if (WM.isDefined(text)) {
text = text === 'null' ? null : text; //For select, null is returned as string null. Set this back to ull
if (text === null) {
if (fields.length > 1) {
_.set(rowData, fields[0], text); //For related fields, set the object to null
} else {
_.set(rowData, colDef.field, ''); //Set to empty for normal fields
}
} else {
_.set(rowData, colDef.field, text);
}
} else {
//Set undefined while editing the rows
if (fields.length === 1 && !isNewRow) {
_.set(rowData, colDef.field, text);
}
}
}
});
if (isNewRow) {
if (advancedEdit && _.isEmpty(rowData)) {
self.removeNewRow($row);
if ($.isFunction(options.success)) {
options.success(false, undefined, true);
}
return;
}
if ($.isFunction(this.options.onBeforeRowInsert)) {
isValid = this.options.onBeforeRowInsert(rowData, e);
if (isValid === false) {
return;
}
}
this.options.onRowInsert(rowData, e, options.success);
} else {
if ($.isFunction(this.options.onBeforeRowUpdate)) {
isValid = this.options.onBeforeRowUpdate(rowData, e);
if (isValid === false) {
return;
}
}
this.options.afterRowUpdate(rowData, e, options.success);
}
} else {
this.cancelEdit($row);
if (!options.noMsg) {
this.options.noChangesDetected();
}
if ($.isFunction(options.success)) {
options.success(false);
}
}
} else {
if (isNewRow) {
self.removeNewRow($row);
return;
}
// Cancel edit.
this.cancelEdit($row);
}
}
this.addOrRemoveScroll();
},
cancelEdit: function ($row) {
var self = this,
$editableElements = $row.find('td.cell-editing'),
$cancelButton = $row.find('.cancel-edit-row-button'),
$saveButton = $row.find('.save-edit-row-button'),
$editButton = $row.find('.edit-row-button');
this.disableActions(false);
this._setGridEditMode(false);
$row.removeClass('row-editing');
$editableElements.off('click');
$editableElements.each(function () {
var $el = $(this),
value = $el.data('originalValue'),
originalValue,
template;
$el.removeClass('datetime-wrapper cell-editing required-field form-group');
if (!value) {
$el.text($el.data('originalText') || '');
} else {
originalValue = value;
if (originalValue.template) {
template = self.options.getCompiledTemplate(originalValue.template, originalValue.rowData, originalValue.colDef);
$el.html(template);
} else {
$el.html(originalValue || '');
}
}
});
$editButton.removeClass('hidden');
$cancelButton.addClass('hidden');
$saveButton.addClass('hidden');
},
hideRowEditMode: function ($row) {
var $editableElements = $row.find('td.cell-editing'),
$editButton = $row.find('.edit-row-button'),
$cancelButton = $row.find('.cancel-edit-row-button'),
$saveButton = $row.find('.save-edit-row-button'),
self = this;
$row.removeClass('row-editing');
$editableElements.off('click');
this.disableActions(false);
this._setGridEditMode(false);
$editableElements.each(function () {
var $el = $(this),
value = $el.data('originalValue'),
originalValue,
template,
text,
colDef;
$el.removeClass('datetime-wrapper cell-editing required-field form-group');
if (!value) {
colDef = self.preparedHeaderData[$el.attr('data-col-id')];
text = self.getTextValue($el, colDef, colDef.field.split('.'));
$el.text(WM.isDefined(text) ? text : '');
} else {
originalValue = value;
if (originalValue.template) {
template = self.options.getCompiledTemplate(originalValue.template, originalValue.rowData, originalValue.colDef, true);
$el.html(template);
} else {
$el.html(originalValue || '');
}
}
});
$editButton.removeClass('hidden');
$cancelButton.addClass('hidden');
$saveButton.addClass('hidden');
this.addOrRemoveScroll();
},
/* Deletes a row. */
deleteRow: function (e) {
e.stopPropagation();
var $row = $(e.target).closest('tr'),
rowId = $row.attr('data-row-id'),
rowData = this.options.data[rowId],
isNewRow = rowId >= this.preparedData.length,
className,
isActiveRow,
self = this;
if ($.isFunction(this.options.beforeRowDelete)) {
this.options.beforeRowDelete(rowData, e);
}
if (isNewRow) {
this.disableActions(false);
this._setGridEditMode(false);
$row.attr('data-removed', true);
$row.remove();
if (!this.preparedData.length) {
//On delete of a new row with no data, show no data message
this.setStatus('nodata', this.dataStatus.nodata);
}
this.addOrRemoveScroll();
return;
}
if ($.isFunction(this.options.onRowDelete)) {
className = this.options.cssClassNames.deleteRow;
isActiveRow = $row.attr('class').indexOf('active') !== -1;
if (isActiveRow) {
$row.removeClass('active');
}
$row.addClass(className);
this.options.onRowDelete(rowData, function () {
if (isActiveRow) {
$row.addClass('active');
}
$row.removeClass(className);
self.addOrRemoveScroll();
}, e, function (skipFocus, error) {
//For quick edit, on clicking of delete button or DELETE key, edit the next row
if (self.options.editmode !== self.CONSTANTS.QUICK_EDIT || !($(e.target).hasClass('delete-row-button') || self.Utils.isDeleteKey(e))) {
return;
}
//Call set status, so that the rows are visible for fom operations
self.__setStatus();
var rowID,
$nextRow;
if (error) {
return;
}
//On success, Focus the next row. If row is not present, focus the previous row
rowID = +$(e.target).closest('tr').attr('data-row-id');
$nextRow = self.gridBody.find('tr[data-row-id="' + rowID + '"]');
if (!$nextRow.length) {
$nextRow = self.gridBody.find('tr[data-row-id="' + (rowID - 1) + '"]');
}
$nextRow.trigger('click', [undefined, {action: 'edit', skipFocus: skipFocus}]);
});
}
},
/* Deletes a row and updates the header checkbox if multiselect is true. */
deleteRowAndUpdateSelectAll: function (e) {
this.deleteRow(e);
this.updateSelectAllCheckboxState();
},
/* Keeps a track of the currently selected row, and deselects the previous row, if multiselect is false. */
_deselectPreviousSelection: function ($row) {
var selectedRows = this.gridBody.find('tr.active'),
rowId = $row.attr('data-row-id'),
self = this;
selectedRows.each(function () {
var id = $(this).attr('data-row-id'),
preparedData = self.preparedData[id];
if (id !== rowId && preparedData) {
$(this).find('input:radio').prop('checked', false);
preparedData.selected = preparedData.checked = false;
$(this).removeClass('active');
}
});
},
//Method to remove sort icons from the column header cells
resetSortIcons: function ($el) {
var $sortContainer;
//If sort icon is not passed, find out the sort icon from the active class
if (!$el && this.gridHeader) {
$sortContainer = this.gridHeader.find('.sort-buttons-container.active');
$el = $sortContainer.find('i.sort-icon');
$sortContainer.removeClass('active');
}
$el.removeClass('desc asc').removeClass(this.options.cssClassNames.descIcon).removeClass(this.options.cssClassNames.ascIcon);
},
/* Handles table sorting. */
sortHandler: function (e) {
e.stopImmediatePropagation();
var $e = $(e.target),
$th = $e.closest('th.app-datagrid-header-cell'),
id = $th.attr('data-col-id'),
$sortContainer = $th.find('.sort-buttons-container'),
$sortIcon = $sortContainer.find('i.sort-icon'),
direction = $sortIcon.hasClass('asc') ? 'desc' : $sortIcon.hasClass('desc') ? '' : 'asc',
sortInfo = this.options.sortInfo,
$previousSortMarker = this.gridHeader.find('.sort-buttons-container.active'),
field = $th.attr('data-col-field'),
$previousSortedColumn,
$previousSortIcon,
colId,
colDef;
this.resetSortIcons($sortIcon);
$sortIcon.addClass(direction);
//Add the classes based on the direction
if (direction === 'asc') {
$sortIcon.addClass(this.options.cssClassNames.ascIcon);
$sortContainer.addClass('active');
} else if (direction === 'desc') {
$sortIcon.addClass(this.options.cssClassNames.descIcon);
$sortContainer.addClass('active');
}
if ($previousSortMarker.length) {
//Reset the previous sorted column icons and info
$previousSortedColumn = $previousSortMarker.closest('th.app-datagrid-header-cell');
colId = $previousSortedColumn.attr('data-col-id');
colDef = this.preparedHeaderData[colId];
$previousSortIcon = $previousSortMarker.find('i.sort-icon');
if (colDef.field !== field) {
$previousSortMarker.removeClass('active');
this.resetSortIcons($previousSortIcon);
}
colDef.sortInfo = {'sorted': false, 'direction': ''};
}
sortInfo.direction = direction;
sortInfo.field = field;
if (direction !== '') {
this.preparedHeaderData[id].sortInfo = {'sorted': true, 'direction': direction};
}
this.options.sortHandler.call(this, this.options.sortInfo, e, 'sort');
},
//Method to handle up and next key presses
processUpDownKeys: function (event, $row, direction) {
var self = this;
if ($row.hasClass('row-editing') && self.options.editmode === self.CONSTANTS.QUICK_EDIT) {
self.toggleEditRow(event, {
'action' : 'save',
'noMsg' : true,
'success' : function (skipFocus, error) {
self.editSuccessHandler(skipFocus, error, event, $row, true, direction);
}
});
} else {
$row = direction === 'down' ? $row.next() : $row.prev();
$row.focus();
}
},
// Handles keydown event on row items.
onKeyDown: function (event) {
var $target = $(event.target),
$row = $target.closest('tr'),
quickEdit = this.options.editmode === this.CONSTANTS.QUICK_EDIT,
rowId,
isNewRow;
if (this.Utils.isDeleteKey(event)) { //Delete Key
//For input elements, dont delete the row
if ($target.is('input') || $target.hasClass('form-control')) {
return;
}
this.deleteRow(event);
return;
}
if (event.which === 27) { //Escape key
rowId = parseInt($row.attr('data-row-id'), 10);
isNewRow = rowId >= this.preparedData.length;
//On Escape, cancel the row edit
$row.trigger('click', [undefined, {action: 'cancel'}]);
if (!isNewRow) {
$row.focus();
}
return;
}
if (event.which === 13) { //Enter key
if (quickEdit && $target.hasClass('app-datagrid-row')) {
$row.trigger('click', [undefined, {action: 'edit'}]);
} else {
$row.trigger('click');
}
//Stop the enter keypress from submitting any parent form. If target is button, event should not be stopped as this stops click event on button
if (!$target.is('button')) {
event.stopPropagation();
event.preventDefault();
}
return;
}
if (event.which === 38) { // up-arrow action
this.processUpDownKeys(event, $row, 'up');
return;
}
if (event.which === 40) { // down-arrow action
this.processUpDownKeys(event, $row, 'down');
}
},
editSuccessHandler: function (skipFocus, error, e, $row, isSameRow, direction) {
var self = this,
rowID,
$nextRow;
//Call set status, so that the rows are visible for fom operations
self.__setStatus();
//On error, focus the current row first element
if (error) {
self.setFocusOnElement(e);
return;
}
//On success, make next row editable. If next row is not present, add new row
rowID = +$row.attr('data-row-id');
if (direction) {
rowID = direction === 'down' ? ++rowID : --rowID;
$nextRow = self.gridBody.find('tr[data-row-id="' + rowID + '"]');
if ($nextRow.length) {
$nextRow.focus();
} else {
$row.focus();
}
return;
}
if (!isSameRow) {
rowID++;
}
$nextRow = self.gridBody.find('tr[data-row-id="' + rowID + '"]');
if ($nextRow.length) {
$nextRow.trigger('click', [undefined, {action: 'edit', skipFocus: skipFocus, skipSelect: self.options.multiselect}]);
} else {
self.addNewRow(skipFocus);
}
},
/* Attaches all event handlers for the table. */
attachEventHandlers: function ($htm) {
var rowOperationsCol = this._getRowActionsColumnDef(),
$header = this.gridHeader,
self = this,
deleteRowHandler;
if (this.options.enableRowSelection) {
$htm.on('click', this.rowSelectionHandler.bind(this));
$htm.on('dblclick', this.rowDblClickHandler.bind(this));
$htm.on('keydown', this.onKeyDown.bind(this));
}
if ($header) {
if (this.options.enableColumnSelection) {
$header.find('th[data-col-selectable]').on('click', this.columnSelectionHandler.bind(this));
} else {
$header.find('th[data-col-selectable]').off('click');
}
if (this.options.enableSort) {
if (this.options.enableColumnSelection) {
$header.find('th[data-col-sortable] .header-data').on('click', this.sortHandler.bind(this));
} else {
$header.find('th[data-col-sortable]').on('click', this.sortHandler.bind(this));
}
} else {
if (this.options.enableColumnSelection) {
$header.find('th[data-col-sortable] .header-data').off('click');
} else {
$header.find('th[data-col-sortable]').off('click');
}
}
}
if (this.options.rowActions.length) {
$htm.find('.row-action').on('click', {action: 'edit'}, this._handleCustomEvents.bind(this));
$htm.find('.cancel-edit-row-button').on('click', {action: 'cancel'}, this.toggleEditRow.bind(this));
$htm.find('.save-edit-row-button').on('click', {action: 'save'}, this.toggleEditRow.bind(this));
} else {
if ((this.options.editmode !== this.CONSTANTS.FORM && this.options.editmode !== this.CONSTANTS.DIALOG) || (rowOperationsCol && _.includes(rowOperationsCol.operations, 'update'))) {
$htm.find('.edit-row-button').on('click', {action: 'edit'}, this.toggleEditRow.bind(this));
$htm.find('.cancel-edit-row-button').on('click', {action: 'cancel'}, this.toggleEditRow.bind(this));
$htm.find('.save-edit-row-button').on('click', {action: 'save'}, this.toggleEditRow.bind(this));
}
if (rowOperationsCol && _.includes(rowOperationsCol.operations, 'delete')) {
deleteRowHandler = this.deleteRowAndUpdateSelectAll;
if (!this.options.multiselect) {
deleteRowHandler = this.deleteRow;
}
$htm.find('td .delete-row-button').on('click', deleteRowHandler.bind(this));
}
}
if (self.options.editmode === self.CONSTANTS.QUICK_EDIT) {
//On tab out of a row, save the current row and make next row editable
$htm.on('focusout', 'tr', function (e) {
var $target = $(e.target),
$row = $target.closest('tr'),
$relatedTarget = $(e.relatedTarget),
invalidTargets = '.row-editing, .row-action-button, .app-datagrid-cell, .caption';
//Check if the focus out element is outside the grid or some special elements
function isInvalidTarget() {
if (!$relatedTarget.closest('.app-grid').length) {
return true;
}
return $relatedTarget.is(invalidTargets);
}
//Save the row on last column of the data table. If class has danger, confirm dialog is opened, so dont save the row.
if (!$target.closest('td').is(':last-child') || $row.hasClass('danger') || e.relatedTarget === null) {
return;
}
//If focusout is because of input element or row action or current row, dont save the row
if ($relatedTarget.attr('focus-target') === '' || isInvalidTarget()) {
return;
}
self.toggleEditRow(e, {
'action' : 'save',
'noMsg' : true,
'success' : function (skipFocus, error, isNewRow) {
if (!isNewRow) {
self.editSuccessHandler(skipFocus, error, e, $row);
}
}
});
});
}
},
/* Replaces all the templates needing angular compilation with the actual compiled templates. */
_findAndReplaceCompiledTemplates: function () {
if (!this.gridBody) {
return;
}
var $compiledCells = this.gridBody.find('td[data-compiled-template]'),
self = this;
$compiledCells.each(function () {
var $cell = $(this),
id = $cell.attr('data-compiled-template');
$cell.replaceWith(self.compiledCellTemplates[id]);
});
},
/* Renders the search box. */
_renderSearch: function () {
var $htm = $(this._getSearchTemplate()),
self = this,
$searchBox;
function search(e) {
e.stopPropagation();
var searchText = $htm.find('[data-element="dgSearchText"]')[0].value,
$filterField = $htm.find('[data-element="dgFilterValue"]'),
field = $filterField[0].value,
colDefIndex = $htm.find('option:selected').attr('data-coldef-index'),
colDef = self.options.colDefs[colDefIndex],
type = colDef && colDef.type ? colDef.type : '';
self.searchObj = {
'field': field,
'value': searchText,
'type': type,
'event': e
};
self.options.searchHandler.call(self, self.searchObj, e, 'search');
}
this.element.find('.form-search').remove();
$htm.insertBefore(this.gridContainer);
this.gridSearch = this.element.find('.form-search');
$searchBox = this.gridSearch.find('[data-element="dgSearchText"]');
this.gridSearch.find('.app-search-button').on('click', search);
this.gridSearch.find('[data-element="dgFilterValue"]').on('change', function (e) {
// If "No data found" message is shown, and user changes the selection, then fetch all data.
if (self.dataStatusContainer.find('.status').text() === self.options.dataStates.nodata) {
search(e);
}
});
$searchBox.on('keyup', function (e) {
e.stopPropagation();
// If the search text is empty then show all the rows.
if (!$(this).val()) {
if (self.searchObj.value) {
self.searchObj.value = '';
search(e);
}
}
/* Search only when enter key is pressed. */
if (e.which === 13) {
search(e);
}
});
},
//Get the respective widget template
_getFilterWidgetTemplate: function (field) {
var widget = field.filterwidget || 'text',
placeholder = field.filterplaceholder || '',
fieldName = field.field,
widgetName = ' name="' + this.options.name + '_filter_' + fieldName + '"',
template;
widget = widget === 'number' ? 'text' : widget;
widget = widget === 'autocomplete' ? 'search' : widget;
template = '<wm-' + widget + widgetName + ' placeholder="' + placeholder + '" scopedatavalue="rowFilter[\'' + fieldName + '\'].value" on-change="onRowFilterChange(\'' + fieldName + '\',\'' + field.type + '\')" disabled="{{emptyMatchModes.indexOf(rowFilter[\'' + fieldName + '\'].matchMode) > -1}}"';
switch (field.filterwidget) {
case 'number':
template += ' type="number" ';
break;
case 'select':
if (field.isLiveVariable) {
template += ' scopedataset="fullFieldDefs[' + field.index + '].filterdataset"';
} else {
template += ' dataset="' + this.options.getBindDataSet() + '" datafield="' + fieldName + '" displayfield="' + fieldName + '"';
}
template += ' orderby="' + fieldName + ':asc"';
break;
case 'autocomplete':
template += ' type="autocomplete" dataset="' + this.options.getBindDataSet() + '" datafield="' + fieldName + '" searchkey="' + fieldName + '" displaylabel="' + fieldName + '" on-submit="onRowFilterChange()" orderby="' + fieldName + ':asc"';
break;
case 'time':
template += ' timepattern="hh:mm:ss a" ';
break;
}
template += '></wm-' + widget + '>';
return template;
},
//Generate the row level filter
_renderRowFilter: function () {
var htm = '<tr class="filter-row">',
self = this,
$headerElement = (this.options.isMobile && !this.options.showHeader) ? this.gridElement : this.gridHeaderElement,
compiledFilterTl;
$headerElement.find('.filter-row').remove();
this.preparedHeaderData.forEach(function (field, index) {
var fieldName = field.field,
widget = field.filterwidget || 'text';
if (!field.searchable) {
htm += '<th data-col-id="' + index + '"></th>';
return;
}
htm += '<th data-col-id="' + index + '">' +
'<span class="input-group ' + widget + '">' +
self._getFilterWidgetTemplate(field) +
'<span class="input-group-addon filter-clear-icon" ng-if="showClearIcon(\'' + fieldName + '\')"><button class="btn-transparent btn app-button" type="button" ng-click="clearRowFilter(\'' + fieldName + '\')"><i class="app-icon wi wi-clear"></i></button></span>' +
'<span class="input-group-addon" uib-dropdown dropdown-append-to-body>' +
'<button class="btn-transparent btn app-button" type="button" uib-dropdown-toggle><i class="app-icon wi wi-filter-list"></i></button>' +
'<ul class="matchmode-dropdown dropdown-menu" uib-dropdown-menu> <li ng-repeat="matchMode in matchModeTypesMap[\'' + field.type + '\' || \'string\']" ng-class="{active: matchMode === (rowFilter[\'' + fieldName + '\'].matchMode || matchModeTypesMap[\'' + field.type + '\' || \'string\'][0])}"><a href="javascript:void(0);" ng-click="onFilterConditionSelect(\'' + fieldName + '\', matchMode)">{{matchModeMsgs[matchMode]}}</a></li> </ul>' +
'</span>' +
'</span>' +
'</th>';
}, this);
htm += '</tr>';
compiledFilterTl = this.options.compileTemplateInGridScope(htm);
if (this.options.showHeader) {
this.gridHeader.append(compiledFilterTl);
} else {
if (this.options.isMobile) {
$headerElement.append($('<thead></thead>').append(compiledFilterTl));
} else {
$headerElement.append('<thead></thead>').append(compiledFilterTl);
}
}
this.gridSearch = $headerElement.find('.filter-row');
},
/* Renders the table header. */
_renderHeader: function () {
var headerTemplate = this._getHeaderTemplate(),
$colgroup = headerTemplate.colgroup,
self = this,
$header;
/*On scroll of the content table, scroll the header*/
this.gridElement.parent().scroll(function () {
self.gridHeaderElement.parent().prop('scrollLeft', this.scrollLeft);
});
if (!this.options.showHeader) {
this.gridHeaderElement.append($colgroup);
this.gridElement.prepend($colgroup.clone());
return;
}
$header = headerTemplate.header;
function toggleSelectAll(e) {
var $checkboxes = $('tbody tr:visible td input[name="gridMultiSelect"]:checkbox', self.gridElement),
checked = this.checked;
$checkboxes.prop('checked', checked);
$checkboxes.each(function () {
var $row = $(this).closest('tr'),
rowId = $row.attr('data-row-id'),
rowData = self.options.data[rowId];
self.toggleRowSelection($row, checked);
if (checked && $.isFunction(self.options.onRowSelect)) {
self.options.onRowSelect(rowData, e);
}
if (!checked && $.isFunction(self.options.onRowDeselect)) {
self.options.onRowDeselect(rowData, e);
}
});
}
/*For mobile view, append header to the main table only*/
if (this.options.isMobile) {
this.gridElement.append($colgroup).append($header);
this.gridHeader = this.gridElement.find('thead');
} else {
/**Append the colgroup to the header and the body.
* Colgroup is used to maintain the consistent widths between the header table and body table**/
this.gridHeaderElement.append($colgroup).append($header);
/**As jquery references the colgroup, clone the colgroup and add it to the table body**/
this.gridElement.prepend($colgroup.clone());
this.gridHeader = this.gridHeaderElement.find('thead');
}
/**Add event handler, to the select all checkbox on the header**/
$header.on('click', '.app-datagrid-header-cell input:checkbox', toggleSelectAll);
if ($.isFunction(this.options.onHeaderClick)) {
this.gridHeader.find('th.app-datagrid-header-cell').on('click', this.headerClickHandler.bind(this));
}
if (!this.options.isMobile && this.gridHeaderElement.length) {
this.gridHeaderElement.find('th[data-col-resizable]').resizable({
handles: 'e',
minWidth: 50,
// set COL width
/* This is needed because if width is initially set on col from coldefs,
* then that column was not getting resized.*/
resize: function (evt, ui) {
var $colElement,
$colHeaderElement,
$cellElements,
colIndex = +ui.helper.attr('data-col-id') + 1,
originalWidth = ui.helper.width(),
newWidth = ui.size.width,
originalTableWidth,
newTableWidth;
$colHeaderElement = self.gridHeaderElement.find('colgroup > col:nth-child(' + colIndex + ')');
$colElement = self.gridElement.find('colgroup > col:nth-child(' + colIndex + ')');
$cellElements = self.gridElement.find('tr > td:nth-child(' + colIndex + ') > div');
$colElement.width(newWidth);
$colHeaderElement.width(newWidth);
$cellElements.width(newWidth);
// height must be set in order to prevent IE9 to set wrong height
$(this).css('height', 'auto');
/*Adjust the table width only if the column width is increased*/
if (newWidth > ui.originalSize.width) {
/*Increase or decrease table width on resizing the column*/
originalTableWidth = self.gridHeaderElement.width();
newTableWidth = originalTableWidth + newWidth - originalWidth;
self.gridHeaderElement.width(newTableWidth);
self.gridElement.width(newTableWidth);
}
self.addOrRemoveScroll();
self.options.redrawWidgets();
}
});
}
},
addOrRemoveScroll: function () {
var gridContent = this.gridContainer.find('.app-grid-content').get(0),
gridHeader = this.gridContainer.find('.app-grid-header');
/*If scroll bar is present on the grid content, add padding to the header*/
if ((gridContent.scrollHeight > gridContent.clientHeight) && !this.Utils.isMac()) {
gridHeader.addClass('scroll-visible');
} else {
gridHeader.removeClass('scroll-visible');
}
},
//Triggers actual function in scope
_handleCustomEvents: function (e, options) {
this.options.handleCustomEvents(e, options);
},
//Generates markup for row operations
_getRowActionsTemplate: function () {
var saveCancelTemplateAdded = false,
rowOperationsCol,
actionsTemplate = '<span> ',
saveCancelTemplate = '<button type="button" class="save row-action-button btn app-button btn-transparent save-edit-row-button hidden" title="Save"><i class="wi wi-done"></i></button> ' +
'<button type="button" class="cancel row-action-button btn app-button btn-transparent cancel-edit-row-button hidden" title="Cancel"><i class="wi wi-cancel"></i></button> ';
//Generate the expression for properties which have binding expression
function generateBindExpr(val) {
if (_.startsWith(val, 'bind:')) {
return '{{' + _.replace(val, 'bind:', '') + '}}';
}
return val;
}
if (this.options.rowActions.length) {
_.forEach(this.options.rowActions, function (def) {
var clsAttr = 'row-action row-action-button app-button btn ' + def.class,
ngShowAttr = '',
ngDisabled = def.disabled ? ' ng-disabled="' + _.replace(def.disabled, 'bind:', '') + '" ' : '';
if (def.show === 'true' || def.show === 'false') {
clsAttr += def.show === 'true' ? '' : ' ng-hide ';
} else if (_.includes(def.show, 'bind:')) {
ngShowAttr = _.replace(def.show, 'bind:', '');
}
//Adding 'edit' class if at least one of the action is 'editRow()'
if (_.includes(def.action, 'editRow()')) {
clsAttr += ' edit edit-row-button ';
} else if (_.includes(def.action, 'deleteRow()')) {
clsAttr += ' delete delete-row-button ';
}
actionsTemplate += '<button type="button" data-action-key="' + def.key + '" class="' + clsAttr + '" title="' + generateBindExpr(def.title) + '" ' + (ngShowAttr ? ' ng-show="' + ngShowAttr + '"' : '') + (def.tabindex ? (' tabindex="' + def.tabindex + '"') : '') + ngDisabled + '>'
+ '<i class="app-icon ' + def.iconclass + '"></i>';
if (def.displayName) {
actionsTemplate += '<span class="btn-caption">' + generateBindExpr(def.displayName) + '</span>';//Appending display name
}
actionsTemplate += '</button>';
if (_.includes(def.action, 'editRow()')) {
actionsTemplate += !saveCancelTemplateAdded ? saveCancelTemplate : '';
saveCancelTemplateAdded = true;
}
});
} else {
//Appending old template for old projects depending on grid level attributes
rowOperationsCol = this._getRowActionsColumnDef() || {};
if (_.includes(rowOperationsCol.operations, 'update')) {
actionsTemplate += '<button type="button" class="row-action-button btn app-button btn-transparent edit edit-row-button" title="Edit Row"><i class="wi wi-pencil"></i></button> ' +
saveCancelTemplate;
}
if (_.includes(rowOperationsCol.operations, 'delete')) {
actionsTemplate += '<button type="button" class="row-action-button btn app-button btn-transparent delete delete-row-button" title="Delete Record"><i class="wi wi-trash"></i></button> ';
}
}
actionsTemplate += '</span>';
return actionsTemplate;
},
//Appends row operations markup to grid template
_appendRowActions : function ($htm, isNewRow, rowData) {
var self, template,
rowOperationsCol = this._getRowActionsColumnDef();
if (this.options.rowActions.length || rowOperationsCol) {
self = this;
template = self._getRowActionsTemplate();
$htm.find("[data-identifier='actionButtons']").each(function (index) {
if (isNewRow) {
$(this).empty().append(self.options.getCompiledTemplate(template, rowData, rowOperationsCol));
} else {
$(this).empty().append(self.options.getCompiledTemplate(template, self.preparedData[index], rowOperationsCol));
}
});
}
},
/* Renders the table body. */
_renderGrid: function () {
var $htm = $(this._getGridTemplate());
this.gridElement.append($htm);
// Set proper data status messages after the grid is rendered.
if (!this.options.data.length && this.dataStatus.state === 'nodata') {
this.setStatus('nodata');
} else {
this.dataStatus.state = this.dataStatus.state || 'loading';
this.dataStatus.message = this.dataStatus.message || this.options.dataStates.loading;
this.setStatus(this.dataStatus.state, this.dataStatus.message);
}
this.gridBody = this.gridElement.find('tbody');
this._findAndReplaceCompiledTemplates();
this._appendRowActions($htm);
this.attachEventHandlers($htm);
this.__setStatus();
this.setColGroupWidths();
if ($.isFunction(this.options.onDataRender)) {
this.options.onDataRender();
}
if (this.options.selectFirstRow) {
if (this.options.multiselect) {
//Set selectFirstRow to false, to prevent first item being selected in next page
this.options.selectFirstRow = false;
}
this.selectFirstRow(true, true);
}
},
/* Renders the table container. */
_render: function () {
if (!this.tableId) {
this.tableId = this.Utils.generateGuid();
}
var statusContainer =
'<div class="overlay" style="display: none;">' +
'<div class="status"><i class="' + this.options.loadingicon + '"></i><span class="message"></span></div>' +
'</div>',
table = '<div class="table-container table-responsive"><div class="app-grid-header ' +
'"><div class="app-grid-header-inner"><table class="' + this.options.cssClassNames.gridDefault + ' ' + this.options.cssClassNames.grid + '" id="table_header_' + this.tableId + '">' +
'</table></div></div><div class="app-grid-content" style="height:' + this.options.height + ';"><table class="' + this.options.cssClassNames.gridDefault + ' ' + this.options.cssClassNames.grid + '" id="table_' + this.tableId + '">' +
'</table></div>' +
'</div>';
this.gridContainer = $(table);
this.gridElement = this.gridContainer.find('.app-grid-content table');
this.gridHeaderElement = this.gridContainer.find('.app-grid-header table');
// Remove the grid table element.
this.element.find('.table-container').remove();
this.element.append(this.gridContainer);
this.dataStatusContainer = $(statusContainer);
this.gridContainer.append(this.dataStatusContainer);
this._renderHeader();
if (this.options.filtermode === this.CONSTANTS.SEARCH) {
this._renderSearch();
} else if (this.options.filtermode === this.CONSTANTS.MULTI_COLUMN) {
this._renderRowFilter();
}
if (this.options.spacing === 'condensed') {
this._toggleSpacingClasses('condensed');
}
this._renderGrid();
},
__setStatus: function () {
var loadingIndicator = this.dataStatusContainer.find('.fa'),
state = this.dataStatus.state;
this.dataStatusContainer.find('.message').text(this.dataStatus.message);
if (state === 'loading') {
loadingIndicator.show();
} else {
loadingIndicator.hide();
}
if (state === 'ready') {
this.dataStatusContainer.hide();
} else {
this.dataStatusContainer.show();
}
if (state === 'nodata' || state === 'loading' || state === 'error') {
if (this.options.height === '100%' || this.options.height === 'auto') { //If height is auto or 100%, Set the loading overlay height as present grid content height
if (state === 'nodata') {
this.dataStatusContainer.css('height', 'auto');
this.dataStatus.contentHeight = 0;
} else {
this.dataStatus.height = this.dataStatus.height || this.dataStatusContainer.outerHeight();
this.dataStatus.contentHeight = this.gridElement.outerHeight() || this.dataStatus.contentHeight;
this.dataStatusContainer.css('height', this.dataStatus.height > this.dataStatus.contentHeight ? 'auto' : this.dataStatus.contentHeight);
}
}
this.gridContainer.addClass('show-msg');
} else {
this.gridContainer.removeClass('show-msg');
}
this.addOrRemoveScroll();
},
//This method is used to show or hide data loading/ no data found overlay
setStatus: function (state, message) {
this.dataStatus.state = state;
this.dataStatus.message = message || this.options.dataStates[state];
//First time call the status function, afterwards use debounce with 100 ms wait
if (this._setStatusCalled) {
this._setStatus();
} else {
this.__setStatus();
this._setStatusCalled = true;
}
},
setGridDimensions: function (key, value) {
if (value.indexOf('px') === -1 && value.indexOf('%') === -1 && value.indexOf('em') === -1 && value != 'auto') {
value = value + 'px';
}
this.options[key] = value;
if (key === 'height') {
this.gridContainer.find('.app-grid-content').css(key, value);
this.dataStatusContainer.css(key, value);
}
this.addOrRemoveScroll();
},
/*Change the column header title. function will be called if display name changes in runmode*/
setColumnProp: function (fieldName, property, val, isGroup) {
var $col;
switch (property) {
case 'displayName':
if (isGroup) {
$col = this.gridHeader.find('th[data-col-group="' + fieldName + '"]');
} else {
$col = this.gridHeader.find('th[data-col-field="' + fieldName + '"]');
}
$col.attr('title', val);
$col.find('.header-data').html(val);
break;
}
},
_destroy: function () {
this.element.text('');
window.clearTimeout(this.refreshGridTimeout);
}
});
|
Francesco-Lanciana/pockets | src/utils/supplierData.js | const metadata = {
"asos": {
deliveryMin: 2,
deliveryMax: 20,
returns: "unused",
saleItemReturns: true,
returnShippingFee: false,
international: true,
},
"the iconic": {
deliveryMin: 1,
deliveryMax: 7,
returns: "unused",
saleItemReturns: true,
returnShippingFee: false,
international: false,
},
"poche posh": {
deliveryMin: 5,
deliveryMax: 20,
returns: "unused",
saleItemReturns: true,
returnShippingFee: false,
international: true,
},
"zaful": {
deliveryMin: 6,
deliveryMax: 25,
returns: "warranty",
saleItemReturns: false,
returnShippingFee: false,
international: true,
}
}
export default metadata; |
bcgov/gwa-ui | src/main/java/ca/bc/gov/gwa/v2/model/Service.java | <gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ca.bc.gov.gwa.v2.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
public class Service implements Comparable<Service> {
static final boolean TIME_IN_SECONDS = true;
String id;
String name;
List<Route> routes;
List<Plugin> plugins;
List<String> hosts; // legacy
List<String> paths; // legacy
Tags tags;
@JsonProperty("created_at")
Long createdAt;
@JsonProperty("updated_at")
Long updatedAt;
@JsonIgnore
Map<String, Object> data;
public Service (Object payload) {
this.data = (Map<String, Object>) payload;
id = (String) data.get("id");
name = (String) data.get("name");
tags = new Tags(data);
createdAt = ( (BigDecimal) data.get("created_at")).longValue() * (TIME_IN_SECONDS ? 1000:1);
updatedAt = ( (BigDecimal) data.get("updated_at")).longValue() * (TIME_IN_SECONDS ? 1000:1);
routes = new ArrayList<>();
plugins = new ArrayList<>();
hosts = new ArrayList<>();
paths = new ArrayList<>();
}
public void addRoute (Route route) {
routes.add(route);
if (route.getHosts() != null) {
for ( String host : route.getHosts() ) {
if (!hosts.contains(host)) {
hosts.add(host);
}
}
}
if (route.getPaths() != null) {
for ( String path : route.getPaths() ) {
if (!paths.contains(path)) {
paths.add(path);
}
}
}
}
public void addPlugin (Plugin plugin) {
plugins.add(plugin);
}
public boolean hasPlugin (String name) {
return plugins.stream().filter(p -> p.getName().equals(name)).count() != 0;
}
public Optional<Plugin> getPlugin (String name) {
return plugins.stream().filter(p -> p.getName().equals(name)).findFirst();
}
@Override
public int compareTo(Service o) {
return name.compareToIgnoreCase(o.getName());
}
public boolean isOwner (String ns) {
// return plugins.stream().filter(p -> p.getName().equals("bcgov-gwa-endpoint"))
// .map(p -> p.getConfigStringArray("api_owners"))
// .findFirst().get().stream()
// .filter(owner -> owner.equals(String.format("#/team/%s", ns)))
// .findFirst().isPresent();
return tags.stream().filter(t -> t.equals(String.format("ns.%s", ns)))
.findFirst().isPresent();
}
}
|
felixWackernagel/sidekick-ui | library/src/main/java/de/wackernagel/android/sidekick/utils/ApplicationUtils.java | <reponame>felixWackernagel/sidekick-ui
package de.wackernagel.android.sidekick.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class ApplicationUtils {
private ApplicationUtils() {
}
/**
* @param context of application
* @return VersionName from manifest or null
*/
@Nullable
public static String getVersionName( @NonNull final Context context ) {
try {
final PackageInfo pInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), 0 );
return pInfo != null ? pInfo.versionName : null;
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
/**
* @param context of application
* @return VersionCode from manifest or 0
*/
public static int getVersionCode( @NonNull final Context context ) {
try {
final PackageInfo pInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), 0 );
return pInfo != null ? pInfo.versionCode : 0;
} catch (PackageManager.NameNotFoundException e) {
return 0;
}
}
} |
kkcookies99/UAST | Dataset/Leetcode/test/13/829.java | <filename>Dataset/Leetcode/test/13/829.java
public int XXX(String s) {
HashMap<String, Integer> hashMap = new HashMap<>(13);
hashMap.put("I", 1);
hashMap.put("V", 5);
hashMap.put("X", 10);
hashMap.put("L", 50);
hashMap.put("C", 100);
hashMap.put("D", 500);
hashMap.put("M", 1000);
hashMap.put("IV", 4);
hashMap.put("IX", 9);
hashMap.put("XL", 40);
hashMap.put("XC", 90);
hashMap.put("CD", 400);
hashMap.put("CM", 900);
Integer integer;
int number = 0;
while (s.length() >= 2) {
String substring = s.substring(0, 2);
if (hashMap.containsKey(substring)) {
integer = hashMap.get(substring);
number += integer;
s = s.substring(2);
} else {
integer = hashMap.get(substring.substring(0, 1));
number += integer;
s = s.substring(1);
}
}
if (hashMap.containsKey(s)) {
integer = hashMap.get(s);
number += integer;
}
return number;
}
undefined
for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
|
jhonatasrm/chromium-android | app/src/main/java/org/chromium/components/viz/service/frame_sinks/ExternalBeginFrameSourceAndroid.java | // Copyright 2018 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.
package org.chromium.components.viz.service.frame_sinks;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.MainDex;
import org.chromium.ui.VSyncMonitor;
/**
* Provides a VSyncMonitor backed BeginFrameSource.
*/
@JNINamespace("viz")
@MainDex
public class ExternalBeginFrameSourceAndroid {
private final long mNativeExternalBeginFrameSourceAndroid;
private boolean mVSyncNotificationsEnabled;
private final VSyncMonitor mVSyncMonitor;
private final VSyncMonitor.Listener mVSyncListener = new VSyncMonitor.Listener() {
@Override
public void onVSync(VSyncMonitor monitor, long vsyncTimeMicros) {
if (!mVSyncNotificationsEnabled) {
return;
}
nativeOnVSync(mNativeExternalBeginFrameSourceAndroid, vsyncTimeMicros,
mVSyncMonitor.getVSyncPeriodInMicroseconds());
mVSyncMonitor.requestUpdate();
}
};
@CalledByNative
private ExternalBeginFrameSourceAndroid(long nativeExternalBeginFrameSourceAndroid) {
mNativeExternalBeginFrameSourceAndroid = nativeExternalBeginFrameSourceAndroid;
mVSyncMonitor = new VSyncMonitor(ContextUtils.getApplicationContext(), mVSyncListener);
}
@CalledByNative
private void setEnabled(boolean enabled) {
if (mVSyncNotificationsEnabled == enabled) {
return;
}
mVSyncNotificationsEnabled = enabled;
if (mVSyncNotificationsEnabled) {
mVSyncMonitor.requestUpdate();
}
}
private native void nativeOnVSync(long nativeExternalBeginFrameSourceAndroid,
long vsyncTimeMicros, long vsyncPeriodMicros);
};
|
xmar/pythran | pythran/pythonic/__builtin__/ZeroDivisionError.hpp | <gh_stars>0
#ifndef PYTHONIC_BUILTIN_ZERODIVISIONERROR_HPP
#define PYTHONIC_BUILTIN_ZERODIVISIONERROR_HPP
#include "pythonic/include/__builtin__/ZeroDivisionError.hpp"
#include "pythonic/types/exceptions.hpp"
namespace pythonic
{
namespace __builtin__
{
PYTHONIC_EXCEPTION_IMPL(ZeroDivisionError)
}
}
#endif
|
lord-pradhan/SnowBot | all_raspi_code_backup/StartScript.py | <filename>all_raspi_code_backup/StartScript.py
"""
Program: StartProgram
Revised On: 11/20/2019
"""
### Library Imports
from os import system
### Main Program
system('sudo pigpiod')
##system('python3 /home/pi/Desktop/EMSD/MainProgram.py')
|
AdamCorbinFAUPhD/COP5339-Object-Oriented-Software-Design | Homeworks/Homework4/q6.2/src/Manager.java | <reponame>AdamCorbinFAUPhD/COP5339-Object-Oriented-Software-Design
public class Manager extends Employee {
private Double bonus;
Manager(String name) {
super(name);
}
public Double getBonus() {
return bonus;
}
public void setBonus(Double bonus) {
this.bonus = bonus;
}
}
|
sachinsuthars/frontend | src/Campaign/searchComponents/table.js | <filename>src/Campaign/searchComponents/table.js
import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import {Link} from 'react-router';
import SortableTbl from 'react-sort-search-table';
import Edit from './editor.js';
import Manager from './manager.js';
/*
customTd={[
{custd: EditComponent, keyItem: "edit"},
{custd: ViewComponent, keyItem: "view"},
]}
*/
const ProductsTblPage = (props) =>{
let col = [
"Name",
"Date",
"Description",
"Creatives",
"UnpublishedCreatives",
"Status",
"edit",
];
let tHead = [
"Name",
"Updated",
"Description",
"Creative",
"Unpublished",
"Status",
"Edit",
];
//let dynamoToJSON = props.data.map(unmarshalItem);
return (
<SortableTbl tblData={props.data}
tHead={tHead}
dKey={col}
customTd={[
{custd: Edit, keyItem: "edit"},
{custd: Manager, keyItem: "manage"},
]}
defaultCSS={true}
/>
);
};
ProductsTblPage.propTypes = {
};
export default (ProductsTblPage);
|
Yehezkiel01/main | src/main/java/tagline/logic/commands/group/RemoveMemberFromGroupCommand.java | //@@author e0031374
package tagline.logic.commands.group;
import static java.util.Objects.requireNonNull;
import static tagline.logic.parser.group.GroupCliSyntax.PREFIX_CONTACTID;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import tagline.logic.commands.CommandResult;
import tagline.logic.commands.CommandResult.ViewType;
import tagline.logic.commands.exceptions.CommandException;
import tagline.model.Model;
import tagline.model.group.Group;
import tagline.model.group.GroupDescription;
import tagline.model.group.GroupName;
import tagline.model.group.GroupNameEqualsKeywordPredicate;
import tagline.model.group.MemberId;
/**
* Edits the details of an existing group in the address book.
*/
public class RemoveMemberFromGroupCommand extends EditGroupCommand {
public static final String COMMAND_WORD = "remove";
public static final String MESSAGE_USAGE = COMMAND_KEY + " " + COMMAND_WORD
+ ": Remove a contact to the group identified "
+ "by the group name and the contact ID number displayed in the contact list.\n "
+ "Parameters: GROUP_NAME (one word, cannot contain space) "
+ "[" + PREFIX_CONTACTID + " CONTACT_ID]...\n"
+ "Example: " + COMMAND_KEY + " " + COMMAND_WORD + " BTS_ARMY "
+ PREFIX_CONTACTID + " 47337 ";
public static final String MESSAGE_REMOVE_MEMBER_SUCCESS = "Attempting to remove contact(s) from group.";
public static final String MESSAGE_NOT_REMOVED = "At least one contactID to be removed must be provided.";
//private final Group group;
private final GroupNameEqualsKeywordPredicate predicate;
private final EditGroupDescriptor editGroupDescriptor;
/**
* @param predicate of the group in the filtered group list to edit
* @param editGroupDescriptor details to edit the group with
*/
public RemoveMemberFromGroupCommand(GroupNameEqualsKeywordPredicate predicate,
EditGroupDescriptor editGroupDescriptor) {
requireNonNull(predicate);
requireNonNull(editGroupDescriptor);
//this.index = index;
this.predicate = predicate;
this.editGroupDescriptor = new EditGroupDescriptor(editGroupDescriptor);
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
Group groupToEdit = findOneGroup(model, predicate);
Optional<Set<MemberId>> optMembers = editGroupDescriptor.getMemberIds();
//assert optMembers.isPresent();
Set<MemberId> membersNotFound = new HashSet<>();
if (optMembers.isPresent()) {
membersNotFound = GroupCommand.memberIdDoesntExistInContactModel(model, optMembers.get());
}
// removes all user-input contactIds as members of this Group checks deferred
Group editedGroup = createRemovedMemberGroup(groupToEdit, editGroupDescriptor);
// check to ensure Group members are ContactIds that can be found in Model
// this Group should only have contactId of contacts found in ContactList after calling setGroup
Group verifiedGroup = GroupCommand.verifyGroupWithModel(model, editedGroup);
model.setGroup(groupToEdit, verifiedGroup);
model.updateFilteredContactList(GroupCommand.groupToContactIdPredicate(verifiedGroup));
model.updateFilteredGroupList(GroupNameEqualsKeywordPredicate.generatePredicate(verifiedGroup));
return new CommandResult(MESSAGE_REMOVE_MEMBER_SUCCESS
+ GroupCommand.notFoundString(membersNotFound), ViewType.GROUP_PROFILE);
}
/**
* Creates and returns a {@code Group} with the details of {@code groupToEdit}
* edited with {@code editGroupDescriptor}.
*/
private static Group createRemovedMemberGroup(Group groupToEdit, EditGroupDescriptor editGroupDescriptor) {
assert groupToEdit != null;
GroupName updatedGroupName = editGroupDescriptor.getGroupName().orElse(groupToEdit.getGroupName());
GroupDescription updatedGroupDescription = editGroupDescriptor.getGroupDescription()
.orElse(groupToEdit.getGroupDescription());
Set<MemberId> updatedMemberIds = new HashSet<>();
if (editGroupDescriptor.getMemberIds().isPresent()) {
updatedMemberIds.addAll(groupToEdit.getMemberIds().stream()
.filter(member -> !editGroupDescriptor.getMemberIds().get().contains(member))
.collect(Collectors.toSet())
);
} else {
// if no memberIds found in editGroupDescriptor, do not remove any groups
updatedMemberIds.addAll(groupToEdit.getMemberIds());
}
return new Group(updatedGroupName, updatedGroupDescription, updatedMemberIds);
}
/**
* Checks and returns a set of {@code MemberId} which cannot be found as members of {@code Group}
*/
private static Set<MemberId> notFound(Group group, Collection<MemberId> toRemove) {
return toRemove.stream()
.filter(target -> !group.getMemberIds().stream()
.map(members -> members.value)
.anyMatch(members -> members.equalsIgnoreCase(target.value)))
.collect(Collectors.toSet());
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof RemoveMemberFromGroupCommand)) {
return false;
}
// state check
RemoveMemberFromGroupCommand e = (RemoveMemberFromGroupCommand) other;
return predicate.equals(e.predicate)
&& editGroupDescriptor.equals(e.editGroupDescriptor);
}
}
|
TimDovg/Sales.CRM | Frontend/src/components/crmUI/CRMTag/CRMTagStyles.js | <reponame>TimDovg/Sales.CRM<filename>Frontend/src/components/crmUI/CRMTag/CRMTagStyles.js
// @flow
import commonStyles from 'crm-styles/common';
import {
STATUS_FILTER_BACKGROUND,
HEADER_CELL,
ICON_COLOR,
WHITE,
} from 'crm-constants/jss/colors';
const CRMTagStyles = ({
spacing,
typography: {
caption: { fontSize },
fontWeightRegular,
},
}: Object) => ({
tag: {
fontSize,
'font-weight': fontWeightRegular,
'border-radius': spacing(0.5),
'margin-left': spacing(0.5),
'margin-top': spacing(0.5),
'padding-top': spacing(0.5),
'padding-right': spacing(0),
'padding-bottom': spacing(0.5),
'padding-left': spacing(0),
'color': HEADER_CELL,
'background': STATUS_FILTER_BACKGROUND,
'box-shadow': '0px 1px 1px rgba(0, 25, 91, 0.15)',
'height': 'auto',
},
listTag: {
'background': WHITE,
'box-shadow': '0 0 0 0',
'&:hover': {
'background': STATUS_FILTER_BACKGROUND,
},
},
avatar: {
opacity: 0.5,
'padding': spacing(0),
'margin-right': spacing(0),
'max-height': spacing(3),
'max-width': spacing(3),
'background-color': 'inherit',
'border-radius': 'inherit',
'color': HEADER_CELL,
},
pointer: {
'cursor': 'pointer',
},
label: {
'margin-left': spacing(),
'padding-left': spacing(0),
},
deleteIcon: {
'max-height': spacing(3),
'max-width': spacing(2),
'opacity': 0.5,
'margin-left': spacing(0),
'padding-left': spacing(0),
'color': ICON_COLOR,
},
...commonStyles,
});
export default CRMTagStyles;
|
kkkitsch/zhiyou_workbench | mybatis_6/src/com/zhiyou/mybatis/dao/ClazzMapper.java | package com.zhiyou.mybatis.dao;
import com.zhiyou.mybatis.bean.Clazz;
public interface ClazzMapper {
Clazz getClazzById(int id);
}
|
louisyoungx/rocket | node_modules/element-plus/lib/utils/constants.js | <reponame>louisyoungx/rocket
export var UPDATE_MODEL_EVENT = 'update:modelValue';
export var CHANGE_EVENT = 'change';
export var VALIDATE_STATE_MAP = {
validating: 'el-icon-loading',
success: 'el-icon-circle-check',
error: 'el-icon-circle-close'
}; |
Pustur/edabit-js-challenges | src/Hiding the Card Number/index.js | const cardHide = str => '*'.repeat(str.length - 4) + str.slice(-4);
export default cardHide;
|
markiewb/fakereplace | core/src/main/java/org/fakereplace/core/BuiltinClassData.java | <filename>core/src/main/java/org/fakereplace/core/BuiltinClassData.java
/*
* Copyright 2016, <NAME>, and individual contributors as indicated
* by the @authors tag.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fakereplace.core;
public class BuiltinClassData {
private static final String[] doNotInstrument = {"org/fakereplace", "java/math", "java/lang", "java/util/concurrent", "java/util/Currency", "java/util/Random", "java/util",};
private static final String[] exceptions = {"java/lang/reflect/Proxy",};
public static boolean skipInstrumentation(String className) {
if(className == null) {
return true;
}
className = className.replace('.', '/');
for (String s : exceptions) {
if (className.startsWith(s)) {
return false;
}
}
for (String s : doNotInstrument) {
if (className.startsWith(s)) {
return true;
}
}
return false;
}
}
|
heurezjusz/Athena | athenet/models/alexnet.py | <filename>athenet/models/alexnet.py
"""AlexNet model."""
from athenet import Network
from athenet.layers import ConvolutionalLayer, ReLU, LRN, MaxPool, \
FullyConnectedLayer, Dropout, Softmax
from athenet.utils import load_data, get_bin_path
ALEXNET_FILENAME = 'alexnet_weights.pkl.gz'
def alexnet(trained=True, weights_filename=ALEXNET_FILENAME, weights_url=None):
if trained:
weights = load_data(get_bin_path(weights_filename), weights_url)
if weights is None:
raise Exception("cannot load AlexNet weights")
# Normalization parameters
local_range = 5
alpha = 0.0001
beta = 0.75
k = 1
net = Network([
ConvolutionalLayer(image_shape=(227, 227, 3),
filter_shape=(11, 11, 96),
stride=(4, 4)),
ReLU(),
LRN(local_range=local_range,
alpha=alpha,
beta=beta,
k=k),
MaxPool(poolsize=(3, 3),
stride=(2, 2)),
ConvolutionalLayer(filter_shape=(5, 5, 256),
padding=(2, 2),
n_groups=2),
ReLU(),
LRN(local_range=local_range,
alpha=alpha,
beta=beta,
k=k),
MaxPool(poolsize=(3, 3),
stride=(2, 2)),
ConvolutionalLayer(filter_shape=(3, 3, 384),
padding=(1, 1)),
ReLU(),
ConvolutionalLayer(filter_shape=(3, 3, 384),
padding=(1, 1),
n_groups=2),
ReLU(),
ConvolutionalLayer(filter_shape=(3, 3, 256),
padding=(1, 1),
n_groups=2),
ReLU(),
MaxPool(poolsize=(3, 3),
stride=(2, 2)),
FullyConnectedLayer(4096),
ReLU(),
Dropout(),
FullyConnectedLayer(4096),
ReLU(),
Dropout(),
FullyConnectedLayer(1000),
Softmax()
])
if trained:
net.set_params(weights)
return net
|
digital-10/dataprep-external | src/main/java/kr/co/digitalship/dprep/custom/schedule/job/listener/ListenerJob1.java | <reponame>digital-10/dataprep-external
package kr.co.digitalship.dprep.custom.schedule.job.listener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import kr.co.digitalship.dprep.custom.PropertiesUtil;
import kr.co.digitalship.dprep.custom.Singleton;
import kr.co.digitalship.dprep.custom.redis.SpringRedisTemplateUtil;
import kr.co.digitalship.dprep.custom.schedule.job.Job2CreateDataset;
import kr.co.digitalship.dprep.custom.schedule.util.QuartzConfigUtil;
@Component
@ConditionalOnBean(type = "kr.co.digitalship.dprep.custom.schedule.QuartzConfig")
public class ListenerJob1 implements JobListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ListenerJob1.class);
@Value("${dataprep.node.count:0}")
private int nodeCount;
@Value("${dataprep.node.no:0}")
private int nodeNo;
@Value("${schedule.job.dependence.wait:0}")
private int dependenceWait;
// @Value("${schedule.job1.reschedule:}")
// private boolean job1Reschedule;
// @Value("${schedule.job1_2.cronExp:}")
// private String job1cronExp_2;
@Value("${dataset.service.url:}")
private String[] datasetServiceUrl;
@Autowired
private SpringRedisTemplateUtil springRedisTemplateUtil;
@Autowired
private Job2CreateDataset job2CreateDataset;
@Autowired
private ListenerJob2 listenerJob2;
@Autowired
private ListenerTrigger2 listenerTrigger2;
@PostConstruct
public void init() {
PropertiesUtil properties = Singleton.getInstance().getPropertiesUtil();
nodeCount = Integer.parseInt(properties.getProperty("dataprep.node.count"));
nodeNo = Integer.parseInt(properties.getProperty("dataprep.node.no"));
dependenceWait = Integer.parseInt(properties.getProperty("schedule.job.dependence.wait"));
// job1Reschedule = Boolean.parseBoolean(properties.getProperty("schedule.job1.reschedule"));
// job1cronExp_2 = properties.getProperty("schedule.job1_2.cronExp");
datasetServiceUrl = properties.getProperty("dataset.service.url").trim().split("\\s*,\\s*");
}
@Override
public String getName() {
return getClass().getSimpleName();
}
/**
* JobDetail이 실행될 떄 스케줄러에의해서 호출되는 메서드
* Job 상태 정보 초기 셋팅 및 실행 여부 판단
*
* @param context
*/
@Override
public void jobToBeExecuted(JobExecutionContext context) {
LOGGER.debug(String.format(context.getJobDetail().getKey().getName() + " jobToBeExecuted (%d)", nodeNo));
// DATE_OF_PROCESSING 대한 결정과 이전값과 다른 경우에 Redis에 저장
String yyyyMMdd1 = (String)springRedisTemplateUtil.valueGet("DATE_OF_PROCESSING");
String yyyyMMdd2 = DateFormatUtils.format(new Date(), "yyyyMMdd", Locale.KOREA);
if(StringUtils.isNotEmpty(yyyyMMdd1)) {
if(!yyyyMMdd2.equals(yyyyMMdd1)) {
springRedisTemplateUtil.valueSet("DATE_OF_PROCESSING", yyyyMMdd2);
}
}
else {
springRedisTemplateUtil.valueSet("DATE_OF_PROCESSING", yyyyMMdd2);
}
context.getJobDetail().getJobDataMap().put("job1IsDonePossible", false); // Job 종료 가능여부
}
@Override
public void jobExecutionVetoed(JobExecutionContext context) {
LOGGER.debug(String.format(context.getJobDetail().getKey().getName() + " jobExecutionVetoed (%d)", nodeNo));
}
/**
* Job 실행이 완료된 후 호출되는 메서드
* Job 의 종료 및 후속 실행 Job 셋팅
*
* @param context
* @param jobException
*/
@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
LOGGER.debug(String.format(context.getJobDetail().getKey().getName() + " jobWasExecuted (%d)", nodeNo));
if(context.getJobDetail().getJobDataMap().getBoolean("job1IsDonePossible")) {
/*
int realNodeCount = context.getJobDetail().getJobDataMap().getInt("realNodeCount");
for(int i = nodeCount - 1; i >= 0; i--) {
List<String> jobStatusNode = new ArrayList<String>(Arrays.asList(new String[]{"DONE", "NEW", "NEW", "NEW"}));
if(realNodeCount <= i) {
jobStatusNode = new ArrayList<String>(Arrays.asList(new String[]{"END", "END", "END", "END"}));
springRedisTemplateUtil.valueSet("JOB_STATUS_NODE_" + i, jobStatusNode);
continue;
}
springRedisTemplateUtil.valueSet("JOB_STATUS_NODE_" + i, jobStatusNode);
if(0 == i) {
QuartzConfigUtil.deleteJob(context);
QuartzConfigUtil.scheduleJob(context, job2CreateDataset, listenerJob2, listenerTrigger2);
}
// 개별 노드 Async Call - 개별노드의 Scheduler 에 job2CreateDataset 를 추가한다.
else {
QuartzConfigUtil.addJobToNode(datasetServiceUrl[i], "job2CreateDataset");
}
}
*/
String[] nodeLiveChk = (String[])context.getJobDetail().getJobDataMap().get("nodeLiveChk");
for(int i = nodeLiveChk.length - 1; i >= 0; i--) {
List<String> jobStatusNode = new ArrayList<String>(Arrays.asList(new String[]{"DONE", "NEW", "NEW", "NEW"}));
if("OFF".equals(nodeLiveChk[i])) {
jobStatusNode = new ArrayList<String>(Arrays.asList(new String[]{"END", "END", "END", "END"}));
springRedisTemplateUtil.valueSet("JOB_STATUS_NODE_" + i, jobStatusNode);
continue;
}
springRedisTemplateUtil.valueSet("JOB_STATUS_NODE_" + i, jobStatusNode);
if(0 == i) {
QuartzConfigUtil.deleteJob(context);
QuartzConfigUtil.scheduleJob(context, job2CreateDataset, listenerJob2, listenerTrigger2);
}
// 개별 노드 Async Call - 개별노드의 Scheduler 에 job2CreateDataset 를 추가한다.
else {
QuartzConfigUtil.addJobToNode(datasetServiceUrl[i], "job2CreateDataset");
}
}
}
}
}
|
mangelosalvio/pos | public/bower_components/pouchdb/lib/adapters/leveldb/readAsBlobOrBuffer-browser.js | 'use strict';
var binToBluffer = require('../../deps/binary/binaryStringToBlobOrBuffer');
module.exports = function readAsBlobOrBuffer(storedObject, type) {
// In the browser, we've stored a binary string
return binToBluffer(storedObject, type);
}; |
ThePixly/TGEngine | TGEngine/Stdbase.hpp | <reponame>ThePixly/TGEngine
#pragma once
#include <stdio.h>
#include <iostream>
#include <cstddef>
#ifdef _WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#endif
#undef VK_NO_PROTOTYPES
#include <vulkan/vulkan.hpp>
#include <vector>
#include <string>
#include "util/Annotations.hpp"
#include <thread>
#include "io/Properties.hpp"
#include "util/Math.hpp"
#include <glm/glm.hpp>
#include "util/TGVertex.hpp"
#include "Error.hpp"
extern prop::Properties* properties;
extern uint32_t image_count;
SINCE(0, 0, 4)
#define TGE_VERSION VK_MAKE_VERSION(0, 0, 4)
SINCE(0, 0, 1)
#define HANDEL(result)\
if (result != VK_SUCCESS) {\
TGERROR(result)\
}
SINCE(0, 0, 1)
#define HANDEL_RECREATE(result)\
if(result == VK_ERROR_OUT_OF_DATE_KHR){\
if(window_list[0]->minimized){\
return;\
}\
recreateSwapchain(ibuffer, vbuffer);\
} else {\
HANDEL(result)\
}
SINCE(0, 0, 1)
USAGE_DEBUG
#ifdef DEBUG
#define OUT_LV_DEBUG(out) std::cout << "DEBUG: " << out << std::endl;
#else
#define OUT_LV_DEBUG(out)
#endif
|
keichi/RAJA | include/RAJA/policy/sequential/kernel/Collapse.hpp | /*!
******************************************************************************
*
* \file
*
* \brief Header file for sequential kernel loop collapse executors.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_policy_sequential_kernel_Collapse_HPP
#define RAJA_policy_sequential_kernel_Collapse_HPP
#include "RAJA/pattern/kernel.hpp"
namespace RAJA
{
namespace internal
{
//
// Termination case for seq_exec collapsed loops
//
template <typename... EnclosedStmts, typename Types>
struct StatementExecutor<
statement::Collapse<seq_exec, ArgList<>, EnclosedStmts...>, Types> {
template <typename Data>
static RAJA_INLINE void exec(Data &data)
{
// termination case: no more loops, just execute enclosed statements
execute_statement_list<camp::list<EnclosedStmts...>, Types>(data);
}
};
//
// Executor that handles collapsing of an arbitrarily deep set of seq_exec
// loops
//
template <camp::idx_t Arg0, camp::idx_t... ArgRest, typename... EnclosedStmts, typename Types>
struct StatementExecutor<statement::Collapse<seq_exec,
ArgList<Arg0, ArgRest...>,
EnclosedStmts...>, Types> {
template <typename Data>
static RAJA_INLINE void exec(Data &data)
{
// Set the argument type for this loop
using NewTypes = setSegmentTypeFromData<Types, Arg0, Data>;
// compute next-most inner loop Executor
using next_loop_t = StatementExecutor<
statement::Collapse<seq_exec, ArgList<ArgRest...>, EnclosedStmts...>, NewTypes>;
auto len0 = segment_length<Arg0>(data);
RAJA_NO_SIMD
for (auto i0 = 0; i0 < len0; ++i0) {
data.template assign_offset<Arg0>(i0);
next_loop_t::exec(data);
}
}
};
} // namespace internal
} // end namespace RAJA
#endif /* RAJA_pattern_kernel_HPP */
|
Nikeshh/Ecommerce-Platform | Website/Frontend/admindashboard/src/components/screens/users_screen.js | import React from "react";
import Sidebar from "../sidebar.js";
import Header from "../header.js";
import Users from "./users/users.js";
const UsersScreen = () => {
return(
<>
<Sidebar />
<main className="main-wrap">
<Header />
<Users />
</main>
</>
);
}
export default UsersScreen; |
arne-bdt/jena | jena-db/jena-dboe-trans-data/src/test/java/org/apache/jena/dboe/trans/bplustree/rewriter/TestBPlusTreeRewriterNonTxn.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.dboe.trans.bplustree.rewriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.jena.atlas.lib.Bytes;
import org.apache.jena.dboe.base.block.BlockMgr;
import org.apache.jena.dboe.base.block.BlockMgrFactory;
import org.apache.jena.dboe.base.file.BufferChannel;
import org.apache.jena.dboe.base.file.FileFactory;
import org.apache.jena.dboe.base.file.FileSet;
import org.apache.jena.dboe.base.record.Record;
import org.apache.jena.dboe.base.record.RecordFactory;
import org.apache.jena.dboe.sys.Names;
import org.apache.jena.dboe.trans.bplustree.BPTreeException;
import org.apache.jena.dboe.trans.bplustree.BPlusTree;
import org.apache.jena.dboe.trans.bplustree.BPlusTreeParams;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestBPlusTreeRewriterNonTxn extends Assert
{
// See also CmdTestBlusTreeRewriter for randomized soak testing.
static int KeySize = 4;
static int ValueSize = 8;
static RecordFactory recordFactory = new RecordFactory(KeySize,ValueSize);
// The BPlusTreeRewriter works directly on storage.
static boolean b;
@BeforeClass public static void beforeClass() { b = BlockMgrFactory.AddTracker; BlockMgrFactory.AddTracker = false ; }
@AfterClass public static void afterClass() { BlockMgrFactory.AddTracker = b ;}
@Test public void bpt_rewrite_01() { runTest(2, 0); }
@Test public void bpt_rewrite_02() { runTest(3, 0); }
@Test public void bpt_rewrite_03() { runTest(2, 1); }
@Test public void bpt_rewrite_04() { runTest(3, 1); }
@Test public void bpt_rewrite_05() { runTest(2, 2); }
@Test public void bpt_rewrite_06() { runTest(3, 2); }
@Test public void bpt_rewrite_07() { runTest(2, 100); }
@Test public void bpt_rewrite_08() { runTest(3, 100); }
@Test public void bpt_rewrite_99() { runTest(5, 1000); }
static void runTest(int order, int N)
{ runOneTest(order, N , recordFactory, false); }
public static void runOneTest(int order, int N, RecordFactory recordFactory, boolean debug) {
BPlusTreeParams bptParams = new BPlusTreeParams(order, recordFactory);
//BPlusTreeRewriter.debug = debug;
// ---- Test data
List<Record> originaldata = TestBPlusTreeRewriterNonTxn.createData(N, recordFactory);
if ( debug )
System.out.println("Test data: "+originaldata);
FileSet destination = FileSet.mem();
// ---- Rewrite
BufferChannel rootState = FileFactory.createBufferChannel(destination, Names.extBptState);
// Write leaves to ...
BlockMgr blkMgr1 = BlockMgrFactory.create(destination, Names.extBptTree, bptParams.getCalcBlockSize(), 10, 10);
// Write nodes to ...
BlockMgr blkMgr2 = BlockMgrFactory.create(destination, Names.extBptTree, bptParams.getCalcBlockSize(), 10, 10);
BPlusTree bpt2 = BPlusTreeRewriter.packIntoBPlusTree(originaldata.iterator(), bptParams, recordFactory,
rootState, blkMgr1, blkMgr2);
if ( debug ) {
BPlusTreeRewriterUtils.divider();
bpt2.dump();
}
// ---- Checking
bpt2.check();
scanComparision(originaldata, bpt2);
findComparison(originaldata, bpt2);
sizeComparison(originaldata, bpt2);
}
public static void scanComparision(List<Record> originaldata, BPlusTree bpt2) {
// ** Scan comparisonSetupIndex
Iterator<Record> iter1 = originaldata.iterator();
Iterator<Record> iter2 = bpt2.iterator();
long count = 0;
for (; iter1.hasNext() ; ) {
count++;
Record r1 = iter1.next();
if ( ! iter2.hasNext() )
error("Deviation: new B+Tree is smaller");
Record r2 = iter2.next();
if ( ! Record.equals(r1, r2) )
error("Deviation in iteration record %d: %s : %s", count, r1, r2);
}
if ( iter2.hasNext() )
error("New B+Tree larger than original");
}
public static void findComparison(List<Record> originaldata, BPlusTree bpt2) {
Iterator<Record> iter1 = originaldata.iterator();
long count = 0;
for (; iter1.hasNext() ; ) {
count++;
Record r1 = iter1.next();
Record r3 = bpt2.find(r1);
if ( r3 == null ) {
r3 = bpt2.find(r1);
error("Deviation in find at record %d: %s : null", count, r1);
}
if ( ! Record.equals(r1, r3) )
error("Deviation in find at record %d: %s : %s", count, r1, r3);
}
}
public static void sizeComparison(List<Record> originaldata, BPlusTree bpt2) {
long count1 = originaldata.size();
long count2 = bpt2.size();
//System.out.printf("Sizes = %d / %d\n", count1, count2);
if ( count1 != count2 )
// Not error - this test does not identify why there was a problem so continue.
System.err.println("**** DIFFERENT");
}
static List<Record> createData(int N, RecordFactory recordFactory) {
List<Record> originaldata = new ArrayList<>(N);
for ( int i = 0; i < N; i++ ) {
Record record = recordFactory.create();
Bytes.setInt(i+1, record.getKey());
if ( recordFactory.hasValue() )
Bytes.setInt(10*i+1, record.getValue());
originaldata.add(record);
}
return originaldata;
}
private static void error(String string, Object ...args) {
String msg = String.format(string, args);
System.err.println(msg);
throw new BPTreeException(msg);
}
}
|
hpc/hxhim | examples/hxhim/print_results.c | <reponame>hpc/hxhim<gh_stars>1-10
#include <float.h>
#include <inttypes.h>
#include <stdio.h>
#include "hxhim/accessors.h"
#include "print_results.h"
#include "utils/elen.h"
void print_by_type(void *value, size_t value_len, enum hxhim_data_t type) {
switch (type) {
case HXHIM_DATA_INVALID:
printf("Invalid Type: %d (%zu bytes)", type, value_len);
break;
case HXHIM_DATA_INT32:
printf("%" PRId32, * (int32_t *) value);
break;
case HXHIM_DATA_INT64:
printf("%" PRId64, * (int64_t *) value);
break;
case HXHIM_DATA_UINT32:
printf("%" PRId32, * (uint32_t *) value);
break;
case HXHIM_DATA_UINT64:
printf("%" PRId64, * (uint64_t *) value);
break;
case HXHIM_DATA_FLOAT:
printf("%.*f", FLT_DECIMAL_DIG, * (float *) value);
break;
case HXHIM_DATA_DOUBLE:
printf("%.*f", DBL_DECIMAL_DIG, * (double *) value);
break;
case HXHIM_DATA_BYTE:
printf("%.*s", (int) value_len, (char *) value);
break;
case HXHIM_DATA_POINTER:
printf("%p", value);
break;
default:
printf("Unknown Type: %d (%zu bytes)", type, value_len);
break;
}
}
void print_results(hxhim_t *hx, const int print_rank, hxhim_results_t *results) {
if (!results) {
return;
}
HXHIM_C_RESULTS_LOOP(results) {
if (print_rank) {
int rank = -1;
if (hxhimGetMPI(hx, NULL, &rank, NULL) != HXHIM_SUCCESS) {
printf("Could not get rank\n");
}
else {
printf("Rank %d ", rank);
}
}
enum hxhim_op_t op = HXHIM_INVALID;
hxhim_result_op(results, &op);
int status = HXHIM_ERROR;
hxhim_result_status(results, &status);
int range_server = -1;
hxhim_result_range_server(results, &range_server);
void *subject = NULL;
size_t subject_len = 0;
enum hxhim_data_t subject_type = HXHIM_DATA_INVALID;
void *predicate = NULL;
size_t predicate_len = 0;
enum hxhim_data_t predicate_type = HXHIM_DATA_INVALID;
hxhim_result_subject(results, &subject, &subject_len, &subject_type);
hxhim_result_predicate(results, &predicate, &predicate_len, &predicate_type);
switch (op) {
case HXHIM_PUT:
printf("PUT {");
print_by_type(subject, subject_len, subject_type);
printf(", ");
print_by_type(predicate, predicate_len, predicate_type);
printf("} returned %s from range server %d\n", (status == HXHIM_SUCCESS)?"SUCCESS":"ERROR", range_server);
break;
case HXHIM_GET:
case HXHIM_GETOP:
printf("GET returned ");
if (status == HXHIM_SUCCESS) {
void *object = NULL;
size_t object_len = 0;
enum hxhim_data_t object_type;
hxhim_result_object(results, &object, &object_len, &object_type);
printf("{");
print_by_type(subject, subject_len, subject_type);
printf(", ");
print_by_type(predicate, predicate_len, predicate_type);
printf("} -> ");
print_by_type(object, object_len, object_type);
}
else {
printf("ERROR");
}
printf(" from range server %d\n", range_server);
break;
case HXHIM_DELETE:
printf("DEL {");
print_by_type(subject, subject_len, subject_type);
printf(", ");
print_by_type(predicate, predicate_len, predicate_type);
printf("} returned %s from range server %d\n", (status == HXHIM_SUCCESS)?"SUCCESS":"ERROR", range_server);
break;
default:
printf("Bad Operation: %d\n", (int) op);
break;
}
}
}
|
reels-research/iOS-Private-Frameworks | PassKitUI.framework/PKDiscoveryArticleAnimatedTransitioningHandler.h | <filename>PassKitUI.framework/PKDiscoveryArticleAnimatedTransitioningHandler.h
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/PassKitUI.framework/PassKitUI
*/
@interface PKDiscoveryArticleAnimatedTransitioningHandler : NSObject <UIViewControllerAnimatedTransitioning> {
bool _completed;
UIView * _containerView;
double _duration;
PKDiscoveryArticleViewController * _presentedVC;
UIView * _presentedView;
bool _presenting;
PKPassGroupsViewController * _presentingVC;
UIView * _presentingView;
<UIViewControllerContextTransitioning> * _transitionContext;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (nonatomic) double duration;
@property (readonly) unsigned long long hash;
@property (getter=isPresenting, nonatomic) bool presenting;
@property (readonly) Class superclass;
- (void).cxx_destruct;
- (void)_moveCardView:(id)arg1 toView:(id)arg2 belowView:(id)arg3;
- (void)_updateWithTransitionContext:(id)arg1;
- (void)animateTransition:(id)arg1;
- (double)duration;
- (bool)isPresenting;
- (void)setDuration:(double)arg1;
- (void)setPresenting:(bool)arg1;
- (double)transitionDuration:(id)arg1;
@end
|
annajohny/sdp | tug_observers/tug_observer_plugins/tug_observer_plugin_utils/scripts/filter/valuefilter.py | <filename>tug_observers/tug_observer_plugins/tug_observer_plugin_utils/scripts/filter/valuefilter.py
#!/usr/bin/env python
from tug_python_utils import YamlHelper as Config
class ValueFilter():
"""
Base class for filter.
"""
def __init__(self):
self.sample_size = 0
pass
def update(self, new_value):
"""
Give the filter a new value. Maybe its necessary to apply the filter each time.
Consider the use of resources, because this can be called very often.
:param new_value: New value for the filter
"""
pass
def get_value(self):
"""
Return the result here. Maybe its necessary to apply the filter first.
:return: Result of the filter
"""
return None, None
def reset(self):
"""
Reset the filter, to remove any history. Necessary for a clean restart.
"""
pass
class ValueFilterFactory():
"""
Factory for getting the right filter instance.
"""
def __init__(self):
pass
@staticmethod
def create_value_filter(config):
"""
Decode filter type from config and return new instance of corresponding filter.
:param config: Configuration from yaml file
:return: New instance of a corresponding filter
"""
value_filter_type = Config.get_param(config, 'type')
if value_filter_type == "mean":
return MeanValueFilter(config)
elif value_filter_type == "median":
return MedianValueFilter(config)
elif value_filter_type == "kmeans":
return KMeansValueFilter(config)
elif value_filter_type == "ewma":
return ExponentiallyWeightedMovingAverageValueFilter(config)
elif value_filter_type == "nofilter":
return NoValueFilter(config)
else:
return ValueFilter()
# raise NameError("'" + str(value_filter_type) + "' from config not found in value-filter!")
class MedianValueFilter(ValueFilter):
"""
Filter for getting the median of a defined number of values
"""
def __init__(self, config):
"""
Constructor for median filter object. Uses a ringbuffer of given size.
:param config: Configuration from yaml file
"""
from collections import deque
ValueFilter.__init__(self)
self.window_size = Config.get_param(config, 'window_size')
self._ring_buffer = deque(maxlen=self.window_size)
def update(self, new_value):
"""
Append new value to ringbuffer.
:param new_value: New value, which should be added to ring buffer
"""
self._ring_buffer.append(new_value)
self.sample_size = len(self._ring_buffer)
def get_value(self):
"""
Apply the filter and return the resulting value.
:return: Result of the applied filter
"""
data = sorted(self._ring_buffer)
n = len(data)
if n == 0:
result = None
elif n % 2 == 1:
result = data[n//2]
else:
i = n//2
result = (data[i - 1] + data[i])/2
return result, self.sample_size
def reset(self):
"""
Reset the filter, that cleans the buffer.
"""
self._ring_buffer.clear()
self.sample_size = 0
class MeanValueFilter(ValueFilter):
"""
Filter for getting the mean of a defined number of values
"""
def __init__(self, config):
"""
Constructor for mean filter object. Uses a ringbuffer of given size.
:param config: Configuration from yaml file
"""
from collections import deque
ValueFilter.__init__(self)
self.window_size = Config.get_param(config, 'window_size')
self._ring_buffer = deque(maxlen=self.window_size)
def update(self, new_value):
"""
Append new value to ringbuffer.
:param new_value: New value, which should be added to ring buffer
"""
self._ring_buffer.append(new_value)
self.sample_size = len(self._ring_buffer)
def get_value(self):
"""
Apply the filter and return the resulting value.
:return: Result of the applied filter
"""
size = len(self._ring_buffer)
if not size:
result = None
else:
result = sum(self._ring_buffer) / size
return result, self.sample_size
def reset(self):
"""
Reset the filter, that cleans the buffer.
"""
self._ring_buffer.clear()
self.sample_size = 0
class KMeansValueFilter(ValueFilter):
"""
Filter for getting the k-means of a defined number of values in a defined buffer.
"""
def __init__(self, config):
"""
Constructor for k-mean filter object. Uses a ringbuffer of given size and take the mean of window.
:param config: Configuration from yaml file
"""
from collections import deque
ValueFilter.__init__(self)
self.k_half = Config.get_param(config, 'k_size') / 2
self.window_size = Config.get_param(config, 'window_size')
self._ring_buffer = deque(maxlen=self.window_size)
def update(self, new_value):
"""
Append new value to ringbuffer.
:param new_value: New value, which should be added to ring buffer
"""
self._ring_buffer.append(new_value)
self.sample_size = len(self._ring_buffer)
def get_value(self):
"""
Apply the filter and return the resulting value.
:return: Result of the applied filter
"""
size = len(self._ring_buffer)
if not size:
result = None
else:
center_index = size // 2
lower_index = max(center_index - self.k_half, 0)
upper_index = min(center_index + self.k_half, size)
small_list = list(self._ring_buffer)[lower_index:upper_index + 1]
result = sum(small_list) / len(small_list)
return result, self.sample_size
def reset(self):
"""
Reset the filter, that cleans the buffer.
"""
self._ring_buffer.clear()
self.sample_size = 0
class ExponentiallyWeightedMovingAverageValueFilter(ValueFilter):
"""
Filter for applying weighted values to history.
"""
def __init__(self, config):
"""
Constructor for exponentially weighted moving average (EWMA) filter object.
Applies new values weighted to history.
:param config: Configuration from yaml file
"""
ValueFilter.__init__(self)
self._decay_rate = Config.get_param(config, 'decay_rate')
if Config.has_key(config, 'window_size'):
from collections import deque
self.window_size = Config.get_param(config, 'window_size')
self._ring_buffer = deque(maxlen=self.window_size)
self.update = self.update_buffered
self.get_value = self.get_value_buffered
self.reset = self.reset_buffered
else:
self._current_value = None
self.update = self.update_unbuffered
self.get_value = self.get_value_unbuffered
self.reset = self.reset_unbuffered
def update_unbuffered(self, new_value):
"""
Add new value to the history with given weight.
:param new_value: New value, which should be added to history
"""
if self._current_value is None:
self._current_value = new_value * 1.0
else:
self._current_value = self._current_value * (1.0 - self._decay_rate) + new_value * self._decay_rate
self.sample_size += 1
def update_buffered(self, new_value):
"""
Append new value to ringbuffer.
:param new_value: New value, which should be added to ring buffer
"""
self._ring_buffer.append(new_value)
self.sample_size = len(self._ring_buffer)
def get_value_unbuffered(self):
"""
Filter result is already up-to-date. Just return the value.
:return: Result of the filter
"""
return self._current_value, self.sample_size
def get_value_buffered(self):
"""
Apply the filter and return the resulting value.
:return: Result of the applied filter
"""
if not len(self._ring_buffer):
return None, self.sample_size
value = self._ring_buffer[0]
for index in range(1, len(self._ring_buffer)):
value = value * (1-self._decay_rate) + self._ring_buffer[index] * self._decay_rate
return value, self.sample_size
def reset_unbuffered(self):
"""
Reset the filter, that cleans the history.
"""
self._current_value = None
self.sample_size = 0
def reset_buffered(self):
"""
Reset the filter, that cleans the history.
"""
self._ring_buffer.clear()
self.sample_size = 0
class NoValueFilter(ValueFilter):
"""
This is not a filter. it just stores the current value.
"""
def __init__(self, config):
ValueFilter.__init__(self)
self._current_value = None
def update(self, new_value):
"""
Store new value as current value.
:param new_value: New value, which should be stored
"""
self._current_value = new_value
self.sample_size = 1
def get_value(self):
"""
This is not really a filter. Just return the current value.
:return: current stored value
"""
return self._current_value, self.sample_size
def reset(self):
"""
Reset the filter, that cleans the current value.
"""
self._current_value = None
self.sample_size = 0
|
yop-platform/yop-java-sdk | src/test/java/com/yeepay/yop/sdk/service/common/SmD2DERTest.java | /*
* Copyright: Copyright (c)2011
* Company: 易宝支付(YeePay)
*/
package com.yeepay.yop.sdk.service.common;
import com.yeepay.yop.sdk.utils.Encodes;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.spec.OpenSSHPrivateKeySpec;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* title: <br>
* description: 描述<br>
* Copyright: Copyright (c)2014<br>
* Company: 易宝支付(YeePay)<br>
*
* @author dreambt
* @version 1.0.0
* @since 2021/4/25 15:58
*/
@Ignore
public class SmD2DERTest {
private String name = "sm2p256v1";
// private String name = "secp256r1";
@Before
public void setUp() throws Exception {
Security.addProvider(new BouncyCastleProvider());
}
@Test
public void test() throws NoSuchAlgorithmException, InvalidKeySpecException {
// System.out.println(new BigInteger("66213661209421575346612329707679341349846984049698527221136155542979076962211", 10).toString(16));
// System.out.println(new BigInteger("B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207", 16).toString(10));
// BCECPrivateKey privateKey = gen("00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5", 16);
BCECPrivateKey privateKey = gen("19791495634805870336639420566697069981441064876895811215840904284068948694620", 10);// QA 平台私钥(软实现)
// BCECPrivateKey privateKey = gen("<KEY>", 16);// 测试商户
// BCECPrivateKey privateKey = gen("66213661209421575346612329707679341349846984049698527221136155542979076962211", 10);// QA 测试商户
// BCECPrivateKey privateKey = gen("3280669176762575646620873917953536687380369812122663660521903390632009968484", 10);// 内测 测试商户
System.out.println("a:" + privateKey.getParameters().getCurve().getA().toBigInteger());
System.out.println("b:" + privateKey.getParameters().getCurve().getB().toBigInteger());
System.out.println("x:" + privateKey.getParameters().getG().getAffineXCoord().toBigInteger());
System.out.println("y:" + privateKey.getParameters().getG().getAffineYCoord().toBigInteger());
PKCS8EncodedKeySpec spec8 = new PKCS8EncodedKeySpec(privateKey.getEncoded());
System.out.println("priKey(pkcs8):" + Encodes.encodeBase64(spec8.getEncoded()));
X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(privateKey.getEncoded());
System.out.println("priKey(x509):" + Encodes.encodeBase64(x509Spec.getEncoded()));
OpenSSHPrivateKeySpec opensshSpec = new OpenSSHPrivateKeySpec(privateKey.getEncoded());
System.out.println("priKey(openssh):" + Encodes.encodeBase64(opensshSpec.getEncoded()));
// 计算公钥
ECParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
ECPoint q = new FixedPointCombMultiplier().multiply(spec.getG(), ((BCECPrivateKey) privateKey).getD()).normalize();
// 49490cb687c07c62248fa043d4adb461c151db8cea9abb9bec86952681ec7f1d
// e5a024d9bca7b15cfa569d863f65bfa63ebdf089eb8b0876ca0741e88a64d30b
String publicKeyStr = q.getAffineXCoord().toString() + q.getAffineYCoord().toString();
System.out.println("pubKey 16:" + publicKeyStr);
System.out.println("pubKey 10:" + q.getAffineXCoord().toBigInteger().toString() + "\n" + q.getAffineYCoord().toBigInteger().toString());
//
ECPublicKeySpec keySpec = new ECPublicKeySpec(q, spec);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
spec8 = new PKCS8EncodedKeySpec(publicKey.getEncoded());
System.out.println("pubKey:" + Encodes.encodeBase64(spec8.getEncoded()));
}
private BCECPrivateKey gen(String num, int jinzhi) {
ECParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec(name);
ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(num, jinzhi), ecParameterSpec);
System.out.println("priKey 10进制:" + new BigInteger(num, jinzhi).toString(10));
System.out.println("priKey 16进制:" + new BigInteger(num, jinzhi).toString(16));
try {
KeyFactory keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
return (BCECPrivateKey) keyFactory.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) {
e.printStackTrace();
return null;
}
}
}
|
StepanBarantsev/course_management | web/app/__init__.py | <filename>web/app/__init__.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from web.config import Config
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_mail import Mail
db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = 'Войдите в систему, чтобы просматривать данную страницу!'
bootstrap = Bootstrap()
moment = Moment()
mail = Mail()
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
app.register_error_handler(404, page_not_found)
db.init_app(app)
migrate.init_app(app, db)
login_manager.init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
mail.init_app(app)
from web.app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from web.app.main import bp as main_bp
app.register_blueprint(main_bp)
from web.app.coursecreate import bp as coursecreate_bp
app.register_blueprint(coursecreate_bp, url_prefix='/coursecreate')
from web.app.profile import bp as profile_bp
app.register_blueprint(profile_bp)
from web.app.students import bp as students_bp
app.register_blueprint(students_bp, url_prefix='/students')
from web.app.checks import bp as checks_bp
app.register_blueprint(checks_bp, url_prefix='/checks')
return app
def page_not_found(e):
return render_template('error/404.html'), 404
|
netochaves/IsCoolApp2 | app/src/main/java/easii/com/br/iscoolapp/objetos/DisciplinaAluno.java | package easii.com.br.iscoolapp.objetos;
/**
* Created by gustavo on 15/09/2016.
*/
public class DisciplinaAluno {
private long id;
private String nome;
private String turma;
private String serie;
private String escola;
private String nomeProfessor;
public DisciplinaAluno(long id, String nome, String turmo, String serie, String escola, String professor) {
this.id = id;
this.nome = nome;
this.turma = turmo;
this.serie = serie;
this.escola = escola;
this.nomeProfessor = professor;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTurmo() {
return turma;
}
public void setTurmo(String turmo) {
this.turma = turmo;
}
public String getSerie() {
return serie;
}
public void setSerie(String serie) {
this.serie = serie;
}
public String getEscola() {
return escola;
}
public void setEscola(String escola) {
this.escola = escola;
}
public String getNomeProfessor() {
return nomeProfessor;
}
public void setNomeProfessor(String nomeProfessor) {
this.nomeProfessor = nomeProfessor;
}
}
|
ryoon/vialer-js | gulp/tasks/code.js | <gh_stars>100-1000
const {_extend, promisify} = require('util')
const fs = require('fs')
const path = require('path')
const browserify = require('browserify')
const buffer = require('vinyl-buffer')
const composer = require('gulp-uglify/composer')
const envify = require('gulp-envify')
const gulp = require('gulp')
const ifElse = require('gulp-if-else')
const logger = require('gulplog')
const minifier = composer(require('uglify-es'), console)
const notify = require('gulp-notify')
const size = require('gulp-size')
const source = require('vinyl-source-stream')
const sourcemaps = require('gulp-sourcemaps')
const through = require('through2')
const watchify = require('watchify')
const writeFileAsync = promisify(fs.writeFile)
let bundlers = {}
let helpers = {}
let tasks = {}
module.exports = function(settings) {
/**
* Create a Browserify bundle.
* @param {Object} options - Options to pass.
* @param {Array} options.addons - Extra bundle entries.
* @param {String} options.entry - Entrypoint file.
* @param {String} options.name - Bundle name.
* @param {Array} options.requires - Extra bundle requires.
* @returns {Promise} - Resolves when bundling is finished.
*/
helpers.compile = function({addons = [], entry, requires = [], name}) {
const brand = settings.brands[settings.BRAND_TARGET]
if (!bundlers[name]) {
let bundlerOptions = {
basedir: settings.BASE_DIR,
cache: {},
debug: !settings.BUILD_OPTIMIZED,
packageCache: {},
paths: [
path.join(settings.ROOT_DIR, '../'),
],
}
if (entry) bundlerOptions.entries = entry
bundlers[name] = browserify(bundlerOptions)
if (settings.LIVERELOAD) bundlers[name].plugin(watchify)
for (let _addon of addons) bundlers[name].add(_addon)
for (const _require of requires) bundlers[name].require(_require)
bundlers[name].ignore('buffer')
bundlers[name].ignore('process')
bundlers[name].ignore('rc')
bundlers[name].ignore('module-alias/register')
// Exclude the webextension polyfill from non-webextension builds.
if (name === 'webview') bundlers[name].ignore('webextension-polyfill')
helpers.transform(bundlers[name])
}
return new Promise((resolve) => {
bundlers[name].bundle()
.on('error', notify.onError('Error: <%= error.message %>'))
.on('end', () => {resolve()})
.pipe(source(`${name}.js`))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(helpers.envify(brand))
.pipe(ifElse(settings.BUILD_OPTIMIZED, () => minifier()))
.pipe(sourcemaps.write('./'))
.pipe(size(_extend({title: `${name}.js`}, settings.SIZE_OPTIONS)))
.pipe(gulp.dest(path.join(settings.BUILD_DIR, 'js')))
})
}
helpers.envify = function(brand) {
return envify({
ANALYTICS_ID: brand.telemetry.analytics_id[settings.BUILD_TARGET],
APP_NAME: brand.name.production,
BRAND_TARGET: settings.BRAND_TARGET,
BUILD_VERBOSE: settings.BUILD_VERBOSE,
BUILTIN_AVAILABILITY_ADDONS: brand.plugins.builtin.availability.addons,
BUILTIN_CONTACTS_I18N: brand.plugins.builtin.contacts.i18n,
BUILTIN_CONTACTS_PROVIDERS: brand.plugins.builtin.contacts.providers,
BUILTIN_USER_ADAPTER: brand.plugins.builtin.user.adapter,
BUILTIN_USER_I18N: brand.plugins.builtin.user.i18n,
CUSTOM_MOD: brand.plugins.custom,
NODE_ENV: settings.NODE_ENV,
PLATFORM_URL: brand.permissions,
PORTAL_NAME: brand.vendor.portal.name,
PORTAL_URL: brand.vendor.portal.url,
PUBLISH_CHANNEL: settings.PUBLISH_CHANNEL,
SENTRY_DSN: brand.telemetry.sentry.dsn,
SIP_ENDPOINT: brand.sip_endpoint,
STUN: brand.stun,
VENDOR_NAME: brand.vendor.name,
VENDOR_SUPPORT_EMAIL: brand.vendor.support.email,
VENDOR_SUPPORT_PHONE: brand.vendor.support.phone,
VENDOR_SUPPORT_WEBSITE: brand.vendor.support.website,
VERSION: settings.PACKAGE.version,
})
}
helpers.plugins = async function(sectionModules, appSection) {
let requires = []
for (const moduleName of Object.keys(sectionModules)) {
const sectionModule = sectionModules[moduleName]
// Builtin modules use special markers.
if (['bg', 'i18n'].includes(appSection)) {
if (sectionModule.adapter) {
logger.info(`[${appSection}] adapter plugin ${moduleName} (${sectionModule.adapter})`)
requires.push(`${sectionModule.adapter}/src/js/${appSection}`)
} else if (sectionModule.providers) {
for (const provider of sectionModule.providers) {
logger.info(`[${appSection}] provider plugin ${moduleName} (${provider})`)
requires.push(`${provider}/src/js/${appSection}`)
}
}
}
if (sectionModule.addons) {
for (const addon of sectionModule.addons[appSection]) {
logger.info(`[${appSection}] addon plugin ${moduleName} (${addon})`)
requires.push(`${addon}/src/js/${appSection}`)
}
} else if (sectionModule.name) {
logger.info(`[${appSection}] custom plugin ${moduleName} (${sectionModule.name})`)
// A custom module is limited to a bg or fg section.
if (sectionModule.parts.includes(appSection)) {
requires.push(`${sectionModule.name}/src/js/${appSection}`)
}
}
}
await helpers.compile({name: `app_${appSection}_plugins`, requires})
}
/**
* Allow cleaner imports by rewriting commonjs require.
* From: "vialer-js/bg/plugins/user/adapter"
* To: "vialer-js/src/js/bg/plugins/user/adapter"
*
* Within the node runtime, the same kind of aliasing is applied
* using module-alias. See `package.json` for the alias definition.
* @param {Browserify} bundler - The Browserify bundler.
*/
helpers.transform = function(bundler) {
bundler.transform({global: true}, function(file, opts) {
// Do a negative look-ahead to exclude matches that contain `vialer-js/src`.
const aliasMatch = /(require\('vialer-js)(?!.*src)./g
return through(function(buf, enc, next) {
this.push(buf.toString('utf8').replace(aliasMatch, 'require(\'vialer-js/src/js/'))
next()
})
})
}
tasks.appBg = async function codeAppBg(done) {
await helpers.compile({entry: './src/js/bg/index.js', name: 'app_bg'})
done()
}
tasks.appFg = async function codeAppFg(done) {
await helpers.compile({entry: './src/js/fg/index.js', name: 'app_fg'})
done()
}
tasks.appI18n = async function codeAppI18n(done) {
const builtin = settings.brands[settings.BRAND_TARGET].plugins.builtin
const custom = settings.brands[settings.BRAND_TARGET].plugins.custom
await Promise.all([
helpers.plugins(Object.assign(builtin, custom), 'i18n'),
helpers.compile({entry: './src/js/i18n/index.js', name: 'app_i18n'}),
])
done()
}
tasks.appObserver = async function codeAppObserver(done) {
await helpers.compile({entry: './src/js/observer/index.js', name: 'app_observer'})
done()
}
tasks.plugins = function codeAppPlugins(done) {
const builtin = settings.brands[settings.BRAND_TARGET].plugins.builtin
const custom = settings.brands[settings.BRAND_TARGET].plugins.custom
Promise.all([
helpers.plugins(Object.assign(builtin, custom), 'bg'),
helpers.plugins(Object.assign(builtin, custom), 'fg'),
]).then(() => {
done()
})
}
tasks.electron = function codeElectron(done) {
if (settings.BUILD_TARGET !== 'electron') {
logger.info(`Electron task doesn\'t make sense for build target ${settings.BUILD_TARGET}`)
return
}
// Vendor-specific info for Electron's main.js file.
fs.createReadStream('./src/js/main.js').pipe(
fs.createWriteStream(`./build/${settings.BRAND_TARGET}/${settings.BUILD_TARGET}/main.js`)
)
const electronBrandSettings = settings.brands[settings.BRAND_TARGET].vendor
const settingsFile = `./build/${settings.BRAND_TARGET}/${settings.BUILD_TARGET}/settings.json`
writeFileAsync(settingsFile, JSON.stringify(electronBrandSettings)).then(() => {done()})
}
tasks.vendorBg = async function codeVendorBg(done) {
await helpers.compile({entry: './src/js/bg/vendor.js', name: 'vendor_bg'})
done()
}
tasks.vendorFg = async function codeVendorFg(done) {
await helpers.compile({
addons: [
path.join(settings.TEMP_DIR, settings.BRAND_TARGET, 'build', 'index.js'),
],
entry: './src/js/fg/vendor.js',
name: 'vendor_fg',
})
done()
}
return {helpers, tasks}
}
|
kalik1/q3-server-docker-rest-api | src/api/rcon/index.js | <gh_stars>1-10
'use strict';
const Router = require('express').Router;
const controller = require('./rcon.controller');
let router = new Router();
router.get('/status', controller.status());
router.get('/serverinfo', controller.serverinfo());
router.post('/setVar', controller.setVar);
router.get('/:cmd', controller.command());
// router.get('/', controller.index.bind(controller));
// router.get('/:id', controller.show.bind(controller));
// router.post('/', controller.create.bind(controller));
// router.put('/:id', controller.update.bind(controller));
// router.patch('/:id', controller.update.bind(controller));
// router.delete('/:id', controller.destroy.bind(controller));
module.exports = router;
|
JMMarchant/jung | jung-io/src/test/java/edu/uci/ics/jung/io/graphml/DummyEdge.java | <reponame>JMMarchant/jung
package edu.uci.ics.jung.io.graphml;
import com.google.common.base.Function;
public class DummyEdge extends DummyGraphObjectBase {
public static class EdgeFactory implements Function<EdgeMetadata, DummyEdge> {
int n = 100;
public DummyEdge apply(EdgeMetadata md) {
return new DummyEdge(n++);
}
}
public static class HyperEdgeFactory implements Function<HyperEdgeMetadata, DummyEdge> {
int n = 0;
public DummyEdge apply(HyperEdgeMetadata md) {
return new DummyEdge(n++);
}
}
public DummyEdge() {
}
public DummyEdge(int v) {
super(v);
}
}
|
RBSystems/device-monitoring-microservice | localsystem/hardware.go | <gh_stars>1-10
package localsystem
import (
"context"
"fmt"
"io/ioutil"
"math"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/byuoitav/common/log"
"github.com/byuoitav/common/nerr"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/docker"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/process"
)
const (
temperatureRootPath = "/sys/class/thermal"
uSleepCheckInterval = 3 * time.Second
uSleepResetInterval = 5 * time.Minute
)
var (
avgProcsInit sync.Once
avgProcsInUSleep float64
)
// CPUInfo .
func CPUInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
// get hardware info about cpu
cpuState, err := cpu.Info()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get cpu info")
}
info["hardware"] = cpuState
// get percent usage information per cpu
usage := make(map[string]float64)
info["usage"] = usage
percentages, err := cpu.Percent(0, true)
if err != nil {
return info, nerr.Translate(err).Addf("failed to get cpu info")
}
for i := range percentages {
usage[fmt.Sprintf("cpu%d", i)] = round(percentages[i], .01)
}
// get average usage
avgPercent, err := cpu.Percent(0, false)
if err != nil {
return info, nerr.Translate(err).Addf("failed to get cpu info")
}
if len(avgPercent) == 1 {
usage["avg"] = round(avgPercent[0], .01)
}
// get load average metrics
loadAvg, err := load.Avg()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get load avg info")
}
info["avg1min"] = loadAvg.Load1
info["avg5min"] = loadAvg.Load5
return info, nil
}
// MemoryInfo .
func MemoryInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
vMem, err := mem.VirtualMemory()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get memory info")
}
vMem.UsedPercent = round(vMem.UsedPercent, .01)
info["virtual"] = vMem
sMem, err := mem.SwapMemory()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get memory info")
}
sMem.UsedPercent = round(sMem.UsedPercent, .01)
info["swap"] = sMem
return info, nil
}
// HostInfo .
func HostInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
stat, err := host.Info()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get host info")
}
info["os"] = stat
users, err := host.Users()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get host info")
}
info["users"] = users
temps := make(map[string]float64)
count := make(map[string]int)
info["temperature"] = temps
filepath.Walk(temperatureRootPath, func(path string, info os.FileInfo, err error) error {
if info.Mode()&os.ModeSymlink == os.ModeSymlink && strings.Contains(path, "thermal_") {
// get type
ttype, err := ioutil.ReadFile(path + "/type")
if err != nil {
return err
}
// get temperature
ttemp, err := ioutil.ReadFile(path + "/temp")
if err != nil {
return err
}
stype := strings.TrimSpace(string(ttype))
dtemp, err := strconv.ParseFloat(strings.TrimSpace(string(ttemp)), 64)
temps[fmt.Sprintf("%s%d", stype, count[stype])] = dtemp / 1000
count[stype]++
}
if info.IsDir() && path != temperatureRootPath {
return filepath.SkipDir
}
return nil
})
return info, nil
}
// DiskInfo .
func DiskInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
usage, err := disk.Usage("/")
if err != nil {
return info, nerr.Translate(err).Addf("failed to get disk info")
}
usage.UsedPercent = round(usage.UsedPercent, .01)
info["usage"] = usage
ioCounters, err := disk.IOCounters("sda", "mmcblk0")
if err != nil {
return info, nerr.Translate(err).Addf("failed to get disk info")
}
info["io-counters"] = ioCounters
return info, nil
}
// NetworkInfo .
func NetworkInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
interfaces, err := net.Interfaces()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get network info")
}
info["interfaces"] = interfaces
return info, nil
}
// DockerInfo .
func DockerInfo() (map[string]interface{}, *nerr.E) {
info := make(map[string]interface{})
stats, err := docker.GetDockerStat()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get docker info")
}
info["stats"] = stats
//add section getting the number of running docker containers
ctx := context.Background()
cli, err := client.NewEnvClient()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get docker info")
}
cli.NegotiateAPIVersion(ctx)
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
return info, nerr.Translate(err).Addf("failed to get docker info")
}
info["docker-containers"] = len(containers)
return info, nil
}
// ProcsInfo .
func ProcsInfo() (map[string]interface{}, *nerr.E) {
avgProcsInit.Do(startWatchingUSleep)
info := make(map[string]interface{})
procs, err := process.Processes()
if err != nil {
return info, nerr.Translate(err).Addf("failed to get processes info")
}
bad := []string{}
for _, p := range procs {
status, err := p.Status()
if err != nil {
continue
}
if status == "D" {
name, err := p.Name()
if err != nil {
name = fmt.Sprintf("unable to get name: %s", name)
}
bad = append(bad, name)
}
}
info["cur-procs-u-sleep"] = bad
info["avg-procs-u-sleep"] = avgProcsInUSleep
return info, nil
}
// constantly measure the number of processes that are in sleep and get an average
func startWatchingUSleep() {
avgProcsInUSleep = 0
checkTicker := time.NewTicker(uSleepCheckInterval)
resetTicker := time.NewTicker(uSleepResetInterval)
go func() {
defer checkTicker.Stop()
defer resetTicker.Stop()
for {
select {
case <-checkTicker.C:
procs, err := process.Processes()
if err != nil {
log.L.Warnf("failed to get running processes: %s", err)
continue
}
count := 0
for _, p := range procs {
status, err := p.Status()
if err != nil {
continue
}
if status == "D" {
count++
}
}
avgProcsInUSleep = (avgProcsInUSleep + float64(count)) / 2
avgProcsInUSleep = round(avgProcsInUSleep, .05)
case <-resetTicker.C:
avgProcsInUSleep = 0
}
}
}()
}
func round(x, unit float64) float64 {
return math.Round(x/unit) * unit
}
|
freundlich/fcppt | libs/core/include/fcppt/mpl/map/equal.hpp | <gh_stars>10-100
// Copyright <NAME> 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MPL_MAP_EQUAL_HPP_INCLUDED
#define FCPPT_MPL_MAP_EQUAL_HPP_INCLUDED
#include <fcppt/mpl/apply.hpp>
#include <fcppt/mpl/arg.hpp>
#include <fcppt/mpl/bind.hpp>
#include <fcppt/mpl/constant.hpp>
#include <fcppt/mpl/if.hpp>
#include <fcppt/mpl/lambda.hpp>
#include <fcppt/mpl/list/all_of.hpp>
#include <fcppt/mpl/map/at.hpp>
#include <fcppt/mpl/map/keys.hpp>
#include <fcppt/mpl/map/object_concept.hpp>
#include <fcppt/mpl/set/equal.hpp>
#include <fcppt/mpl/set/to_list.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt::mpl::map
{
namespace detail::equal_impl
{
template <typename Map1, typename Map2>
using map_same_values = fcppt::mpl::list::all_of<
fcppt::mpl::set::to_list<fcppt::mpl::map::keys<Map1>>,
fcppt::mpl::bind<
fcppt::mpl::lambda<std::is_same>,
fcppt::mpl::bind<
fcppt::mpl::lambda<fcppt::mpl::map::at>,
fcppt::mpl::constant<Map1>,
fcppt::mpl::arg<1>>,
fcppt::mpl::bind<
fcppt::mpl::lambda<fcppt::mpl::map::at>,
fcppt::mpl::constant<Map2>,
fcppt::mpl::arg<1>>>>;
}
/**
\brief Checks if two maps are equal.
\ingroup fcpptmpl
Two maps are equal if and only if they contain the same key-value pairs.
Let <code>Map1=map::object<element<K_1,V_1>,...,element<K_n,V_n>></code>
and <code>Map2=map::object<element<K_1',V_1'>,...,element<K_m',V_m'>></code>.
Then the result is <code>std::true_type</code> if
\code
{(K_1,V_1),...,(K_n,V_n)} = {(K_1',V_1'),...,(K_m',V_m')}
\endcode
Otherwise, the result is <code>std::false_type</code>.
*/
template <fcppt::mpl::map::object_concept Map1, fcppt::mpl::map::object_concept Map2>
using equal = fcppt::mpl::apply<fcppt::mpl::if_<
fcppt::mpl::set::equal<fcppt::mpl::map::keys<Map1>, fcppt::mpl::map::keys<Map2>>,
fcppt::mpl::bind<
fcppt::mpl::lambda<fcppt::mpl::map::detail::equal_impl::map_same_values>,
fcppt::mpl::constant<Map1>,
fcppt::mpl::constant<Map2>>,
fcppt::mpl::constant<std::false_type>>>;
}
#endif
|
consected/restructure | app/errors/fs_exception/upload.rb | <gh_stars>1-10
module FsException
class Upload < Exception
end
end
|
bradrf/kubey | kubey/table_row_popen.py | import subprocess
import re
from threading import Thread
class TableRowPopen(subprocess.Popen):
def __init__(self, row_handler, *args, **kwargs):
self._row_handler = row_handler
kwargs['stdout'] = subprocess.PIPE
super(TableRowPopen, self).__init__(*args, **kwargs)
self._stdout_thread = Thread(target=self._parse_table)
self._stdout_thread.start()
def wait(self):
result = super(TableRowPopen, self).wait()
self._stdout_thread.join()
return result
def _parse_table(self):
line_number = 0
with self.stdout as io:
while True:
line = io.readline().rstrip().decode('utf-8')
if not line:
break
line_number += 1
row = self._title_row_from(line) if line_number == 1 else self._row_from(line)
self._row_handler(line_number, row)
def _title_row_from(self, line):
'''Splits the first line of output expecting the first char in each header to indicate the
start of items in following rows for the column data (i.e. left-aligned)
'''
row = re.split(r' +|\t', line) # expects either more than two spaces or tabs as separation
self._column_offsets = []
beg = 0
for col in row:
offset = line.index(col, beg)
self._column_offsets.append(offset)
beg += len(col)
return row
def _row_from(self, line):
row = []
beg = self._column_offsets[0]
for end in self._column_offsets[1:]:
row.append(line[beg:end].strip())
beg = end
row.append(line[beg:].strip())
return row
|
qbizns/Android-Uber-Clone | PartnerApp/app/src/main/java/com/tatx/partnerapp/adapter/ViewAllReferralsListAdapter.java | <gh_stars>0
package com.tatx.partnerapp.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.tatx.partnerapp.R;
import com.tatx.partnerapp.commonutills.Common;
import com.tatx.partnerapp.pojos.AllReferral;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by <NAME> on 27-12-2016.
*/
public class ViewAllReferralsListAdapter extends RecyclerView.Adapter<ViewAllReferralsListAdapter.ViewHolder>
{
List<AllReferral> allReferral;
Context context;
private final String currencyCode;
public ViewAllReferralsListAdapter(Context context, List<AllReferral> allReferral, String currencyCode)
{
this.context = context;
this.allReferral = allReferral;
this.currencyCode = currencyCode;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_referral_code_list_item,viewGroup,false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int i)
{
Common.Log.i("? - allReferral : "+allReferral);
if (allReferral.get(i).profile != null)
{
Picasso.with(context).load(allReferral.get(i).profile).into(holder.ivReferralProfilePic);
}
holder.tvName.setText(allReferral.get(i).firstName+" "+allReferral.get(i).lastName);
holder.tvEmail.setText(allReferral.get(i).email);
holder.tvTotalReferralAmount.setText(allReferral.get(i).totalReferralAmount+" "+currencyCode);
}
@Override
public int getItemCount()
{
Common.Log.i("? - allReferral.size() : "+allReferral.size());
// return allReferral.size();
return (null != allReferral ? allReferral.size() : 0);
}
public class ViewHolder extends RecyclerView.ViewHolder
{
@BindView(R.id.iv_referral_profile_pic) ImageView ivReferralProfilePic;
@BindView(R.id.tv_name) TextView tvName;
@BindView(R.id.tv_email) TextView tvEmail;
@BindView(R.id.tv_total_referral_amount) TextView tvTotalReferralAmount;
public ViewHolder(final View rowView)
{
super(rowView);
ButterKnife.bind(this,rowView);
}
}
}
|
Distrotech/jruby | truffle/src/main/java/org/jruby/truffle/nodes/methods/SetMethodDeclarationContext.java | <reponame>Distrotech/jruby
/*
* Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. This
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
* Eclipse Public License version 1.0
* GNU General Public License version 2
* GNU Lesser General Public License version 2.1
*/
package org.jruby.truffle.nodes.methods;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.FrameSlotKind;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.source.SourceSection;
import org.jruby.runtime.Visibility;
import org.jruby.truffle.nodes.RubyNode;
import org.jruby.truffle.runtime.RubyContext;
import org.jruby.truffle.runtime.core.RubyModule;
public class SetMethodDeclarationContext extends RubyNode {
@Child private RubyNode child;
final Visibility visibility;
final String what;
public SetMethodDeclarationContext(RubyContext context, SourceSection sourceSection, Visibility visibility, String what, RubyNode child) {
super(context, sourceSection);
this.child = child;
this.visibility = visibility;
this.what = what;
}
@Override
public Object execute(VirtualFrame frame) {
CompilerDirectives.transferToInterpreter();
FrameSlot slot = frame.getFrameDescriptor().findOrAddFrameSlot(RubyModule.VISIBILITY_FRAME_SLOT_ID, "visibility for " + what, FrameSlotKind.Object);
Object oldVisibility = frame.getValue(slot);
try {
frame.setObject(slot, visibility);
return child.execute(frame);
} finally {
frame.setObject(slot, oldVisibility);
}
}
}
|
wyan/ack | plat/linux/libsys/execve.c | #include <unistd.h>
#include "libsys.h"
int execve(const char *path, char *const argv[], char *const envp[])
{
return _syscall(__NR_execve, (quad) path, (quad) argv, (quad) envp);
}
|
andrasigneczi/TravelOptimiser | DataCollector/mozilla/xulrunner-sdk/include/mp4_demuxer/Index.h | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef INDEX_H_
#define INDEX_H_
#include "MediaData.h"
#include "MediaResource.h"
#include "mozilla/Monitor.h"
#include "mp4_demuxer/Interval.h"
#include "mp4_demuxer/Stream.h"
#include "nsISupportsImpl.h"
template<class T> class nsRefPtr;
template<class T> class nsAutoPtr;
namespace mp4_demuxer
{
class Index;
class MoofParser;
struct Sample;
typedef int64_t Microseconds;
class SampleIterator
{
public:
explicit SampleIterator(Index* aIndex);
already_AddRefed<mozilla::MediaRawData> GetNext();
void Seek(Microseconds aTime);
Microseconds GetNextKeyframeTime();
private:
Sample* Get();
void Next();
nsRefPtr<Index> mIndex;
size_t mCurrentMoof;
size_t mCurrentSample;
};
class Index
{
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(Index)
struct Indice
{
uint64_t start_offset;
uint64_t end_offset;
uint64_t start_composition;
uint64_t end_composition;
bool sync;
};
Index(const nsTArray<Indice>& aIndex,
Stream* aSource,
uint32_t aTrackId,
bool aIsAudio,
mozilla::Monitor* aMonitor);
void UpdateMoofIndex(const nsTArray<mozilla::MediaByteRange>& aByteRanges);
Microseconds GetEndCompositionIfBuffered(
const nsTArray<mozilla::MediaByteRange>& aByteRanges);
void ConvertByteRangesToTimeRanges(
const nsTArray<mozilla::MediaByteRange>& aByteRanges,
nsTArray<Interval<Microseconds>>* aTimeRanges);
uint64_t GetEvictionOffset(Microseconds aTime);
bool IsFragmented() { return mMoofParser; }
friend class SampleIterator;
private:
~Index();
Stream* mSource;
FallibleTArray<Sample> mIndex;
nsAutoPtr<MoofParser> mMoofParser;
mozilla::Monitor* mMonitor;
};
}
#endif
|
WangZixuan/Leetcode | Medium/654 - Maximum Binary Tree.cpp | <gh_stars>10-100
/*
Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
Note:
The size of the given array will be in the range [1,1000].
@author Zixuan
@date 2017/9/14
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <vector>
using namespace std;
class Solution
{
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums)
{
return constructPart(nums, 0, static_cast<int>(nums.size() - 1));
}
private:
TreeNode* constructPart(vector<int>& nums, int start, int end)
{
if (start == end)
{
auto t = new TreeNode(nums[start]);
return t;
}
//Find the maximum element between start and end
auto index = start;
auto maximumElement = nums[start];
for (auto i = index; i <= end; ++i)
if (nums[i] > maximumElement)
{
index = i;
maximumElement = nums[i];
}
auto t = new TreeNode(maximumElement);
if (index > start)
t->left = constructPart(nums, start, index - 1);
if (index < end)
t->right = constructPart(nums, index + 1, end);
return t;
}
};
|
tetai/mymall | onemall-web/admin-dashboard-react/helpers/validator.js | <reponame>tetai/mymall
// 校验必须是英文或者数字
export function checkTypeWithEnglishAndNumbers (rule, value, callback, text) {
let char = /^[a-zA-Z0-9]+$/
if (char.test(value)) {
callback()
} else {
callback(text)
}
} |
exponentjs/rocker | src/build/commands_test.go | <reponame>exponentjs/rocker
/*-
* Copyright 2015 Grammarly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package build
import (
"fmt"
"reflect"
"testing"
"github.com/grammarly/rocker/src/imagename"
"github.com/kr/pretty"
"github.com/stretchr/testify/mock"
"github.com/fsouza/go-dockerclient"
"github.com/stretchr/testify/assert"
)
// =========== Testing FROM ===========
func TestCommandFrom_Existing(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "from",
args: []string{"existing"},
})
img := &docker.Image{
ID: "123",
Config: &docker.Config{
Hostname: "localhost",
},
}
c.On("InspectImage", "existing:latest").Return(img, nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, "123", state.ImageID)
assert.Equal(t, "localhost", state.Config.Hostname)
}
func TestCommandFrom_NotExisting(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "from",
args: []string{"not-existing"},
})
var nilImg *docker.Image
var nilList []*imagename.ImageName
c.On("InspectImage", "not-existing:latest").Return(nilImg, nil).Once()
c.On("ListImages").Return(nilList, nil).Once()
c.On("ListImageTags", "not-existing:latest").Return(nilList, nil).Once()
_, err := cmd.Execute(b)
c.AssertExpectations(t)
assert.Equal(t, "FROM error: Image not found: not-existing:latest (also checked in the remote registry)", err.Error())
}
// =========== Testing RUN ===========
func TestCommandRun_Simple(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "run",
args: []string{"whoami"},
})
origCmd := []string{"/bin/program"}
b.state.Config.Cmd = origCmd
b.state.ImageID = "123"
c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(State)
assert.Equal(t, []string{"/bin/sh", "-c", "whoami"}, arg.Config.Cmd)
}).Once()
c.On("RunContainer", "456", false).Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, origCmd, b.state.Config.Cmd)
assert.Equal(t, origCmd, state.Config.Cmd)
assert.Equal(t, "123", state.ImageID)
assert.Equal(t, "456", state.NoCache.ContainerID)
}
func TestCommandRun_ArgNoEnv(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "run",
args: []string{"export | grep proxy"},
})
b.state.Config.Cmd = []string{"/bin/program"}
b.state.ImageID = "123"
b.state.NoCache.BuildArgs = map[string]string{"http_proxy": "http://host:3128"}
c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(State)
assert.Equal(t, []string{"http_proxy=http://host:3128"}, arg.Config.Env)
}).Once()
c.On("RunContainer", "456", false).Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, `RUN ["|1" "http_proxy=http://host:3128" "/bin/sh" "-c" "export | grep proxy"]`, state.GetCommits())
assert.Equal(t, []string(nil), state.Config.Env)
}
func TestCommandRun_ArgWithEnv(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "run",
args: []string{"export | grep proxy"},
})
b.state.Config.Cmd = []string{"/bin/program"}
b.state.Config.Env = []string{"foo=bar", "lopata=some_value"}
b.state.ImageID = "123"
b.state.NoCache.BuildArgs = map[string]string{
"http_proxy": "http://host:3128",
"lopata": "default",
}
c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(State)
assert.Equal(t, []string{"foo=bar", "lopata=some_value", "http_proxy=http://host:3128"}, arg.Config.Env)
}).Once()
c.On("RunContainer", "456", false).Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, `RUN ["|1" "http_proxy=http://host:3128" "/bin/sh" "-c" "export | grep proxy"]`, state.GetCommits())
assert.Equal(t, []string{"foo=bar", "lopata=some_value"}, state.Config.Env)
}
// =========== Testing COMMIT ===========
func TestCommandCommit_Simple(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := &CommandCommit{}
resultImage := &docker.Image{ID: "789"}
b.state.ImageID = "123"
b.state.NoCache.ContainerID = "456"
b.state.Commit("a").Commit("b")
c.On("CommitContainer", mock.AnythingOfType("State")).Return(resultImage, nil).Once()
c.On("RemoveContainer", "456").Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, "a; b", b.state.GetCommits())
assert.Equal(t, "", state.GetCommits())
assert.Equal(t, []string(nil), state.Config.Cmd)
assert.Equal(t, "789", state.ImageID)
assert.Equal(t, "", state.NoCache.ContainerID)
}
func TestCommandCommit_NoContainer(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := &CommandCommit{}
resultImage := &docker.Image{ID: "789"}
b.state.ImageID = "123"
b.state.Commit("a").Commit("b")
c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(State)
assert.Equal(t, []string{"/bin/sh", "-c", "#(nop) a; b"}, arg.Config.Cmd)
}).Once()
c.On("CommitContainer", mock.AnythingOfType("State")).Return(resultImage, nil).Once()
c.On("RemoveContainer", "456").Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, "a; b", b.state.GetCommits())
assert.Equal(t, "", state.GetCommits())
assert.Equal(t, "789", state.ImageID)
assert.Equal(t, "", state.NoCache.ContainerID)
}
func TestCommandCommit_NoCommitMsgs(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := &CommandCommit{}
_, err := cmd.Execute(b)
assert.Nil(t, err)
}
// TODO: test skip commit
// =========== Testing ENV ===========
func TestCommandEnv_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "env",
args: []string{"type", "web", "env", "prod"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "ENV type=web env=prod", state.GetCommits())
assert.Equal(t, []string{"type=web", "env=prod"}, state.Config.Env)
}
func TestCommandEnv_Advanced(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "env",
args: []string{"type", "web", "env", "prod"},
})
b.state.Config.Env = []string{"env=dev", "version=1.2.3"}
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "ENV type=web env=prod", state.GetCommits())
assert.Equal(t, []string{"env=prod", "version=1.2.3", "type=web"}, state.Config.Env)
}
// =========== Testing LABEL ===========
func TestCommandLabel_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "label",
args: []string{"type", "web", "env", "prod"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
expectedLabels := map[string]string{
"type": "web",
"env": "prod",
}
t.Logf("Result labels: %# v", pretty.Formatter(state.Config.Labels))
assert.Equal(t, "LABEL type=web env=prod", state.GetCommits())
assert.True(t, reflect.DeepEqual(state.Config.Labels, expectedLabels), "bad result labels")
}
func TestCommandLabel_Advanced(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "label",
args: []string{"type", "web", "env", "prod"},
})
b.state.Config.Labels = map[string]string{
"env": "dev",
"version": "1.2.3",
}
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
expectedLabels := map[string]string{
"type": "web",
"version": "1.2.3",
"env": "prod",
}
t.Logf("Result labels: %# v", pretty.Formatter(state.Config.Labels))
assert.Equal(t, "LABEL type=web env=prod", state.GetCommits())
assert.True(t, reflect.DeepEqual(state.Config.Labels, expectedLabels), "bad result labels")
}
// =========== Testing MAINTAINER ===========
func TestCommandMaintainer_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "maintainer",
args: []string{"terminator"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "", state.GetCommits())
}
// =========== Testing WORKDIR ===========
func TestCommandWorkdir_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "workdir",
args: []string{"/app"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "/app", state.Config.WorkingDir)
}
func TestCommandWorkdir_Relative_HasRoot(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "workdir",
args: []string{"www"},
})
b.state.Config.WorkingDir = "/home"
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "/home/www", state.Config.WorkingDir)
}
func TestCommandWorkdir_Relative_NoRoot(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "workdir",
args: []string{"www"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "/www", state.Config.WorkingDir)
}
// =========== Testing CMD ===========
func TestCommandCmd_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "cmd",
args: []string{"apt-get", "install"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{"/bin/sh", "-c", "apt-get install"}, state.Config.Cmd)
}
func TestCommandCmd_Json(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "cmd",
args: []string{"apt-get", "install"},
attrs: map[string]bool{"json": true},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{"apt-get", "install"}, state.Config.Cmd)
}
// =========== Testing ENTRYPOINT ===========
func TestCommandEntrypoint_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "entrypoint",
args: []string{"/bin/sh"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{"/bin/sh", "-c", "/bin/sh"}, state.Config.Entrypoint)
}
func TestCommandEntrypoint_Json(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "entrypoint",
args: []string{"/bin/bash", "-c"},
attrs: map[string]bool{"json": true},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{"/bin/bash", "-c"}, state.Config.Entrypoint)
}
func TestCommandEntrypoint_Remove(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "entrypoint",
args: []string{},
})
b.state.Config.Entrypoint = []string{"/bin/sh", "-c"}
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{}, state.Config.Entrypoint)
}
// =========== Testing EXPOSE ===========
func TestCommandExpose_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "expose",
args: []string{"80"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
expectedPorts := map[docker.Port]struct{}{
docker.Port("80/tcp"): struct{}{},
}
assert.True(t, reflect.DeepEqual(expectedPorts, state.Config.ExposedPorts), "bad exposed ports")
}
func TestCommandExpose_Add(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "expose",
args: []string{"443"},
})
b.state.Config.ExposedPorts = map[docker.Port]struct{}{
docker.Port("80/tcp"): struct{}{},
}
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
expectedPorts := map[docker.Port]struct{}{
docker.Port("80/tcp"): struct{}{},
docker.Port("443/tcp"): struct{}{},
}
assert.True(t, reflect.DeepEqual(expectedPorts, state.Config.ExposedPorts), "bad exposed ports")
}
// =========== Testing VOLUME ===========
func TestCommandVolume_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "volume",
args: []string{"/data"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
volumes := map[string]struct{}{
"/data": struct{}{},
}
assert.True(t, reflect.DeepEqual(volumes, state.Config.Volumes), "bad volumes")
}
func TestCommandVolume_Add(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "volume",
args: []string{"/var/log"},
})
b.state.Config.Volumes = map[string]struct{}{
"/data": struct{}{},
}
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
volumes := map[string]struct{}{
"/data": struct{}{},
"/var/log": struct{}{},
}
assert.True(t, reflect.DeepEqual(volumes, state.Config.Volumes), "bad volumes")
}
// =========== Testing USER ===========
func TestCommandUser_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "user",
args: []string{"www"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "www", state.Config.User)
}
// =========== Testing ONBUILD ===========
func TestCommandOnBuild_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "onbuild",
args: []string{"RUN", "make", "install"},
original: "ONBUILD RUN make install",
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, []string{"RUN make install"}, state.Config.OnBuild)
}
// =========== Testing COPY ===========
func TestCommandCopy_Simple(t *testing.T) {
// TODO: do we need to check the dest is always a directory?
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "copy",
args: []string{"testdata/Rockerfile", "/Rockerfile"},
})
c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(State)
// TODO: a better check
assert.True(t, len(arg.Config.Cmd) > 0)
}).Once()
c.On("UploadToContainer", "456", mock.AnythingOfType("*io.PipeReader"), "/").Return(nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
t.Logf("state: %# v", pretty.Formatter(state))
c.AssertExpectations(t)
assert.Equal(t, "456", state.NoCache.ContainerID)
}
// =========== Testing TAG ===========
func TestCommandTag_Simple(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "tag",
args: []string{"docker.io/grammarly/rocker:1.0"},
})
b.state.ImageID = "123"
c.On("TagImage", "123", "docker.io/grammarly/rocker:1.0").Return(nil).Once()
_, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
}
func TestCommandTag_WrongArgsNumber(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "tag",
args: []string{},
})
cmd2 := NewCommand(ConfigCommand{
name: "tag",
args: []string{"1", "2"},
})
b.state.ImageID = "123"
_, err := cmd.Execute(b)
assert.EqualError(t, err, "TAG requires exactly one argument")
_, err2 := cmd2.Execute(b)
assert.EqualError(t, err2, "TAG requires exactly one argument")
}
func TestCommandTag_NoImage(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "tag",
args: []string{"docker.io/grammarly/rocker:1.0"},
})
_, err := cmd.Execute(b)
assert.EqualError(t, err, "Cannot TAG on empty image")
}
// =========== Testing PUSH ===========
func TestCommandPush_Simple(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "push",
args: []string{"docker.io/grammarly/rocker:1.0"},
})
b.cfg.Push = true
b.state.ImageID = "123"
c.On("TagImage", "123", "docker.io/grammarly/rocker:1.0").Return(nil).Once()
c.On("PushImage", "docker.io/grammarly/rocker:1.0").Return("sha256:fafa", nil).Once()
_, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
}
func TestCommandPush_WrongArgsNumber(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "push",
args: []string{},
})
cmd2 := NewCommand(ConfigCommand{
name: "push",
args: []string{"1", "2"},
})
b.state.ImageID = "123"
_, err := cmd.Execute(b)
assert.EqualError(t, err, "PUSH requires exactly one argument")
_, err2 := cmd2.Execute(b)
assert.EqualError(t, err2, "PUSH requires exactly one argument")
}
func TestCommandPush_NoImage(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "push",
args: []string{"docker.io/grammarly/rocker:1.0"},
})
_, err := cmd.Execute(b)
assert.EqualError(t, err, "Cannot PUSH empty image")
}
// =========== Testing MOUNT ===========
func TestCommandMount_Simple(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "mount",
args: []string{"/src:/dest"},
})
c.On("ResolveHostPath", "/src").Return("/resolved/src", nil).Once()
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
c.AssertExpectations(t)
assert.Equal(t, []string{"/resolved/src:/dest"}, state.NoCache.HostConfig.Binds)
assert.Equal(t, `MOUNT ["/src:/dest"]`, state.GetCommits())
}
func TestCommandMount_VolumeContainer(t *testing.T) {
b, c := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "mount",
args: []string{"/cache"},
})
containerName := b.mountsContainerName("/cache")
c.On("EnsureContainer", containerName, mock.AnythingOfType("*docker.Config"), mock.AnythingOfType("*docker.HostConfig"), "/cache").Return("123", nil).Run(func(args mock.Arguments) {
arg := args.Get(1).(*docker.Config)
assert.Equal(t, MountVolumeImage, arg.Image)
expectedVolumes := map[string]struct{}{
"/cache": struct{}{},
}
assert.True(t, reflect.DeepEqual(expectedVolumes, arg.Volumes))
}).Once()
cnt := &docker.Container{
Name: "/" + containerName,
Mounts: []docker.Mount{
{
Source: "/volumedir",
Destination: "/cache",
},
},
}
c.On("InspectContainer", containerName).Return(cnt, nil)
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
commitMsg := fmt.Sprintf("MOUNT [\"%s:/cache\"]", containerName)
c.AssertExpectations(t)
assert.Equal(t, []string{"/volumedir:/cache:ro"}, state.NoCache.HostConfig.Binds)
assert.Equal(t, commitMsg, state.GetCommits())
}
// =========== Testing ARG ===========
func TestCommandArg_Simple(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "arg",
args: []string{"foo=bar"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, true, b.allowedBuildArgs["foo"])
assert.Equal(t, "bar", state.NoCache.BuildArgs["foo"])
assert.Equal(t, "ARG foo=bar", state.GetCommits())
}
func TestCommandArg_Allow(t *testing.T) {
b, _ := makeBuild(t, "", Config{})
cmd := NewCommand(ConfigCommand{
name: "arg",
args: []string{"xxx"},
})
state, err := cmd.Execute(b)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, true, b.allowedBuildArgs["xxx"])
assert.NotContains(t, state.NoCache.BuildArgs, "xxx")
assert.Equal(t, "ARG xxx", state.GetCommits())
}
// TODO: test Cleanup
|
mparnaudeau/clib2 | library/contrib/byteswap/byteswap_swab64.c | <gh_stars>1-10
#if defined(__GNUC__) && defined(__PPC__)
/* r3=from, r4=to, r5=len/temp, r6/r7=index, r8/r9=load/store temp, r10=cache hint */
/* This version is unrolled and uses cache-hinting. It appears to gain about 10%
* over a non-unrolled, non-hinting version.
*/
asm("\
.text\n\
.align 2\n\
.globl swab64\n\
.type swab64,@function\n\
swab64:\n\
dcbt 0,%r3\n\
andi. %r10,%r5,31 # The number of bytes handled in '.pre'. Used for prefetch hint.\n\
srawi %r5,%r5,3 # Convert bytes-># of 64-bit words\n\
andi. %r7,%r5,3\n\
li %r6,0\n\
bc 4,gt,.preploop\n\
mtctr %r7\n\
.pre: # One 64-bit word at a time until we have (nLeft%4)==0 \n\
lwbrx %r8,%r6,%r3\n\
addi %r7,%r6,4\n\
lwbrx %r9,%r7,%r3\n\
stwx %r8,%r7,%r4\n\
stwx %r9,%r6,%r4\n\
addi %r6,%r6,8\n\
bc 0,lt,.pre\n\
.preploop:\n\
srawi. %r5,%r5,2 # Divide by 4 again to get number of loops.\n\
addi %r10,%r10,32 # Start address for next loop.\n\
bc 4,gt,.exit\n\
mtctr %r5\n\
.loop: # Loop unrolled 4 times = 32 bytes = 1 cache-line (except on the 970).\n\
dcbt %r10,%r3 # Cache hint (prefetch) for the next iteration\n\
lwbrx %r8,%r6,%r3\n\
addi %r7,%r6,4\n\
lwbrx %r9,%r7,%r3\n\
stwx %r8,%r7,%r4\n\
stwx %r9,%r6,%r4\n\
addi %r6,%r6,8\n\
lwbrx %r8,%r6,%r3\n\
addi %r7,%r6,4\n\
lwbrx %r9,%r7,%r3\n\
stwx %r8,%r7,%r4\n\
stwx %r9,%r6,%r4\n\
addi %r6,%r6,8\n\
lwbrx %r8,%r6,%r3\n\
addi %r7,%r6,4\n\
lwbrx %r9,%r7,%r3\n\
stwx %r8,%r7,%r4\n\
stwx %r9,%r6,%r4\n\
addi %r6,%r6,8\n\
lwbrx %r8,%r6,%r3\n\
addi %r7,%r6,4\n\
lwbrx %r9,%r7,%r3\n\
stwx %r8,%r7,%r4\n\
stwx %r9,%r6,%r4\n\
addi %r6,%r6,8\n\
addi %r10,%r10,32 # Update cache-hint offset\n\
bc 0,lt,.loop\n\
.exit:\n\
or %r3,%r4,%r4\n\
blr\n\
");
#else
#include <sys/types.h>
#include <stdint.h>
void *swab64(void *from,void *to,ssize_t len)
{
int i;
struct {
uint32_t u32[2];
} *u64in=from,*u64out=to;
uint32_t tmp1,tmp2;
for(i=0;i<(len>>3);i++) {
tmp1=u64in[i].u32[0];
tmp2=u64in[i].u32[1];
u64out[i].u32[0]=((tmp2&0xff)<<24)|
((tmp2&0xff00)<<8)|
((tmp2&0xff0000)>>8)|
((tmp2&0xff000000)>>24);
u64out[i].u32[1]=((tmp1&0xff)<<24)|
((tmp1&0xff00)<<8)|
((tmp1&0xff0000)>>8)|
((tmp1&0xff000000)>>24);
}
return(to);
}
#endif
/* vi:set ts=3: */
|
jackx22/fixflow | modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/impl/cmd/GetStartProcessByUserIdCmd.java | package com.founder.fix.fixflow.core.impl.cmd;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.founder.fix.fixflow.core.cache.CacheHandler;
import com.founder.fix.fixflow.core.impl.Context;
import com.founder.fix.fixflow.core.impl.bpmn.behavior.ProcessDefinitionBehavior;
import com.founder.fix.fixflow.core.impl.interceptor.Command;
import com.founder.fix.fixflow.core.impl.interceptor.CommandContext;
import com.founder.fix.fixflow.core.impl.interceptor.CommandExecutor;
import com.founder.fix.fixflow.core.impl.persistence.ProcessDefinitionManager;
import com.founder.fix.fixflow.core.impl.util.StringUtil;
public class GetStartProcessByUserIdCmd implements Command<List<Map<String, String>>>{
protected String userId;
public GetStartProcessByUserIdCmd(String userId){
this.userId=userId;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Map<String, String>> execute(CommandContext commandContext) {
ProcessDefinitionManager processDefinitionManager =commandContext.getProcessDefinitionManager();
CacheHandler cacheHandler=Context.getProcessEngineConfiguration().getCacheHandler();
Object cacheData = cacheHandler.getCacheData("GetStartProcessByUserId_" + this.userId);
if(cacheData==null){
CommandExecutor commandExecutor=Context.getProcessEngineConfiguration().getCommandExecutor();
List<Map<String, Object>> processDefData=commandExecutor.execute(new GetProcessDefinitionGroupKeyCmd());
List<Map<String,String>> processData=new ArrayList<Map<String,String>>();
for (Map<String, Object> map : processDefData) {
String processKey=StringUtil.getString(map.get("PROCESS_KEY"));
boolean state=commandExecutor.execute(new VerificationStartUserCmd(this.userId,processKey,null));
if(state){
Map<String, String> dataMap=new HashMap<String, String>();
ProcessDefinitionBehavior processDefinition = processDefinitionManager
.findLatestProcessDefinitionByKey(processKey);
String startFormKey=null;
if(processDefinition!=null){
startFormKey=processDefinition.getStartFormKey();
}
dataMap.put("startFormKey", startFormKey);
dataMap.put("processDefinitionId", StringUtil.getString(map.get("PROCESS_ID")));
dataMap.put("processDefinitionName", StringUtil.getString(map.get("PROCESS_NAME")));
dataMap.put("processDefinitionKey", StringUtil.getString(map.get("PROCESS_KEY")));
dataMap.put("category", StringUtil.getString(map.get("CATEGORY")));
dataMap.put("version", StringUtil.getString(map.get("VERSION")));
dataMap.put("resourceName", StringUtil.getString(map.get("RESOURCE_NAME")));
dataMap.put("resourceId", StringUtil.getString(map.get("RESOURCE_ID")));
dataMap.put("deploymentId", StringUtil.getString(map.get("DEPLOYMENT_ID")));
dataMap.put("diagramResourceName", StringUtil.getString(map.get("DIAGRAM_RESOURCE_NAME")));
processData.add(dataMap);
}
}
if(processDefData.size()>0){
cacheHandler.putCacheData("GetStartProcessByUserId_" + this.userId, processData);
}
return processData;
}else{
return (List)cacheData;
}
}
}
|
softicar/sqml | com.softicar.sqml.model/src/main/java/com/softicar/sqml/model/builtin/functions/AbstractBuiltInBinaryOperator.java | package com.softicar.sqml.model.builtin.functions;
import com.softicar.platform.db.sql.token.SqlSymbol;
import com.softicar.sqml.model.expressions.ISqmlExpression;
import com.softicar.sqml.model.functions.impl.SqmlFunctionImpl;
import com.softicar.sqml.model.generation.ISqmlSelectGenerator;
import com.softicar.sqml.model.simple.SqmlSimpleFunctionParameter;
import com.softicar.sqml.model.simple.SqmlSimpleTypeReference;
import com.softicar.sqml.model.types.ISqmlType;
import com.softicar.sqml.model.types.ISqmlTypeDefinition;
import java.util.List;
public abstract class AbstractBuiltInBinaryOperator extends SqmlFunctionImpl {
protected final SqlSymbol operator;
private final SqmlSimpleFunctionParameter parameterA;
private final SqmlSimpleFunctionParameter parameterB;
public AbstractBuiltInBinaryOperator(SqlSymbol operator, ISqmlTypeDefinition returnType, ISqmlTypeDefinition leftType, ISqmlTypeDefinition rightType) {
this.operator = operator;
this.parameterA = new SqmlSimpleFunctionParameter("a", leftType);
this.parameterB = new SqmlSimpleFunctionParameter("b", rightType);
setName(operator.getText());
setReturnType(new SqmlSimpleTypeReference(returnType));
getParameters().add(parameterA);
getParameters().add(parameterB);
}
@Override
public void generateSql(ISqmlSelectGenerator generator) {
generator.visit(parameterA);
generator.getBuilder().addToken(operator);
generator.visit(parameterB);
}
@Override
public boolean acceptsArguments(List<ISqmlExpression> arguments) {
return getArgumentConversionCount(arguments) != Integer.MAX_VALUE;
}
@Override
public int getArgumentConversionCount(List<ISqmlExpression> arguments) {
if (arguments.size() != 2) {
return Integer.MAX_VALUE;
}
ISqmlType leftType = arguments.get(0).getSqmlType();
ISqmlType rightType = arguments.get(1).getSqmlType();
return getArgumentConversionCount(leftType, rightType);
}
protected abstract int getArgumentConversionCount(ISqmlType leftType, ISqmlType rightType);
}
|
jrtoocool/geo_ushelf | rmagick/ruby/1.8/gems/will_paginate-3.0.pre2/spec/view_helpers/view_example_group.rb | require 'action_dispatch/testing/assertions'
class ViewExampleGroup < Spec::Example::ExampleGroup
include ActionDispatch::Assertions::SelectorAssertions
def assert(value, message)
raise message unless value
end
def paginate(collection = {}, options = {}, &block)
if collection.instance_of? Hash
page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection)
collection = [1].paginate(page_options)
end
locals = { :collection => collection, :options => options }
@render_output = render(locals)
@html_document = nil
if block_given?
classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class]
assert_select("div.#{classname}", 1, 'no main DIV', &block)
end
@render_output
end
def html_document
@html_document ||= HTML::Document.new(@render_output, true, false)
end
def response_from_page_or_rjs
html_document.root
end
def validate_page_numbers(expected, links, param_name = :page)
param_pattern = /\W#{Regexp.escape(param_name.to_s)}=([^&]*)/
links.map { |e|
e['href'] =~ param_pattern
$1 ? $1.to_i : $1
}.should == expected
end
def assert_links_match(pattern, links = nil, numbers = nil)
links ||= assert_select 'div.pagination a[href]' do |elements|
elements
end
pages = [] if numbers
links.each do |el|
el['href'].should =~ pattern
if numbers
el['href'] =~ pattern
pages << ($1.nil?? nil : $1.to_i)
end
end
pages.should == numbers if numbers
end
def assert_no_links_match(pattern)
assert_select 'div.pagination a[href]' do |elements|
elements.each do |el|
el['href'] !~ pattern
end
end
end
def build_message(message, pattern, *args)
built_message = pattern.dup
for value in args
built_message.sub! '?', value.inspect
end
built_message
end
end
Spec::Example::ExampleGroupFactory.register(:view_helpers, ViewExampleGroup)
module HTML
Node.class_eval do
def inner_text
children.map(&:inner_text).join('')
end
end
Text.class_eval do
def inner_text
self.to_s
end
end
Tag.class_eval do
def inner_text
childless?? '' : super
end
end
end
|
SaladDais/LLUDP-Encryption | indra/newview/llsearchableui.cpp | <gh_stars>1-10
/**
* @file llsearchableui.cpp
*
* $LicenseInfo:firstyear=2019&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2019, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llsearchableui.h"
#include "llview.h"
#include "lltabcontainer.h"
#include "llmenugl.h"
ll::prefs::SearchableItem::~SearchableItem()
{}
void ll::prefs::SearchableItem::setNotHighlighted()
{
mCtrl->setHighlighted( false );
}
bool ll::prefs::SearchableItem::hightlightAndHide( LLWString const &aFilter )
{
if( mCtrl->getHighlighted() )
return true;
LLView const *pView = dynamic_cast< LLView const* >( mCtrl );
if( pView && !pView->getVisible() )
return false;
if( aFilter.empty() )
{
mCtrl->setHighlighted( false );
return true;
}
if( mLabel.find( aFilter ) != LLWString::npos )
{
mCtrl->setHighlighted( true );
return true;
}
return false;
}
ll::prefs::PanelData::~PanelData()
{}
bool ll::prefs::PanelData::hightlightAndHide( LLWString const &aFilter )
{
for( tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr )
(*itr)->setNotHighlighted();
for (tPanelDataList::iterator itr = mChildPanel.begin(); itr != mChildPanel.end(); ++itr)
(*itr)->setNotHighlighted();
// <FS:Ansariel> FIRE-23969: This breaks prefs search - and isn't needed on FS
//if (aFilter.empty())
//{
// return true;
//}
// </FS:Ansariel>
bool bVisible(false);
for( tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr )
bVisible |= (*itr)->hightlightAndHide( aFilter );
for( tPanelDataList::iterator itr = mChildPanel.begin(); itr != mChildPanel.end(); ++itr )
bVisible |= (*itr)->hightlightAndHide( aFilter );
return bVisible;
}
void ll::prefs::PanelData::setNotHighlighted()
{
for (tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr)
(*itr)->setNotHighlighted();
for (tPanelDataList::iterator itr = mChildPanel.begin(); itr != mChildPanel.end(); ++itr)
(*itr)->setNotHighlighted();
}
bool ll::prefs::TabContainerData::hightlightAndHide( LLWString const &aFilter )
{
for( tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr )
(*itr)->setNotHighlighted( );
bool bVisible(false);
for( tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr )
bVisible |= (*itr)->hightlightAndHide( aFilter );
for( tPanelDataList::iterator itr = mChildPanel.begin(); itr != mChildPanel.end(); ++itr )
{
bool bPanelVisible = (*itr)->hightlightAndHide( aFilter );
if( (*itr)->mPanel )
mTabContainer->setTabVisibility( (*itr)->mPanel, bPanelVisible );
bVisible |= bPanelVisible;
}
return bVisible;
}
ll::statusbar::SearchableItem::SearchableItem()
: mMenu(0)
, mCtrl(0)
, mWasHiddenBySearch( false )
{ }
void ll::statusbar::SearchableItem::setNotHighlighted( )
{
for( tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr )
(*itr)->setNotHighlighted( );
if( mCtrl )
{
mCtrl->setHighlighted( false );
if( mWasHiddenBySearch )
mMenu->setVisible( TRUE );
}
}
bool ll::statusbar::SearchableItem::hightlightAndHide(LLWString const &aFilter, bool hide)
{
if ((mMenu && !mMenu->getVisible() && !mWasHiddenBySearch) || dynamic_cast<LLMenuItemTearOffGL*>(mMenu))
return false;
setNotHighlighted( );
if( aFilter.empty() )
{
if( mCtrl )
mCtrl->setHighlighted( false );
return true;
}
bool bHighlighted(!hide);
if( mLabel.find( aFilter ) != LLWString::npos )
{
if( mCtrl )
mCtrl->setHighlighted( true );
bHighlighted = true;
}
bool bVisible(false);
for (tSearchableItemList::iterator itr = mChildren.begin(); itr != mChildren.end(); ++itr)
bVisible |= (*itr)->hightlightAndHide(aFilter, !bHighlighted);
if (mCtrl && !bVisible && !bHighlighted)
{
mWasHiddenBySearch = true;
mMenu->setVisible(FALSE);
}
return bVisible || bHighlighted;
}
|
lcarva/chains | vendor/github.com/butuzov/ireturn/config/reject.go | <reponame>lcarva/chains
package config
import "github.com/butuzov/ireturn/types"
// rejectConfig specifies a list of interfaces (keywords, patters and regular expressions)
// that are rejected by ireturn as valid to return, any non listed interface are allowed.
type rejectConfig struct {
*defaultConfig
}
func rejectAll(patterns []string) *rejectConfig {
return &rejectConfig{&defaultConfig{List: patterns}}
}
func (rc *rejectConfig) IsValid(i types.IFace) bool {
return !rc.Has(i)
}
|
3846masa-tmp/slack-patron | app/public/src/js/components/Sidebar.js | <gh_stars>0
import React from 'react';
import SidebarHeader from './SidebarHeader';
import SlackChannels from './SlackChannels';
export default React.createClass({
render() {
return (
<div className="sidebar">
<SidebarHeader />
<SlackChannels />
</div>
);
}
});
|
lieftsatyamShrivastava/JavaSourceAnalyzer | AnalyzerDashboard/src/org/eaSTars/adashboard/converter/impl/DefaultJavaSequenceOutputConverter.java | <gh_stars>0
package org.eaSTars.adashboard.converter.impl;
import java.io.ByteArrayOutputStream;
import org.eaSTars.adashboard.service.dto.JavaSequenceScript;
public class DefaultJavaSequenceOutputConverter extends AbstractJavaSequenceDiagramConverter<ByteArrayOutputStream> {
@Override
public ByteArrayOutputStream convert(JavaSequenceScript source) {
return getOutputStream(source);
}
}
|
inexor-game/flex | src/entities/domain/Entity.js | <filename>src/entities/domain/Entity.js
const EventEmitter = require('events');
const Relationship = require('./Relationship');
/**
* @module entities
*/
// TODO: dependency: https://www.npmjs.com/package/uuid
const uuidV4 = require('uuid/v4');
/**
* An instance of an entity.
*/
class Entity extends EventEmitter {
/**
* Constructs an entity.
* @param {EntityType} entityType - The type of the entity.
*/
constructor(entityType) {
super();
this.uuid = uuidV4();
this.entityType = entityType;
this.incomingRelationships = [];
this.outgoingRelationships = [];
this.entityType.register(this);
}
/**
* Destroys an entity. Removes all relationships from an to this entity. Also unregisters the entity from the entity type.
* TODO: check if this is enough to get being garbage collected.
*/
destroy() {
for (let i = this.incomingRelationships.length; i >= 0; i--) {
this.incomingRelationships[i].disconnect();
}
for (let i = this.outgoingRelationships.length; i >= 0; i--) {
this.incomingRelationships[i].disconnect();
}
this.entityType.unregister(this);
}
/**
* Returns the UUID of the entity.
* @return {string} The uuid of the entity.
*/
getUuid() {
return this.uuid;
}
/**
* Returns the entity type.
* @return {EntityType} The type of the entity.
*/
getType() {
return this.entityType;
}
/**
* Returns the incoming relationships.
* @param {RelationshipType} relationshipType - Restricts which types of relationships have to be respected or null for any type.
* @return {Array.<Relationship>} The list of incoming relationships of the given type.
*/
getIncomingRelationships(relationshipType) {
if (relationshipType == null) {
return this.incomingRelationships;
} else {
let incomingRelationships = [];
for (let i = 0; i < this.incomingRelationships.length; i++) {
let incomingRelationship = this.incomingRelationships[i];
if (relationshipType.getUuid() == incomingRelationship.getType().getUuid()) {
incomingRelationships.push(incomingRelationship);
}
}
return incomingRelationships;
}
}
/**
* Returns the outgoing relationships.
* @param {RelationshipType} relationshipType - Restricts which types of relationships have to be respected or null for any type.
* @return {Array.<Relationship>} The list of outgoing relationships of the given type.
*/
getOutgoingRelationships(relationshipType) {
if (relationshipType == null) {
return this.outgoingRelationships;
} else {
let outgoingRelationships = [];
for (let i = 0; i < this.outgoingRelationships.length; i++) {
let outgoingRelationship = this.outgoingRelationships[i];
if (relationshipType.getUuid() == outgoingRelationship.getType().getUuid()) {
outgoingRelationships.push(outgoingRelationship);
}
}
return outgoingRelationships;
}
}
/**
* Returns the parent entities.
* @param {RelationshipType} relationshipType - Restricts which types of relationships have to be respected or null for any type.
* @return {Array.<Entity>} The parent entities.
*/
getParentEntities(relationshipType) {
let parents = [];
for (let i = 0; i < this.incomingRelationships.length; i++) {
let incomingRelationship = this.incomingRelationships[i];
if (relationshipType == null || relationshipType.getUuid() == incomingRelationship.getType().getUuid()) {
parents.push(incomingRelationship.getStartEntity());
}
}
return parents;
}
/**
* Returns the child entities.
* @param {RelationshipType} relationshipType - Restricts which types of relationships have to be respected or null for any type.
* @return {Array.<Entity>} The child entities.
*/
getChildEntities(relationshipType) {
let childs = [];
for (let i = 0; i < this.outgoingRelationships.length; i++) {
let outgoingRelationship = this.outgoingRelationships[i];
if (relationshipType == null || relationshipType.getUuid() == outgoingRelationship.getType().getUuid()) {
childs.push(outgoingRelationship.getEndEntity());
}
}
return childs;
}
/**
* Returns true, if an incoming relationship of the given type exists to the given entity.
* @param {Entity} parentEntity - The parent entity.
* @param {RelationshipType} relationshipType - The relationship type or null.
* @return {Boolean} True, if parentEntity is a parent entity.
*/
isParentEntity(parentEntity, relationshipType) {
for (let i = 0; i < this.incomingRelationships.length; i++) {
let incomingRelationship = this.incomingRelationships[i];
if ((relationshipType == null || relationshipType.getUuid() == incomingRelationship.getType().getUuid()) && parentEntity.getUuid() == incomingRelationship.getStartEntity().getUuid()) {
return true;
}
}
return false;
}
/**
* Returns true, if an outgoing relationship of the given type exists to the given entity.
* @param {Entity} childEntity - The child entity.
* @param {RelationshipType} relationshipType - The relationship type or null.
* @return {Boolean} True, if childEntity is a child entity.
*/
isChildEntity(childEntity, relationshipType) {
for (let i = 0; i < this.outgoingRelationships.length; i++) {
let outgoingRelationship = this.outgoingRelationships[i];
if ((relationshipType == null || relationshipType.getUuid() == outgoingRelationship.getType().getUuid()) && childEntity.getUuid() == outgoingRelationship.getEndEntity().getUuid()) {
return true;
}
}
return false;
}
/**
* Adds a parent entity of the given type.
* @param {RelationshipType} relationshipType - The relationship type. Must not be null.
* @param {Entity} parentEntity - The parent entity.
* @return {Relationship} - The created relationship.
*/
addParent(relationshipType, parentEntity) {
let relationship = new Relationship(relationshipType, parentEntity, this);
return relationship;
}
/**
* Adds a child entity of the given type.
* @param {RelationshipType} relationshipType - The relationship type. Must not be null.
* @param {Entity} childEntity - The child entity.
* @return {Relationship} - The created relationship.
*/
addChild(relationshipType, childEntity) {
let relationship = new Relationship(relationshipType, this, childEntity);
return relationship;
}
/**
* Removes all relationships of the given type to the given parent entity.
* @param {RelationshipType} relationshipType - The relationship type or null.
* @param {Entity} parentEntity - The parent entity.
*/
removeParentEntity(relationshipType, parentEntity) {
for (let i = 0; i < this.incomingRelationships.length; i++) {
let incomingRelationship = this.incomingRelationships[i];
if ((relationshipType == null || relationshipType.getUuid() == incomingRelationship.getType().getUuid()) && parentEntity.getUuid() == incomingRelationship.getStartEntity().getUuid()) {
incomingRelationship.disconnect();
// don't skip
i--;
}
}
}
/**
* Removes all relationships of the given type to the given child entity.
* @param {RelationshipType} relationshipType - The relationship type or null.
* @param {Entity} childEntity - The child entity.
*/
removeChildEntity(relationshipType, childEntity) {
for (let i = 0; i < this.outgoingRelationships.length; i++) {
let outgoingRelationship = this.outgoingRelationships[i];
if ((relationshipType == null || relationshipType.getUuid() == outgoingRelationship.getType().getUuid()) && childEntity.getUuid() == outgoingRelationship.getEndEntity().getUuid()) {
outgoingRelationship.disconnect();
// don't skip
i--;
}
}
}
}
module.exports = Entity
|
swaplicado/sa-lib-10 | src/sa/lib/grid/cell/SGridCellRendererIcon.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sa.lib.grid.cell;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import sa.lib.SLibConsts;
import sa.lib.SLibUtils;
import sa.lib.grid.SGridConsts;
/**
*
* @author <NAME>
*/
public class SGridCellRendererIcon extends DefaultTableCellRenderer {
public static final ImageIcon moIconNull = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_null.png"));
public static final ImageIcon moIconAnnul = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_annul.png"));
public static final ImageIcon moIconCross = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_cross.png"));
public static final ImageIcon moIconWarn = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_warn.png"));
public static final ImageIcon moIconOk = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_ok.png"));
public static final ImageIcon moIconDoc = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_doc.png"));
public static final ImageIcon moIconThumbsUp = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_thum_up.png"));
public static final ImageIcon moIconThumbsDown = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_thum_down.png"));
public static final ImageIcon moIconXmlPending = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_xml_pend.png"));
public static final ImageIcon moIconXmlIssued = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_xml_issu.png"));
public static final ImageIcon moIconXmlAnnulled = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_xml_annul.png"));
public static final ImageIcon moIconXmlAnnulledPdf = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_xml_annul_pdf.png"));
public static final ImageIcon moIconXmlAnnulledXml = new ImageIcon(new Object().getClass().getResource("/sa/lib/img/view_xml_annul_xml.png"));
private JLabel moLabel;
public SGridCellRendererIcon() {
moLabel = new JLabel();
moLabel.setOpaque(true);
moLabel.setHorizontalAlignment(JLabel.CENTER);
}
public void setLabel(JLabel o) { moLabel = o; }
public JLabel getLabel() { return moLabel; }
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
int icon = SLibConsts.UNDEFINED;
try {
icon = value == null ? SGridConsts.ICON_NULL : ((Number) value).intValue();
}
catch (java.lang.Exception e) {
SLibUtils.showException(this, e);
}
switch (icon) {
case SGridConsts.ICON_NULL:
moLabel.setIcon(moIconNull);
break;
case SGridConsts.ICON_ANNUL:
moLabel.setIcon(moIconAnnul);
break;
case SGridConsts.ICON_CROSS:
moLabel.setIcon(moIconCross);
break;
case SGridConsts.ICON_WARN:
moLabel.setIcon(moIconWarn);
break;
case SGridConsts.ICON_OK:
moLabel.setIcon(moIconOk);
break;
case SGridConsts.ICON_DOC:
moLabel.setIcon(moIconDoc);
break;
case SGridConsts.ICON_THUMBS_UP:
moLabel.setIcon(moIconThumbsUp);
break;
case SGridConsts.ICON_THUMBS_DOWN:
moLabel.setIcon(moIconThumbsDown);
break;
case SGridConsts.ICON_XML_PEND:
moLabel.setIcon(moIconXmlPending);
break;
case SGridConsts.ICON_XML_ISSU:
moLabel.setIcon(moIconXmlIssued);
break;
case SGridConsts.ICON_XML_ANNUL:
moLabel.setIcon(moIconXmlAnnulled);
break;
case SGridConsts.ICON_XML_ANNUL_PDF:
moLabel.setIcon(moIconXmlAnnulledPdf);
break;
case SGridConsts.ICON_XML_ANNUL_XML:
moLabel.setIcon(moIconXmlAnnulledXml);
break;
default:
moLabel.setIcon(moIconNull);
}
if (isSelected) {
if (table.isCellEditable(row, col)) {
moLabel.setForeground(SGridConsts.COLOR_FG_EDIT);
moLabel.setBackground(hasFocus ? SGridConsts.COLOR_BG_SELECT_EDIT_FOCUS : SGridConsts.COLOR_BG_SELECT_EDIT);
}
else {
moLabel.setForeground(SGridConsts.COLOR_FG_READ);
moLabel.setBackground(hasFocus ? SGridConsts.COLOR_BG_SELECT_READ_FOCUS : SGridConsts.COLOR_BG_SELECT_READ);
}
}
else {
if (table.isCellEditable(row, col)) {
moLabel.setForeground(SGridConsts.COLOR_FG_EDIT);
moLabel.setBackground(SGridConsts.COLOR_BG_PLAIN_EDIT);
}
else {
moLabel.setForeground(SGridConsts.COLOR_FG_READ);
moLabel.setBackground(SGridConsts.COLOR_BG_PLAIN_READ);
}
}
return moLabel;
}
}
|
ovejur/hnie | zyjh/src/main/java/cn/edu/hnie/zyjh/function/service/impl/InfChooseServiceImpl.java | <gh_stars>0
package cn.edu.hnie.zyjh.function.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.edu.hnie.zyjh.function.dao.InfChooseDao;
import cn.edu.hnie.zyjh.function.entity.InfChoose;
import cn.edu.hnie.zyjh.function.entity.InfStudent;
/*
* 双选的业务层
*/
@Service
public class InfChooseServiceImpl {
@Autowired
private InfChooseDao chooseDao;
//学生选择企业
public void chooseEachOther(String srcId,String destId){
InfChoose choose = new InfChoose();
choose.setSrcId(srcId);
choose.setDestId(destId);
choose.setSrcType("1");
//choose.setStatus(ChooseType.STUDENT_TO_COMPANY);
choose.setCreateTime(new Date());
//chooseDao.save(choose);
}
//企业选择学生
//由于企业可以一次性选择多个卓越班的学生
public void chooseEachOther(String srcId,String[] destId){
ArrayList<InfChoose> list = new ArrayList<>();
for(int i = 0;i<destId.length;i++){
InfChoose choose = new InfChoose();
choose.setSrcId(srcId);
choose.setDestId(destId[2]);
choose.setSrcType("2");
// choose.setStatus(ChooseType.COMPANY_TO_STUDENT);
choose.setCreateTime(new Date());
}
}
//老师指定
public void teacherSet(String srcId,String[] destId){
ArrayList<InfChoose> list = new ArrayList<>();
for(int i = 0;i<destId.length;i++){
InfChoose choose = new InfChoose();
choose.setSrcId(srcId);
choose.setDestId(destId[2]);
choose.setSrcType("3");
//choose.setStatus(ChooseType.TEACHER_SET);
choose.setCreateTime(new Date());
}
}
//修改双选的记录
//第一轮互选成功的记录
public List<HashMap<String,Object>> querySuccess(int srcType,int status){
HashMap<String, Object> map = new HashMap<>();
map.put("srcType", srcType);
map.put("status", status);
List<HashMap<String,Object>> chooseMapList = chooseDao.querySuccess(map );
return chooseMapList;
}
//查询两轮双选不成功的学生
public List<InfStudent> queryTwofailStudent(){
List<InfStudent> stuList = chooseDao.queryTwofailStudent();
return stuList;
}
}
|
Sproutigy/verve | webserver/src/main/java/com/sproutigy/verve/webserver/actions/FinishWebAction.java | package com.sproutigy.verve.webserver.actions;
import com.sproutigy.verve.webserver.HttpRequestContext;
import lombok.Data;
@Data
public class FinishWebAction implements WebAction {
public final static FinishWebAction INSTANCE = new FinishWebAction();
@Override
public Object execute(HttpRequestContext context) {
return null;
}
}
|
IceKhan13/ecosystem | tests/utils/test_utils.py | """Tests for manager."""
import os
from unittest import TestCase
from ecosystem.models.repository import Repository
from ecosystem.utils import parse_submission_issue
class TestUtils(TestCase):
"""Test class for manager functions."""
def setUp(self) -> None:
current_dir = os.path.dirname(os.path.abspath(__file__))
with open(
"{}/../resources/issue.md".format(current_dir), "r"
) as issue_body_file:
self.issue_body = issue_body_file.read()
def test_issue_parsing(self):
""" "Tests issue parsing function:
Function:
-> parse_submission_issue
Args:
issue_body
Return : Repository
"""
parsed_result = parse_submission_issue(self.issue_body)
self.assertTrue(isinstance(parsed_result, Repository))
self.assertEqual(parsed_result.name, "awesome")
self.assertEqual(parsed_result.url, "http://github.com/awesome/awesome")
self.assertEqual(
parsed_result.description, "An awesome repo for awesome project"
)
self.assertEqual(parsed_result.contact_info, "<EMAIL>")
self.assertEqual(parsed_result.alternatives, "tititata")
self.assertEqual(parsed_result.licence, "Apache License 2.0")
self.assertEqual(parsed_result.affiliations, "_No response_")
self.assertEqual(parsed_result.labels, ["tool", "tutorial"])
|
yangyanzhan/code-camp | leetcode/longest-happy-prefix.js | // Hi, I'm Yanzhan. I'm interested in all kinds of algorithmic problems. Also, I'm fascinated with javascript. If you want to learn more about programming problems and javascript, please visit my Youtube Channel (https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber), Twitter Account (https://twitter.com/YangYanzhan), GitHub Repo (https://github.com/yangyanzhan/code-camp) or HomePage (https://yanzhan.site/).
// 开始分析
// 1. 用字符串哈希来解决问题。
// 结束分析
// 开始编码
/**
* @param {string} s
* @return {string}
*/
var longestPrefix = function(s) {
var n = s.length;
var res = '', a = 0, b = 0, base = 131, accBase = 1, mod = Math.pow(10, 9) + 7;
for (var i = 0; i < n - 1; i++) {
var d = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
var v1 = (a * base + d) % mod;
d = s[s.length - 1 - i].charCodeAt(0) - 'a'.charCodeAt(0);
var v2 = (b + d * accBase) % mod;
accBase = (base * accBase) % mod;
if (v1 == v2) {
res = s.substr(0, i + 1);
}
a = v1;
b = v2;
}
return res;
};
|
solomax/openjpa | openjpa-slice/src/main/java/org/apache/openjpa/slice/DistributedStoreManager.java | <reponame>solomax/openjpa<filename>openjpa-slice/src/main/java/org/apache/openjpa/slice/DistributedStoreManager.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.slice;
import java.util.Map;
import org.apache.openjpa.kernel.StoreManager;
import org.apache.openjpa.slice.jdbc.SliceStoreManager;
/**
* A specialized {@link StoreManager Store Manager} that encapsulates multiple concrete Store Managers
* using Distributed Template (or Composite) Design Pattern.
*
* @author <NAME>
*
*/
public interface DistributedStoreManager extends StoreManager {
/**
* Adds the given slice with the given properties. This newly added slice
* will participate in the current and subsequent transaction.
*
* @param name logical name of the to be added slice. Must be different from
* any currently available slices.
* @see DistributedBroker#addSlice(String, Map)
* @see DistributedBrokerFactory#addSlice(String, Map)
*
* @return the store manager for the newly added slice.
*
*/
public SliceStoreManager addSlice(Slice slice);
}
|
SanSYS/fraudbusters | src/main/java/com/rbkmoney/fraudbusters/listener/payment/ResultAggregatorListener.java | <gh_stars>0
package com.rbkmoney.fraudbusters.listener.payment;
import com.rbkmoney.fraudbusters.config.KafkaConfig;
import com.rbkmoney.fraudbusters.converter.FraudResultToEventConverter;
import com.rbkmoney.fraudbusters.domain.FraudResult;
import com.rbkmoney.fraudbusters.repository.EventRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import java.util.List;
@Slf4j
@Component
@RequiredArgsConstructor
public class ResultAggregatorListener {
private final EventRepository eventRepository;
private final FraudResultToEventConverter fraudResultToEventConverter;
@KafkaListener(topics = "${kafka.topic.result}", containerFactory = "kafkaListenerContainerFactory")
public void listen(List<FraudResult> batch, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) Integer partition,
@Header(KafkaHeaders.OFFSET) Long offset) throws InterruptedException {
try {
log.info("ResultAggregatorListener listen result size: {} partition: {} offset: {}", batch.size(), partition, offset);
eventRepository.insertBatch(fraudResultToEventConverter.convertBatch(batch));
} catch (Exception e) {
log.warn("Error when ResultAggregatorListener listen e: ", e);
Thread.sleep(KafkaConfig.THROTTLING_TIMEOUT);
throw e;
}
}
}
|
Torbaz/nestrischamps | public/views/competition_admin.js | const dom = {
roomid: document.querySelector('#roomid'),
producer_count: document.querySelector('#producer_count'),
logo: document.querySelector('#logo input'),
bestof: document.querySelector('#bestof'),
clear_victories: document.querySelector('#clear_victories'),
player_link: document.querySelector('#player_link'),
};
const MAX_BEST_OF = 13;
const remoteAPI = {
setBestOf: function(n) {
connection.send(['setBestOf', n]);
},
setPlayer: function(player_idx, user_id) {
connection.send(['setPlayer', player_idx, user_id]);
},
setVictories: function(player_idx, num_wins) {
connection.send(['setVictories', player_idx, num_wins]);
},
setWinner: function(player_idx) {
connection.send(['setWinner', player_idx]);
},
setDisplayName: function(player_idx, name) {
connection.send(['setDisplayName', player_idx, name]);
},
setProfileImageURL: function(player_idx, url) {
connection.send(['setProfileImageURL', player_idx, url]);
},
resetVictories: function() {
connection.send(['resetVictories']);
},
playVictoryAnimation: function(player_idx) {
connection.send(['playVictoryAnimation', player_idx]);
},
clearVictoryAnimation: function(player_idx) {
connection.send(['clearVictoryAnimation', player_idx]);
},
setLogo: function(url) {
connection.send(['setLogo', url]);
}
};
let players;
let room_data;
let connection;
function getProducer(pid) {
return room_data.producers.find(producer => producer.id == pid);
}
class Player {
constructor(idx, dom) {
this.idx = idx;
this.dom = dom;
this.victories = 0;
this.bestof = -1;
// link dom events
this.dom.name.onchange
= this.dom.name.onkeyup
= this.dom.name.onblur
= () => {
remoteAPI.setDisplayName(this.idx, this.dom.name.value.trim());
};
this.dom.avatar_url.onchange
= this.dom.avatar_url.onkeyup
= this.dom.avatar_url.onblur
= () => {
const avatar_url = this.dom.avatar_url.value.trim();
remoteAPI.setProfileImageURL(this.idx, avatar_url);
this.dom.avatar_img.src = avatar_url;
};
this.dom.producers.onchange = () => this._pickProducer(parseInt(this.dom.producers.value, 10));
this.dom.win_btn.onclick = () => {
remoteAPI.setWinner(this.idx);
}
}
setProducers(producers) {
this.dom.producers.innerHTML = '';
const option = document.createElement('option');
option.value = '-';
option.textContent = '-';
this.dom.producers.appendChild(option);
producers.forEach(producer => {
const option = document.createElement('option');
option.value = producer.id;
option.textContent = producer.login;
this.dom.producers.appendChild(option);
});
}
setBestOf(n) {
if (this.bestof === n) return;
this.bestof = n;
this.dom.victories.innerHTML = '';
const heart = 'Œ';
const num_heart = Math.ceil(n / 2);
const items = ['-', ...Array(num_heart).fill(heart)];
items.forEach((content, idx) => {
const span = document.createElement('span');
span.innerHTML = content;
span.onclick = () => this._pickVictories(idx);
this.dom.victories.append(span);
});
}
_pickProducer(pid) {
remoteAPI.setPlayer(this.idx, parseInt(pid, 10));
}
setProducer(pid) {
const selected_pid = parseInt(this.dom.producers.value, 10);
if (selected_pid === pid) return;
const producer = getProducer(pid);
this.dom.producers.value = pid
if (!producer) return;
this.dom.name.value = producer.display_name;
this.dom.avatar_url.value = producer.profile_image_url;
this.dom.avatar_img.src = producer.profile_image_url;
}
_pickVictories(n) {
remoteAPI.setVictories(this.idx, n);
}
setVictories(n) {
if (this.victories == n) return;
this.victories = n;
this.dom.victories.querySelectorAll('span').forEach((span, idx) => {
if (idx && idx <= (n || 0)) {
span.classList.add('win');
}
else {
span.classList.remove('win');
}
});
}
setState(state) {
this.setVictories(state.victories);
this.setProducer(state.id);
this.dom.name.value = state.display_name;
this.dom.avatar_url.value = state.profile_image_url;
this.dom.avatar_img.src = state.profile_image_url;
}
}
function setBestOfOptions(n, selected) {
const select = dom.bestof;
for (; n >= 3; n -= 2) {
const option = document.createElement('option');
option.value = n;
option.textContent = n;
if (n === selected) {
option.setAttribute('selected', 'selected')
}
select.prepend(option);
}
}
function setState(_room_data) {
room_data = _room_data;
// room stats
room_data.producers.sort((a, b) => a < b);
dom.producer_count.textContent = room_data.producers.length;
players.forEach((player, idx) => {
player.setProducers(room_data.producers);
player.setBestOf(room_data.bestof);
player.setState(room_data.players[idx]);
});
}
function bootstrap() {
players = [1, 2].map(num => new Player(num - 1, {
producers: document.querySelector(`#producers .p${num} select`),
name: document.querySelector(`#names .p${num} input`),
avatar_url: document.querySelector(`#avatar_urls .p${num} input`),
avatar_img: document.querySelector(`#avatars .p${num} img`),
victories: document.querySelector(`#victories .p${num}`),
win_btn: document.querySelector(`#wins .p${num} button`),
}));
setBestOfOptions(MAX_BEST_OF, 3);
dom.roomid.textContent = location.pathname.split('/')[3] || '_default';
dom.producer_count.textContent = 0;
dom.bestof.onchange = () => remoteAPI.setBestOf(parseInt(dom.bestof.value, 10));
dom.logo.onchange
= logo.onkeyup
= logo.onkeydown
= logo.onblur
= () => remoteAPI.setLogo(dom.logo.value.trim());
dom.clear_victories.addEventListener('click', () => remoteAPI.resetVictories());
// =====
connection = new Connection();
connection.onMessage = function(message) {
const [command, ...args] = message;
switch (command) {
case 'state': {
setState(args[0]);
break;
}
case 'setOwner': {
const owner = args[0];
const player_url = `${location.protocol}//${location.host}/room/u/${owner.login}/producer`;
dom.player_link.href = player_url;
dom.player_link.textContent = player_url;
break;
}
default: {
console.log(`Received unknow command ${command}`);
}
}
};
}
bootstrap();
|
Go-Va/lavarun-plugin | src/main/java/me/gong/lavarun/plugin/util/NumberUtils.java | package me.gong.lavarun.plugin.util;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class NumberUtils {
public static Random random = new Random();
public static SecureRandom secureRandom = new SecureRandom();
public static int getRandom(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
public static int getSecureRandom(int min, int max) {
return secureRandom.nextInt((max - min) + 1) + min;
}
public static void knockEntity(Vector from, Entity e, float knockback) {
Vector vec = e.getVelocity();
double motX = vec.getX(), motY = vec.getY(), motZ = vec.getZ();
float f = MathHelper.sqrt_double(from.getX() * from.getX() + from.getZ() * from.getZ());
motX /= 2;
motZ /= 2;
motX -= from.getX() / (double) f * (double) knockback;
motZ -= from.getZ() / (double) f * (double) knockback;
motX *= 0.6;
motZ *= 0.6;
if(e.isOnGround()) {
motY /= 2;
motY = Math.min(0.4000000059604645D, motY + knockback);
}
e.setVelocity(new Vector(motX, motY, motZ));
}
public static void knockEntityWithKnockback(Entity from, Entity e, float knockback) {
knockEntity(new Vector((double) MathHelper.sin(from.getLocation().getYaw() * 0.017453292F), 0,
(double) (-MathHelper.cos(from.getLocation().getYaw() * 0.017453292F))), e, knockback);
}
public static void knockEntityWithDamage(Entity from, Entity e) {
knockEntity(new Vector(from.getLocation().getX() - e.getLocation().getX(), 0,
from.getLocation().getZ() - e.getLocation().getZ()), e, 0.5f);
}
public static double trim(int level, double value) {
StringBuilder sb = new StringBuilder("#.#");
for(int i=0; i < level; i++) sb.append("#");
return Double.valueOf(new DecimalFormat(sb.toString()).format(value));
}
public static Vector getVectorForPlayer(Player player) {
float yaw = player.getLocation().getYaw(), pitch = player.getLocation().getPitch();
float f = MathHelper.cos(-yaw * 0.017453292F - (float) Math.PI); //negative yaw -> radians - 180 in radians, cosine
float f1 = MathHelper.sin(-yaw * 0.017453292F - (float) Math.PI);
float f2 = -MathHelper.cos(-pitch * 0.017453292F);
float f3 = MathHelper.sin(-pitch * 0.017453292F);
return new Vector((double) (f1 * f2), (double) f3, (double) (f * f2));
}
public static Set<Location> getSphere(Location center, int radius, int height, boolean hollow, boolean sphere, int plus_y) {
Set<Location> locs = new HashSet<>();
int cx = center.getBlockX();
int cy = center.getBlockY();
int cz = center.getBlockZ();
for (int x = cx - radius; x <= cx + radius; x++) {
for (int z = cz - radius; z <= cz + radius; z++) {
for (int y = (sphere ? cy - radius : cy); y < (sphere ? cy + radius : cy + height); y++) {
double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0);
if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1))) {
Location l = new Location(center.getWorld(), x, y + plus_y, z);
locs.add(l);
}
}
}
}
return locs;
}
public static Set<Location> getSphere(Location center, int radius) {
return getSphere(center, radius, 0, false, true, 0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.