repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Max-PJB/python-learning2
|
LeetCode/weekly-contest-144-2019.11.04/defangIPaddr_1108.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2019/11/4 14:12
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
-------------------------------------------------
Description : 1108. IP 地址无效化
https://leetcode-cn.com/contest/weekly-contest-144/problems/defanging-an-ip-address/
-------------------------------------------------
"""
import time
from typing import List
__author__ = 'Max_Pengjb'
start_time = time.time()
# 下面写上代码块
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]")
# 上面中间写上代码块
end_time = time.time()
print('Running time: %s Seconds' % (end_time - start_time))
|
graphisoft-python/TextEngine
|
Support/Modules/Geometry/Real.hpp
|
#if !defined (REAL_HPP)
#define REAL_HPP
#pragma once
#include <math.h>
#if !defined (REALNUMBER_H)
#include "RealNumber.h"
#endif
namespace Geometry {
// =============================================================================
//
// General comparision functions (allowing number type-templated algorihms
//
// (no general implementation, only specializations)
// =============================================================================
template <class NumberType> bool IsNear (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsNotNear (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsGreaterOrNear (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsLessOrNear (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsGreater (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsLess (const NumberType& r1, const NumberType& r2);
template <class NumberType> bool IsNearZero (const NumberType& r);
template <class NumberType> bool IsNotNearZero (const NumberType& r);
template <class NumberType> bool IsNegative (const NumberType& r);
template <class NumberType> bool IsNotNegative (const NumberType& r);
template <class NumberType> bool IsPositive (const NumberType& r);
template <class NumberType> bool IsNotPositive (const NumberType& r);
template <class NumberType> bool IsNear (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsNotNear (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsGreaterOrNear (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsLessOrNear (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsGreater (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsLess (const NumberType& r1, const NumberType& r2, double givenEps);
template <class NumberType> bool IsNearZero (const NumberType& r, double givenEps);
template <class NumberType> bool IsNotNearZero (const NumberType& r, double givenEps);
template <class NumberType> bool IsNegative (const NumberType& r, double givenEps);
template <class NumberType> bool IsNotNegative (const NumberType& r, double givenEps);
template <class NumberType> bool IsPositive (const NumberType& r, double givenEps);
template <class NumberType> bool IsNotPositive (const NumberType& r, double givenEps);
template <class NumberType> NumberType Discretize (NumberType r);
template <class NumberType> NumberType Discretize (NumberType r, double givenEps);
template <class NumberType> NumberType Abs (const NumberType& param); // absolute value
template <class NumberType> NumberType Sgn (const NumberType& param); // signum value
template <class NumberType> NumberType Sqrt (const NumberType& param); // square root value
template <class NumberType> double GetEps (void);
// =============================================================================
//
// General comparision functions specialized for doubles
//
// =============================================================================
template<>
inline bool IsNear (const double& r1, const double& r2)
{
return fabs (r1 - r2) <= EPS;
}
template<>
inline bool IsNotNear (const double& r1, const double& r2)
{
return fabs (r1 - r2) > EPS;
}
template<>
inline bool IsGreaterOrNear (const double& r1, const double& r2)
{
return r2 - r1 <= EPS;
}
template<>
inline bool IsLessOrNear (const double& r1, const double& r2)
{
return r1 - r2 <= EPS;
}
template<>
inline bool IsGreater (const double& r1, const double& r2)
{
return r1 - r2 > EPS;
}
template<>
inline bool IsLess (const double& r1, const double& r2)
{
return r2 - r1 > EPS;
}
template<>
inline bool IsNearZero (const double& r)
{
return fabs (r) <= EPS;
}
template<>
inline bool IsNotNearZero (const double& r)
{
return fabs (r) > EPS;
}
template<>
inline bool IsNegative (const double& r)
{
return r < -EPS;
}
template<>
inline bool IsNotNegative (const double& r)
{
return r >= -EPS;
}
template<>
inline bool IsPositive (const double& r)
{
return r > EPS;
}
template<>
inline bool IsNotPositive (const double& r)
{
return r <= EPS;
}
template<>
inline bool IsNear (const double& r1, const double& r2, double givenEps)
{
return fabs (r1 - r2) <= givenEps;
}
template<>
inline bool IsNotNear (const double& r1, const double& r2, double givenEps)
{
return fabs (r1 - r2) > givenEps;
}
template<>
inline bool IsGreaterOrNear (const double& r1, const double& r2, double givenEps)
{
return r2 - r1 <= givenEps;
}
template<>
inline bool IsLessOrNear (const double& r1, const double& r2, double givenEps)
{
return r1 - r2 <= givenEps;
}
template<>
inline bool IsGreater (const double& r1, const double& r2, double givenEps)
{
return r1 - r2 > givenEps;
}
template<>
inline bool IsLess (const double& r1, const double& r2, double givenEps)
{
return r2 - r1 > givenEps;
}
template<>
inline bool IsNearZero (const double& r, double givenEps)
{
return fabs (r) <= givenEps;
}
template<>
inline bool IsNotNearZero (const double& r, double givenEps)
{
return fabs (r) > givenEps;
}
template<>
inline bool IsNegative (const double& r1, double givenEps)
{
return r1 < -givenEps;
}
template<>
inline bool IsNotNegative (const double& r1, double givenEps)
{
return r1 >= -givenEps;
}
template<>
inline bool IsPositive (const double& r1, double givenEps)
{
return r1 > givenEps;
}
template<>
inline bool IsNotPositive (const double& r1, double givenEps)
{
return r1 <= givenEps;
}
template<>
inline double Discretize (double r)
{
return floor((r + EPS/2) / EPS);;
}
template<>
inline double Discretize (double r, double givenEps)
{
return floor((r + givenEps/2) / givenEps);
}
template<>
inline double Abs (const double& r)
{
return fabs (r);
}
template<>
inline double Sgn (const double& r)
{
if (IsNearZero (r)) {
return 0.0;
} else if (r < 0.0) {
return -1.0;
} else {
return 1.0;
}
}
template<>
inline double Sqrt (const double& r)
{
return sqrt (r);
}
template<>
inline float Sqrt (const float& r)
{
return sqrt (r);
}
template<>
inline double GetEps<double> (void)
{
return EPS;
}
// =============================================================================
//
// Real number class
//
// =============================================================================
class GEOMETRY_DLL_EXPORT Real {
private:
double value;
static double eps;
inline static void SetEps (double eps);
public:
static const Real Zero;
inline Real (void);
inline Real (const Real& source);
inline explicit Real (double real);
inline ~Real ();
friend bool IsNear <Real> (const Real& r1, const Real& r2);
friend bool IsNotNear <Real> (const Real& r1, const Real& r2);
friend bool IsGreaterOrNear <Real> (const Real& r1, const Real& r2);
friend bool IsLessOrNear <Real> (const Real& r1, const Real& r2);
friend bool IsGreater <Real> (const Real& r1, const Real& r2);
friend bool IsLess <Real> (const Real& r1, const Real& r2);
friend bool IsNearZero <Real> (const Real& r);
friend bool IsNotNearZero <Real> (const Real& r);
friend bool IsNegative <Real> (const Real& r);
friend bool IsNotNegative <Real> (const Real& r);
friend bool IsPositive <Real> (const Real& r);
friend bool IsNotPositive <Real> (const Real& r);
friend bool IsNear <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsNotNear <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsGreaterOrNear <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsLessOrNear <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsGreater <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsLess <Real> (const Real& r1, const Real& r2, double givenEps);
friend bool IsNearZero <Real> (const Real& r, double givenEps);
friend bool IsNotNearZero <Real> (const Real& r, double givenEps);
friend bool IsNegative <Real> (const Real& r, double givenEps);
friend bool IsNotNegative <Real> (const Real& r, double givenEps);
friend bool IsPositive <Real> (const Real& r, double givenEps);
friend bool IsNotPositive <Real> (const Real& r, double givenEps);
inline Real operator- (void) const;
friend Real operator+ (const Real& r1, const Real& r2);
friend Real operator- (const Real& r1, const Real& r2);
friend Real operator* (const Real& r1, const Real& r2);
friend Real operator/ (const Real& r1, const Real& r2);
inline Real& operator= (const Real& source);
inline Real& operator+= (const Real& other);
inline Real& operator-= (const Real& other);
inline Real& operator*= (const Real& other);
inline Real& operator/= (const Real& other);
friend Real Abs <Real> (const Real& r);
friend Real Sgn <Real> (const Real& r);
friend Real Sqrt <Real> (const Real& r);
friend Real Min (const Real& r1, const Real& r2);
friend Real Max (const Real& r1, const Real& r2);
inline operator double () const;
inline double GetValue (void) const;
friend double GetEps <Real> (void);
};
Real::Real (void)
:value (0.0)
{
}
Real::Real (const Real& source)
:value (source.value)
{
}
Real::Real (double real)
:value (real)
{
}
Real::~Real ()
{
// empty
}
Real Real::operator- (void) const
{
return Real (-value);
}
Real& Real::operator= (const Real& source)
{
if (this != &source) {
this->value = source.value;
}
return *this;
}
Real& Real::operator+= (const Real& other)
{
value += other.value;
return *this;
}
Real& Real::operator-= (const Real& other)
{
value -= other.value;
return *this;
}
Real& Real::operator*= (const Real& other)
{
value *= other.value;
return *this;
}
Real& Real::operator/= (const Real& other)
{
value /= other.value;
return *this;
}
// =============================================================================
//
// General comparision functions specialized for Reals
//
// =============================================================================
// The eps could be accessed with "Real::" instead of "real."
// In the future it is imaginable that all Reals have an own eps.
// This notation express this possible direction.
template<>
inline bool IsNear (const Real& r1, const Real& r2)
{
return fabs (r1.value - r2.value) <= r1.eps;
}
template<>
inline bool IsNotNear (const Real& r1, const Real& r2)
{
return fabs (r1.value - r2.value) > r1.eps;
}
template<>
inline bool IsGreaterOrNear (const Real& r1, const Real& r2)
{
return r2.value - r1.value <= r1.eps;
}
template<>
inline bool IsLessOrNear (const Real& r1, const Real& r2)
{
return r1.value - r2.value <= r1.eps;
}
template<>
inline bool IsGreater (const Real& r1, const Real& r2)
{
return r1.value - r2.value > r1.eps;
}
template<>
inline bool IsLess (const Real& r1, const Real& r2)
{
return r2.value - r1.value > r1.eps;
}
template<>
inline bool IsNearZero (const Real& r)
{
return fabs (r.value) <= r.eps;
}
template<>
inline bool IsNotNearZero (const Real& r)
{
return fabs (r.value) > r.eps;
}
template<>
inline bool IsNegative (const Real& r)
{
return r.value < -r.eps;
}
template<>
inline bool IsNotNegative (const Real& r)
{
return r.value >= -r.eps;
}
template<>
inline bool IsPositive (const Real& r)
{
return r.value > r.eps;
}
template<>
inline bool IsNotPositive (const Real& r)
{
return r.value <= r.eps;
}
template<>
inline bool IsNear (const Real& r1, const Real& r2, double givenEps)
{
return fabs (r1.value - r2.value) <= givenEps;
}
template<>
inline bool IsNotNear (const Real& r1, const Real& r2, double givenEps)
{
return fabs (r1.value - r2.value) > givenEps;
}
template<>
inline bool IsGreaterOrNear (const Real& r1, const Real& r2, double givenEps)
{
return r2.value - r1.value <= givenEps;
}
template<>
inline bool IsLessOrNear (const Real& r1, const Real& r2, double givenEps)
{
return r1.value - r2.value <= givenEps;
}
template<>
inline bool IsGreater (const Real& r1, const Real& r2, double givenEps)
{
return r1.value - r2.value > givenEps;
}
template<>
inline bool IsLess (const Real& r1, const Real& r2, double givenEps)
{
return r2.value - r1.value > givenEps;
}
template<>
inline bool IsNearZero (const Real& r, double givenEps)
{
return fabs (r.value) <= givenEps;
}
template<>
inline bool IsNotNearZero (const Real& r, double givenEps)
{
return fabs (r.value) > givenEps;
}
template<>
inline bool IsNegative (const Real& r1, double givenEps)
{
return r1.value < -givenEps;
}
template<>
inline bool IsNotNegative (const Real& r1, double givenEps)
{
return r1.value >= -givenEps;
}
template<>
inline bool IsPositive (const Real& r1, double givenEps)
{
return r1.value > givenEps;
}
template<>
inline bool IsNotPositive (const Real& r1, double givenEps)
{
return r1.value <= givenEps;
}
inline Real operator+ (const Real& r1, const Real& r2)
{
return Real (r1.value + r2.value);
}
inline Real operator- (const Real& r1, const Real& r2)
{
return Real (r1.value - r2.value);
}
inline Real operator* (const Real& r1, const Real& r2)
{
return Real (r1.value * r2.value);
}
inline Real operator/ (const Real& r1, const Real& r2)
{
return Real (r1.value / r2.value);
}
inline Real::operator double () const
{
return value;
}
inline double Real::GetValue () const
{
return value;
}
inline void Real::SetEps (double newEps)
{
eps = newEps;
}
template<>
inline double GetEps<Real> (void)
{
return Real::eps;
}
template<>
inline Real Abs<Real> (const Real& r)
{
return Real (fabs (r.value));
}
template<>
inline Real Sgn<Real> (const Real& r)
{
return Real (Sgn (r.value));
}
template<>
inline Real Sqrt<Real> (const Real& r)
{
return Real (sqrt (r.value));
}
inline Real Min (const Real& r1, const Real& r2)
{
return Real (r1.value < r2.value ? r1.value : r2.value);
}
inline Real Max (const Real& r1, const Real& r2)
{
return Real (r1.value > r2.value ? r1.value : r2.value);
}
} // namespace Geometry
#endif
|
uk-gov-mirror/hmcts.hwf-staffapp
|
db/migrate/20151210152605_create_business_entities.rb
|
class CreateBusinessEntities < ActiveRecord::Migration[5.2]
def up
create_table :business_entities do |t|
t.references :office, null: false, index: true
t.references :jurisdiction, null: false, index: true
t.string :code, null: false, index: true
t.string :name, null: false, index: true
t.timestamps null: false
end
add_index :business_entities, [:office_id, :jurisdiction_id], unique: true, name: :unique_office_jurisdiction
insert_sql = <<-SQL.gsub(/^\s+\|/, '')
|INSERT INTO business_entities (office_id, jurisdiction_id, code, name, created_at, updated_at)
|SELECT
| offices.id,
| jurisdictions.id,
| offices.entity_code,
| concat_ws(' - ', offices.name, jurisdictions.name),
| NOW(),
| NOW()
|FROM offices
|CROSS JOIN jurisdictions
SQL
execute(insert_sql)
end
def down
remove_index :business_entities, name: :unique_office_jurisdiction
drop_table :business_entities
end
end
|
webdevhub42/Lambda
|
WEEKS/CD_Sata-Structures/_MISC/misc-examples/python3-book-examples/asyncio/asyncio_coroutine.py
|
# Copyright (c) 2014 <NAME>. All rights reserved.
"""Starting a coroutine
"""
# end_pymotw_header
import asyncio
async def coroutine():
print("in coroutine")
event_loop = asyncio.get_event_loop()
try:
print("starting coroutine")
coro = coroutine()
print("entering event loop")
event_loop.run_until_complete(coro)
finally:
print("closing event loop")
event_loop.close()
|
ci123chain/ci123chain
|
pkg/ibc/core/channel/keeper/grpc_query.go
|
<filename>pkg/ibc/core/channel/keeper/grpc_query.go<gh_stars>0
package keeper
import (
"context"
"github.com/ci123chain/ci123chain/pkg/ibc/core/exported"
"strconv"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
prefix "github.com/ci123chain/ci123chain/pkg/abci/store"
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
sdkerrors "github.com/ci123chain/ci123chain/pkg/abci/types/errors"
query "github.com/ci123chain/ci123chain/pkg/abci/types/pagination"
"github.com/ci123chain/ci123chain/pkg/ibc/core/channel/types"
clienttypes "github.com/ci123chain/ci123chain/pkg/ibc/core/clients/types"
connectiontypes "github.com/ci123chain/ci123chain/pkg/ibc/core/connection/types"
host "github.com/ci123chain/ci123chain/pkg/ibc/core/host"
)
var _ types.QueryServer = (*Keeper)(nil)
// Channel implements the Query/Channel gRPC method
func (q Keeper) Channel(c context.Context, req *types.QueryChannelRequest) (*types.QueryChannelResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId)
if !found {
return nil, status.Error(
codes.NotFound,
sdkerrors.Wrapf(types.ErrChannelNotFound, "port-id: %s, channel-id %s", req.PortId, req.ChannelId).Error(),
)
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryChannelResponse(channel, nil, selfHeight), nil
}
// Channels implements the Query/Channels gRPC method
func (q Keeper) Channels(c context.Context, req *types.QueryChannelsRequest) (*types.QueryChannelsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
channels := []*types.IdentifiedChannel{}
store := prefix.NewPrefixStore(ctx.KVStore(q.storeKey), []byte(host.KeyChannelEndPrefix))
pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error {
var result types.Channel
if err := q.cdc.UnmarshalBinaryBare(value, &result); err != nil {
return err
}
portID, channelID, err := host.ParseChannelPath(string(key))
if err != nil {
return err
}
identifiedChannel := types.NewIdentifiedChannel(portID, channelID, result)
channels = append(channels, &identifiedChannel)
return nil
})
if err != nil {
return nil, err
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryChannelsResponse{
Channels: channels,
Pagination: pageRes,
Height: selfHeight,
}, nil
}
// ConnectionChannels implements the Query/ConnectionChannels gRPC method
func (q Keeper) ConnectionChannels(c context.Context, req *types.QueryConnectionChannelsRequest) (*types.QueryConnectionChannelsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := host.ConnectionIdentifierValidator(req.Connection); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
ctx := sdk.UnwrapSDKContext(c)
channels := []*types.IdentifiedChannel{}
store := prefix.NewPrefixStore(ctx.KVStore(q.storeKey), []byte(host.KeyChannelEndPrefix))
pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error {
var result types.Channel
if err := q.cdc.UnmarshalBinaryBare(value, &result); err != nil {
return err
}
// ignore channel and continue to the next item if the connection is
// different than the requested one
if result.ConnectionHops[0] != req.Connection {
return nil
}
portID, channelID, err := host.ParseChannelPath(string(key))
if err != nil {
return err
}
identifiedChannel := types.NewIdentifiedChannel(portID, channelID, result)
channels = append(channels, &identifiedChannel)
return nil
})
if err != nil {
return nil, err
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryConnectionChannelsResponse{
Channels: channels,
Pagination: pageRes,
Height: selfHeight,
}, nil
}
// ChannelClientState implements the Query/ChannelClientState gRPC method
func (q Keeper) ChannelClientState(c context.Context, req *types.QueryChannelClientStateRequest) (*types.QueryChannelClientStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
clientID, clientState, err := q.GetChannelClientState(ctx, req.PortId, req.ChannelId)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
identifiedClientState := clienttypes.NewIdentifiedClientState(clientID, clientState)
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryChannelClientStateResponse(identifiedClientState, nil, selfHeight), nil
}
// ChannelConsensusState implements the Query/ChannelConsensusState gRPC method
func (q Keeper) ChannelConsensusState(c context.Context, req *types.QueryChannelConsensusStateRequest) (*types.QueryChannelConsensusStateResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
channel, found := q.GetChannel(ctx, req.PortId, req.ChannelId)
if !found {
return nil, status.Error(
codes.NotFound,
sdkerrors.Wrapf(types.ErrChannelNotFound, "port-id: %s, channel-id %s", req.PortId, req.ChannelId).Error(),
)
}
connection, found := q.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0])
if !found {
return nil, status.Error(
codes.NotFound,
sdkerrors.Wrapf(connectiontypes.ErrConnectionNotFound, "connection-id: %s", channel.ConnectionHops[0]).Error(),
)
}
consHeight := clienttypes.NewHeight(req.RevisionNumber, req.RevisionHeight)
consensusState, found := q.clientKeeper.GetClientConsensusState(ctx, connection.ClientId, consHeight)
if !found {
return nil, status.Error(
codes.NotFound,
sdkerrors.Wrapf(clienttypes.ErrConsensusStateNotFound, "client-id: %s", connection.ClientId).Error(),
)
}
anyConsensusState, err := clienttypes.PackConsensusState(consensusState)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryChannelConsensusStateResponse(connection.ClientId, anyConsensusState, consHeight, nil, selfHeight), nil
}
// PacketCommitment implements the Query/PacketCommitment gRPC method
func (q Keeper) PacketCommitment(c context.Context, req *types.QueryPacketCommitmentRequest) (*types.QueryPacketCommitmentResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
if req.Sequence == 0 {
return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0")
}
ctx := sdk.UnwrapSDKContext(c)
commitmentBz := q.GetPacketCommitment(ctx, req.PortId, req.ChannelId, req.Sequence)
if len(commitmentBz) == 0 {
return nil, status.Error(codes.NotFound, "packet commitment hash not found")
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryPacketCommitmentResponse(commitmentBz, nil, selfHeight), nil
}
// PacketCommitments implements the Query/PacketCommitments gRPC method
func (q Keeper) PacketCommitments(c context.Context, req *types.QueryPacketCommitmentsRequest) (*types.QueryPacketCommitmentsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
commitments := []*types.PacketState{}
store := prefix.NewPrefixStore(ctx.KVStore(q.storeKey), []byte(host.PacketCommitmentPrefixPath(req.PortId, req.ChannelId)))
pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error {
keySplit := strings.Split(string(key), "/")
sequence, err := strconv.ParseUint(keySplit[len(keySplit)-1], 10, 64)
if err != nil {
return err
}
commitment := types.NewPacketState(req.PortId, req.ChannelId, sequence, value)
commitments = append(commitments, &commitment)
return nil
})
if err != nil {
return nil, err
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryPacketCommitmentsResponse{
Commitments: commitments,
Pagination: pageRes,
Height: selfHeight,
}, nil
}
// PacketReceipt implements the Query/PacketReceipt gRPC method
func (q Keeper) PacketReceipt(c context.Context, req *types.QueryPacketReceiptRequest) (*types.QueryPacketReceiptResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
if req.Sequence == 0 {
return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0")
}
ctx := sdk.UnwrapSDKContext(c)
_, recvd := q.GetPacketReceipt(ctx, req.PortId, req.ChannelId, req.Sequence)
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryPacketReceiptResponse(recvd, nil, selfHeight), nil
}
// PacketAcknowledgement implements the Query/PacketAcknowledgement gRPC method
func (q Keeper) PacketAcknowledgement(c context.Context, req *types.QueryPacketAcknowledgementRequest) (*types.QueryPacketAcknowledgementResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
if req.Sequence == 0 {
return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0")
}
ctx := sdk.UnwrapSDKContext(c)
acknowledgementBz, found := q.GetPacketAcknowledgement(ctx, req.PortId, req.ChannelId, req.Sequence)
if !found || len(acknowledgementBz) == 0 {
return nil, status.Error(codes.NotFound, "packet acknowledgement hash not found")
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryPacketAcknowledgementResponse(acknowledgementBz, nil, selfHeight), nil
}
// PacketAcknowledgements implements the Query/PacketAcknowledgements gRPC method
func (q Keeper) PacketAcknowledgements(c context.Context, req *types.QueryPacketAcknowledgementsRequest) (*types.QueryPacketAcknowledgementsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
acks := []*types.PacketState{}
store := prefix.NewPrefixStore(ctx.KVStore(q.storeKey), []byte(host.PacketAcknowledgementPrefixPath(req.PortId, req.ChannelId)))
pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error {
keySplit := strings.Split(string(key), "/")
sequence, err := strconv.ParseUint(keySplit[len(keySplit)-1], 10, 64)
if err != nil {
return err
}
ack := types.NewPacketState(req.PortId, req.ChannelId, sequence, value)
acks = append(acks, &ack)
return nil
})
if err != nil {
return nil, err
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryPacketAcknowledgementsResponse{
Acknowledgements: acks,
Pagination: pageRes,
Height: selfHeight,
}, nil
}
// UnreceivedPackets implements the Query/UnreceivedPackets gRPC method. Given
// a list of counterparty packet commitments, the querier checks if the packet
// has already been received by checking if a receipt exists on this
// chain for the packet sequence. All packets that haven't been received yet
// are returned in the response
// Usage: To use this method correctly, first query all packet commitments on
// the sending chain using the Query/PacketCommitments gRPC method.
// Then input the returned sequences into the QueryUnreceivedPacketsRequest
// and send the request to this Query/UnreceivedPackets on the **receiving**
// chain. This gRPC method will then return the list of packet sequences that
// are yet to be received on the receiving chain.
//
// NOTE: The querier makes the assumption that the provided list of packet
// commitments is correct and will not function properly if the list
// is not up to date. Ideally the query height should equal the latest height
// on the counterparty's client which represents this chain.
func (q Keeper) UnreceivedPackets(c context.Context, req *types.QueryUnreceivedPacketsRequest) (*types.QueryUnreceivedPacketsResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
var unreceivedSequences = []uint64{}
for i, seq := range req.PacketCommitmentSequences {
if seq == 0 {
return nil, status.Errorf(codes.InvalidArgument, "packet sequence %d cannot be 0", i)
}
// if packet receipt exists on the receiving chain, then packet has already been received
if _, found := q.GetPacketReceipt(ctx, req.PortId, req.ChannelId, seq); !found {
unreceivedSequences = append(unreceivedSequences, seq)
}
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryUnreceivedPacketsResponse{
Sequences: unreceivedSequences,
Height: selfHeight,
}, nil
}
// UnreceivedAcks implements the Query/UnreceivedAcks gRPC method. Given
// a list of counterparty packet acknowledgements, the querier checks if the packet
// has already been received by checking if the packet commitment still exists on this
// chain (original sender) for the packet sequence.
// All acknowledgmeents that haven't been received yet are returned in the response.
// Usage: To use this method correctly, first query all packet acknowledgements on
// the original receiving chain (ie the chain that wrote the acks) using the Query/PacketAcknowledgements gRPC method.
// Then input the returned sequences into the QueryUnreceivedAcksRequest
// and send the request to this Query/UnreceivedAcks on the **original sending**
// chain. This gRPC method will then return the list of packet sequences whose
// acknowledgements are already written on the receiving chain but haven't yet
// been received back to the sending chain.
//
// NOTE: The querier makes the assumption that the provided list of packet
// acknowledgements is correct and will not function properly if the list
// is not up to date. Ideally the query height should equal the latest height
// on the counterparty's client which represents this chain.
func (q Keeper) UnreceivedAcks(c context.Context, req *types.QueryUnreceivedAcksRequest) (*types.QueryUnreceivedAcksResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
var unreceivedSequences = []uint64{}
for i, seq := range req.PacketAckSequences {
if seq == 0 {
return nil, status.Errorf(codes.InvalidArgument, "packet sequence %d cannot be 0", i)
}
// if packet commitment still exists on the original sending chain, then packet ack has not been received
// since processing the ack will delete the packet commitment
if commitment := q.GetPacketCommitment(ctx, req.PortId, req.ChannelId, seq); len(commitment) != 0 {
unreceivedSequences = append(unreceivedSequences, seq)
}
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return &types.QueryUnreceivedAcksResponse{
Sequences: unreceivedSequences,
Height: selfHeight,
}, nil
}
// NextSequenceReceive implements the Query/NextSequenceReceive gRPC method
func (q Keeper) NextSequenceReceive(c context.Context, req *types.QueryNextSequenceReceiveRequest) (*types.QueryNextSequenceReceiveResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if err := validategRPCRequest(req.PortId, req.ChannelId); err != nil {
return nil, err
}
ctx := sdk.UnwrapSDKContext(c)
sequence, found := q.GetNextSequenceRecv(ctx, req.PortId, req.ChannelId)
if !found {
return nil, status.Error(
codes.NotFound,
sdkerrors.Wrapf(types.ErrSequenceReceiveNotFound, "port-id: %s, channel-id %s", req.PortId, req.ChannelId).Error(),
)
}
selfHeight := clienttypes.GetSelfHeight(ctx)
return types.NewQueryNextSequenceReceiveResponse(sequence, nil, selfHeight), nil
}
func validategRPCRequest(portID, channelID string) error {
if err := host.PortIdentifierValidator(portID); err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
if err := host.ChannelIdentifierValidator(channelID); err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
return nil
}
// GetChannelClientState returns the associated client state with its ID, from a port and channel identifier.
func (k Keeper) GetChannelClientState(ctx sdk.Context, portID, channelID string) (string, exported.ClientState, error) {
channel, found := k.GetChannel(ctx, portID, channelID)
if !found {
return "", nil, sdkerrors.Wrapf(types.ErrChannelNotFound, "port-id: %s, channel-id: %s", portID, channelID)
}
connection, found := k.connectionKeeper.GetConnection(ctx, channel.ConnectionHops[0])
if !found {
return "", nil, sdkerrors.Wrapf(connectiontypes.ErrConnectionNotFound, "connection-id: %s", channel.ConnectionHops[0])
}
clientState, found := k.clientKeeper.GetClientState(ctx, connection.ClientId)
if !found {
return "", nil, sdkerrors.Wrapf(clienttypes.ErrClientNotFound, "client-id: %s", connection.ClientId)
}
return connection.ClientId, clientState, nil
}
|
vedant080102/FSD-MERN-GRP27-METER_DOWN
|
middleware/auth.js
|
<reponame>vedant080102/FSD-MERN-GRP27-METER_DOWN<filename>middleware/auth.js
const jwt= require("jsonwebtoken")
const fs = require('fs');
const path = require('path');
const pathToKey = path.join(__dirname, '..', 'id_rsa_pub.pem');
const PUB_KEY = fs.readFileSync(pathToKey, 'utf8');
const User = require("../models/User")
const checkToken=(req,res,next)=>{
if (req.signedCookies.jwt == undefined){
res.status(404).send({msg:"no token",userData:{}})
}else{
let token
try {
token=req.signedCookies.jwt.slice(7)
} catch (error) {
res.status(401).clearCookie('jwt').send({msg:"invalid token",userData:{}})
return
}
jwt.verify(token, PUB_KEY, function(err, decoded) {
console.log(decoded)
if(err){
res.status(401).send({msg:"error"})
}else{
if(decoded.exp<Date.now()){
console.log(decoded.exp,Date.now())
res.status(401).clearCookie('jwt').send({msg:"token expired",userData:{}})
}else{
req.headers.authorization=req.signedCookies.jwt
req.userId=decoded.sub
console.log("Authorized!")
next()
}
}
});
}}
const isPassenger=(req,res,next)=>{
User.findOne({_id:req.userId})
.then(user=>{
if(!user){
res.status(403).send({
"msg":"No user logged in"
})
}else{
if(user.type=="passenger"){
req.Passenger=true
next()
}
else{
res.status(403).send({
"msg":"Not a passenger"
} )
}
}
})
}
const isDriver=(req,res,next)=>{
User.findOne({_id:req.userId})
.then(user=>{
if(!user){
res.status(403).send({
"msg":"No user logged in"
})
}else{
if(user.type=="driver"){
req.isDriver=true
next()
}
else{
res.status(403).send({
"msg":"Not a driver"
} )
}
}
})
}
module.exports={
checkToken,
isPassenger,
isDriver
}
|
nwtgck/scala
|
test/files/pos/t4205/1.scala
|
trait A[OUT[_]] {
null.asInstanceOf[B[OUT]].b1("")
}
|
ubidreams/wisdom
|
core/wisdom-vertx-engine/src/main/java/org/wisdom/framework/vertx/WebSocketHandler.java
|
<gh_stars>10-100
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* 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.
* #L%
*/
package org.wisdom.framework.vertx;
import io.vertx.core.Handler;
import io.vertx.core.http.ServerWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles web socket frames.
*/
public class WebSocketHandler implements Handler<ServerWebSocket> {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketHandler.class);
/**
* The structure used to access services.
*/
private final ServiceAccessor accessor;
/**
* The server configuration.
*/
private final Server configuration;
/**
* Creates an instance of {@link org.wisdom.framework.vertx.WebSocketHandler}
*
* @param accessor the service accessor
* @param server the server configuration - used to check whether or not the message should be
* allowed or denied
*/
public WebSocketHandler(ServiceAccessor accessor, Server server) {
this.accessor = accessor;
this.configuration = server;
}
/**
* Handles a web socket connection.
*
* @param socket the opening socket.
*/
@Override
public void handle(final ServerWebSocket socket) {
LOGGER.info("New web socket connection {}, {}", socket, socket.uri());
if (! configuration.accept(socket.uri())) {
LOGGER.warn("Web Socket connection denied on {} by {}", socket.uri(), configuration.name());
return;
}
final Socket sock = new Socket(socket);
accessor.getDispatcher().addSocket(socket.path(), sock);
socket.closeHandler(event -> {
LOGGER.info("Web Socket closed {}, {}", socket, socket.uri());
accessor.getDispatcher().removeSocket(socket.path(), sock);
});
socket.handler(event -> accessor.getDispatcher().received(socket.path(), event.getBytes(), sock));
}
}
|
bayusamudra5502/PustakaCpp
|
STL/eksperimen/median.cpp
|
<reponame>bayusamudra5502/PustakaCpp
#include <bits/stdc++.h>
using namespace std;
int n, db[10];
int median(int low, int high)
{
// BANYAK KECOA DISINI :v
if (low == high)
return db[low];
int l = low, r = high;
int pivot = db[(l + r) / 2];
int tengah = (l + r) / 2;
while (l < r)
{
while (db[l] < pivot)
{
l++;
}
while (db[r] > pivot)
{
r--;
}
if (l < r)
{
swap(db[l], db[r]);
}
}
if (tengah < r)
{
return median(low, r);
}
else
{
return median(r + 1, high);
}
}
int main(int argc, const char **argv)
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> db[i];
cout << median(0, n - 1);
return 0;
}
|
mcanlas/6502-opcodes
|
src/main/scala/com/htmlism/mos6502/dsl/Operand.scala
|
package com.htmlism.mos6502.dsl
trait Operand[A] {
self =>
def toAddressLiteral(x: A): String
/**
* Suitable for comments
*/
def toShow(x: A): String
def operandType: OperandType
}
object Operand {
implicit val operandInt: Operand[Int] =
new Operand[Int] {
val operandType: OperandType =
ValueLiteral
def toShow(x: Int): String =
x.toString
def toAddressLiteral(x: Int): String =
String.format("#$%02x", x)
}
implicit def operandForMapping[A](implicit ev: Mapping[A]): Operand[A] =
new Operand[A] {
def toAddressLiteral(x: A): String =
"#" + ev.label(x)
def toShow(x: A): String =
ev.label(x)
def operandType: OperandType =
ValueLiteral
}
}
|
subuta/blog-js
|
src/views/pages/auth/cb.js
|
<gh_stars>1-10
import React from 'react'
import _ from 'lodash'
import { withRouter } from 'next/router'
import Head from 'next/head'
import connext from 'src/views/hoc/connext'
import auth0 from 'src/views/utils/auth0'
import storage from 'src/views/utils/storage'
import CustomLoader from 'src/views/components/common/CustomLoader'
import withStyles from 'src/views/components/layout/otherStyle'
import {
requestCreateUser
} from 'src/views/modules/user'
import {
compose,
lifecycle
} from 'recompose'
const enhance = compose(
withStyles,
withRouter,
lifecycle({
componentWillMount () {
const {requestCreateUser, router} = this.props
const prevPath = storage.getItem('prev-path')
auth0.parseHash().then((result) => {
auth0.setSession(result)
const {locale, nickname, picture, sub} = result.idTokenPayload
requestCreateUser({locale, nickname, auth0Id: sub, avatar: picture})
.then(() => {
router.push(prevPath ? prevPath : '/')
storage.removeItem('prev-path')
})
})
}
})
)
const LoginCallback = enhance(({styles}) => {
const title = 'Auth callback | sub-labo'
return (
<div className={styles.Container}>
<Head>
<title>{title}</title>
</Head>
<CustomLoader
label="Auth0 login succeeded :) Redirect back to sub-labo.com ..."
isShow={true}
size={80}
/>
</div>
)
})
const mapStateToProps = () => {
return {}
}
const mapDispatchToProps = {
requestCreateUser
}
export default connext(mapStateToProps, mapDispatchToProps)(LoginCallback)
|
manel1874/libscapi
|
include/infra/MathAlgorithms.hpp
|
<reponame>manel1874/libscapi
/**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#pragma once
#include "Common.hpp"
/**
* This class holds general math algorithms needed by cryptographic algorithms.<p>
* Each algorithm is represented by a static function that can be called independently from the other algorithms.
*/
class MathAlgorithms {
public:
static biginteger modInverse(biginteger a, biginteger m);
/**
* Computes the integer x that is expressed through the given primes and the
* congruences with the chinese remainder theorem (CRT).
*
* @param congruences
* the congruences c_i
* @param moduli
* the primes p_i
* @return an integer x for that x % p_i == c_i
*/
static biginteger chineseRemainderTheorem(const vector<biginteger> & congruences, const vector<biginteger> & moduli);
/**
* Computes n! (n factorial)
* @param n
* @return n!
*/
static int factorial(int n);
/**
* Computes n! (n factorial)
* @param n
* @return n! as a BigInteger
*/
static biginteger factorialBI(int n);
/*-------------------------------------------------------------*/
/**
* This class holds the result of calculating the square root of a BigInteger.
* @author Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (<NAME>)
*
*/
class SquareRootResults {
biginteger root1;
biginteger root2;
public:
SquareRootResults(const biginteger & root1, const biginteger & root2) {
this->root1 = root1;
this->root2 = root2;
}
biginteger getRoot1() {
return root1;
}
biginteger getRoot2() {
return root2;
}
};
/**
* This function calculates the square root of z mod p if and only if p is a prime such that p = 3 mod 4.
* This function assumes that p is a prime and does not perform the primality check for efficiency reasons.
* @param z the number for which we calculate the square root
* @param p the mod
* @throws IllegalArgumentException if p != 3 mod 4
* @return SquareRootResults which is a pair of BigIntegers x and -x such that z = x^2 and z = -x^2
*/
static SquareRootResults sqrtModP_3_4(const biginteger & z, const biginteger & p);
};
|
pooja-gera/TheWireUsChallenge
|
Web Scraping (Beautiful Soup, Scrapy, Selenium)/Web Scraping_ Day22/Locating Elements from html using selenium/SourceCode.py
|
<gh_stars>0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium. webdriver.support.ui import WebDriverwait
from selenium. webdriver.support import expected_conditions as EC
import time
PATH = "C:Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://techwithtim.net")
print(driver.title)
search = driver.find_element_by_name("s")
search.send_keys("test")
search.send_keys(Keys.RETURN)
try:
main = WebDriverwait(driver, 18).until(
EC.presence_of_element_located((By.ID, "main")
)
articles = main.find_elements_by_tag_name("article")
for article in articles:
header - article.find_element_by_class_name("entry-summary")
print(header.text)
finally:
driver.quit()
|
medismailben/llvm-project
|
llvm/include/llvm/ADT/PriorityQueue.h
|
//===- llvm/ADT/PriorityQueue.h - Priority queues ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the PriorityQueue class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ADT_PRIORITYQUEUE_H
#define LLVM_ADT_PRIORITYQUEUE_H
#include <algorithm>
#include <queue>
namespace llvm {
/// PriorityQueue - This class behaves like std::priority_queue and
/// provides a few additional convenience functions.
///
template<class T,
class Sequence = std::vector<T>,
class Compare = std::less<typename Sequence::value_type> >
class PriorityQueue : public std::priority_queue<T, Sequence, Compare> {
public:
explicit PriorityQueue(const Compare &compare = Compare(),
const Sequence &sequence = Sequence())
: std::priority_queue<T, Sequence, Compare>(compare, sequence)
{}
template<class Iterator>
PriorityQueue(Iterator begin, Iterator end,
const Compare &compare = Compare(),
const Sequence &sequence = Sequence())
: std::priority_queue<T, Sequence, Compare>(begin, end, compare, sequence)
{}
/// erase_one - Erase one element from the queue, regardless of its
/// position. This operation performs a linear search to find an element
/// equal to t, but then uses all logarithmic-time algorithms to do
/// the erase operation.
///
void erase_one(const T &t) {
// Linear-search to find the element.
typename Sequence::size_type i = find(this->c, t) - this->c.begin();
// Logarithmic-time heap bubble-up.
while (i != 0) {
typename Sequence::size_type parent = (i - 1) / 2;
this->c[i] = this->c[parent];
i = parent;
}
// The element we want to remove is now at the root, so we can use
// priority_queue's plain pop to remove it.
this->pop();
}
/// reheapify - If an element in the queue has changed in a way that
/// affects its standing in the comparison function, the queue's
/// internal state becomes invalid. Calling reheapify() resets the
/// queue's state, making it valid again. This operation has time
/// complexity proportional to the number of elements in the queue,
/// so don't plan to use it a lot.
///
void reheapify() {
std::make_heap(this->c.begin(), this->c.end(), this->comp);
}
/// clear - Erase all elements from the queue.
///
void clear() {
this->c.clear();
}
};
} // End llvm namespace
#endif
|
Canfone2209/Website-Gatsby
|
src/components/shop/components/phone_products/index.js
|
import React, { Fragment } from 'react';
import Item from './item';
function Phone({packages, order_data, setPhonePackage, updatePhonePortOption, updatePhonePortAuthorization, lang}) {
const products = packages.map((item) =>
<Item
key={item.id}
id={item.id}
lang={lang}
title={item.title}
description={item.description}
price={item.price}
selected_phone_package_id={order_data.phone_package_id}
setPhonePackage={setPhonePackage}
updatePhonePortOption={updatePhonePortOption}
updatePhonePortAuthorization={updatePhonePortAuthorization}
order_data={order_data}
/>
);
return (
<Fragment>
{products.length > 0 &&
products
}
</Fragment>
)
}
export default Phone;
|
flowermy/chovietjp
|
views/src/components/account/authActions.js
|
<reponame>flowermy/chovietjp
import axios from 'axios';
import {apiUrls} from "../../common/url-configs/common-url";
export default function login(data) {
return () => {
return axios.post(apiUrls.INIT + apiUrls.LOGIN, data, {withCredentials: true}).then((res) => {
const token = res.data.token;
localStorage.setItem('jwtToken', token);
window.location.reload();
}).catch((err) => {
return err;
});
}
}
|
victorgallegosGIT/Serenity-PageObject-Sistema
|
src/test/java/motoresdebusqueda/SistemaAcuerdos/steps/AltaDePerfil.java
|
package motoresdebusqueda.SistemaAcuerdos.steps;
import motoresdebusqueda.SistemaAcuerdos.pageobject.ConfiguracionAltaPerfil;
import motoresdebusqueda.SistemaAcuerdos.pageobject.VisualizacionesAltas;
import motoresdebusqueda.SistemaAcuerdos.pageobject.SistemaDeAcuerdosLogin;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import motoresdebusqueda.SistemaAcuerdos.pageobject.BotonesAltas;
import net.thucydides.core.annotations.Steps;
public class AltaDePerfil {
@Steps
SistemaDeAcuerdosLogin paginaPrincipal;
@Steps
VisualizacionesAltas visualizacionesAltas;
@Steps
BotonesAltas cart;
@Steps
ConfiguracionAltaPerfil AltaPerfil;
@Given("nos encontramos en la pagina principal de Sistema de Acuerdos")
public void NosEncontramosEnlaPaginaPrincipalDeSistemaDeAcuerdos() {
paginaPrincipal.setDefaultBaseUrl("http://10.1.1.132:9791/");
paginaPrincipal.open();
}
@When("nos logueamos rellenando el modal con los siguientes datos: {string} {string}")
public void ingresaUsuarioYPassword(String usuario, String password) {
paginaPrincipal.ingresarUsuario(usuario);
paginaPrincipal.ingresarPassword(password);
paginaPrincipal.hacerClickEnElBotonLogIn();
}
@Then("deberíamos visualizar el mensaje de bienvenida: {string}")
public void deberiaVisualizarElMensajeDeBienvenida(String mensaje) {
visualizacionesAltas.visualizarMensajeDeBienvenida(mensaje);
}
@When("hacemos clic en alta and perfil")
public void hacemosClicEnAltaAndPerfil() {
cart.botonAlta();
cart.botonAltaPerfil();
}
@Then("deberíamos dirigirnos hacia la seccion: {string}")
public void deberiamosDirigirnosHaciaLaSeccion(String mensajealta) {
visualizacionesAltas.visualizarMensajeAltaDePerfiles(mensajealta);
}
@And("rellenamos el formulario con los siguientes datos: {string} {string} {string}")
public void rellenamosElFormularioConLosSiguientesDatos(String CodigoPerfil, String NombreDePerfil, String Delegacion) {
AltaPerfil.ingresarCodigoPerfil(CodigoPerfil);
AltaPerfil.IngresarNombreDePerfil(NombreDePerfil);
AltaPerfil.ingresarDelegaciones(Delegacion);
AltaPerfil.checkBoxAdministrador();
AltaPerfil.checkboxPermisosCrear();
AltaPerfil.checkboxPermisosCosultar();
AltaPerfil.checkboxPermisosModificar();
}
@And("le damos guadar perfil")
public void le_damos_guadar_perfil() {
AltaPerfil.buttonGuardarPerfil();
}
}
|
clayne/RGA
|
source/radeon_gpu_analyzer_gui/rg_resource_usage_csv_file_parser.cpp
|
<reponame>clayne/RGA
// C++.
#include <cassert>
// Local.
#include "radeon_gpu_analyzer_gui/rg_resource_usage_csv_file_parser.h"
bool RgResourceUsageCsvFileParser::ProcessLineTokens(const std::vector<std::string>& tokens)
{
bool ret = false;
// Verify that the number of tokens matches the number of columns in the file being parsed.
int num_tokens = static_cast<int>(tokens.size());
assert(num_tokens == rgResourceUsageCsvFileColumns::kCount);
if (num_tokens == rgResourceUsageCsvFileColumns::kCount)
{
// Extract all info from the file's line tokens.
resource_usage_data_.device = tokens[rgResourceUsageCsvFileColumns::kDevice];
resource_usage_data_.scratch_memory = std::atoi(tokens[rgResourceUsageCsvFileColumns::kScratchMemory].c_str());
resource_usage_data_.threads_per_workgroup = std::atoi(tokens[rgResourceUsageCsvFileColumns::kThreadsPerWorkgroup].c_str());
resource_usage_data_.wavefront_size = std::atoi(tokens[rgResourceUsageCsvFileColumns::kWavefrontSize].c_str());
resource_usage_data_.available_lds_bytes = std::atoi(tokens[rgResourceUsageCsvFileColumns::kAvailableLdsBytes].c_str());
resource_usage_data_.used_lds_bytes = std::atoi(tokens[rgResourceUsageCsvFileColumns::kUsedLdsBytes].c_str());
resource_usage_data_.available_sgprs = std::atoi(tokens[rgResourceUsageCsvFileColumns::kAvailableSgprs].c_str());
resource_usage_data_.used_sgprs = std::atoi(tokens[rgResourceUsageCsvFileColumns::kUsedSgprs].c_str());
resource_usage_data_.sgpr_spills = std::atoi(tokens[rgResourceUsageCsvFileColumns::kSgprSpills].c_str());
resource_usage_data_.available_vgprs = std::atoi(tokens[rgResourceUsageCsvFileColumns::kAvailableVgprs].c_str());
resource_usage_data_.used_vgprs = std::atoi(tokens[rgResourceUsageCsvFileColumns::kUsedVgprs].c_str());
resource_usage_data_.vgpr_spills = std::atoi(tokens[rgResourceUsageCsvFileColumns::kVgprSpills].c_str());
resource_usage_data_.cl_workgroup_x_dimension = std::atoi(tokens[rgResourceUsageCsvFileColumns::kClWorkgroupXDimension].c_str());
resource_usage_data_.cl_workgroup_y_dimension = std::atoi(tokens[rgResourceUsageCsvFileColumns::kClWorkgroupYDimension].c_str());
resource_usage_data_.cl_workgroup_z_dimension = std::atoi(tokens[rgResourceUsageCsvFileColumns::kClWorkgroupZDimension].c_str());
resource_usage_data_.isa_size = std::atoi(tokens[rgResourceUsageCsvFileColumns::kIsaSize].c_str());
ret = true;
}
return ret;
}
|
ray1888/go-leetcode
|
src/heap/Merge-k-sorted-lists.go
|
package heap
type ListNode struct {
Val int
Next *ListNode
}
// func mergeKListsMinHeap(lists []*ListNode) *ListNode {
// }
func mergeTwoList(left, right *ListNode) *ListNode {
dummy := &ListNode{}
cur := dummy
for left != nil && right != nil {
if left.Val > right.Val {
cur.Next = right
right = right.Next
} else {
cur.Next = left
left = left.Next
}
cur = cur.Next
}
if left != nil {
cur.Next = left
left = left.Next
cur = cur.Next
}
if right != nil {
cur.Next = right
right = right.Next
cur = cur.Next
}
return dummy.Next
}
func merge(nodelist []*ListNode, start, end int) *ListNode {
if start == end {
return nodelist[start]
} else if start > end {
return nil
}
mid := start + (end-start)/2
left := merge(nodelist, start, mid)
right := merge(nodelist, mid+1, end)
return mergeTwoList(left, right)
}
func mergeKListsDivideConq(lists []*ListNode) *ListNode {
if len(lists) == 0 || lists == nil {
return nil
}
return merge(lists, 0, len(lists)-1)
}
|
aviral243/interviewbit-solutions-1
|
Arrays/infinite_2d_array.cpp
|
<reponame>aviral243/interviewbit-solutions-1
#include <iostream>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
int coverPoints(vector<int> &A, vector<int> &B)
{
int positionX = *A.begin(), positionY = *B.begin();
int steps = 0;
int i = 1;
int diffX, diffY, minDiff;
while (i < A.size())
{
diffX = abs(positionX - *(A.begin() + i));
diffY = abs(positionY - *(B.begin() + i));
minDiff = min(diffX, diffY);
// cout << positionX << " " << positionY << " " << minDiff << endl;
// return 0;
if (minDiff == 0)
{
if (diffY == 0)
{
if ((positionX) < *(A.begin() + i))
{
positionX += diffX;
}
else
{
positionX -= diffX;
}
steps += diffX;
}
if (diffX == 0)
{
if ((positionY) < *(B.begin() + i))
{
positionY += diffY;
}
else
{
positionY -= diffY;
}
steps += diffY;
}
}
else
{
if ((positionY) < *(B.begin() + i))
{
positionY += minDiff;
}
else
{
positionY -= minDiff;
}
if ((positionX) < *(A.begin() + i))
{
positionX += minDiff;
}
else
{
positionX -= minDiff;
}
steps += minDiff;
}
if (positionX == *(A.begin() + i) && positionY == *(B.begin() + i))
{
i++;
}
}
return steps;
}
int main()
{
vector<int> v1{4, 8, -7, -5, -13, 9, -7, 8}, v2{4, -15, -10, -3, -13, 12, 8, -8};
int minSteps = coverPoints(v1, v2);
cout << minSteps;
return 0;
}
|
alecnunn/mud
|
src/lang/Types.h
|
#pragma once
#include <lang/Forward.h>
#if !defined MUD_MODULES || defined MUD_TYPE_LIB
#include <type/Type.h>
#include <type/Vector.h>
#endif
#ifndef MUD_MODULES
#include <infra/Types.h>
#include <type/Types.h>
#include <pool/Types.h>
#include <refl/Types.h>
#endif
#ifndef MUD_CPP_20
#include <string>
#include <cstdint>
#include <vector>
#endif
namespace mud
{
// Exported types
export_ template <> MUD_LANG_EXPORT Type& type<mud::Language>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Interpreter>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Pipe>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Process>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ScriptClass>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ScriptError>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::StreamBranch>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Valve>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::LuaInterpreter>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessCallable>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessCreate>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessDisplay>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessFunction>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessGetMember>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessInput>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessMethod>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessOutput>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessScript>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessSetMember>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::ProcessValue>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Script>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::Stream>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::TextScript>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::VisualScript>();
export_ template <> MUD_LANG_EXPORT Type& type<mud::WrenInterpreter>();
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Interpreter*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Pipe*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Process*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ScriptClass*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ScriptError*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::StreamBranch*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Valve*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::LuaInterpreter*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessCallable*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessCreate*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessDisplay*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessFunction*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessGetMember*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessInput*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessMethod*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessOutput*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessScript*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessSetMember*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::ProcessValue*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Script*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::Stream*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::TextScript*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::VisualScript*>>;
export_ template struct MUD_LANG_EXPORT Typed<std::vector<mud::WrenInterpreter*>>;
}
|
mgpavlov/SoftUni
|
Java/Java Web/02.Java MVC Frameworks - Spring - February 2019/03.Unit Testing And Isolation/Exercise/cardealer-Integration Tests/src/test/java/org/softuni/cardealer/service/SaleServiceTests.java
|
package org.softuni.cardealer.service;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.modelmapper.ModelMapper;
import org.softuni.cardealer.domain.entities.Car;
import org.softuni.cardealer.domain.entities.Customer;
import org.softuni.cardealer.domain.entities.Part;
import org.softuni.cardealer.domain.models.service.*;
import org.softuni.cardealer.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
public class SaleServiceTests {
@Autowired
private CarSaleRepository carSaleRepository;
@Autowired
private PartSaleRepository partSaleRepository;
@Autowired
private SupplierRepository supplierRepository;
@Autowired
private CustomerRepository customerRepository;
@Autowired
private CarRepository carRepository;
@Autowired
private PartRepository partRepository;
private ModelMapper modelMapper;
private SaleService saleService;
@Before
public void init() {
this.modelMapper = new ModelMapper();
this.saleService = new SaleServiceImpl(this.carSaleRepository, this.partSaleRepository, this.modelMapper);
CustomerServiceModel customer = new CustomerServiceModel() {{
setName("Misho");
setBirthDate(LocalDate.now());
setYoungDriver(true);
}};
PartServiceModel part = new PartServiceModel() {{
setName("shaft");
setPrice(new BigDecimal("112.88"));
}};
CarServiceModel car = new CarServiceModel() {{
setMake("BMW");
setModel("7");
setTravelledDistance(35000L);
}};
customerRepository.saveAndFlush(this.modelMapper.map(customer, Customer.class));
partRepository.saveAndFlush(this.modelMapper.map(part, Part.class));
carRepository.saveAndFlush(this.modelMapper.map(car, Car.class));
}
//Tests with correct data:
@Test
public void saleService_saleCarWithCorrectFieldsValues_returnsServiceModel() {
CarSaleServiceModel model = new CarSaleServiceModel() {{
setCar(modelMapper.map(carRepository.findAll().get(0), CarServiceModel.class));
setCustomer(modelMapper.map(customerRepository.findAll().get(0), CustomerServiceModel.class));
setDiscount(2D);
}};
CarSaleServiceModel actual = this.saleService.saleCar(model);
CarSaleServiceModel expected = this.modelMapper
.map(this.carSaleRepository.findAll().get(0), CarSaleServiceModel.class);
Assert.assertEquals("Sale Car doesn't work", actual.getCar().getId(), expected.getCar().getId());
Assert.assertEquals("Sale Car doesn't work", actual.getId(), expected.getId());
Assert.assertEquals("Sale Car doesn't work", actual.getCustomer().getId(), expected.getCustomer().getId());
Assert.assertEquals("Sale Car doesn't work", actual.getDiscount(), expected.getDiscount());
}
@Test
public void saleService_salePartWithCorrectFieldsValues_returnsServiceModel() {
PartSaleServiceModel model = new PartSaleServiceModel() {{
setPart(modelMapper.map(partRepository.findAll().get(0), PartServiceModel.class));
setCustomer(modelMapper.map(customerRepository.findAll().get(0), CustomerServiceModel.class));
setQuantity(666);
setDiscount(333.33);
}};
PartSaleServiceModel actual = this.saleService.salePart(model);
PartSaleServiceModel expected = this.modelMapper
.map(this.partSaleRepository.findAll().get(0), PartSaleServiceModel.class);
Assert.assertEquals("Sale Part doesn't work", actual.getPart().getName(), expected.getPart().getName());
Assert.assertEquals("Sale Part doesn't work", actual.getId(), expected.getId());
Assert.assertEquals("Sale Part doesn't work", actual.getCustomer().getName(), expected.getCustomer().getName());
Assert.assertEquals("Sale Part doesn't work", actual.getDiscount(), expected.getDiscount());
}
//Tests with incorrect data:
@Test(expected = Exception.class)
public void saleService_salePartWithFieldsValuesNull_throwsException() {
PartSaleServiceModel partSaleServiceModel = this.saleService.salePart(new PartSaleServiceModel());
}
@Test(expected = Exception.class)
public void saleService_saleCarWithFieldsValuesNull_throwsException() {
CarSaleServiceModel carSaleServiceModel = this.saleService.saleCar(new CarSaleServiceModel());
}
}
|
xhuangmlnx/libocoms
|
ocoms/dstore/hash/dstore_hash.h
|
/*
* Copyright (c) 2010 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2012 Los Alamos National Security, Inc. All rights reserved.
* Copyright (c) 2014 Intel, Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef OCOMS_DSTORE_HASH_H
#define OCOMS_DSTORE_HASH_H
#include "ocoms/util/ocoms_hash_table.h"
#include "ocoms/dstore/dstore.h"
BEGIN_C_DECLS
OCOMS_MODULE_DECLSPEC extern ocoms_dstore_base_component_t mca_dstore_hash_component;
typedef struct {
ocoms_dstore_base_module_t api;
ocoms_hash_table_t hash_data;
} mca_dstore_hash_module_t;
OCOMS_MODULE_DECLSPEC extern mca_dstore_hash_module_t ocoms_dstore_hash_module;
END_C_DECLS
#endif /* OCOMS_DSTORE_HASH_H */
|
KristianJerpetjon/IncludeOS
|
api/util/units.hpp
|
<filename>api/util/units.hpp<gh_stars>1-10
// -*-C++-*-
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 IncludeOS AS, Oslo, Norway
//
// 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.
#pragma once
#ifndef UTIL_UNITS_HPP
#define UTIL_UNITS_HPP
#include <chrono>
#include <iostream>
namespace util {
inline namespace literals
{
/**
* Memory size literals
*/
using int_t = unsigned long long;
constexpr auto operator"" _b ( int_t x)
{ return 1ULL * x; }
constexpr auto operator"" _KiB ( int_t x)
{ return 1024_b * x; }
constexpr auto operator"" _MiB ( int_t x )
{ return 1024_KiB * x; }
constexpr auto operator"" _GiB ( int_t x )
{ return 1024_MiB * x; }
constexpr auto operator"" _TiB ( int_t x )
{ return 1024_GiB * x; }
/**
* Frequency literals
*/
using Hz = std::chrono::duration<double>;
using KHz = std::chrono::duration<double, std::kilo>;
using MHz = std::chrono::duration<double, std::mega>;
using GHz = std::chrono::duration<double, std::giga>;
constexpr Hz operator"" _hz(long double d) {
return Hz(d);
}
constexpr KHz operator"" _khz(long double d) {
return KHz(d);
}
constexpr MHz operator"" _mhz(long double d) {
return MHz(d);
}
constexpr GHz operator"" _ghz(long double d) {
return GHz(d);
}
} // ns literals
/** String representation of bytes as KiB, MiB, GiB **/
struct Byte_r {
Byte_r(uint64_t b) : b_{b}{}
std::string to_string() const {
char frep[20];
double dbl = static_cast<double>(b_);
if (b_ >= 1_TiB) {
sprintf(frep, "%0.3f", dbl / 1_TiB);
return std::string(frep) + "_TiB";
}
if (b_ >= 1_GiB) {
sprintf(frep, "%0.3f", dbl / 1_GiB);
return std::string(frep) + "_GiB";
}
if (b_ >= 1_MiB) {
sprintf(frep, "%0.3f", dbl / 1_MiB);
return std::string(frep) + "_MiB";
}
if (b_ >= 1_KiB) {
sprintf(frep, "%0.3f", dbl / 1_KiB);
return std::string(frep) + "_KiB";
}
return std::to_string(b_) + "_b";
}
uint64_t b_{};
};
inline std::ostream& operator <<(std::ostream& out, const Byte_r& b){
return out << b.to_string();
}
} // ns util
#endif
|
CodingSoldier/java-learn
|
spring-cloud-2/app002/src/main/java/com/cpq/app002/Test002Ctrl.java
|
<reponame>CodingSoldier/java-learn
package com.cpq.app002;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Description
* @Author chenpiqian
* @Date: 2019-07-03
*/
@RestController
@RequestMapping("/test02")
public class Test002Ctrl {
@GetMapping("/get/{id}")
public String test02Get(@PathVariable("id") Integer id){
return "test02/get/"+id;
}
@PostMapping("/post")
public Map<String, String> test02Post(@RequestBody Map<String, String> map){
map.put("app", "app002");
return map;
}
@PostMapping("/timeout1")
public Map<String, String> timeout1(@RequestBody Map<String, String> map) throws Exception{
TimeUnit.SECONDS.sleep(600L);
return map;
}
}
|
msonst/rpi-iot
|
rpi-iot-common/src/main/java/de/sonsts/rpi/iot/communication/common/messaage/DocumentMessageFactory.java
|
package de.sonsts.rpi.iot.communication.common.messaage;
import java.util.List;
import de.sonsts.rpi.iot.communication.common.ComplexValue;
import de.sonsts.rpi.iot.communication.common.DoubleSampleValue;
import de.sonsts.rpi.iot.communication.common.SpectrumValue;
import de.sonsts.rpi.iot.communication.common.messaage.payload.MappingPayloadDescriptor;
import de.sonsts.rpi.iot.communication.common.messaage.payload.SampleValuePayload;
public class DocumentMessageFactory
{
public static DocumentMessage<SampleValuePayload<DoubleSampleValue>> createDoubleSampleValueMessage(
MappingPayloadDescriptor<Integer, String> descriptor, List<DoubleSampleValue> values)
{
DocumentMessage<SampleValuePayload<DoubleSampleValue>> retVal = new DocumentMessage<SampleValuePayload<DoubleSampleValue>>();
retVal.setPayload(new SampleValuePayload<DoubleSampleValue>(descriptor, values));
return retVal;
}
public static DocumentMessage<SampleValuePayload<DoubleSampleValue>> createDoubleSampleValueMessage(List<DoubleSampleValue> values)
{
return createDoubleSampleValueMessage(null, values);
}
public static DocumentMessage<SampleValuePayload<ComplexValue>> createComplexValueMessage(
MappingPayloadDescriptor<Integer, String> descriptor, List<ComplexValue> values)
{
DocumentMessage<SampleValuePayload<ComplexValue>> retVal = new DocumentMessage<SampleValuePayload<ComplexValue>>();
retVal.setPayload(new SampleValuePayload<ComplexValue>(descriptor, values));
return retVal;
}
public static DocumentMessage<SampleValuePayload<SpectrumValue>> createSpectrumValueMessage(
MappingPayloadDescriptor<Integer, String> descriptor, List<SpectrumValue> values)
{
DocumentMessage<SampleValuePayload<SpectrumValue>> retVal = new DocumentMessage<SampleValuePayload<SpectrumValue>>();
retVal.setPayload(new SampleValuePayload<SpectrumValue>(descriptor, values));
return retVal;
}
}
|
monogenics/pdfviewers
|
my-pdf-app/public/WebViewer/samples/advanced/redaction/redaction-viewer.js
|
<gh_stars>0
// @link WebViewerInstance: https://www.pdftron.com/api/web/WebViewerInstance.html
// @link WebViewerInstance.loadDocument: https://www.pdftron.com/api/web/WebViewerInstance.html#loadDocument__anchor
// @link WebViewerInstance.disableTools: https://www.pdftron.com/api/web/WebViewerInstance.html#disableTools__anchor
// @link WebViewerInstance.enableTools: https://www.pdftron.com/api/web/WebViewerInstance.html#enableTools__anchor
// @link WebViewerInstance.setToolMode: https://www.pdftron.com/api/web/WebViewerInstance.html#setToolMode__anchor
WebViewer(
{
path: '../../../lib',
initialDoc: 'https://s3.amazonaws.com/pdftron/downloads/pl/legal-contract.pdf',
fullAPI: true,
enableRedaction: true,
},
document.getElementById('viewer')
).then(instance => {
samplesSetup(instance);
document.getElementById('select').onchange = e => {
instance.loadDocument(e.target.value);
};
document.getElementById('file-picker').onchange = e => {
const file = e.target.files[0];
if (file) {
instance.loadDocument(file);
}
};
document.getElementById('url-form').onsubmit = e => {
e.preventDefault();
instance.loadDocument(document.getElementById('url').value);
};
instance.disableTools();
instance.enableTools(['AnnotationCreateRedaction']);
instance.setToolMode('AnnotationCreateRedaction');
});
|
kvsurii/capstone
|
src/js/pages/Tribunal.js
|
import React from "react";
import { IndexLink, Link } from "react-router";
export default class Tribunal extends React.Component {
render() {
return (
<section class="tribunal">
<div class="container">
<h2><strong>About Us</strong></h2>
<br/>
<h4 class="tribunal-heading">Who are we?</h4>
<div class="row">
<div class="col-md-12">
<p><strong>The Act</strong></p>
<p>
The Consumer Protection Act, 1986 (In short,‘The Act’) is a social legislation that lays down the promotion and protection of consumer rights applicable to all goods and services. It provides for the establishment of consumer councils for settlement of consumer disputes. The territorial jurisdiction or legal power of the act extends to the whole of India except Jammu & Kashmir. If the cause of action arises outside of India, the matter cannot be tried in India under this Act.
</p>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12">
<p><strong>The Tribunal</strong></p>
<p>
Under the context of the Act, the National Consumer Disputes Redressal Commission (NCDRC) was constituted in the year 1988. The President of NCDRC is a sitting or retired Judge of the Supreme Court of India who is appointed in consultation with the Chief Justice of India. The Chairman of NCDRC is Minister of Consumer Affairs in the Cabinet. The central tribunal office is head quartered at the capital city of New Delhi, India.
</p>
</div>
</div>
<br/>
<div class="cta-div">
<p class="cta-further-options"><strong>Further options</strong></p>
<img src="../../media/images/cta-arrow.png" class="cta-arrow"/>
<Link to="help" class="cta-button">
Refer Legal Dictionary
</Link>
</div>
<br/>
<h4 class="tribunal-heading">What we do?</h4>
<div class="row">
<div class="col-md-12">
<p><strong>The Purpose</strong></p>
<p>
The NCDRC and its affiliated bodies are dedicated towards bolstering, safeguarding and strengthening consumer rights such as -
<ul>
<li>right to be protected against the marketing of goods and services which are hazardous to life and property;</li>
<li>right to be informed about the quality, quantity, potency, purity, standard and price of goods or services and unfair trade practices;</li>
<li>right to be assured, access to a variety of goods and services at competitive prices;</li>
<li>right to be heard and to be assured that consumer's interests will receive due consideration at appropriate forums;</li>
<li>right to seek redressal against unfair trade practices or restrictive trade practices or unscrupulous exploitation of consumers; and</li>
<li>right to consumer education.</li>
</ul>
</p>
</div>
</div>
<br/>
<div class="alert alert-dismissible alert-warning">
<p><strong>Power of the National Commission to make regulations -</strong></p>
<ul class="tribunal-bullets">
<li>The National Commission may, with approval of the Central Government, by notification, make regulations not inconsistent with this Act to provide for all matters for which provision is necessary or expedient for the purpose of giving effect to the provisions of this Act.</li>
<li>In particular and without prejudice to the generality of the foregoing power, such regulations may make provisions for the cost of adjournment of any proceeding before the District Forum, the State Commission or the National Commission, as the case may be, which a party may be ordered to pay.</li>
</ul>
</div>
<br/>
<h4 class="tribunal-heading">Tribunal Jurisdiction</h4>
<div class="row">
<div class="col-md-12">
<p><strong>Heirarchy</strong></p>
<p>
The Act provides for the establishment of a three-tier structure for simple, speedy and effective consumer disputes redressal. All three agencies are quasi-judicial. The hierarchy from bottom to top is:
</p>
<ul class="tribunal-jurisdiction-list">
<li class="row">
<div class="col-md-1">
<img src="../../media/images/district.png" class="tribunal-jurisdiction-img"/>
</div>
<div class="col-md-9 tribunal-jurisdiction-details">
<p><strong>District Forums</strong></p>
<p>
These are the lowest Consumer Courts in the chain. The Act mandates that a State must constitute at least one District Forum in each and every district of the country. Consequently, this forum can entertain all complaints coming from that particular district. A district forum can admit matters for claims upto ₹ 20 lakh.
</p>
</div>
</li>
<li class="row">
<div class="col-md-1">
<img src="../../media/images/state.png" class="tribunal-jurisdiction-img"/>
</div>
<div class="col-md-9 tribunal-jurisdiction-details">
<p><strong>State Commissions</strong></p>
<p>
These are established at the State level and stand above District Forum in the hierarchy. State Commissions are empowered to deal with matters where the value of claim exceeds ₹ 20 lakh, but does not go beyond ₹ 1 crore.
</p>
</div>
</li>
<li class="row">
<div class="col-md-1">
<img src="../../media/images/national.png" class="tribunal-jurisdiction-img"/>
</div>
<div class="col-md-9 tribunal-jurisdiction-details">
<p><strong>National Commission</strong></p>
<p>
It stands at the top of the hierarchy of all the three redressal agencies and is considered as an apex court because it oversees the functioning of State Commissions and District Forums. The National Commission can entertain all the matters where the value of service or goods exceed ₹ 1 crore.
</p>
</div>
</li>
</ul>
</div>
</div>
<br/>
<div class="cta-div">
<p class="cta-further-options"><strong>Further options</strong></p>
<img src="../../media/images/cta-arrow.png" class="cta-arrow"/>
<Link to="dead" class="cta-button">
Circuit Benches
</Link>
<Link to="dead" class="cta-button">
Organization Chart
</Link>
<Link to="dead" class="cta-button">
Members of NCDRC
</Link>
</div>
</div>
</section>
);
}
}
|
ClaudiaVisentin/eeros-framework
|
examples/system/MockRobotSequencer.hpp
|
#ifndef MOCK_ROBOT_SEQUENCER_HPP_
#define MOCK_ROBOT_SEQUENCER_HPP_
#include <eeros/sequencer/Sequencer.hpp>
#include <eeros/sequencer/Sequence.hpp>
#include <eeros/sequencer/Step.hpp>
#include <eeros/sequencer/Wait.hpp>
#include "MockRobotControlSystem.hpp"
#include "MockRobotSafetyProperties.hpp"
using namespace eeros;
using namespace eeros::sequencer;
using namespace eeros::safety;
using namespace eeros::logger;
class MoveUp : public Step {
public:
MoveUp(std::string name, Sequence* caller, MockRobotControlSystem& cs) : Step(name, caller), cs(cs) { }
int action() {
Matrix<2,1,double> dest{8.2, 27.0};
cs.pp.move(dest);
return 0;
}
bool checkExitCondition() {return cs.pp.endReached();}
MockRobotControlSystem& cs;
};
class MoveDown : public Step {
public:
MoveDown(std::string name, Sequence* caller, MockRobotControlSystem& cs) : Step(name, caller), cs(cs) { }
int action() {
Matrix<2,1,double> dest{-5, 3};
cs.pp.move(dest);
return 0;
}
bool checkExitCondition() {return cs.pp.endReached();}
MockRobotControlSystem& cs;
};
class UpAndDownSequence : public Sequence {
public:
UpAndDownSequence(std::string name, Sequence* caller, MockRobotControlSystem& cs)
: Sequence(name, caller, true),
moveUp("move up", this, cs),
moveDown("move down", this, cs) { }
int action() {
while (Sequencer::running) {
moveUp();
moveDown();
}
return 0;
}
MoveUp moveUp;
MoveDown moveDown;
};
class HomingSequence : public Sequence {
public:
HomingSequence(std::string name, Sequence* caller, MockRobotControlSystem& cs, SafetySystem& ss, MockRobotSafetyProperties& sp)
: Sequence(name, caller, true), cs(cs), ss(ss), sp(sp) { }
int action() {
cs.setpoint.setValue({0.1, 0.1});
return 0;
}
bool checkExitCondition() {
Matrix<2,1,double> val = cs.i.getOut().getSignal().getValue();
bool done = val[0] >= 1.0 && val[1] >= 1.0;
if (val[0] >= 1.0) cs.setpoint.setValue({0, cs.setpoint.getValue()[1]});
if (val[1] >= 1.0) cs.setpoint.setValue({cs.setpoint.getValue()[0], 0});
if (done) ss.triggerEvent(sp.homingDone);
return done;
}
MockRobotControlSystem& cs;
SafetySystem& ss;
MockRobotSafetyProperties& sp;
};
class MainSequence : public Sequence {
public:
MainSequence(std::string name, Sequencer& seq, MockRobotControlSystem& cs, SafetySystem& ss, MockRobotSafetyProperties& sp)
: Sequence(name, seq), cs(cs), ss(ss), sp(sp),
homing("Homing Sequence", this, cs, ss, sp),
upDown("UpDown Sequence", this, cs),
wait("wait", this) { }
int action() {
while(Sequencer::running) {
if (ss.getCurrentLevel() == sp.slHoming) {
homing();
} else if(ss.getCurrentLevel() == sp.slReady) {
wait(2);
cs.sw.switchToInput(1);
ss.triggerEvent(sp.startMoving);
} else if(ss.getCurrentLevel() == sp.slMoving) {
upDown();
}
wait(0.1);
}
return 0;
}
MockRobotControlSystem& cs;
SafetySystem& ss;
MockRobotSafetyProperties& sp;
HomingSequence homing;
UpAndDownSequence upDown;
Wait wait;
};
#endif // MOCK_ROBOT_SEQUENCER_HPP_
|
abreuboom/yap
|
node_modules/gatsby/dist/utils/worker/pool.js
|
"use strict";
const Worker = require(`jest-worker`).default;
const {
cpuCoreCount
} = require(`gatsby-core-utils`);
const create = () => new Worker(require.resolve(`./child`), {
numWorkers: cpuCoreCount(),
forkOptions: {
silent: false
}
});
module.exports = {
create
};
//# sourceMappingURL=pool.js.map
|
fstudio/Phoenix
|
lib/AutoCompletion/PhoenixAutoComplete.cpp
|
/*********************************************************************************************************
* PhoenixAutoComplete.cpp
* Note: AutoCompletion.
* @2014.08
* E-mail:<<EMAIL>>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#include <Phoenix.h>
#include <clang-c/CXCompilationDatabase.h>
#include <clang-c/Index.h>
#include <clang-c/Documentation.h>
#include "PhoenixAutoComplete.h"
/************************************************************************************************************
* Libclang tools add, if build x64 platform must build libclang.dll<x64>
*
*************************************************************************************************************/
PhoenixAutoComplete::PhoenixAutoComplete()
{
//
}
|
trespasserw/MPS
|
plugins/mps-kotlin/languages/kotlin/source_gen/jetbrains/mps/kotlin/constraints/CompanionObject_Constraints.java
|
<gh_stars>0
package jetbrains.mps.kotlin.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import jetbrains.mps.smodel.runtime.ConstraintFunction;
import jetbrains.mps.smodel.runtime.ConstraintContext_CanBeChild;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.smodel.runtime.CheckingNodeContext;
import jetbrains.mps.smodel.runtime.base.BasePropertyConstraintsDescriptor;
import jetbrains.mps.smodel.runtime.ConstraintsDescriptor;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.smodel.SNodePointer;
import java.util.Map;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.smodel.runtime.PropertyConstraintsDescriptor;
import java.util.HashMap;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class CompanionObject_Constraints extends BaseConstraintsDescriptor {
public CompanionObject_Constraints() {
super(CONCEPTS.CompanionObject$TE);
}
@Override
protected ConstraintFunction<ConstraintContext_CanBeChild, Boolean> calculateCanBeChildConstraint() {
return new ConstraintFunction<ConstraintContext_CanBeChild, Boolean>() {
@NotNull
public Boolean invoke(@NotNull ConstraintContext_CanBeChild context, @Nullable CheckingNodeContext checkingNodeContext) {
boolean result = staticCanBeAChild(context.getNode(), context.getParentNode(), context.getConcept(), context.getLink());
if (!(result) && checkingNodeContext != null) {
checkingNodeContext.setBreakingNode(canBeChildBreakingPoint);
}
return result;
}
};
}
public static class CustomName_Property extends BasePropertyConstraintsDescriptor {
public CustomName_Property(ConstraintsDescriptor container) {
super(PROPS.customName$sUyF, container, false, false, true);
}
@Override
public boolean validateValue(SNode node, Object propertyValue, CheckingNodeContext checkingNodeContext) {
boolean result = staticValidateProperty(node, SPropertyOperations.castString(propertyValue));
if (!(result) && checkingNodeContext != null) {
checkingNodeContext.setBreakingNode(new SNodePointer("r:133e8cac-c6ad-447f-a90c-5146ca3b1aed(jetbrains.mps.kotlin.constraints)", "2324909103767447709"));
}
return result;
}
private static boolean staticValidateProperty(SNode node, String propertyValue) {
return (propertyValue == null || propertyValue.length() == 0) || Identifiers.isValidNonKeyword(propertyValue);
}
}
public static class Name_Property extends BasePropertyConstraintsDescriptor {
public Name_Property(ConstraintsDescriptor container) {
super(PROPS.name$MnvL, container, true, false, false);
}
@Override
public Object getValue(SNode node) {
if (isNotEmptyString(SPropertyOperations.getString(node, PROPS.customName$sUyF))) {
return SPropertyOperations.getString(node, PROPS.customName$sUyF);
} else {
return "Companion";
}
}
private static boolean isNotEmptyString(String str) {
return str != null && str.length() > 0;
}
}
@Override
protected Map<SProperty, PropertyConstraintsDescriptor> getSpecifiedProperties() {
Map<SProperty, PropertyConstraintsDescriptor> properties = new HashMap<SProperty, PropertyConstraintsDescriptor>();
properties.put(PROPS.customName$sUyF, new CustomName_Property(this));
properties.put(PROPS.name$MnvL, new Name_Property(this));
return properties;
}
private static boolean staticCanBeAChild(SNode node, SNode parentNode, SAbstractConcept childConcept, SContainmentLink link) {
return !(SNodeOperations.isInstanceOf(parentNode, CONCEPTS.CompanionObject$TE));
}
private static final SNodePointer canBeChildBreakingPoint = new SNodePointer("r:133e8cac-c6ad-447f-a90c-5146ca3b1aed(jetbrains.mps.kotlin.constraints)", "2324909103759187732");
private static final class CONCEPTS {
/*package*/ static final SConcept CompanionObject$TE = MetaAdapterFactory.getConcept(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x28bef6d7551af57dL, "jetbrains.mps.kotlin.structure.CompanionObject");
}
private static final class PROPS {
/*package*/ static final SProperty customName$sUyF = MetaAdapterFactory.getProperty(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x28bef6d7551af57dL, 0x2043bc831118d92cL, "customName");
/*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
}
}
|
Duffney/azure-sdk-for-go
|
sdk/messaging/azservicebus/internal/rpc_test.go
|
<gh_stars>0
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package internal
import (
"context"
"net"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/amqpwrap"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/test"
"github.com/Azure/go-amqp"
"github.com/stretchr/testify/require"
)
// TestRPCLinkNonErrorRequiresRecovery shows that an error, if it requires recovery,
// will cause the RPCLink to properly broadcast the failure so the caller can initiate
// a link recreation/connection recovery (or potentially just fail out)
func TestRPCLinkNonErrorRequiresRecovery(t *testing.T) {
tester := &rpcTester{t: t, ResponsesCh: make(chan *rpcTestResp, 1000)}
link, err := NewRPCLink(RPCLinkArgs{
Client: &rpcTesterClient{
session: tester,
},
Address: "some-address",
LogEvent: "rpctesting",
})
require.NoError(t, err)
require.NotNil(t, link)
defer func() { require.NoError(t, link.Close(context.Background())) }()
messagesCh := make(chan string, 10000)
endCapture := test.CaptureLogsForTestWithChannel(messagesCh)
defer endCapture()
responses := []*rpcTestResp{
// this error requires recovery (in this case, connection but there's no
// distinction between types in RPCLink)
{E: &net.DNSError{}},
}
resp, err := link.RPC(context.Background(), &amqp.Message{
ApplicationProperties: map[string]interface{}{
rpcTesterProperty: responses,
},
})
require.Nil(t, resp)
// (give the response router a teeny bit to shut down)
time.Sleep(500 * time.Millisecond)
var netOpError net.Error
require.ErrorAs(t, err, &netOpError)
LogLoop:
for {
select {
case msg := <-messagesCh:
if msg == "[rpctesting] "+responseRouterShutdownMessage {
break LogLoop
}
default:
require.Fail(t, "RPC router never shut down")
}
}
}
func TestRPCLinkNonErrorRequiresNoRecovery(t *testing.T) {
tester := &rpcTester{t: t, ResponsesCh: make(chan *rpcTestResp, 1000), Accepted: make(chan *amqp.Message, 1)}
link, err := NewRPCLink(RPCLinkArgs{
Client: &rpcTesterClient{
session: tester,
},
Address: "some-address",
LogEvent: "rpctesting",
})
require.NoError(t, err)
require.NotNil(t, link)
defer func() { require.NoError(t, link.Close(context.Background())) }()
cleanupLogs := test.CaptureLogsForTest()
defer cleanupLogs()
responses := []*rpcTestResp{
// server busy is a "retry, no reconnect needed" type of error. The response router
// will just immediately go back to receiving.
{E: exampleServerBusyError},
// uncorrelated message, will generate a warning but we'll continue on
{M: exampleUncorrelatedMessage},
// this is an actual response and it correlates to the message we sent. We'll get this
// response back.
{M: exampleMessageWithStatusCode(200)},
}
resp, err := link.RPC(context.Background(), &amqp.Message{
ApplicationProperties: map[string]interface{}{
rpcTesterProperty: responses,
},
Properties: &amqp.MessageProperties{
MessageID: "hello",
},
})
require.NoError(t, err)
require.Equal(t, 200, resp.Code)
require.Equal(t, "response from service", resp.Message.Value)
acceptedMessage := <-tester.Accepted
require.Equal(t, "response from service", acceptedMessage.Value, "successfully received message is accepted")
logMessages := cleanupLogs()
require.Contains(t, logMessages, "[rpctesting] RPCLink had no response channel for correlation ID you've-never-seen-this", "exampleUncorrelatedMessage causes warning for uncorrelated message")
require.Contains(t, logMessages, "[rpctesting] Non-fatal error in RPCLink, starting to receive again: *Error{Condition: com.microsoft:server-busy, Description: , Info: map[]}")
}
func TestRPCLinkNonErrorLockLostDoesNotBreakAnything(t *testing.T) {
tester := &rpcTester{t: t, ResponsesCh: make(chan *rpcTestResp, 1000), Accepted: make(chan *amqp.Message, 1)}
link, err := NewRPCLink(RPCLinkArgs{
Client: &rpcTesterClient{
session: tester,
},
Address: "some-address",
LogEvent: "rpctesting",
})
require.NoError(t, err)
require.NotNil(t, link)
resp, err := link.RPC(context.Background(), &amqp.Message{
ApplicationProperties: map[string]interface{}{
rpcTesterProperty: []*rpcTestResp{
{M: exampleMessageWithStatusCode(400)},
},
},
})
// the 400 automatically gets translated into an RPC error. The response router should still be running.
require.Nil(t, resp)
var rpcErr rpcError
require.ErrorAs(t, err, &rpcErr)
require.Equal(t, 400, rpcErr.RPCCode())
acceptedMessage := <-tester.Accepted
require.Equal(t, "response from service", acceptedMessage.Value, "successfully received message is accepted")
// validate that a normal error doesn't cause the response router to shut down
resp, err = link.RPC(context.Background(), &amqp.Message{
ApplicationProperties: map[string]interface{}{
rpcTesterProperty: []*rpcTestResp{
{M: exampleMessageWithStatusCode(200)},
},
},
})
require.NoError(t, err)
require.Equal(t, "response from service", resp.Message.Value)
acceptedMessage = <-tester.Accepted
require.Equal(t, "response from service", acceptedMessage.Value, "successfully received message is accepted")
}
// rpcTester has all the functions needed (for our RPC tests) to be:
// - an AMQPSession
// - an AMQPReceiverCloser
// - an AMQPSenderCloser
// This just makes it simpler since there's this request/response pattern that the tests need. Rather than
// spread it out we can do all the communicating here.
type rpcTester struct {
amqpwrap.AMQPSenderCloser
amqpwrap.AMQPReceiverCloser
// Accepted contains all the messages where we called AcceptMessage(msg)
// We only call this when we
Accepted chan *amqp.Message
ResponsesCh chan *rpcTestResp
t *testing.T
}
type rpcTestResp struct {
M *amqp.Message
E error
}
type rpcTesterClient struct {
session amqpwrap.AMQPSession
}
func (c *rpcTesterClient) NewSession(opts ...amqp.SessionOption) (amqpwrap.AMQPSession, error) {
return c.session, nil
}
func (c *rpcTesterClient) Close() error { return nil }
func (tester *rpcTester) NewReceiver(opts ...amqp.LinkOption) (AMQPReceiverCloser, error) {
return tester, nil
}
func (tester *rpcTester) NewSender(opts ...amqp.LinkOption) (AMQPSenderCloser, error) {
return tester, nil
}
func (tester *rpcTester) Close(ctx context.Context) error {
return nil
}
// receiver functions
func (tester *rpcTester) AcceptMessage(ctx context.Context, msg *amqp.Message) error {
require.NotNil(tester.t, tester.Accepted, "No messages should be AcceptMessage()'d since the tester.Accepted channel was nil")
tester.Accepted <- msg
return nil
}
func (tester *rpcTester) Receive(ctx context.Context) (*amqp.Message, error) {
resp := <-tester.ResponsesCh
return resp.M, resp.E
}
// sender functions
func (tester *rpcTester) Send(ctx context.Context, msg *amqp.Message) error {
require.NotEmpty(tester.t, msg.Properties.MessageID)
// we'll let the payload dictate the response
if msg.ApplicationProperties["test-send-error"] != nil {
sendErr := msg.ApplicationProperties["test-send-error"].(error)
delete(msg.ApplicationProperties, "test-send-error")
if sendErr != nil {
return sendErr
}
}
// okay, we're simulating a Send() that works. Let's enqueue the appropriate
// test response.
resps := msg.ApplicationProperties[rpcTesterProperty].([]*rpcTestResp)
for _, resp := range resps {
if resp.M != nil && resp.M.Properties.CorrelationID == nil {
// auto-associate it since it's intended to be the response for this message
resp.M.Properties.CorrelationID = msg.Properties.MessageID
}
tester.ResponsesCh <- resp
}
return nil
}
// rpcTesterProperty is the property we can shove some messages under that will get
// routed through our rpcTester. It's 100% a test only thing.
const rpcTesterProperty = "test-resps"
var exampleServerBusyError error = &amqp.Error{Condition: amqp.ErrorCondition("com.microsoft:server-busy")}
var exampleUncorrelatedMessage = &amqp.Message{
Value: "response from service",
Properties: &amqp.MessageProperties{
// this message doesn't actually correlate to a message that was sent
// it just gets logged and ignored
CorrelationID: "you've-never-seen-this",
},
}
func exampleMessageWithStatusCode(statusCode int32) *amqp.Message {
return &amqp.Message{
Value: "response from service",
Properties: &amqp.MessageProperties{
// will get auto-filled in by the test
CorrelationID: nil,
},
ApplicationProperties: map[string]interface{}{
statusCodeKey: statusCode,
},
}
}
|
thp/wipeout-pulse-shipedit
|
src/psp-save/psp-save.c
|
<reponame>thp/wipeout-pulse-shipedit
/* Copyright (c) 2018 38_ViTa_38
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2.0 or later versions.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License 2.0 for more details.
*
* A copy of the GPL 2.0 should have been included with the program.
* If not, see http://www.gnu.org/licenses/
*
* Description: a tool for encryption and decryption of PSP saves.
*/
/* decrypt_data() and encrypt_data() are from
* https://github.com/hrydgard/ppsspp/tree/master/Tools/SaveTool, so here's the
* copyright:
*
* PSP Software Development Kit - http://www.pspdev.org
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE in PSPSDK root for details.
*
* Copyright (c) 2005 <NAME> <<EMAIL>>
* Coypright (c) 2005 psp123
*/
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "chnnlsv.h"
#include "hash.h"
#include "kirk_engine.h"
#include "psp-save.h"
#define SFO_LEN 0x1330
static int align16(unsigned int v)
{
return ((v + 0xF) >> 4) << 4;
}
FILE *try_open(const char *path, const char *mode)
{
FILE *fp;
if (!(fp = fopen(path, mode)))
die("Can't open %s: %s\n", path, strerror(errno));
return fp;
}
int filesize(FILE *fp) /* intentionally not size_t or long */
{
int size;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
if (size <= 0)
die("Bad file size %ld\n", size);
rewind(fp);
return size;
}
void die(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(EXIT_FAILURE);
}
void decrypt_file(FILE *in, FILE *out, unsigned char *key, unsigned int mode)
{
unsigned char *data;
int len = filesize(in), aligned_len, tmp;
aligned_len = align16(len);
if (!(data = malloc(aligned_len)))
die("Cannot allocate %d bytes\n", aligned_len);
memset(data + len, 0, aligned_len - len);
if ((tmp = fread(data, 1, len, in)) != len) {
free(data);
die("decrypt_file: read %d bytes, %d expected\n", tmp, len);
}
decrypt_data(mode, data, &len, &aligned_len, key);
if ((tmp = fwrite(data, 1, len, out)) != len) {
free(data);
die("decrypt_file: wrote %d bytes, %d expected\n", tmp, len);
}
free(data);
}
/* Do the actual hardware decryption.
mode is 3 for saves with a cryptkey, or 1 otherwise
data, dataLen, and cryptkey must be multiples of 0x10.
cryptkey is NULL if mode == 1.
*/
int decrypt_data(unsigned int mode, unsigned char *data, int *data_len,
int *aligned_len, unsigned char *key)
{
pspChnnlsvContext1 ctx1;
pspChnnlsvContext2 ctx2;
/* Need a 16-byte IV plus some data */
if (*aligned_len <= 0x10)
return -1;
*data_len -= 0x10;
*aligned_len -= 0x10;
/* Set up buffers */
memset(&ctx1, 0, sizeof(ctx1));
memset(&ctx2, 0, sizeof(ctx2));
/* Perform the magic */
if (sceSdSetIndex_(&ctx1, mode) < 0)
return -2;
if (sceSdCreateList_(&ctx2, mode, 2, data, key) < 0)
return -3;
if (sceSdRemoveValue_(&ctx1, data, 0x10) < 0)
return -4;
if (sceSdRemoveValue_(&ctx1, data + 0x10, *aligned_len) < 0)
return -5;
if (sceSdSetMember_(&ctx2, data + 0x10, *aligned_len) < 0)
return -6;
/* Verify that it decrypted correctly */
if (sceChnnlsv_21BE78B4_(&ctx2) < 0)
return -7;
/* The decrypted data starts at data + 0x10, so shift it back. */
memmove(data, data + 0x10, *data_len);
return 0;
}
void encrypt_file(FILE *in, FILE *out, const char *name, FILE *sfo_in,
FILE *sfo_out, unsigned char *key, unsigned int mode)
{
unsigned char *data, *hash, sfo[SFO_LEN];
int len = filesize(in), aligned_len, tmp;
aligned_len = align16(len);
if ((tmp = filesize(sfo_in)) != SFO_LEN)
die("PARAM.SFO is not %d bytes long\n", SFO_LEN);
if (!(data = malloc(aligned_len + 16)))
die("Cannot allocate %d bytes\n", aligned_len + 16);
if (!(hash = malloc(16)))
die("Cannot allocate 16 bytes, what a shame\n");
memset(data + len, 0, aligned_len - len);
if ((tmp = fread(data, 1, len, in)) != len) {
free(data);
free(hash);
die("encrypt_file: read %d bytes, %d expected\n", tmp, len);
}
if ((tmp = fread(sfo, 1, SFO_LEN, sfo_in)) != SFO_LEN) {
free(data);
free(hash);
die("encrypt_file: read %d bytes, %d expected\n", tmp, SFO_LEN);
}
if ((tmp = encrypt_data(mode, data, &len, &aligned_len, hash, key))) {
free(data);
free(hash);
die("encrypt_data failed (%d)\n", tmp);
}
if ((tmp = fwrite(data, 1, len, out)) != len) {
free(data);
free(hash);
die("encrypt_file: wrote %d bytes, %d expected\n", tmp, len);
}
free(data);
if ((tmp = update_hashes(sfo, SFO_LEN, name, hash, key ? 3 : 1))) {
/*free(hash);*/
printf("update_hashes returned %d\n", tmp);
}
if ((tmp = fwrite(sfo, 1, SFO_LEN, sfo_out)) != SFO_LEN) {
free(hash);
die("encrypt_file: wrote %d bytes, %d expected\n", tmp, SFO_LEN);
}
free(hash);
}
/* Do the actual hardware encryption.
mode is 3 for saves with a cryptkey, or 1 otherwise
data, dataLen, and cryptkey must be multiples of 0x10.
cryptkey is NULL if mode == 1.
*/
int encrypt_data(unsigned int mode, unsigned char *data, int *dataLen,
int *alignedLen, unsigned char *hash, unsigned char *cryptkey)
{
pspChnnlsvContext1 ctx1;
pspChnnlsvContext2 ctx2;
/* Make room for the IV in front of the data. */
memmove(data + 0x10, data, *alignedLen);
/* Set up buffers */
memset(&ctx1, 0, sizeof(ctx1));
memset(&ctx2, 0, sizeof(ctx2));
memset(hash, 0, 0x10);
memset(data, 0, 0x10);
/* Build the 0x10-byte IV and setup encryption */
if (sceSdCreateList_(&ctx2, mode, 1, data, cryptkey) < 0)
return -1;
if (sceSdSetIndex_(&ctx1, mode) < 0)
return -2;
if (sceSdRemoveValue_(&ctx1, data, 0x10) < 0)
return -3;
if (sceSdSetMember_(&ctx2, data + 0x10, *alignedLen) < 0)
return -4;
/* Clear any extra bytes left from the previous steps */
memset(data + 0x10 + *dataLen, 0, *alignedLen - *dataLen);
/* Encrypt the data */
if (sceSdRemoveValue_(&ctx1, data + 0x10, *alignedLen) < 0)
return -5;
/* Verify encryption */
if (sceChnnlsv_21BE78B4_(&ctx2) < 0)
return -6;
/* Build the file hash from this PSP */
if (sceSdGetLastIndex_(&ctx1, hash, cryptkey) < 0)
return -7;
/* Adjust sizes to account for IV */
*alignedLen += 0x10;
*dataLen += 0x10;
/* All done */
return 0;
}
|
Josephu/go
|
iso_host/iso8583_reversal_req_handler.go
|
<gh_stars>0
package iso_host
import "go/iso8583"
func handleReversalReq(isoResp *iso8583.Iso8583Message) {
msgTypeField := isoResp.GetFieldByName("Message Type")
msgTypeField.SetData(iso8583.IsoMsg1430)
}
|
IAries/VEDO
|
src/aries/utility/MatrixFs.h
|
#ifndef _ARIES_MATRIX_FORTRAN_STYLE_H
#define _ARIES_MATRIX_FORTRAN_STYLE_H
#include <aries/utility/DataType.h>
#include <aries/utility/XSolver.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <iomanip>
namespace aries
{
class MatrixFs
{
public:
MatrixFs(const _uint_t& rows, const _uint_t& columns);
MatrixFs(const _uint_t& rows, const _uint_t& columns, const _float_t& value);
MatrixFs(const _uint_t& rows, const _uint_t& columns, const _float_t* tpvalue);
MatrixFs(const MatrixFs& m);
const MatrixFs& operator = (const MatrixFs& m);
~MatrixFs();
void resize(const _uint_t& rows, const _uint_t& columns, const _float_t& value);
void Resize(const _uint_t& rows, const _uint_t& columns, const _float_t& value);
void resize(const _uint_t& rows, const _uint_t& columns);
void Resize(const _uint_t& rows, const _uint_t& columns);
inline _uint_t rows() const
{
return _rows;
}
inline _uint_t columns() const
{
return _columns;
}
inline const _float_t* Reference() const
{
return _matval;
}
const MatrixFs& operator = (const _float_t& value);
MatrixFs operator + (const MatrixFs& m) const;
MatrixFs operator + (const _float_t& value) const;
const MatrixFs& operator += (const _float_t& value);
MatrixFs operator - (const MatrixFs& m) const;
MatrixFs operator - (const _float_t& value) const;
const MatrixFs& operator -= (const _float_t& value);
MatrixFs operator * (const MatrixFs& M) const;
MatrixFs operator * (const _float_t& value) const;
const MatrixFs& operator *= (const _float_t& value);
MatrixFs operator / (const _float_t& value) const;
const MatrixFs& operator /= (const _float_t& value);
const std::string characteristic() const;
MatrixFs transpose() const;
MatrixFs Transpose() const;
_float_t determine() const;
_uint_t rank() const;
MatrixFs adjoint() const;
MatrixFs Adjoint() const;
MatrixFs SubMatrix(const _uint_t& row, const _uint_t& column) const;
MatrixFs inverse() const;
MatrixFs Inverse() const;
_float_t& operator () (const _uint_t& r, const _uint_t& c);
_float_t get(const _uint_t& r, const _uint_t& c) const;
inline const XSolver* GetXSolver() const
{
return _XSolver;
}
inline void SetXSolver(const XSolver* xs)
{
_XSolver = xs;
}
// {Y} = [A] {X}, give [A] & {Y}, solve {X}
MatrixFs SolveX(const MatrixFs& mY) const;
protected:
_uint_t _rows;
_uint_t _columns;
_float_t** _matrix;
_float_t* _matval;
MatrixFs();
const XSolver* _XSolver;
void print() const;
};
} // namespace aries
aries::MatrixFs operator - (const aries::MatrixFs& m);
aries::MatrixFs operator * (const aries::_float_t& s, const aries::MatrixFs& m);
std::ostream& operator << (std::ostream& os, const aries::MatrixFs& m);
#endif // _ARIES_MATRIX_FORTRAN_STYLE_H
|
AuDigitalHealth/clinical-document-library-java
|
src/main/java/au/gov/nehta/sample/diagnosticImage/SampleDiagnosticImageCreation_3A.java
|
package diagnosticImage;
import au.gov.nehta.builder.diagnostic.image.DiagnosticImageReportCreator;
import au.gov.nehta.builder.util.UUIDTool;
import au.gov.nehta.model.cda.common.address.PostalAddress;
import au.gov.nehta.model.cda.common.address.PostalAddressImpl;
import au.gov.nehta.model.cda.common.address.PostalAddressUseEnum;
import au.gov.nehta.model.cda.common.code.*;
import au.gov.nehta.model.cda.common.custodian.*;
import au.gov.nehta.model.cda.common.document.ClinicalDocument;
import au.gov.nehta.model.cda.common.document.ClinicalDocumentFactory;
import au.gov.nehta.model.cda.common.id.*;
import au.gov.nehta.model.cda.common.org.Organization;
import au.gov.nehta.model.cda.common.org.OrganizationImpl;
import au.gov.nehta.model.cda.common.org.OrganizationName;
import au.gov.nehta.model.cda.common.org.OrganizationNameImpl;
import au.gov.nehta.model.cda.common.person.Person;
import au.gov.nehta.model.cda.common.person.PersonImpl;
import au.gov.nehta.model.cda.common.telecom.Telecom;
import au.gov.nehta.model.cda.common.telecom.TelecomImpl;
import au.gov.nehta.model.cda.common.telecom.TelecomMedium;
import au.gov.nehta.model.cda.common.telecom.TelecomUse;
import au.gov.nehta.model.cda.common.time.*;
import au.gov.nehta.model.cda.diagnostic.DiagnosticImagingReportCdaModel;
import au.gov.nehta.model.clinical.common.*;
import au.gov.nehta.model.clinical.common.participation.*;
import au.gov.nehta.model.clinical.common.types.*;
import au.gov.nehta.model.clinical.diagnostic.imaging.*;
import au.gov.nehta.model.clinical.diagnostic.pathology.*;
import au.gov.nehta.model.clinical.etp.common.item.AttachedMedia;
import au.gov.nehta.model.clinical.etp.common.participation.EntitlementType;
import au.gov.nehta.model.clinical.etp.common.participation.*;
import org.w3c.dom.Document;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
/**
* This sample class shows usage of the Diagnostic Image CDA Document creator to produce a 3A level
* Diagnostic Image document.
*/
public class SampleDiagnosticImageCreation_3A {
public static void main(String[] args) throws Exception {
ZonedDateTime now = ZonedDateTime.now();
// Setup context
// ***************************
// ***** Subject Of Care *****
// ***************************
IHI subjectIHI = new IHI("8003600300001283");
String subjectFamilyName = "Harding";
ZonedDateTime dob = LocalDate.of(1982, 11, 28).atStartOfDay(ZoneId.systemDefault());
// Always use the unstructured address style (as opposed to individual unit/street/level number) if possible.
AustralianAddress patientAddress = new AustralianAddressImpl();
patientAddress.addUnstructuredAddressLine("10 browning st");
patientAddress.setCity("West End");
patientAddress.setState(AustralianStateTerritory.QUEENSLAND.getAbbreviation());
patientAddress.setPostcode("4101");
AddressContext subjectOfCareAddress = new AddressContextImpl(patientAddress,
AddressPurpose.RESIDENTIAL_PERMANENT);
PersonName subjectPersonName = new PersonNameImpl(subjectFamilyName);
subjectPersonName.addNameTitle(NameTitle.MISTER.getDescriptor());
subjectPersonName.addNameSuffix(NameSuffix.JUNIOR.getDescriptor());
subjectPersonName.addGivenName("Frank");
subjectPersonName.addPersonNameUsage(PersonNameUsage.MAIDEN_NAME_OR_NAME_AT_BIRTH);
DateAccuracy dobAccuracy = new DateAccuracyImpl(true, true, true);
DateOfBirthDetail subjectDOB = new DateOfBirthDetailImpl(dob, dobAccuracy);
subjectDOB.setDateOfBirthAccuracyIndicator(dobAccuracy);
subjectDOB.setDateOfBirthIsCalculatedFromAge(true);
ExtendedDemographicDataImpl demoData = new ExtendedDemographicDataImpl(Sex.MALE, subjectDOB);
demoData.setMothersOriginalFamilyName("O'Maiden");
DateAccuracy deathDateAccuracy = new DateAccuracyImpl(true, true, true);
ZonedDateTime deathDate = ZonedDateTime.of(1980, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
demoData.setDateOfDeath(new DateOfDeathImpl(deathDate, deathDateAccuracy,
SourceOfDeathNotificationCode.HEALTH_CARE_PROVIDER));
demoData.setBirthPlurality(5);
demoData.setBirthOrder(2);
int age = 31;
demoData.setAgeInYears(age);
demoData.setAgeAccurate(true);
demoData.setIndigenousStatus(IndigenousStatus.NOT_STATED_OR_INADEQUATELY_DESCRIBED);
demoData.setBirthPlace(new CountryStateImpl(CountryEnum.AUSTRALIA.getDescriptor(),
AustralianStateTerritory.NEW_SOUTH_WALES.getAbbreviation()));
SubjectOfCarePerson subjectOfCarePerson = new ExtendedSubjectOfCarePerson(subjectPersonName,
demoData);
MedicareCardIdentifier medicareCard = new MedicareCardIdentifier("4324567871");
SubjectOfCareParticipant subject = new SubjectOfCareParticipantImpl(
Arrays.asList(subjectIHI, medicareCard), subjectOfCareAddress, subjectOfCarePerson);
Telecom subjectTelephone = new TelecomImpl(TelecomMedium.TELEPHONE, "0712345678",
TelecomUse.PERSONAL);
Telecom subjectEmail = new TelecomImpl(TelecomMedium.EMAIL,
"<EMAIL>", TelecomUse.PERSONAL);
List<Telecom> subjectOfCareElectronicCommunicationDetailList = new ArrayList<>();
subjectOfCareElectronicCommunicationDetailList.add(subjectTelephone);
subjectOfCareElectronicCommunicationDetailList.add(subjectEmail);
subject.setElectronicCommunicationDetails(subjectOfCareElectronicCommunicationDetailList);
Entitlement subjectEntitlement = new EntitlementImpl(medicareCard,
EntitlementType.MEDICARE_BENEFITS);
subjectEntitlement.setEntitlementValidityDuration(RestrictedTimeInterval.getLowWidthInstance(
// From today (day only precision) for two weeks
new PrecisionDate(Precision.DAY, now), new TimeQuantity(2, TimeUnitOfMeasure.WEEK)));
List<Entitlement> subjectOfCareEntitlementList = new ArrayList<>();
subjectOfCareEntitlementList.add(subjectEntitlement);
subject.setEntitlements(subjectOfCareEntitlementList);
// ************************
// ***** Author *****
// ************************
HPII authorHPII = new HPII("8003610000001145");
PersonName authorPersonName = new PersonNameImpl("Patrick");
authorPersonName.addGivenName("Pathologist");
authorPersonName.addNameTitle(NameTitle.MISTER.getDescriptor());
Occupation authorOccupation = new OccupationImpl(
new ANZSCO_1ED_REV1("599915", "Clinical Coder"));
ProviderEmploymentDetail providerEmploymentDetail = new ProviderEmploymentDetailImpl(
authorOccupation);
ProviderPerson authorPerson = new ProviderPersonImpl(authorPersonName);
authorPerson.setEmploymentDetail(providerEmploymentDetail);
AustralianAddress fullAddress = new AustralianAddressImpl();
fullAddress.addUnstructuredAddressLine("Level 1, 10 Browning street");
fullAddress.setCity("West End");
fullAddress.setState(AustralianStateTerritory.QUEENSLAND.getAbbreviation());
fullAddress.setPostcode("4101");
ProviderAddress authorOrganisationAddress = new ProviderAddressImpl(false, fullAddress,
AddressPurpose.BUSINESS);
Telecom authorEmail = new TelecomImpl(TelecomMedium.EMAIL, "<EMAIL>",
TelecomUse.BUSINESS);
Telecom authorFax = new TelecomImpl(TelecomMedium.FAX, "0212345678", TelecomUse.BUSINESS);
Telecom authorTelephone = new TelecomImpl(TelecomMedium.TELEPHONE, "0212345678",
TelecomUse.BUSINESS);
AsEntityIdentifier nataLabID = new AsEntityIdentifierImpl();
nataLabID.setExtension("3715");
nataLabID.setAssigningAuthorityName("NATA");
nataLabID.setRoot("1.2.36.1.2001.1005.12");
CodeImpl nataLabCode = new CodeImpl();
nataLabCode.setDisplayName("Organization identifier");
nataLabCode.setCodeSystemName("Identifier Type (HL7)");
nataLabCode.setCodeSystem("2.16.840.1.113883.12.203");
nataLabCode.setCode("XX");
nataLabID.setCode(nataLabCode);
String hpioNumber = "8003621231167886";
EmploymentOrganisationImpl pathologyLabEmployment = new EmploymentOrganisationImpl(
Arrays.asList(new HPIO(hpioNumber), nataLabID),
"Pete's Pathologies");
pathologyLabEmployment.setOrganisationNameUsage(OrganisationNameUsage.BUSINESS_NAME);
pathologyLabEmployment.setEmploymentType(CodeImpl.fromOriginalText("Permanent/Full Time"));
pathologyLabEmployment.setDepartmentUnit("Front Office");
pathologyLabEmployment.setPositionInOrganisation(CodeImpl.fromOriginalText("Counter Staff"));
pathologyLabEmployment.setOccupation(new ANZSCO_1ED_REV1("253915", "Pathologist"));
List<Telecom> electronicCommunicationDetailList = Arrays
.asList(authorEmail, authorFax, authorTelephone);
PathologyParticipantImpl authorParticipant = new PathologyParticipantImpl(authorHPII,
authorPerson, pathologyLabEmployment, authorOrganisationAddress,
electronicCommunicationDetailList);
Entitlement entitlement = new EntitlementImpl(new MedicarePrescriberNumber("1234567A"),
EntitlementType.MEDICARE_PRESCRIBER_NUMBER);
entitlement.setEntitlementValidityDuration(RestrictedTimeInterval.getLowInstance(
// From today (day only precision)
new PrecisionDate(Precision.DAY, now)));
authorParticipant.addEntitlement(entitlement);
Entitlement entitlement2 = new EntitlementImpl(new MedicarePrescriberNumber("1234567B"),
EntitlementType.MEDICARE_PRESCRIBER_NUMBER);
entitlement2.setEntitlementValidityDuration(RestrictedTimeInterval.getLowInstance(
// From today (day only precision)
new PrecisionDate(Precision.DAY, now)));
authorParticipant.addEntitlement(entitlement2);
authorParticipant.setQualifications("M.B.B.S., F.R.A.C.S.");
DocumentParticipant author = new DocumentParticipantImpl(authorOccupation, authorParticipant);
// ************************
// ***** Requester *****
// ************************
AsEntityIdentifier RequesterIdentifier = new AsEntityIdentifierImpl("1.22.333.4444.55555",
"12345678");
// this should probably be omitted if it's not a
// MEDICARE_PRESCRIBER_NUMBER
// for instance, a PENSIONER_CONCESSION makes no sense here
Entitlement requesterEntitlement = new EntitlementImpl(RequesterIdentifier,
EntitlementType.MEDICARE_PRESCRIBER_NUMBER);
requesterEntitlement.setEntitlementValidityDuration(RestrictedTimeInterval.getLowInstance(
// From today (day only precision)
new PrecisionDate(Precision.DAY, now)));
Telecom requesterTelephone = new TelecomImpl("0756781234");
Telecom requesterFax = new TelecomImpl(TelecomMedium.FAX, "0756781234", TelecomUse.BUSINESS);
List<Telecom> requesterComms = new ArrayList<>();
requesterComms.add(requesterTelephone);
requesterComms.add(requesterFax);
// "Unstructured" address example
AustralianAddress requesterFullAddress = new AustralianAddressImpl();
requesterFullAddress.addUnstructuredAddressLine("level 2, 10 browning street");
requesterFullAddress.setCity("West End");
requesterFullAddress.setState(AustralianStateTerritory.QUEENSLAND.getAbbreviation());
requesterFullAddress.setPostcode("4101");
ProviderAddress requesterAddress = new ProviderAddressImpl(false, requesterFullAddress,
AddressPurpose.BUSINESS);
Occupation requesterOccupation = new OccupationImpl(
new ANZSCO_1ED_REV1("253915", "Pathologist"));
Role doctor = new RoleImpl(requesterOccupation);
ProviderEmploymentDetail requesterEmploymentDetail = new ProviderEmploymentDetailImpl(
requesterOccupation);
PersonName requesterPersonName = new PersonNameImpl("Requester");
ProviderPerson requesterPerson = new ProviderPersonImpl(requesterPersonName);
requesterPerson.setEmploymentDetail(requesterEmploymentDetail);
List<AsEntityIdentifier> organisationIds = Collections.singletonList(new AsEntityIdentifierImpl(hpioNumber));
Organisation clinic = new OrganisationImpl("Cool Clinic", OrganisationNameUsage.BUSINESS_NAME);
RequesterParticipant requesterParticipant = new RequesterParticipantImpl(
new AsEntityIdentifierImpl("8003610000001145"), organisationIds, clinic, requesterPerson);
requesterParticipant.setAddress(requesterAddress);
requesterParticipant.addEntitlement(requesterEntitlement);
requesterParticipant.setElectronicCommunicationDetail(requesterComms);
RequesterParticipation requester = new RequesterParticipationImpl(doctor, requesterParticipant,
now);
DiagnosticImageOrderDetails order = new DiagnosticImageOrderDetailsImpl(
PathologyId.orderID(hpioNumber), PathologyId.diAccessionID(hpioNumber),
new SNOMEDCode("26604007", "Complete blood count"));
DiagnosticImageReportContext imageContext = new DiagnosticImageReportContextImpl(subject,
requester, author, order);
// DocumentAuthorOrDevice reportingPathologist DocumentAuthorOrDevice reportingPathologist =
// DocumentAuthorOrDeviceImpl.getAuthorAsAPerson(
// author.getParticipant(), authorOccupation );
DocumentParticipant reportingPathologist = new DocumentParticipantImpl(authorOccupation,
authorParticipant);
UniqueIdentifier documentID = new UniqueIdentifierImpl(UUID.randomUUID().toString());
AttachedMedia testResult = new AttachedMedia(new File("test-result.pdf"));
String title = "Serum and Glucose Report for Peter Patient";
// Add an original text without changing the static code for all users
Code code = SNOMED_CT_ResultStatusCode.FINAL_RESULTS.copy();
code.setOriginalText("Final Results");
ReportDocument testResultDocument = new ReportDocumentImpl(title, testResult, documentID, code,
now);
AnatomicalSite leftThorax = new AnatomicalSiteImpl(
new SNOMED_AU_Code("51185008", "thorax"),
new SNOMED_AU_Code("7771000", "left")
);
List<AnatomicalSite> sites = new ArrayList<>();
sites.add(new AnatomicalSiteImpl("upper chest"));
sites.add(leftThorax);
ImagingExaminationResult result1 = ImagingExaminationResultImpl.base(
new SNOMED_AU_Code("399208008", "chest x-ray"),
new SNOMED_AU_Code("363680008", "x-ray"),
SNOMED_CT_ResultStatusCode.FINAL_RESULTS,
PrecisionDate.today(),
"The examination was carried out using the particular procedure.",
new AnatomicalRegionImpl(NCTISAnatomicalRegion.Region.CHEST, "Chest/Thorax")
);
ImagingExaminationResult result2 = ImagingExaminationResultImpl.withRelatedImage(
new SNOMED_AU_Code("241601008", "Magnetic resonance imaging of head (procedure)"),
new SNOMED_AU_Code("113091000", "Magnetic resonance imaging (procedure)"),
SNOMED_CT_ResultStatusCode.RESULTS_STORED,
PrecisionDate.today(),
"The examination was carried out using the particular procedure.",
new AnatomicalRegionImpl(NCTISAnatomicalRegion.Region.HEAD, "Head/Cerebral cortex"),
"x-ray.png"
);
List<AnatomicalSite> sitesForResult3 = new ArrayList<>();
sitesForResult3
.add(new AnatomicalSiteImpl(new SNOMED_AU_Code("123850002", "Head part (body structure)")));
sitesForResult3.add(leftThorax);
ImagingExaminationResult result3 = ImagingExaminationResultImpl.withSites(
new SNOMED_AU_Code("241601008", "Magnetic resonance imaging of head (procedure)"),
new SNOMED_AU_Code("113091000", "Magnetic resonance imaging (procedure)"),
SNOMED_CT_ResultStatusCode.CORRECTION_TO_RESULTS,
PrecisionDate.today(),
"The examination was carried out using the particular procedure.",
new AnatomicalRegionImpl(NCTISAnatomicalRegion.Region.HEAD, "Head/Cerebral cortex"),
sitesForResult3
);
ImagingExaminationResult result4 = ImagingExaminationResultImpl.withSitesAndRelatedImage(
new SNOMED_AU_Code("241601008", "Magnetic resonance imaging of head (procedure)"),
new SNOMED_AU_Code("113091000", "Magnetic resonance imaging (procedure)"),
SNOMED_CT_ResultStatusCode.SOME_BUT_NOT_ALL,
PrecisionDate.today(),
"The examination was carried out using the particular procedure.",
new AnatomicalRegionImpl(NCTISAnatomicalRegion.Region.HEAD, "Head/Cerebral cortex"),
sites,
"http://a.uri.for.this.image/id/3213131"
);
List<ImagingExaminationResult> imageResults = Arrays.asList(result1, result2, result3, result4);
DiagnosticImageReportContent diagnosticImageContent = new DiagnosticImageReportContentImpl(
imageResults, testResultDocument, reportingPathologist/*, authorisationToPost*/);
// Create Pathology Report
DiagnosticImageResultReport diagnosticImageReport = new DiagnosticImageResultReportImpl(
imageContext, diagnosticImageContent);
// *******************************
// ***** Legal Authenticator *****
// *******************************
List<PersonName> legalAuthenticatorsNames = new ArrayList<>(2);
legalAuthenticatorsNames.add(PersonNameImpl
.getInstance("Black", "Jane", NameTitle.MRS.getDescriptor(),
NameSuffix.JUNIOR.getDescriptor(), PersonNameUsage.REGISTERED_NAME_OR_LEGAL_NAME));
legalAuthenticatorsNames.add(PersonNameImpl
.getInstance("Alias", "other", NameTitle.MISS.getDescriptor(),
PersonNameUsage.MAIDEN_NAME_OR_NAME_AT_BIRTH));
HPII authenticatorHPII = new HPII("8003610000001145");
Person legalAuthenticatorPerson = PersonImpl
.getInstance(authenticatorHPII, legalAuthenticatorsNames);
// This is an alternate way of doing a HPIO, HPII or other identifier
// AsEntityIdentifier hpioTheHardWay =
// AsEntityIdentifierImpl.getInstance(
// "192.168.3.11.2001.1003.0.800362555555" );
// hpioTheHardWay.setAssigningAuthorityName( "HPI-O" );
// hpioTheHardWay.setAssigningGeographicAreaName( "National Identifier"
// );
HPIO authenticatorHPIO = new HPIO(hpioNumber);
Organization legalAuthenticatorOrganisation = OrganizationImpl
.getInstance(authenticatorHPIO, "Pathology Lab Name");
AssignedEntity cdaLegalAuthenticatorAssignedEntity = AssignedEntityImpl
.getInstance(documentID.toString(), legalAuthenticatorPerson, legalAuthenticatorOrganisation);
// You can also create a code the hard way...
Code cdaLegalAuthenticatorAssignedEntityCode = new CodeImpl("253111");
cdaLegalAuthenticatorAssignedEntityCode.setCodeSystem("2.16.840.1.113883.13.62");
cdaLegalAuthenticatorAssignedEntityCode.setCodeSystemName(
"1220.0 - ANZSCO - Australian and New Zealand Standard Classification of Occupations, First Edition, Revision 1\"");
cdaLegalAuthenticatorAssignedEntityCode.setDisplayName("General Medical Practitioner");
// ...or use a pre-baked version
cdaLegalAuthenticatorAssignedEntity
.setCode(new ANZSCO_1ED_REV1("253111", "General Medical Practitioner"));
AustralianAddress authenticatorAddress = new AustralianAddressImpl();
authenticatorAddress.addUnstructuredAddressLine("101 Browning Street");
authenticatorAddress.setState("QLD");
authenticatorAddress.setPostcode("4101");
authenticatorAddress.setCity("Brisbane");
PostalAddress authenticatorPostalAddress = new PostalAddressImpl(authenticatorAddress,
PostalAddressUseEnum.WORKPLACE);
cdaLegalAuthenticatorAssignedEntity.setAddress(Collections.singletonList(authenticatorPostalAddress));
Telecom authenticatorEmail = new TelecomImpl(TelecomMedium.EMAIL, "<EMAIL>",
TelecomUse.BUSINESS_AND_PERSONAL);
cdaLegalAuthenticatorAssignedEntity.setTelecom(Collections.singletonList(authenticatorEmail));
LegalAuthenticator cdaLegalAuthenticator = LegalAuthenticatorImpl
.getInstance(now, cdaLegalAuthenticatorAssignedEntity);
// *********************
// ***** Custodian *****
// *********************
AsEntityIdentifier custodianIdentifier = new HPIO(hpioNumber);
Telecom contact = new TelecomImpl(TelecomMedium.EMAIL, "<EMAIL>",
TelecomUse.BUSINESS);
AustralianAddress custodianAddress = new AustralianAddressImpl();
custodianAddress.addUnstructuredAddressLine("99 Clinician Street");
custodianAddress.setCity("Nehtaville");
custodianAddress.setState("QLD");
custodianAddress.setPostcode("5555");
custodianAddress.setAdditionalLocator("32568931");
UniqueIdentifier typedDocumentID = new UniqueIdentifierImpl(documentID.toString());
// You can also use additional identifiers
UniqueIdentifier otherId = new UniqueIdentifierImpl(UUID.randomUUID().toString());
CustodianOrganization custodianOrganization = CustodianOrganizationImpl
.getInstance(Arrays.asList(typedDocumentID, otherId), custodianIdentifier);
OrganizationName custodianOrganizationName = new OrganizationNameImpl("Custodian organisation");
custodianOrganization.setName(custodianOrganizationName);
custodianOrganization.setTelecom(contact);
custodianOrganization
.setAddress(new PostalAddressImpl(custodianAddress, PostalAddressUseEnum.POSTAL_ADDRESS));
AssignedCustodian assignedCustodian = AssignedCustodianImpl.getInstance(custodianOrganization);
Custodian cdaCustodian = CustodianImpl.getInstance(assignedCustodian);
ClinicalDocument document = ClinicalDocumentFactory.getDiagnosticImagingReport();
document.setSetId(documentID.toString());
// We can set the document number to something other than 1 if required
document.setVersionNumber(2);
// As an example we can add another template if needed.
document.addTemplateId(TemplateIdImpl.getInstance("1.0", "1.2.36.1.2001.1001.100.149"));
document.setCompletionCode(DocumentStatusCode.FINAL);
// prescriptionIdentifier
// String prescriptionDocumentId =
// "2.25.36901752580752676809846395044082807160";
// Must be an OID to pass into PCEHR
// You can also use the conversion tool
String documentUUID = UUID.randomUUID().toString();
String documentIdAsAnOid = UUIDTool.uuidToOid(documentUUID);
document.setClinicalDocumentId(documentIdAsAnOid);
DiagnosticImagingReportCdaModel model = new DiagnosticImagingReportCdaModel(document,
cdaLegalAuthenticator, cdaCustodian, now);
DiagnosticImageReportCreator diCreator = new DiagnosticImageReportCreator(model,
diagnosticImageReport);
Document clinicalDocument = diCreator.create();
String cdaString = documentToXML(clinicalDocument);
System.out.println(cdaString);
}
/**
* Convert a Document to a String
*/
public static String documentToXML(Document clinicalDocument) {
String cdaXml = "";
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource domSource = new DOMSource(clinicalDocument);
transformer.transform(domSource, result);
writer.flush();
writer.close();
cdaXml = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return cdaXml;
}
}
|
SebastianWebdev/SebaKoduje
|
src/components/MainSlider.js
|
import React from "react"
import styles from "../styles/main_slider.module.css"
import Slide from "./Slide.js"
import { Carousel } from "react-bootstrap"
import { useStaticQuery, graphql } from "gatsby"
const MainSlider = props => {
const posts = useStaticQuery(graphql`
query {
gcms {
posts {
cover {
url
}
coverSmall{
url
}
date
tittle
description
id
isPopular
slug
stage
coverAuthor
tagi {
tagName
}
}
}
}
`).gcms.posts
const {imgData} = props
console.log("DAne z props do slajdera", imgData)
return (
<div className={styles.container}>
<div className={styles.slide_container}>
<Carousel controls={false} fade={false}>
{posts.map(item => (
<Carousel.Item key={item.id}>
<Slide data={item} imgData={imgData} />
</Carousel.Item>
))}
</Carousel>
</div>
</div>
)
}
export default MainSlider
/*
slidaer z bootstrap
graphCMS połączony
*/
|
sreenivas8084/cQube
|
tests/src/Teacher_Attendance/check_data_range.py
|
import re
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from reuse_func import GetData
class DateRange():
def __init__(self, driver):
self.driver = driver
def check_date_range(self):
count =0
cal = GetData()
cal.click_on_state(self.driver)
cal.page_loading(self.driver)
year = Select(self.driver.find_element_by_id('year'))
count = len(year.options)
month = Select(self.driver.find_element_by_id('month'))
for i in range(1,len(year.options)):
year.select_by_index(i)
print(year.options[i].text)
cal.page_loading(self.driver)
cal.page_loading(self.driver)
return count
|
spurious/safecode-mirror
|
test/cstdlib/strncat-003.c
|
<gh_stars>1-10
// RUN: test.sh -e -t %t %s
// The destination string is written to out of bounds.
#include <string.h>
int main()
{
char a[10];
char b[500];
a[0] = '\0';
memset(b, 'b', 10);
strncat(a, b, 50);
return 0;
}
|
ym6745476/andbase-x
|
andbase/src/main/java/com/andbase/library/view/sample/AbOuterScrollView.java
|
<gh_stars>1-10
package com.andbase.library.view.sample;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Copyright ymbok.com
* Author 还如一梦中
* Date 2016/6/14 17:54
* Email <EMAIL>
* Info ScrollView 里面有X方向的滚动View时能避免冲突
*/
public class AbOuterScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public AbOuterScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(distanceY!=0&&distanceX!=0){
}
if(Math.abs(distanceY) >= Math.abs(distanceX)) {
return true;
}
return false;
}
}
}
|
victorgveloso/RefactoringMiner
|
src/gr/uom/java/xmi/UMLAbstractClass.java
|
package gr.uom.java.xmi;
import gr.uom.java.xmi.decomposition.OperationInvocation;
import gr.uom.java.xmi.decomposition.VariableDeclaration;
import gr.uom.java.xmi.diff.CodeRange;
import gr.uom.java.xmi.diff.RenamePattern;
import gr.uom.java.xmi.diff.StringDistance;
import org.refactoringminer.util.PrefixSuffixUtils;
import java.util.*;
public abstract class UMLAbstractClass {
protected LocationInfo locationInfo;
protected String packageName;
protected String name;
protected final List<UMLOperation> operations;
protected final List<UMLAttribute> attributes;
protected final List<UMLComment> comments;
private final List<UMLAnonymousClass> anonymousClassList;
private Map<String, VariableDeclaration> fieldDeclarationMap;
public UMLAbstractClass() {
this.operations = new ArrayList<>();
this.attributes = new ArrayList<>();
this.comments = new ArrayList<>();
this.anonymousClassList = new ArrayList<>();
}
public List<UMLOperation> getOperationsWithOverrideAnnotation() {
List<UMLOperation> operations = new ArrayList<>();
for(UMLOperation operation : this.operations) {
if(operation.hasOverrideAnnotation() && !operation.isConstructor() && !operation.overridesObject()) {
operations.add(operation);
}
}
return operations;
}
public List<UMLOperation> getOperationsWithoutOverrideAnnotation() {
List<UMLOperation> operations = new ArrayList<>();
for(UMLOperation operation : this.operations) {
if(!operation.hasOverrideAnnotation() && !operation.isConstructor() && !operation.overridesObject()) {
operations.add(operation);
}
}
return operations;
}
public LocationInfo getLocationInfo() {
return locationInfo;
}
public String getPackageName() {
return this.packageName;
}
public void addOperation(UMLOperation operation) {
this.operations.add(operation);
}
public void addAttribute(UMLAttribute attribute) {
this.attributes.add(attribute);
}
public List<UMLOperation> getOperations() {
return operations;
}
public List<UMLAttribute> getAttributes() {
return attributes;
}
public List<UMLComment> getComments() {
return comments;
}
public Map<String, VariableDeclaration> getFieldDeclarationMap() {
if(this.fieldDeclarationMap == null) {
fieldDeclarationMap = new LinkedHashMap<>();
for(UMLAttribute attribute : attributes) {
fieldDeclarationMap.put(attribute.getName(), attribute.getVariableDeclaration());
}
}
return fieldDeclarationMap;
}
//returns true if the "innerClass" parameter is inner class of this
public boolean isInnerClass(UMLAbstractClass innerClass) {
return this.getName().equals(innerClass.packageName);
}
public UMLOperation operationWithTheSameSignature(UMLOperation operation) {
for(UMLOperation originalOperation : operations) {
if(originalOperation.equalSignature(operation))
return originalOperation;
}
return null;
}
public boolean containsOperationWithTheSameSignature(UMLOperation operation) {
for(UMLOperation originalOperation : operations) {
if(originalOperation.equalSignature(operation))
return true;
}
return false;
}
public UMLOperation operationWithTheSameSignatureIgnoringChangedTypes(UMLOperation operation) {
List<UMLOperation> matchingOperations = new ArrayList<>();
for(UMLOperation originalOperation : operations) {
boolean matchesOperation = isInterface() ?
originalOperation.equalSignatureIgnoringChangedTypes(operation) :
originalOperation.equalSignatureWithIdenticalNameIgnoringChangedTypes(operation);
if(matchesOperation) {
boolean originalOperationEmptyBody = originalOperation.getBody() == null || originalOperation.hasEmptyBody();
boolean operationEmptyBody = operation.getBody() == null || operation.hasEmptyBody();
if(originalOperationEmptyBody == operationEmptyBody)
matchingOperations.add(originalOperation);
}
}
if(matchingOperations.size() == 1) {
return matchingOperations.get(0);
}
else if(matchingOperations.size() > 1) {
int minDistance = StringDistance.editDistance(matchingOperations.get(0).toString(), operation.toString());
UMLOperation matchingOperation = matchingOperations.get(0);
for(int i=1; i<matchingOperations.size(); i++) {
int distance = StringDistance.editDistance(matchingOperations.get(i).toString(), operation.toString());
if(distance < minDistance) {
minDistance = distance;
matchingOperation = matchingOperations.get(i);
}
}
return matchingOperation;
}
return null;
}
public boolean containsOperationWithTheSameSignatureIgnoringChangedTypes(UMLOperation operation) {
for(UMLOperation originalOperation : operations) {
if(originalOperation.equalSignatureIgnoringChangedTypes(operation)) {
boolean originalOperationEmptyBody = originalOperation.getBody() == null || originalOperation.hasEmptyBody();
boolean operationEmptyBody = operation.getBody() == null || operation.hasEmptyBody();
if(originalOperationEmptyBody == operationEmptyBody)
return true;
}
}
return false;
}
public boolean containsOperationWithTheSameName(UMLOperation operation) {
for(UMLOperation originalOperation : operations) {
if(originalOperation.getName().equals(operation.getName()))
return true;
}
return false;
}
public boolean containsOperationWithTheSameRenamePattern(UMLOperation operation, RenamePattern pattern) {
if(pattern == null)
return false;
for(UMLOperation originalOperation : operations) {
String originalOperationName = originalOperation.getName();
if(originalOperationName.contains(pattern.getBefore())) {
String originalOperationNameAfterReplacement = originalOperationName.replace(pattern.getBefore(), pattern.getAfter());
if(originalOperationNameAfterReplacement.equals(operation.getName()))
return true;
}
}
return false;
}
public UMLAttribute attributeWithTheSameNameIgnoringChangedType(UMLAttribute attribute) {
for(UMLAttribute originalAttribute : attributes) {
if(originalAttribute.equalsIgnoringChangedType(attribute))
return originalAttribute;
}
return null;
}
public boolean containsAttributeWithTheSameNameIgnoringChangedType(UMLAttribute attribute) {
for(UMLAttribute originalAttribute : attributes) {
if(originalAttribute.equalsIgnoringChangedType(attribute))
return true;
}
return false;
}
public boolean containsRenamedAttributeWithIdenticalTypeAndInitializer(UMLAttribute attribute) {
for(UMLAttribute originalAttribute : attributes) {
if(originalAttribute.renamedWithIdenticalTypeAndInitializer(attribute))
return true;
}
return false;
}
public boolean containsAttributeWithTheSameName(UMLAttribute attribute) {
for(UMLAttribute originalAttribute : attributes) {
if(originalAttribute.getName().equals(attribute.getName()))
return true;
}
return false;
}
public boolean containsAttributeWithTheSameRenamePattern(UMLAttribute attribute, RenamePattern pattern) {
if(pattern == null)
return false;
for(UMLAttribute originalAttribute : attributes) {
String originalAttributeName = originalAttribute.getName();
if(originalAttributeName.contains(pattern.getBefore())) {
String originalAttributeNameAfterReplacement = originalAttributeName.replace(pattern.getBefore(), pattern.getAfter());
if(originalAttributeNameAfterReplacement.equals(attribute.getName()))
return true;
}
}
return false;
}
public boolean containsAttributeWithName(String attributeName) {
for(UMLAttribute originalAttribute : attributes) {
if(originalAttribute.getName().equals(attributeName))
return true;
}
return false;
}
public boolean hasAttributesAndOperationsWithCommonNames(UMLAbstractClass umlClass) {
Set<UMLOperation> commonOperations = new LinkedHashSet<>();
int totalOperations = 0;
for(UMLOperation operation : operations) {
if(!operation.isConstructor() && !operation.overridesObject()) {
totalOperations++;
if(umlClass.containsOperationWithTheSameName(operation)) {
commonOperations.add(operation);
}
}
}
for(UMLOperation operation : umlClass.operations) {
if(!operation.isConstructor() && !operation.overridesObject()) {
totalOperations++;
if(this.containsOperationWithTheSameName(operation)) {
commonOperations.add(operation);
}
}
}
Set<UMLAttribute> commonAttributes = new LinkedHashSet<>();
int totalAttributes = 0;
for(UMLAttribute attribute : attributes) {
totalAttributes++;
if(umlClass.containsAttributeWithTheSameName(attribute)) {
commonAttributes.add(attribute);
}
}
for(UMLAttribute attribute : umlClass.attributes) {
totalAttributes++;
if(this.containsAttributeWithTheSameName(attribute)) {
commonAttributes.add(attribute);
}
}
if(this.isTestClass() && umlClass.isTestClass()) {
return commonOperations.size() > Math.floor(totalOperations/2.0) || commonOperations.containsAll(this.operations);
}
if(this.isSingleAbstractMethodInterface() && umlClass.isSingleAbstractMethodInterface()) {
return commonOperations.size() == totalOperations;
}
return (commonOperations.size() >= Math.floor(totalOperations/2.0) && (commonAttributes.size() > 2 || totalAttributes == 0)) ||
(commonAttributes.size() >= Math.floor(totalAttributes/2.0) && (commonOperations.size() > 2 || totalOperations == 0)) ||
(commonOperations.size() == totalOperations && commonOperations.size() > 2 && this.attributes.size() == umlClass.attributes.size()) ||
(commonOperations.size() == totalOperations && commonOperations.size() > 2 && totalAttributes == 1);
}
public boolean hasCommonAttributesAndOperations(UMLAbstractClass umlClass) {
String commonPrefix = PrefixSuffixUtils.longestCommonPrefix(this.name, umlClass.name);
String commonSuffix = PrefixSuffixUtils.longestCommonSuffix(this.name, umlClass.name);
RenamePattern pattern = null;
if(!commonPrefix.isEmpty() && !commonSuffix.isEmpty()) {
int beginIndexS1 = this.name.indexOf(commonPrefix) + commonPrefix.length();
int endIndexS1 = this.name.lastIndexOf(commonSuffix);
String diff1 = beginIndexS1 > endIndexS1 ? "" : this.name.substring(beginIndexS1, endIndexS1);
int beginIndexS2 = umlClass.name.indexOf(commonPrefix) + commonPrefix.length();
int endIndexS2 = umlClass.name.lastIndexOf(commonSuffix);
String diff2 = beginIndexS2 > endIndexS2 ? "" : umlClass.name.substring(beginIndexS2, endIndexS2);
pattern = new RenamePattern(diff1, diff2);
}
Set<UMLOperation> commonOperations = new LinkedHashSet<>();
int totalOperations = 0;
for(UMLOperation operation : operations) {
if(!operation.isConstructor() && !operation.overridesObject()) {
totalOperations++;
if(umlClass.containsOperationWithTheSameSignatureIgnoringChangedTypes(operation) ||
(pattern != null && umlClass.containsOperationWithTheSameRenamePattern(operation, pattern.reverse()))) {
commonOperations.add(operation);
}
}
}
for(UMLOperation operation : umlClass.operations) {
if(!operation.isConstructor() && !operation.overridesObject()) {
totalOperations++;
if(this.containsOperationWithTheSameSignatureIgnoringChangedTypes(operation) ||
(pattern != null && this.containsOperationWithTheSameRenamePattern(operation, pattern))) {
commonOperations.add(operation);
}
}
}
Set<UMLAttribute> commonAttributes = new LinkedHashSet<>();
int totalAttributes = 0;
for(UMLAttribute attribute : attributes) {
totalAttributes++;
if(umlClass.containsAttributeWithTheSameNameIgnoringChangedType(attribute) ||
umlClass.containsRenamedAttributeWithIdenticalTypeAndInitializer(attribute) ||
(pattern != null && umlClass.containsAttributeWithTheSameRenamePattern(attribute, pattern.reverse()))) {
commonAttributes.add(attribute);
}
}
for(UMLAttribute attribute : umlClass.attributes) {
totalAttributes++;
if(this.containsAttributeWithTheSameNameIgnoringChangedType(attribute) ||
this.containsRenamedAttributeWithIdenticalTypeAndInitializer(attribute) ||
(pattern != null && this.containsAttributeWithTheSameRenamePattern(attribute, pattern))) {
commonAttributes.add(attribute);
}
}
if(this.isTestClass() && umlClass.isTestClass()) {
return commonOperations.size() > Math.floor(totalOperations/2.0) || commonOperations.containsAll(this.operations);
}
if(this.isSingleAbstractMethodInterface() && umlClass.isSingleAbstractMethodInterface()) {
return commonOperations.size() == totalOperations;
}
if((commonOperations.size() > Math.floor(totalOperations/2.0) && (commonAttributes.size() > 2 || totalAttributes == 0)) ||
(commonOperations.size() > Math.floor(totalOperations/3.0*2.0) && (commonAttributes.size() >= 2 || totalAttributes == 0)) ||
(commonAttributes.size() > Math.floor(totalAttributes/2.0) && (commonOperations.size() > 2 || totalOperations == 0)) ||
(commonOperations.size() == totalOperations && commonOperations.size() > 2 && this.attributes.size() == umlClass.attributes.size()) ||
(commonOperations.size() == totalOperations && commonOperations.size() > 2 && totalAttributes == 1)) {
return true;
}
Set<UMLOperation> unmatchedOperations = new LinkedHashSet<>(umlClass.operations);
unmatchedOperations.removeAll(commonOperations);
Set<UMLOperation> unmatchedCalledOperations = new LinkedHashSet<>();
for(UMLOperation operation : umlClass.operations) {
if(commonOperations.contains(operation)) {
for(OperationInvocation invocation : operation.getAllOperationInvocations()) {
for(UMLOperation unmatchedOperation : unmatchedOperations) {
if(invocation.matchesOperation(unmatchedOperation, operation, null)) {
unmatchedCalledOperations.add(unmatchedOperation);
break;
}
}
}
}
}
return commonOperations.size() + unmatchedCalledOperations.size() > Math.floor(totalOperations / 2.0) && (commonAttributes.size() > 2 || totalAttributes == 0);
}
public boolean hasSameAttributesAndOperations(UMLAbstractClass umlClass) {
if(this.attributes.size() != umlClass.attributes.size())
return false;
if(this.operations.size() != umlClass.operations.size())
return false;
for(UMLOperation operation : operations) {
if(!umlClass.containsOperationWithTheSameSignatureIgnoringChangedTypes(operation)) {
return false;
}
}
for(UMLOperation operation : umlClass.operations) {
if(!this.containsOperationWithTheSameSignatureIgnoringChangedTypes(operation)) {
return false;
}
}
for(UMLAttribute attribute : attributes) {
if(!umlClass.containsAttributeWithTheSameNameIgnoringChangedType(attribute)) {
return false;
}
}
for(UMLAttribute attribute : umlClass.attributes) {
if(!this.containsAttributeWithTheSameNameIgnoringChangedType(attribute)) {
return false;
}
}
return true;
}
public boolean isTestClass() {
for(UMLOperation operation : operations) {
if(operation.hasTestAnnotation()) {
return true;
}
}
return false;
}
public List<UMLAttribute> attributesOfType(String targetClass) {
List<UMLAttribute> attributesOfType = new ArrayList<>();
for(UMLAttribute attribute : attributes) {
if(targetClass.endsWith("." + attribute.getType().getClassType()) ||
targetClass.equals(attribute.getType().getClassType())) {
attributesOfType.add(attribute);
}
}
return attributesOfType;
}
public UMLAttribute containsAttribute(UMLAttribute otherAttribute) {
for (UMLAttribute attribute : attributes) {
if (attribute.equals(otherAttribute)) {
return attribute;
}
}
return null;
}
public UMLAttribute matchAttribute(UMLAttribute otherAttribute) {
for (UMLAttribute attribute : attributes) {
if (attribute.getName().equals(otherAttribute.getName())) {
String thisAttributeType = attribute.getType().getClassType();
String otherAttributeType = otherAttribute.getType().getClassType();
int thisArrayDimension = attribute.getType().getArrayDimension();
int otherArrayDimension = otherAttribute.getType().getArrayDimension();
String thisAttributeTypeComparedString;
if (thisAttributeType.contains("."))
thisAttributeTypeComparedString = thisAttributeType.substring(thisAttributeType.lastIndexOf(".") + 1);
else
thisAttributeTypeComparedString = thisAttributeType;
String otherAttributeTypeComparedString;
if (otherAttributeType.contains("."))
otherAttributeTypeComparedString = otherAttributeType.substring(otherAttributeType.lastIndexOf(".") + 1);
else
otherAttributeTypeComparedString = otherAttributeType;
if (thisAttributeTypeComparedString.equals(otherAttributeTypeComparedString) && thisArrayDimension == otherArrayDimension)
return attribute;
}
}
return null;
}
public abstract boolean isSingleAbstractMethodInterface();
public abstract boolean isInterface();
public abstract String getName();
public String getNonQualifiedName() {
return name;
}
public String getSourceFile() {
return locationInfo.getFilePath();
}
public CodeRange codeRange() {
return locationInfo.codeRange();
}
public Map<String, Set<String>> aliasedAttributes() {
for(UMLOperation operation : getOperations()) {
if(operation.isConstructor()) {
Map<String, Set<String>> aliased = operation.aliasedAttributes();
if(!aliased.isEmpty()) {
return aliased;
}
}
}
return new LinkedHashMap<>();
}
public void addAnonymousClass(UMLAnonymousClass anonymousClass) {
anonymousClassList.add(anonymousClass);
}
public List<UMLAnonymousClass> getAnonymousClassList() {
return anonymousClassList;
}
public boolean containsAnonymousWithSameAttributesAndOperations(UMLAnonymousClass anonymous) {
for(UMLAnonymousClass thisAnonymous : anonymousClassList) {
if(thisAnonymous.hasSameAttributesAndOperations(anonymous))
return true;
}
return false;
}
}
|
qianbinbin/leetcode
|
c/tests/string_to_integer_atoi_test.cpp
|
<filename>c/tests/string_to_integer_atoi_test.cpp
#include <gtest/gtest.h>
extern "C" {
#include "string_to_integer_atoi.h"
}
TEST(string_to_integer_atoi_test, myAtoi_8_1) {
EXPECT_EQ(42, myAtoi_8_1("42"));
EXPECT_EQ(-42, myAtoi_8_1("-42"));
EXPECT_EQ(4193, myAtoi_8_1("4193 with words"));
EXPECT_EQ(0, myAtoi_8_1("words and 987"));
EXPECT_EQ(INT_MIN, myAtoi_8_1("-91283472332"));
}
|
bgyori/chemical-roles
|
src/chemical_roles/export/bel.py
|
# -*- coding: utf-8 -*-
"""Export to BEL."""
import pybel
from pybel import BELGraph, dsl
from tqdm import tqdm
from .utils import get_relations_df
__all__ = [
'get_bel',
]
_type_map = {
'biological process': dsl.BiologicalProcess,
'chemical': dsl.Abundance,
'organism': dsl.Population,
'phenotype': dsl.Pathology,
'protein': dsl.Protein,
'protein family': dsl.Protein,
'protein complex': dsl.NamedComplexAbundance,
}
_adders = {
'activator': BELGraph.add_directly_activates,
'agonist': BELGraph.add_directly_activates,
'antagonist': BELGraph.add_directly_inhibits,
'inhibitor': BELGraph.add_directly_inhibits,
'inverse agonist': BELGraph.add_directly_activates,
'modulator': BELGraph.add_directly_regulates,
}
def get_bel(use_inferred: bool = True, add_evidence: bool = True) -> BELGraph:
"""Get Chemical Roles as BEL."""
df = get_relations_df(use_inferred=use_inferred)
graph = BELGraph(name='Chemical Roles Graph')
it = tqdm(df.dropna().values, total=len(df.index), desc='mapping to BEL', unit_scale=True)
evidence = 'Manually curated.' if add_evidence else None
for source_db, source_id, source_name, modulation, target_type, target_db, target_id, target_name in it:
if target_type == 'molecular function':
continue
source = pybel.dsl.Abundance(
namespace=source_db,
identifier=source_id,
name=source_name,
)
target = _type_map[target_type](
namespace=target_db,
identifier=target_id,
name=target_name,
)
adder = _adders[modulation]
adder(
graph, source, target,
citation=('doi', '10.26434/chemrxiv.12591221'),
evidence=evidence,
)
return graph
|
liamtong/click-to-deploy
|
vm/chef/cookbooks/mautic/recipes/default.rb
|
# Copyright 2019 Google LLC
#
# 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.
include_recipe 'php73'
include_recipe 'php73::composer'
include_recipe 'php73::module_libapache2'
include_recipe 'php73::module_mysql'
include_recipe 'php73::module_xmlrpc'
include_recipe 'composer::composer-only'
include_recipe 'git'
include_recipe 'mysql'
include_recipe 'apache2'
include_recipe 'apache2::ipv4-listen'
include_recipe 'apache2::mod-rewrite'
include_recipe 'apache2::rm-index'
include_recipe 'apache2::security-config'
package 'Install packages' do
package_name node['mautic']['packages']
action :install
end
bash 'php configuration' do
user 'root'
code <<-EOH
sed -i 's/^memory_limit = 128M/memory_limit = 512M/' /etc/php/7.3/apache2/php.ini
sed -i 's/^short_open_tag = Off/short_open_tag = On/' /etc/php/7.3/apache2/php.ini
sed -i 's/^upload_max_filesize = 2M/upload_max_filesize = 128M/' /etc/php/7.3/apache2/php.ini
sed -i 's/^max_execution_time = 30/max_execution_time = 300/' /etc/php/7.3/apache2/php.ini
sed -i 's/^;date.timezone =/date.timezone = UTC/' /etc/php/7.3/apache2/php.ini
phpenmod imap
EOH
end
bash 'MySQL configuration' do
user 'root'
code 'mysql -u root -e "CREATE DATABASE ${defdb}"'
environment({
'defdb' => node['mautic']['db']['name'],
})
end
git '/var/www/html/mautic' do
repository 'https://github.com/mautic/mautic.git'
revision node['mautic']['version']
action :checkout
end
template '/etc/apache2/sites-available/000-default.conf' do
source 'default-apache.erb'
end
template '/etc/cron.d/mautic' do
source 'mautic-crontab.erb'
mode '0644'
end
bash 'install requirements' do
user 'root'
cwd '/var/www/html/mautic/'
code <<-EOH
composer install
chown -R ${user}:${user} ../mautic
EOH
environment({
'user' => node['mautic']['user'],
})
end
# Download licenses/source code for OSPO
remote_file '/var/www/html/mautic/vendor/ip2location/ip2location-php/LICENSE' do
source 'https://raw.githubusercontent.com/chrislim2888/IP2Location-PHP-Module/master/LICENSE.TXT'
owner node['mautic']['user']
group node['mautic']['user']
mode '0644'
action :create
end
git '/usr/src/device-detector' do
repository 'https://github.com/matomo-org/device-detector.git'
action :checkout
end
c2d_startup_script 'mautic'
|
lchb369/chaos
|
chaos/utility/noncopyable.h
|
<filename>chaos/utility/noncopyable.h
/*
* Copyright 2012, <NAME>. All rights reserved.
* https://github.com/lyjdamzwf/chaos
*
* Use of this source code is governed by a BSD-style
* license that can be found in the License file.
*/
#ifndef _CHAOS_NONCOPYALBE_H_
#define _CHAOS_NONCOPYALBE_H_
/**
* @file noncopyable.h
* @author yunjie.lu
* @email <EMAIL>
* @weibo http://weibo.com/crazyprogramerlyj
* @date
* @brief
* @last changed
*
*/
namespace chaos
{
namespace utility
{
class noncopyable_t
{
protected:
noncopyable_t() {}
~noncopyable_t() {}
//! yunjie: 将拷贝构造和赋值函数 设置为私有
private:
noncopyable_t( const noncopyable_t& );
const noncopyable_t& operator = ( const noncopyable_t& );
};
}
}
#endif //! _CHAOS_NONCOPYALBE_H_
|
boyskylake/maintain-soat
|
resources/js/src/Officer/pages/Lookscreen/Lookscreen.js
|
<reponame>boyskylake/maintain-soat
import React, { useState, useEffect } from "react";
import { Helmet } from "react-helmet";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import { useBodyClass, useScript } from "../../../helpers";
import { userActions } from "../../redux/actions";
const Lookscreen = () => {
const [pass, setPass] = useState();
useBodyClass("hold-transition");
useBodyClass("lockscreen");
useScript("/officer/bower_components/bootstrap/dist/js/bootstrap.min.js");
const dispatch = useDispatch();
const authentication = useSelector((state) => state.authentication);
let history = useHistory();
useEffect(() => {
if (authentication.loggedIn && authentication.refreshIn) {
// history.goBack();
history.push("/officer/home");
}
if (!authentication.refreshIn && !authentication.loggedIn) {
history.push("/officer/login");
}
}, [authentication, history]);
let handleSubmit = (e) => {
e.preventDefault();
dispatch(userActions.refresh());
};
return (
<div className="lockscreen-wrapper">
<Helmet>
<meta
name="description"
content="บริษัทโซแอ็ท โซลูชั่น จำกัด"
/>
<meta property="og:locale" content="th_TH" />
<meta property="og:type" content="website" />
<meta
property="og:title"
content="บริษัทโซแอ็ท โซลูชั่น จำกัด"
/>
<meta
property="og:description"
content="บริษัทโซแอ็ท โซลูชั่น จำกัด"
/>
<meta property="og:url" content={window.location.href} />
<link rel="canonical" href={window.location.href} />
<meta
property="og:site_name"
content="บริษัทโซแอ็ท โซลูชั่น จำกัด"
/>
<link
rel="stylesheet"
href="/officer/bower_components/bootstrap/dist/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="/officer/bower_components/font-awesome/css/font-awesome.min.css"
/>
<link
rel="stylesheet"
href="/officer/bower_components/Ionicons/css/ionicons.min.css"
/>
<link rel="stylesheet" href="/officer/dist/css/AdminLTE.css" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"
/>
</Helmet>
<div className="lockscreen-logo">
<b>Soat</b>Officer
</div>
{/* User name */}
<div className="lockscreen-name"><NAME></div>
{/* START LOCK SCREEN ITEM */}
<div className="lockscreen-item">
{/* lockscreen image */}
<div className="lockscreen-image">
<img
src="/officer/dist/img/user1-128x128.jpg"
alt="User Image"
/>
</div>
{/* /.lockscreen-image */}
{/* lockscreen credentials (contains the form) */}
<form
className="lockscreen-credentials"
onSubmit={(e) => handleSubmit(e)}
>
<div className="input-group">
<input
type="password"
onChange={(event) => setPass(event.target.value)}
className="form-control"
placeholder="password"
required
/>
<div className="input-group-btn">
<button type="submit" className="btn">
<i className="fa fa-arrow-right text-muted" />
</button>
</div>
</div>
</form>
{/* /.lockscreen credentials */}
</div>
{/* /.lockscreen-item */}
<div className="help-block text-center">
Enter your password to retrieve your session
</div>
<div className="text-center">
<a href="login.html">Or sign in as a different user</a>
</div>
<div className="lockscreen-footer text-center">
Copyright © 2014-2016{" "}
<b>
<a href="https://adminlte.io" className="text-black">
Almsaeed Studio
</a>
</b>
<br />
All rights reserved
</div>
</div>
);
};
export default Lookscreen;
|
RanerL/analyzer
|
tests/juliet/testcases/CWE369_Divide_by_Zero/s01/CWE369_Divide_by_Zero__float_zero_83.h
|
<reponame>RanerL/analyzer<gh_stars>10-100
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_zero_83.h
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-83.tmpl.h
*/
/*
* @description
* CWE: 369 Divide by Zero
* BadSource: zero Fixed value of zero
* GoodSource: A hardcoded non-zero number (two)
* Sinks:
* GoodSink: Check value of or near zero before dividing
* BadSink : Divide a constant by data
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
#include <math.h>
namespace CWE369_Divide_by_Zero__float_zero_83
{
#ifndef OMITBAD
class CWE369_Divide_by_Zero__float_zero_83_bad
{
public:
CWE369_Divide_by_Zero__float_zero_83_bad(float dataCopy);
~CWE369_Divide_by_Zero__float_zero_83_bad();
private:
float data;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE369_Divide_by_Zero__float_zero_83_goodG2B
{
public:
CWE369_Divide_by_Zero__float_zero_83_goodG2B(float dataCopy);
~CWE369_Divide_by_Zero__float_zero_83_goodG2B();
private:
float data;
};
class CWE369_Divide_by_Zero__float_zero_83_goodB2G
{
public:
CWE369_Divide_by_Zero__float_zero_83_goodB2G(float dataCopy);
~CWE369_Divide_by_Zero__float_zero_83_goodB2G();
private:
float data;
};
#endif /* OMITGOOD */
}
|
ysBach/irafdocgen
|
iraf.v2161/vendor/x11iraf/obm/ObmW/MenuBar.c
|
/* Generated by wbuild from "MenuBar.w"
** (generator version $Revision: 2.0 $ of $Date: 93/07/06 16:08:04 $)
*/
#include <X11/IntrinsicP.h>
#include <X11/StringDefs.h>
/* #include "PullDown.h" */
#include <X11/Shell.h>
#include <stdio.h>
#include "MenuBarP.h"
static void menu_popdown(
#if NeedFunctionPrototypes
Widget,XEvent*,String*,Cardinal*
#endif
);
static XtActionsRec actionsList[] = {
{"menu_popdown", menu_popdown},
};
static char defaultTranslations[] = "\
<Btn1Up>: menu_popdown() \n\
";
static void _resolve_inheritance(
#if NeedFunctionPrototypes
WidgetClass
#endif
);
static void initialize(
#if NeedFunctionPrototypes
Widget ,Widget,ArgList ,Cardinal *
#endif
);
static void process_menu(
#if NeedFunctionPrototypes
Widget,Widget ,Cursor
#endif
);
static void popdown_cb(
#if NeedFunctionPrototypes
Widget ,XtPointer ,XtPointer
#endif
);
/*ARGSUSED*/static void popdown_cb(menu,client_data,call_data)Widget menu;XtPointer client_data;XtPointer call_data;
{
Widget self = (Widget) client_data;
XtRemoveCallback(menu, XtNpopdownCallback, popdown_cb, self);
/*
XtUngrabKey(menu, AnyKey, AnyModifier);
XtUngrabButton(menu, AnyButton, AnyModifier);
XtRemoveGrab($);
*/
((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu = NULL;
}
static XtResource resources[] = {
{XtNframeType,XtCFrameType,XtRFrameType,sizeof(((XfwfMenuBarRec*)NULL)->xfwfFrame.frameType),XtOffsetOf(XfwfMenuBarRec,xfwfFrame.frameType),XtRImmediate,(XtPointer)XfwfRaised },
{XtNtraversalOn,XtCTraversalOn,XtRBoolean,sizeof(((XfwfMenuBarRec*)NULL)->xfwfCommon.traversalOn),XtOffsetOf(XfwfMenuBarRec,xfwfCommon.traversalOn),XtRImmediate,(XtPointer)False },
};
XfwfMenuBarClassRec xfwfMenuBarClassRec = {
{ /* core_class part */
(WidgetClass) &xfwfRowColClassRec,
"XfwfMenuBar",
sizeof(XfwfMenuBarRec),
NULL,
_resolve_inheritance,
FALSE,
initialize,
NULL,
XtInheritRealize,
actionsList,
1,
resources,
2,
NULLQUARK,
False ,
FALSE ,
False ,
False ,
NULL,
XtInheritResize,
XtInheritExpose,
NULL,
NULL,
XtInheritSetValuesAlmost,
NULL,
XtInheritAcceptFocus,
XtVersion,
NULL,
defaultTranslations,
XtInheritQueryGeometry,
XtInheritDisplayAccelerator,
NULL
},
{ /* composite_class part */
XtInheritGeometryManager,
XtInheritChangeManaged,
XtInheritInsertChild,
XtInheritDeleteChild,
NULL
},
{ /* XfwfCommon_class part */
XtInherit_compute_inside,
XtInherit_highlight_border,
XtInherit_unhighlight_border,
XtInherit_would_accept_focus,
XtInherit_traverse,
XtInherit_choose_color,
XtInherit_lighter_color,
XtInherit_darker_color,
NULL ,
},
{ /* XfwfFrame_class part */
0
},
{ /* XfwfBoard_class part */
XtInherit_set_abs_location,
},
{ /* XfwfRowCol_class part */
XtInherit_layout,
},
{ /* XfwfMenuBar_class part */
process_menu,
},
};
WidgetClass xfwfMenuBarWidgetClass = (WidgetClass) &xfwfMenuBarClassRec;
/*ARGSUSED*/
static void menu_popdown(self,event,params,num_params)Widget self;XEvent*event;String*params;Cardinal*num_params;
{
if (((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu != NULL) {
XtPopdown(((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu);
((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu = NULL;
}
}
static void _resolve_inheritance(class)
WidgetClass class;
{
XfwfMenuBarWidgetClass c = (XfwfMenuBarWidgetClass) class;
XfwfMenuBarWidgetClass super;
static CompositeClassExtensionRec extension_rec = {
NULL, NULLQUARK, XtCompositeExtensionVersion,
sizeof(CompositeClassExtensionRec), True};
CompositeClassExtensionRec *ext;
ext = (XtPointer)XtMalloc(sizeof(*ext));
*ext = extension_rec;
ext->next_extension = c->composite_class.extension;
c->composite_class.extension = ext;
if (class == xfwfMenuBarWidgetClass) return;
super = (XfwfMenuBarWidgetClass)class->core_class.superclass;
if (c->xfwfMenuBar_class.process_menu == XtInherit_process_menu)
c->xfwfMenuBar_class.process_menu = super->xfwfMenuBar_class.process_menu;
}
/*ARGSUSED*/static void initialize(request,self,args,num_args)Widget request;Widget self;ArgList args;Cardinal * num_args;
{
((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu = NULL;
}
/*ARGSUSED*/static void process_menu(self,menu,cursor)Widget self;Widget menu;Cursor cursor;
{
if (menu == ((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu) return;
if (((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu) XtPopdown(((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu);
XtAddGrab(self, True, False);
/*
XtGrabButton(menu, AnyButton, AnyModifier, True, ButtonPressMask |
ButtonReleaseMask | EnterWindowMask | LeaveWindowMask
| PointerMotionMask, GrabModeAsync, GrabModeAsync,
None, cursor);
XtGrabKey(menu, AnyKey, AnyModifier, True, GrabModeAsync,
GrabModeAsync);
*/
XtAddCallback(menu, XtNpopdownCallback, popdown_cb, self);
((XfwfMenuBarWidget)self)->xfwfMenuBar.current_menu = menu;
XtPopup(menu, XtGrabNonexclusive);
}
/*ARGSUSED*/Boolean XfwfCallProcessMenu(self,menu,cursor)Widget self;Widget menu;Cursor cursor;
{
if (XtIsSubclass(self, xfwfMenuBarWidgetClass) && ((XfwfMenuBarWidgetClass)self->core.widget_class)->xfwfMenuBar_class.process_menu) {
((XfwfMenuBarWidgetClass)self->core.widget_class)->xfwfMenuBar_class.process_menu(self, menu, cursor);
return True;
} else
return False;
}
|
COFS-UWA/MPM3D
|
SimulationsOMP/RigidObject/ContactModel3D.h
|
<filename>SimulationsOMP/RigidObject/ContactModel3D.h
#ifndef __Contact_Model_3D_h__
#define __Contact_Model_3D_h__
#include "Geometry3D.h"
#include "ParticleVariablesGetter.h"
class ContactModel3D
{
public:
struct Position { double x, y, z; };
struct Force { double x, y, z; };
explicit ContactModel3D();
virtual ~ContactModel3D();
virtual void cal_contact_force(
// in
size_t substp_id,
size_t ori_pcl_id,
double dist,
const Vector3D& norm,
const Point3D& cont_pos,
double pcl_len,
ParticleVariablesGetter &pv_getter,
// out
Vector3D &cont_force
) = 0;
inline static double sign(double num) noexcept { return num < 0.0 ? -1.0 : 1.0; }
};
#endif
|
wrapper755/diirt
|
graphene/graphene-rrdtool/src/test/java/org/epics/graphene/rrdtool/RrdToolOutputParserTest.java
|
<filename>graphene/graphene-rrdtool/src/test/java/org/epics/graphene/rrdtool/RrdToolOutputParserTest.java
/**
* Copyright (C) 2012-14 graphene developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.epics.graphene.rrdtool;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.epics.util.array.ListDouble;
import org.epics.util.time.Timestamp;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
/**
*
* @author carcassi
*/
public class RrdToolOutputParserTest {
public RrdToolOutputParserTest() {
}
@Test
public void parse1() {
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("rrdtool1.out")));
RrdToolOutputParser instance = new RrdToolOutputParser();
TimeSeriesMulti result = instance.parse(reader);
assertThat(result.getTime().size(), equalTo(241));
assertThat(result.getValues().size(), equalTo(1));
ListDouble values = result.getValues().get("load_1min");
assertThat(values.size(), equalTo(241));
assertThat(result.getTime().get(0), equalTo(Timestamp.of(1349877960, 0)));
assertThat(values.getDouble(0), equalTo(Double.NaN));
assertThat(result.getTime().get(150), equalTo(Timestamp.of(1349931960, 0)));
assertThat(values.getDouble(150), equalTo(1.1737083333e+00));
assertThat(result.getTime().get(240), equalTo(Timestamp.of(1349964360, 0)));
assertThat(values.getDouble(240), equalTo(Double.NaN));
}
@Test
public void parse2() {
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("rrdtool2.out")));
RrdToolOutputParser instance = new RrdToolOutputParser();
TimeSeriesMulti result = instance.parse(reader);
assertThat(result.getTime().size(), equalTo(241));
assertThat(result.getValues().size(), equalTo(18));
assertThat(result.getValues().keySet(), equalTo((Set<String>) new HashSet<String>(
Arrays.asList("Setpoint", "Fan1cfm", "Temp1", "Temp3", "Fan2Rpm", "TempOvrSet", "Fan2cfm", "Totalcfm", "Fan1Status", "Temp2", "Fan1Rpm", "Fan2Status", "Fan3cfm", "Fan3Rpm", "Fan3Status", "Fan4cfm", "Fan4Rpm", "Fan4Status"))));
ListDouble values = result.getValues().get("Temp1");
assertThat(values.size(), equalTo(241));
assertThat(result.getTime().get(0), equalTo(Timestamp.of(1355416920, 0)));
assertThat(values.getDouble(0), equalTo(9.2500000000e+01));
assertThat(result.getTime().get(150), equalTo(Timestamp.of(1355470920, 0)));
assertThat(values.getDouble(150), equalTo(9.1000000000e+01));
assertThat(result.getTime().get(240), equalTo(Timestamp.of(1355503320, 0)));
assertThat(values.getDouble(240), equalTo(Double.NaN));
}
}
|
AlisonBernardino/AlgosAndLogic-JAVA-
|
src/baseCourse/classes/class03/Architect.java
|
package baseCourse.classes.class03;
import java.util.Scanner;
public class Architect {
// Final value = No changes, "getters" or "setters" after the "final" definition
private final double salaryIncreaseIndex = 0.06;
private String architectFirstName;
private String architectRegisterCode;
private double architectSalary;
private String architectModality;
// Modalities =
// Alpha = Chief architect
// Beta = 2nd chief architect
// Standard = Common architect
public Architect(){
}
public Architect(String proMemberFirstName, String proMemberRegisterCode, double proMemberSalary){
super();
this.architectFirstName = proMemberFirstName;
this.architectRegisterCode = proMemberRegisterCode;
this.architectSalary = proMemberSalary;
}
// Salary boosts from "salaryBoost" method =
// >> Common architect = 15% added to salary + US$850,00
// >> Beta architect = 20% added to salary + US$1150,00
// >> Alpha architect = 25% added to salary + US$1450,00
public double getSalaryBoost(){
Scanner dataInsertion = new Scanner(System.in);
System.out.println("Insert the architect modality = ");
String modalityInput = dataInsertion.next();
if(modalityInput == "Standard"){
return this.architectSalary += (architectSalary * salaryIncreaseIndex) + 850.0;
}else if(modalityInput == "Beta"){
return this.architectSalary += (architectSalary * salaryIncreaseIndex) + 1150.0;
}else if(modalityInput == "Alpha"){
return this.architectSalary += (architectSalary * salaryIncreaseIndex) + 1450.0;
}else{
System.out.println("Error! It was not possible to identify the Architect modality. Please, try again!");
return 0;
}
}
// "Permanent salary increase" method
public double salaryIncrease(){
return this.architectSalary += (architectSalary * 0.13);
}
public String getArchitectFirstName() {
return architectFirstName;
}
public void setArchitectFirstName(String architectFirstName) {
this.architectFirstName = architectFirstName;
}
public String getArchitectRegisterCode() {
return architectRegisterCode;
}
public void setArchitectRegisterCode(String architectRegisterCode) {
this.architectRegisterCode = architectRegisterCode;
}
public double getArchitectSalary() {
// To return the architect salary + salary boost
return architectSalary + getSalaryBoost();
}
public void setArchitectSalary(double architectSalary) {
this.architectSalary = architectSalary;
}
public String getModality() {
return architectModality;
}
public void setModality(String architectModality) {
this.architectModality = architectModality;
}
}
|
MPDL/INGe
|
transformationManager/src/main/java/de/mpg/mpdl/inge/transformation/results/VoResult.java
|
<gh_stars>1-10
package de.mpg.mpdl.inge.transformation.results;
import de.mpg.mpdl.inge.model.valueobjects.ValueObject;
import de.mpg.mpdl.inge.transformation.exceptions.TransformationException;
import de.mpg.mpdl.inge.transformation.sources.TransformerSource;
import de.mpg.mpdl.inge.transformation.sources.TransformerVoSource;
public class VoResult extends TransformerResultAbstractImpl<ValueObject> implements TransformerResult {
public VoResult(ValueObject r) {
super(r);
}
public VoResult() {
super(null);
}
@Override
public TransformerSource createSourceFromInBetweenResult() throws TransformationException {
return new TransformerVoSource(this.getResult());
}
}
|
XUyongjie2000/Study-Java
|
Study day02/day02_2/src/com/czxy/demo1/Demo2_2.java
|
<filename>Study day02/day02_2/src/com/czxy/demo1/Demo2_2.java
package com.czxy.demo1;
public class Demo2_2 {
public static void main(String[] args) {
//特殊定义方式:先定义,后赋值
int aa;
aa=10;
aa=20;
aa=30;
System.out.println(aa);
}
}
|
NoMariusz/Praeteritum
|
match/tests/MatchWithCardDataTestCase.py
|
from django.test import TestCase
from match.logic.Match import Match
from .utils import make_test_users, make_match, make_test_card
class MatchWithCardDataTestCase(TestCase):
""" parent class for tests needing match, player indexes and unit set on
setUp method """
def setUp(self):
""" prepare variables for children """
# prepare match
test_players = make_test_users()
self.match: Match = make_match(test_players)
# made card for unit
card = make_test_card()
# prepare player indexes
self.p1_index = 0
self.p2_index = 1
# made card data
self.card_data: dict = self.match._cards_manager.made_card_data(
card)
|
youyouqiu/hybrid-development
|
clbs/src/main/java/com/zw/platform/dto/driverMiscern/DriverDiscernStatisticsExport.java
|
<filename>clbs/src/main/java/com/zw/platform/dto/driverMiscern/DriverDiscernStatisticsExport.java
package com.zw.platform.dto.driverMiscern;
import com.zw.platform.util.excel.annotation.ExcelField;
import lombok.Data;
/**
* @author denghuabing
* @version V1.0
* @description: TODO
* @date 2020/9/25
**/
@Data
public class DriverDiscernStatisticsExport {
/**
* 车辆名称
*/
@ExcelField(title = "监控对象")
private String monitorName;
/**
* 企业名称
*/
@ExcelField(title = "所属企业")
private String orgName;
@ExcelField(title = "比对结果")
private String identificationResultStr;
@ExcelField(title = "比对相似度")
private String matchRateStr;
@ExcelField(title = "比对相似度阈值")
private String matchThresholdStr;
@ExcelField(title = "比对类型")
private String identificationTypeStr;
private String driverId;
@ExcelField(title = "比对人脸id")
private String faceId;
@ExcelField(title = "比对驾驶员姓名")
private String driverName;
@ExcelField(title = "从业资格证号")
private String cardNumber;
@ExcelField(title = "比对时间")
private String identificationTimeStr;
}
|
electrolobzik/cupboard
|
library/src/androidTest/java/nl/qbusict/cupboard/StringArrayFieldConverter.java
|
package nl.qbusict.cupboard;
import android.content.ContentValues;
import android.database.Cursor;
import nl.qbusict.cupboard.convert.EntityConverter.ColumnType;
import nl.qbusict.cupboard.convert.FieldConverter;
public class StringArrayFieldConverter implements FieldConverter<String[]> {
@Override
public String[] fromCursorValue(Cursor cursor, int columnIndex) {
return cursor.getString(columnIndex).split(",");
}
@Override
public void toContentValue(String[] value, String key, ContentValues values) {
}
@Override
public ColumnType getColumnType() {
return ColumnType.JOIN;
}
}
|
twizoapi/lib-api-java
|
src/com/twizo/services/registrationwidget/JsonRegistrationWidgetService.java
|
<filename>src/com/twizo/services/registrationwidget/JsonRegistrationWidgetService.java<gh_stars>0
package com.twizo.services.registrationwidget;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.twizo.exceptions.RegistrationWidgetException;
import com.twizo.exceptions.TwizoJsonParseException;
import com.twizo.models.RegistrationWidget;
import com.twizo.services.AbstractService;
/**
* This file is part of the Twizo Java API
*
* For the full copyright and licence information, please view the Licence file that was distributed
* with this source code
*
* (c) Twizo - <EMAIL>
*/
public class JsonRegistrationWidgetService extends AbstractService implements
RegistrationWidgetService {
/**
* Parse RegistrationWidget data received from the server to a RegistrationWidget object
*
* @param data data to parse
* @return RegistrationWidget instance
* @throws RegistrationWidgetException when something goes wrong during the process
* @throws TwizoJsonParseException when something goes wrong during JSON parsing
*/
@Override
public RegistrationWidget parseRegistrationWidget(String data) throws RegistrationWidgetException, TwizoJsonParseException {
if (data != null) {
try {
JsonObject jsonObject = new JsonObject();
RegistrationWidget registrationWidget = gson.fromJson(data, RegistrationWidget.class);
return registrationWidget;
} catch (JsonSyntaxException ex) {
throw new TwizoJsonParseException(ex);
}
}
throw new RegistrationWidgetException("Twizo didn't respond as expected, please try again");
}
}
|
nixford/SoftUni-JavaScript-2020-TasksAndExams
|
JS-Advanced/Tasks/Function-Context-Exercise/01. Company.js
|
// 01. Company
class Company {
constructor(){
this.departments = []
}
addEmployee(username, salary, position, department){
if (!username || !salary || !position || !department) {
throw new Error("Invalid input!");
}
if (salary < 0) {
throw new Error("Invalid input!");
}
if (!this.departments[department]) {
this.departments[department] = [];
}
this.departments[department].push({username, salary, position});
return `New employee is hired. Name: ${username}. Position: ${position}`;
};
bestDepartment(){
let departmentsOutput = {};
Object.entries(this.departments).forEach(([department, employees]) => {
let totalSalary = employees.map(e => e.salary).reduce((acc, curr) => acc += curr);
departmentsOutput[department] = totalSalary / employees.length;
});
let maxSalary = 0;
let bestDepartment;
Object.entries(departmentsOutput).forEach(([department, avgSalary]) => {
if (avgSalary > maxSalary) {
maxSalary = avgSalary;
bestDepartment = department;
}
});
let output = `Best Department is: ${bestDepartment}\nAverage salary: ${maxSalary.toFixed(2)}\n`;
this.departments[bestDepartment]
.sort((a, b) => b.salary - a.salary || a.username.localeCompare(b.username))
.forEach(e => {
output += `${e.username} ${e.salary} ${e.position}\n`;
});
return output.trim();
};
}
|
NU-CBITS/telehealth_prim_engine
|
spec/models/telehealth_prim_engine/pre_screening_question_spec.rb
|
<reponame>NU-CBITS/telehealth_prim_engine
require "rails_helper"
module TelehealthPrimEngine
RSpec.describe PreScreeningQuestion, type: :model do
def valid_attributes
[{ pre_screening: PreScreening.new, label: "label", position: 1 }]
end
def invalid_attributes
[
{ pre_screening: nil, label: "label", position: 1 },
{ pre_screening: PreScreening.new, label: nil, position: 1 },
{ pre_screening: PreScreening.new, label: "abcd" * 60, position: 1 },
{ pre_screening: PreScreening.new, label: "label", position: -1 }
]
end
it "accepts valid attributes" do
valid_attributes.each do |a|
expect(PreScreeningQuestion.new(a)).to be_valid
end
end
it "rejects invalid attributes" do
invalid_attributes.each do |a|
expect(PreScreeningQuestion.new(a)).not_to be_valid
end
end
end
end
|
metaversethailand/snapshot-strategies
|
dist/strategies/holds-tokens/index.js
|
<reponame>metaversethailand/snapshot-strategies<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.strategy = exports.version = exports.author = void 0;
const multichain_1 = require("../multichain");
exports.author = 'lightninglu10';
exports.version = '0.1.0';
async function strategy(space, network, provider, addresses, options, snapshot) {
const tokens = options.tokenAddresses || [];
options.strategies = tokens.map((token) => ({
name: 'erc20-with-balance',
network: token.network,
params: {
address: token.address,
decimals: token.decimals,
minBalance: token.minBalance
}
}));
const scores = await (0, multichain_1.strategy)(space, network, provider, addresses, options, snapshot);
return Object.fromEntries(Object.entries(scores).map((address) => [
address[0],
address[1] === tokens.length ? 1 : 0
]));
}
exports.strategy = strategy;
|
CI6/gmchain-core
|
src/key_const.h
|
<gh_stars>1-10
//
// const_string.h
// gmchain-core
//
// Created by AnonymityMaster on 2019/12/22.
// Copyright © 2019 ci6. All rights reserved.
//
#ifndef key_const_h
#define key_const_h
#include <stdio.h>
static const char *KCType = "type"; // => 类型
static const char *KCPath = "path"; // => 路径
static const char *KCDatabase = "database"; // => 数据库
static const char *KCHost = "host"; // => 主机
static const char *KCPort = "port"; // => 端口
static const char *KCUser = "user"; // => 用户
static const char *KCPassword = "password"; // => 密码
static const char *KCProposal = "proposal"; // => 提案
static const char *KCDelay = "delay"; // => 延时
static const char *KCVoteDelay = "vote"; // => 投票
static const char *KCEnable = "enable"; // => 启用
static const char *KCLog = "log"; // => 日志
static const char *KCLevel = "level"; // => 级别
static const char *KCAddress = "address"; // => 地址
static const char *KCPublicKey = "public_key"; // => 公钥
static const char *KCPrivateKey = "private_key"; // => 私匙
static const char *KCEnvDevelopment = "development"; // => 开发环境
static const char *KCEnvTest = "test"; // => 测试环境
static const char *KCEnvProduction = "production"; // => 生产环境
static const char *KCTRACE = "TRACE"; // => 日志[DEBUG]
static const char *KCDEBUG = "DEBUG"; // => 日志[DEBUG]
static const char *KCINFO = "INFO"; // => 日志[INFO]
static const char *KCWARN = "WARN"; // => 日志[WARN]
static const char *KCERROR = "ERROR"; // => 日志[ERROR]
static const char *KCFATAL = "FATAL"; // => 日志[FATAL]
static const char *KCBlockStorePath = "block_store_path"; // => 区块存储路径
#endif /* key_const_h */
|
EyeOfDarkness/Arc
|
extensions/box2d/src/arc/box2d/JointEdge.java
|
package arc.box2d;
/**
* A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an
* edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for
* each attached body.
*/
public class JointEdge{
public final Body other;
public final Joint joint;
protected JointEdge(Body other, Joint joint){
this.other = other;
this.joint = joint;
}
}
|
npocmaka/Windows-Server-2003
|
admin/netui/macprint/pstodib/ti/src/font/fontenco.h
|
<gh_stars>10-100
/*
* Copyright (c) 1989,90 Microsoft Corporation
*/
/* @WIN; take out the static def of dict data. The tables will be allocated
* thru global alloc, and contents be loaded at run time, in "fontinit.c".
*/
#ifdef KANJI
/* ********************************************************************** */
/* File: fontencod.h Created by <NAME> 06-20-1990 */
/* */
/* Structure and table for encoding array of EncodingDirectory */
/* */
/* ********************************************************************** */
typedef struct {
fix16 array_idx;
char FAR *char_name; /*@WIN*/
} encoding_data;
typedef struct {
char FAR *encoding_name; /*@WIN*/
fix16 encod_type;
fix16 encod_size;
} encoding_table_s;
static encoding_table_s Encoding_table[] = {
{"JISEncoding", NAMETYPE, 256},
{"ShiftJISEncoding", NAMETYPE, 256},
{"ExtShiftJIS-A-CFEncoding", INTEGERTYPE, 31},
{"KatakanaEncoding", NAMETYPE, 256},
{"NotDefEncoding", NAMETYPE, 256},
{(char FAR *)NULL, (fix16)0, (fix16)0} }; /*@WIN*/
/* @WIN ---begin--- move def out; to be loaded at run time, in "fontinit.c" */
extern encoding_data FAR * JISEncoding_Enco;
extern encoding_data FAR * ShiftJISEncoding_Enco;
extern encoding_data FAR * ExtShiftJIS_A_CFEncoding_Enco;
extern encoding_data FAR * KatakanaEncoding_Enco;
static encoding_data FAR *Encoding_array[5];
/* @WIN --- end --- */
static encoding_data NotDefEncoding_Enco[]={ { 0,(char FAR *)NULL } }; /*@WIN*/
#endif /*KANJI*/
/* -------------------- End of fontencod.h ------------------------------- */
|
hydra41/constellation
|
CoreGraphFramework/src/au/gov/asd/tac/constellation/graph/undo/NormalisingGraphEdit.java
|
<reponame>hydra41/constellation<filename>CoreGraphFramework/src/au/gov/asd/tac/constellation/graph/undo/NormalisingGraphEdit.java
/*
* Copyright 2010-2019 Australian Signals Directorate
*
* 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 au.gov.asd.tac.constellation.graph.undo;
import au.gov.asd.tac.constellation.graph.GraphElementType;
import au.gov.asd.tac.constellation.graph.GraphIndexType;
import au.gov.asd.tac.constellation.graph.GraphOperation;
import au.gov.asd.tac.constellation.graph.GraphWriteMethods;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author sirius
*/
public class NormalisingGraphEdit implements GraphEdit {
private final GraphEdit graphEdit;
private static final String NOT_SUPPORTED = "Not supported yet.";
public NormalisingGraphEdit(GraphEdit graphEdit) {
this.graphEdit = graphEdit;
}
@Override
public void execute(GraphWriteMethods graph) {
graphEdit.execute(graph);
}
@Override
public void undo(GraphWriteMethods graph) {
graphEdit.undo(graph);
}
@Override
public void addChild(GraphEdit childEdit) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void finish() {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setPrimaryKey(GraphElementType elementType, int[] oldKeys, int[] newKeys) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void addVertex(int vertex) {
Vertex newVertex = new Vertex(vertex);
Vertex currentVertex = vertices.put(vertex, newVertex);
if (currentVertex != null) {
newVertex.setPrevious(currentVertex);
newVertex.setVersion(currentVertex.getVersion() + 1);
}
}
@Override
public void removeVertex(int vertex) {
Vertex currentVertex = vertices.get(vertex);
if (currentVertex == null) {
currentVertex = new Vertex(vertex);
vertices.put(vertex, currentVertex);
}
currentVertex.setDeleted(true);
}
@Override
public void addTransaction(int sourceVertex, int destinationVertex, boolean directed, int transaction) {
Vertex currentSource = vertices.get(sourceVertex);
if (currentSource == null) {
currentSource = new Vertex(sourceVertex);
vertices.put(sourceVertex, currentSource);
}
Vertex currentDestination = vertices.get(destinationVertex);
if (currentDestination != null) {
currentDestination = new Vertex(destinationVertex);
vertices.put(destinationVertex, currentDestination);
}
Transaction newTransaction = new Transaction(transaction);
// newTransaction.source = currentSource;
// newTransaction.destination = currentDestination;
newTransaction.directed = directed;
Transaction currentTransaction = transactions.put(transaction, newTransaction);
if (currentTransaction != null) {
newTransaction.setPrevious(currentTransaction);
newTransaction.setVersion(currentTransaction.getVersion() + 1);
}
}
@Override
public void removeTransaction(int sourceVertex, int destinationVertex, boolean directed, int transaction) {
Transaction currentTransaction = transactions.get(transaction);
if (currentTransaction == null) {
Vertex currentSource = vertices.get(sourceVertex);
if (currentSource == null) {
currentSource = new Vertex(sourceVertex);
vertices.put(sourceVertex, currentSource);
}
Vertex currentDestination = vertices.get(destinationVertex);
if (currentDestination != null) {
currentDestination = new Vertex(destinationVertex);
vertices.put(destinationVertex, currentDestination);
}
currentTransaction = new Transaction(transaction);
// currentTransaction.source = currentSource;
// currentTransaction.destination = currentDestination;
currentTransaction.directed = directed;
transactions.put(transaction, currentTransaction);
}
currentTransaction.setDeleted(true);
}
@Override
public void setTransactionSourceVertex(int transaction, int oldSourceVertex, int newSourceVertex, boolean reverseTransaction) {
Vertex newSource = vertices.get(newSourceVertex);
if (newSource == null) {
newSource = new Vertex(newSourceVertex);
vertices.put(newSourceVertex, newSource);
}
Transaction currentTransaction = transactions.get(transaction);
if (currentTransaction == null) {
currentTransaction = new Transaction(transaction);
transactions.put(transaction, currentTransaction);
}
// currentTransaction.source = newSource;
}
@Override
public void setTransactionDestinationVertex(int transaction, int oldDestinationVertex, int newDestinationVertex, boolean reverseTransaction) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void addAttribute(GraphElementType elementType, String attributeType, String label, String description, Object defaultValue, String attributeMergerId, int attribute) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void removeAttribute(GraphElementType elementType, String attributeType, String label, String description, Object defaultValue, String attributeMergerId, int attribute) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void updateAttributeName(int attribute, String oldName, String newName) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void updateAttributeDescription(int attribute, String oldDescription, String newDescription) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void updateAttributeDefaultValue(int attribute, Object oldObject, Object newObject) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setByteValue(int attribute, int id, byte oldValue, byte newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setShortValue(int attribute, int id, short oldValue, short newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setIntValue(int attribute, int id, int oldValue, int newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setLongValue(int attribute, int id, long oldValue, long newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setFloatValue(int attribute, int id, float oldValue, float newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setDoubleValue(int attribute, int id, double oldValue, double newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setBooleanValue(int attribute, int id, boolean oldValue, boolean newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setCharValue(int attribute, int id, char oldValue, char newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setObjectValue(int attribute, int id, Object oldValue, Object newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void executeGraphOperation(GraphOperation operation) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setAttributeIndexType(int attribute, GraphIndexType oldValue, GraphIndexType newValue) {
throw new UnsupportedOperationException(NOT_SUPPORTED); //To change body of generated methods, choose Tools | Templates.
}
private class Element<E> {
public final int id;
private boolean deleted = false;
private int version;
private E previous = null;
public Element(int id) {
this.id = id;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public E getPrevious() {
return previous;
}
public void setPrevious(E previous) {
this.previous = previous;
}
}
private class Vertex extends Element<Vertex> {
public Vertex(int id) {
super(id);
}
}
private final Map<Integer, Vertex> vertices = new HashMap<>();
private class Transaction extends Element<Transaction> {
//TODO: Determine whether unused fields are needed
private Vertex newSource;
private Vertex oldSource;
private Vertex newDestination;
private Vertex oldDestination;
private boolean directed;
public Transaction(int id) {
super(id);
}
}
private final Map<Integer, Transaction> transactions = new HashMap<>();
}
|
ThibaultLatrille/ControverSciences
|
config/application.rb
|
<filename>config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SampleApp
class Application < Rails::Application
# TODO Stop-gap workaround to carrierwave doing "require 'fog'"
# This let's us get ./lib in the load path, where our own
# fog.rb is loaded for carrierwave, but we've already loaded
# fog-aws, which is all we need anyway.
config.before_configuration do
require 'carrierwave'
end
require 'ext/string'
config.assets.paths << "#{Rails}/vendor/assets/fonts"
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
I18n.enforce_available_locales = true
I18n.available_locales = :en, :fr
I18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
I18n.default_locale = :fr
end
end
|
ZhuJunJi/base_cloud
|
system-user/user-microservice-mapper/src/main/java/com/zhujunji/user/domain/SysUserDO.java
|
<gh_stars>0
package com.zhujunji.user.domain;
import com.zhujunji.common.domain.BaseObject;
import lombok.Data;
/**
*
* @author J.zhu
* @date 2019/7/11
*/
@Data
public class SysUserDO extends BaseObject {
/**
* 用户ID
*/
private Long userId;
/**
* 用户名称
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickname;
/**
* 邮件
*/
private String email;
/**
* 状态(0:锁定,1:解锁)
*/
private Integer status = 0;
}
|
skylarbpayne/parseq
|
contrib/parseq-restli-client/src/test/java/com/linkedin/restli/examples/greetings/client/StreamingGreetingsRequestBuilders.java
|
package com.linkedin.restli.examples.greetings.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import javax.annotation.Generated;
import com.linkedin.data.template.DataTemplateUtil;
import com.linkedin.data.template.DynamicRecordMetadata;
import com.linkedin.data.template.FieldDef;
import com.linkedin.restli.client.OptionsRequestBuilder;
import com.linkedin.restli.client.RestliRequestOptions;
import com.linkedin.restli.client.base.BuilderBase;
import com.linkedin.restli.common.ResourceMethod;
import com.linkedin.restli.common.ResourceSpec;
import com.linkedin.restli.common.ResourceSpecImpl;
import com.linkedin.restli.examples.greetings.api.Greeting;
/**
* generated from: com.linkedin.restli.examples.greetings.server.StreamingGreetings
*
*/
@Generated(value = "com.linkedin.pegasus.generator.JavaCodeUtil", comments = "Rest.li Request Builder. Generated from /Users/jodzga/dev/pegasus_trunk/pegasus/restli-int-test-api/src/main/idl/com.linkedin.restli.examples.greetings.client.streamingGreetings.restspec.json.", date = "Wed Apr 06 14:21:38 PDT 2016")
public class StreamingGreetingsRequestBuilders
extends BuilderBase
{
private final static String ORIGINAL_RESOURCE_PATH = "streamingGreetings";
private final static ResourceSpec _resourceSpec;
static {
HashMap<String, DynamicRecordMetadata> requestMetadataMap = new HashMap<String, DynamicRecordMetadata>();
ArrayList<FieldDef<?>> actionAttachmentsAllowedButDislikedParams = new ArrayList<FieldDef<?>>();
requestMetadataMap.put("actionAttachmentsAllowedButDisliked", new DynamicRecordMetadata("actionAttachmentsAllowedButDisliked", actionAttachmentsAllowedButDislikedParams));
ArrayList<FieldDef<?>> actionNoAttachmentsAllowedParams = new ArrayList<FieldDef<?>>();
requestMetadataMap.put("actionNoAttachmentsAllowed", new DynamicRecordMetadata("actionNoAttachmentsAllowed", actionNoAttachmentsAllowedParams));
HashMap<String, DynamicRecordMetadata> responseMetadataMap = new HashMap<String, DynamicRecordMetadata>();
responseMetadataMap.put("actionAttachmentsAllowedButDisliked", new DynamicRecordMetadata("actionAttachmentsAllowedButDisliked", Collections.singletonList(new FieldDef<Boolean>("value", Boolean.class, DataTemplateUtil.getSchema(Boolean.class)))));
responseMetadataMap.put("actionNoAttachmentsAllowed", new DynamicRecordMetadata("actionNoAttachmentsAllowed", Collections.singletonList(new FieldDef<Integer>("value", Integer.class, DataTemplateUtil.getSchema(Integer.class)))));
HashMap<String, com.linkedin.restli.common.CompoundKey.TypeInfo> keyParts = new HashMap<String, com.linkedin.restli.common.CompoundKey.TypeInfo>();
_resourceSpec = new ResourceSpecImpl(EnumSet.of(ResourceMethod.GET, ResourceMethod.CREATE, ResourceMethod.UPDATE, ResourceMethod.DELETE), requestMetadataMap, responseMetadataMap, Long.class, null, null, Greeting.class, keyParts);
}
public StreamingGreetingsRequestBuilders() {
this(RestliRequestOptions.DEFAULT_OPTIONS);
}
public StreamingGreetingsRequestBuilders(RestliRequestOptions requestOptions) {
super(ORIGINAL_RESOURCE_PATH, requestOptions);
}
public StreamingGreetingsRequestBuilders(String primaryResourceName) {
this(primaryResourceName, RestliRequestOptions.DEFAULT_OPTIONS);
}
public StreamingGreetingsRequestBuilders(String primaryResourceName, RestliRequestOptions requestOptions) {
super(primaryResourceName, requestOptions);
}
public static String getPrimaryResource() {
return ORIGINAL_RESOURCE_PATH;
}
public OptionsRequestBuilder options() {
return new OptionsRequestBuilder(getBaseUriTemplate(), getRequestOptions());
}
public StreamingGreetingsUpdateRequestBuilder update() {
return new StreamingGreetingsUpdateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public StreamingGreetingsDeleteRequestBuilder delete() {
return new StreamingGreetingsDeleteRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public StreamingGreetingsGetRequestBuilder get() {
return new StreamingGreetingsGetRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public StreamingGreetingsCreateRequestBuilder create() {
return new StreamingGreetingsCreateRequestBuilder(getBaseUriTemplate(), _resourceSpec, getRequestOptions());
}
public StreamingGreetingsDoActionAttachmentsAllowedButDislikedRequestBuilder actionActionAttachmentsAllowedButDisliked() {
return new StreamingGreetingsDoActionAttachmentsAllowedButDislikedRequestBuilder(getBaseUriTemplate(), Boolean.class, _resourceSpec, getRequestOptions());
}
public StreamingGreetingsDoActionNoAttachmentsAllowedRequestBuilder actionActionNoAttachmentsAllowed() {
return new StreamingGreetingsDoActionNoAttachmentsAllowedRequestBuilder(getBaseUriTemplate(), Integer.class, _resourceSpec, getRequestOptions());
}
}
|
faizol/timescaledb
|
src/debug_guc.h
|
<filename>src/debug_guc.h
/*
* This file and its contents are licensed under the Apache License 2.0.
* Please see the included NOTICE for copyright information and
* LICENSE-APACHE for a copy of the license.
*/
#ifndef TIMESCALEDB_DEBUG_GUC_H
#define TIMESCALEDB_DEBUG_GUC_H
#include <postgres.h>
#include <fmgr.h>
#include <utils/guc.h>
#include "export.h"
/*
* Enable printout inside ts_create_upper based on the stage provided. It is
* possible to enable printout for multiple stages, so we take the existing
* stage list and create a mask from it.
*/
#define STAGE_SETOP (1UL << UPPERREL_SETOP) /* Enabled using "setop" */
#define STAGE_PARTIAL_GROUP_AGG \
(1UL << UPPERREL_PARTIAL_GROUP_AGG) /* Enabled using "partial_group_agg" */
#define STAGE_GROUP_AGG (1UL << UPPERREL_GROUP_AGG) /* Enabled using "group_agg" */
#define STAGE_WINDOW (1UL << UPPERREL_WINDOW) /* Enabled using "window" */
#define STAGE_DISTINCT (1UL << UPPERREL_DISTINCT) /* Enabled using "distinct" */
#define STAGE_ORDERED (1UL << UPPERREL_ORDERED) /* Enabled using "ordered" */
#define STAGE_FINAL (1UL << UPPERREL_FINAL) /* Enabled using "final" */
/*
* Debug flags for the optimizer.
*
* Add new flags here as you see fit, but don't forget to update the flag list
* `flag_names` in guc.c.
*/
typedef struct DebugOptimizerFlags
{
/* Bit mask to represent set of UpperRelationKind, which is used as the
* stage inside create_upper. */
unsigned long show_upper;
bool show_rel;
} DebugOptimizerFlags;
extern TSDLLEXPORT DebugOptimizerFlags ts_debug_optimizer_flags;
extern void ts_debug_init(void);
#endif /* TIMESCALEDB_DEBUG_GUC_H */
|
compbiol/CAMSA
|
camsa/utils/fasta/camsa_points2fasta.py
|
<filename>camsa/utils/fasta/camsa_points2fasta.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import datetime
import logging
import numbers
import os
import sys
from collections import defaultdict
import Bio
import configargparse
import networkx
from Bio import SeqIO
from Bio.Alphabet import generic_dna
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
import camsa
from camsa.core.io import read_pairs, read_seqi_from_input_sources
from camsa.core.data_structures import get_scaffold_edges, Sequence
from camsa.utils.fasta.data_structures import IntraGapFilling, FlankingGapFilling
def get_scaffold_name_from_vertex(v):
return v[:-1]
def reverse_or(orientaiton):
return "+" if orientaiton == "-" else "-"
def reverse_ap(f1, f1_or, f2, f2_or):
return f2, reverse_or(orientaiton=f2_or), f1, reverse_or(orientaiton=f1_or)
def get_assembly_edge(graph):
for edge in graph.edges():
v1, v2 = edge
if v1[:-1] != v2[:-1]:
return edge
return None, None
def get_sequence_of_fragments_from_path(path, assembly_points_by_edges):
path, path_type = path
if len(path) < 2:
logger.error("A sequence resembling an assembly points, that contains less than two scaffolds. Something went wrong.")
exit(1)
result = []
for frag_extremity_v1, frag_extremity_v2 in zip(path[1::2], path[2::2]):
f1_or = "+" if frag_extremity_v1.endswith("h") else "-"
f2_or = "-" if frag_extremity_v2.endswith("h") else "+"
ap = assembly_points_by_edges[tuple(sorted([frag_extremity_v1, frag_extremity_v2]))]
gap_size = ap.gap_size
result.append((get_scaffold_name_from_vertex(v=frag_extremity_v1), f1_or,
get_scaffold_name_from_vertex(v=frag_extremity_v2), f2_or,
gap_size))
return result
if __name__ == "__main__":
full_description = camsa.full_description_template.format(
names=camsa.CAMSA_AUTHORS,
affiliations=camsa.AFFILIATIONS,
dummy=" ",
tool="Converting CAMSA formatted scaffolding results into FASTA files.",
information="For more information refer to {docs}".format(docs=camsa.CAMSA_DOCS_URL),
contact=camsa.CONTACT)
full_description = "=" * 80 + "\n" + full_description + "=" * 80 + "\n"
parser = configargparse.ArgParser(description=full_description, formatter_class=configargparse.RawTextHelpFormatter,
default_config_files=[os.path.join(camsa.root_dir, "utils", "fasta", "camsa_points2fasta.ini"),
os.path.join(camsa.root_dir, "logging.ini")])
parser.add_argument("-c", "--config", is_config_file=True, help="Config file overwriting some of the default settings as well as any flag starting with \"--\".")
parser.add_argument("--version", action="version", version=camsa.VERSION)
parser.add_argument("--fasta", type=configargparse.FileType("rt"), required=True,
help="A stream of fasta formatted sequences of scaffolds, that participate in the scaffold assembly represented in form of CAMSA points")
parser.add_argument("--points", type=configargparse.FileType("rt"), required=True,
help="A stream of CAMSA formatted assembly points, representing a scaffold assembly, that is converted into FASTA formatted sequences")
parser.add_argument("--allow-singletons", action="store_true", dest="allow_singletons", default=False,
help="Whether to include scaffolds, that were not mentioned in the CAMSA formatted assembly points\nDEFAULT: False")
parser.add_argument("--c-sep", type=str,
help="A symbol, that is used to indicate gaps between scaffolds in the translated assemblies\nDEFAULT: N")
parser.add_argument("--c-sep-length", type=int,
help="A default length, that is used for the gap size between scaffolds in the translated assemblies. Used in case, when gap-size column has \"?\" value\nDEFAULT: 20")
parser.add_argument("--scaffold-name-template", type=str,
help="Python string template for the scaffold ids, in the produced FASTA formatted sequences. \"cnt\" attribute can be utilized\nDEFAULT: scaffold_{cnt}")
parser.add_argument("-o", "--output", type=configargparse.FileType("wt"), default=sys.stdout,
help="A stream to which the FASTA formatted converted sequence, representing the CAMSA formatted scaffold assembly, is output\nDEFAULT: stdout")
parser.add_argument("--c-logging-level", dest="logging_level", default=logging.INFO, type=int,
choices=[logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL],
help="Logging level for the converter.\nDEFAULT: {info}".format(info=logging.INFO))
parser.add_argument("--c-logging-formatter-entry",
help="Format string for python logger.")
args = parser.parse_args()
start_time = datetime.datetime.now()
logger = logging.getLogger("CAMSA.utils.camsa_points2fasta")
ch = logging.StreamHandler()
ch.setLevel(args.logging_level)
logger.setLevel(args.logging_level)
logger.addHandler(ch)
logger.info(full_description)
logger.info(parser.format_values())
ch.setFormatter(logging.Formatter(args.c_logging_formatter_entry))
logger.info("Starting the converting process")
logger.info("Reading assembly points")
assembly_points_by_sources = defaultdict(list)
read_pairs(source=args.points, destination=assembly_points_by_sources)
assembly_points_by_sources = [ap for ap_list in assembly_points_by_sources.values() for ap in ap_list]
logger.info("A total of {ap_cnt} assembly points was obtained".format(ap_cnt=len(assembly_points_by_sources)))
assembly_graph = networkx.Graph()
scaffold_edges = get_scaffold_edges(assembly_points=assembly_points_by_sources)
assembly_graph.add_edges_from(scaffold_edges)
assembly_points_by_edges = {}
for ap in assembly_points_by_sources:
for (u, v, weight) in ap.get_edges(sort=True, weight=True):
assembly_graph.add_edge(u, v)
assembly_points_by_edges[tuple(sorted([u, v]))] = ap
logger.debug("Checking that there are no in(semi)conflicting assembly points")
for vertex in assembly_graph.nodes():
degree = assembly_graph.degree[vertex]
if degree > 2:
scaffold_name = get_scaffold_name_from_vertex(v=vertex)
logger.error("Supplied assembly contained a conflict.")
logger.error("Scaffold {scaffold_name} by its extremity {extremity_name} is reported as adjacent to more than one other scaffold's extremity"
"".format(scaffold_name=scaffold_name, extremity_name=vertex))
exit(1)
logger.debug("All clear, no (semi)conflicts, we can proceed")
logger.info("Processing assemblies constructed from obtained assembly points")
logger.debug("Extracting paths from assembly graph")
paths = []
for cc in networkx.connected_components(G=assembly_graph):
cc = assembly_graph.subgraph(cc).copy()
origins = [v for v in cc.nodes() if cc.degree[v] == 1]
if len(origins) == 2:
path = networkx.shortest_path(G=cc, source=origins[0], target=origins[1])
logger.debug("Extracted a linear scaffold of length {scaffold_length}, staring with {s_v} and ending with {e_v}"
"".format(scaffold_length=int(len(path) / 2),
s_v=get_scaffold_name_from_vertex(v=origins[0]),
e_v=get_scaffold_name_from_vertex(v=origins[1])))
paths.append((path, "l"))
if len(origins) == 1:
logger.error("Something is wrong with the assembly graph. We have a connected component with a single vertex of degree 1.")
exit(1)
if len(origins) == 0:
logger.debug("Encountered a circular chromosome. Splitting it at random assembly point")
assembly_edge = get_assembly_edge(graph=cc)
if assembly_edge[0] is None or assembly_edge[1] is None:
logger.error("Something is wrong with the assembly graph. Couldn't find a scaffold edge in a circular scaffold.")
exit(1)
cc.remove_edge(u=assembly_edge[0], v=assembly_edge[1])
path = networkx.shortest_path(G=cc, source=assembly_edge[0], target=assembly_edge[1])
paths.append((path, "c"))
logger.debug("Total number of extracted paths is {path_cnt}".format(path_cnt=len(paths)))
logger.debug("Out of which {linear_cnt} are linear, and {circular_cnt} are circular"
"".format(linear_cnt=len([p for p in paths if p[1] == "l"]),
circular_cnt=len([p for p in paths if p[1] == "c"])))
fragments = [get_sequence_of_fragments_from_path(path=p, assembly_points_by_edges=assembly_points_by_edges) for p in paths]
logger.info("Total number of {scaffold_cnt} scaffolds was obtained from observed assembly points".format(scaffold_cnt=len(fragments)))
logger.info("Reading fasta of contigs/scaffolds from {file}".format(file=args.fasta))
frag_fasta_by_id = {}
s_cnt = 0
for record in SeqIO.parse(args.fasta, "fasta"):
frag_fasta_by_id[record.id] = record
s_cnt += 1
logger.debug("Processed {cnt} records from fasta file \"{file_name}\"".format(cnt=s_cnt, file_name=args.fasta))
logger.info("Total number of contig/scaffold sequences is {seq_cnt}".format(seq_cnt=len(frag_fasta_by_id)))
for fragment_aps in fragments:
for f1, f1_or, f2, f2_or, gap_size in fragment_aps:
if f1 not in frag_fasta_by_id or f2 not in frag_fasta_by_id:
logging.critical("Fragment {f1} or {f2} which is present assembly points is not present in supplied fasta file. Exiting.".format(f1=f1, f2=f2))
exit(1)
used_fragments = set()
logger.info("Outputting new scaffolds. Data is written to {file_name}".format(file_name=args.output))
for s_cnt, fragment_aps in enumerate(fragments):
current = Seq("")
for f_cnt, (f1, f1_or, f2, f2_or, gap_size) in enumerate(fragment_aps):
used_fragments.add(f1)
used_fragments.add(f2)
if f1_or == "+":
current += frag_fasta_by_id[f1].seq
else:
current += frag_fasta_by_id[f1].reverse_complement().seq
sep_length = gap_size if isinstance(gap_size, numbers.Number) else args.c_sep_length
if sep_length <= 0:
sep_length = args.c_sep_length
current += Seq(args.c_sep * int(sep_length))
if f_cnt == len(fragment_aps) - 1:
if f2_or == "+":
current += frag_fasta_by_id[f2].seq
else:
current += frag_fasta_by_id[f2].reverse_complement().seq
name = args.scaffold_name_template.format(cnt=s_cnt)
seq_record = SeqRecord(seq=current, id=name, description="")
SeqIO.write(sequences=seq_record, handle=args.output, format="fasta")
if args.allow_singletons:
logger.info("Adding singleton fragments, that did not participate in any assembly points to the resulting assmebly")
for f_id, fragment in frag_fasta_by_id.items():
if f_id not in used_fragments:
SeqIO.write(sequences=fragment, handle=args.output, format="fasta")
logger.info("All done!")
logger.info("Elapsed time: {el_time}".format(el_time=str(datetime.datetime.now() - start_time)))
|
ViniGom3/repool-front
|
src/views/anuncio/AnuncioDetailsView/index.js
|
/* eslint-disable no-nested-ternary */
import {
Button,
Container,
Divider,
Grid,
IconButton,
List,
makeStyles,
Typography,
} from '@material-ui/core';
import { red } from '@material-ui/core/colors';
import DeleteIcon from '@material-ui/icons/Delete';
import DoneAllIcon from '@material-ui/icons/DoneAll';
import FavoriteIcon from '@material-ui/icons/Favorite';
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import HandIcon from '@material-ui/icons/PanTool';
import StarIcon from '@material-ui/icons/StarRate';
import { Rating } from '@material-ui/lab';
import PropTypes from 'prop-types';
import React, { useContext, useEffect, useState } from 'react';
import CustomSnackbar from 'src/components/CustomSnackbar';
import Page from 'src/components/Page';
import AnuncioContext from 'src/contexts/AnuncioContext';
import AuthContext from 'src/contexts/AuthContext';
import PropriedadeContext from 'src/contexts/PropriedadeContext';
import AnuncioDescription from './AnuncioDescription';
import ComentarioItem from './ComentarioItem';
import ComodidadeItem from './ComodidadeItem';
import ImageList from './ImageList';
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: theme.palette.background.dark,
minHeight: '100%',
paddingBottom: theme.spacing(3),
paddingTop: theme.spacing(3),
},
titleContainer: {
paddingTop: '2em',
paddingBottom: '2em',
},
favoriteText: {
marginLeft: '5%',
},
textGutterBottom: {
marginBottom: '0.5em',
},
pageBottomContainer: {
paddingTop: '3em',
paddingBottom: '3em',
},
commentList: {
width: '100%',
maxWidth: '100%',
overflow: 'auto',
maxHeight: '15em',
paddingTop: '0',
paddingBottom: '0',
},
interestButton: {
height: '3.5em',
},
removeButton: {
height: '3.5em',
color: '#FFFFFF',
backgroundColor: red[400],
'&:hover': {
backgroundColor: red[700],
},
},
}));
const AnuncioDetails = ({ className, ...rest }) => {
const classes = useStyles();
const { activeAnuncio, fetchActiveAnuncio, toggleInterest, toggleFavorite } = useContext(
AnuncioContext
);
const { subscriberConfirmRent, subscriberRemoveRent } = useContext(PropriedadeContext);
const { favorites, user, userToken } = useContext(AuthContext);
const { comodidades } = activeAnuncio;
const [snackbarMessage, setSnackbarMessage] = useState('');
const handleCloseSnackbar = () => {
setSnackbarMessage('');
};
const handleFavoritePress = async () => {
const message = await toggleFavorite(activeAnuncio.id);
setSnackbarMessage(message);
};
const handleInterestPress = async () => {
const message = await toggleInterest(activeAnuncio.id);
setSnackbarMessage(message);
};
const handleConfirmRent = async () => {
const message = await subscriberConfirmRent(activeAnuncio.interest.id);
setSnackbarMessage(message);
};
const handleRemoveRent = async () => {
const message = await subscriberRemoveRent(activeAnuncio.rent.id);
setSnackbarMessage(message);
};
useEffect(() => {
const { pathname } = window.location;
const activeAnuncioId = pathname.replace('/anuncios/', '');
const fetchOneAd = async () => {
const message = await fetchActiveAnuncio(activeAnuncioId);
setSnackbarMessage(message);
};
fetchOneAd();
}, [favorites, user]);
return (
<Page className={classes.root} title='Anúncio'>
<Container className={classes.titleContainer}>
<Grid
justify='space-between'
alignItems='center'
spacing={2}
container
className={classes.textGutterBottom}
>
<Grid item>
<Typography variant='h1'>{activeAnuncio.name}</Typography>
</Grid>
{userToken && user.role !== 'ADMIN' ? (
<Grid item>
{!activeAnuncio.rent ? (
<Grid container spacing={2}>
<Grid item>
{activeAnuncio.isInterest ? (
<Button
className={classes.removeButton}
fullWidth
variant='contained'
startIcon={<DeleteIcon />}
onClick={handleInterestPress}
>
Remover Interesse
</Button>
) : (
<Button
color='primary'
className={classes.interestButton}
fullWidth
variant='contained'
startIcon={<HandIcon />}
onClick={handleInterestPress}
>
Demonstrar Interesse
</Button>
)}
</Grid>
{activeAnuncio.interest && activeAnuncio.interest.pConfirmation ? (
<Grid item>
<Button
color='primary'
className={classes.interestButton}
fullWidth
variant='contained'
startIcon={<DoneAllIcon />}
onClick={handleConfirmRent}
>
Confirmar aluguel
</Button>
</Grid>
) : (
''
)}
</Grid>
) : (
<Grid item>
<Button
className={classes.removeButton}
fullWidth
variant='contained'
startIcon={<DeleteIcon />}
onClick={handleRemoveRent}
>
Desfazer aluguel
</Button>
</Grid>
)}
</Grid>
) : (
<></>
)}
</Grid>
<Grid container justify='space-between' alignItems='baseline' spacing={2}>
<Grid item>
<Rating
name='read-only'
value={activeAnuncio.avg ? activeAnuncio.avg.value : null}
precision={0.2}
readOnly
/>
</Grid>
<IconButton onClick={handleFavoritePress}>
{userToken ? (
activeAnuncio.isFavorite ? (
<>
<FavoriteIcon color='action' />
<Typography className={classes.favoriteText} variant='h4'>
Desfavoritar
</Typography>
</>
) : (
<>
<FavoriteBorderIcon color='action' />
<Typography className={classes.favoriteText} variant='h4'>
Favoritar
</Typography>
</>
)
) : (
<></>
)}
</IconButton>
</Grid>
</Container>
<ImageList images={activeAnuncio.img} />
<AnuncioDescription anuncio={activeAnuncio} />
<Divider />
<Container className={classes.pageBottomContainer}>
<Grid container direction='row' wrap='wrap' spacing={10}>
<Grid item xs={12} sm={6}>
<Grid container direction='column' justify='space-evenly' spacing={6}>
<Grid item>
<Typography gutterBottom variant='h2'>
Comodidades
</Typography>
</Grid>
{comodidades && comodidades.length > 0 ? (
comodidades.map((comodidade) => <ComodidadeItem nome={comodidade.nome} />)
) : (
<Grid item>
<Typography variant='h4'>
Nenhuma comodidade cadastrada nesta propriedade
</Typography>
</Grid>
)}
</Grid>
</Grid>
{activeAnuncio.comentarios > 0 ? (
<Grid item xs={12} sm={6}>
<Grid container direction='column' justify='space-evenly' spacing={6}>
<Grid item>
<Grid container direction='row' wrap='nowrap' spacing={2}>
<Grid item>
<StarIcon color='action' fontSize='large' style={{ color: '#3F51B5' }} />
</Grid>
<Grid item>
<Typography gutterBottom variant='h2'>
{/* TODO nota e quantidade de comentarios */}
{`${activeAnuncio.avg.value || 'Sem nota'} (${0} comentários)`}
</Typography>
</Grid>
</Grid>
</Grid>
<Grid item>
<List className={classes.commentList}>
{/* TODO lista de comentarios que vem da api */}
{/* <ComentarioItem /> */}
</List>
</Grid>
</Grid>
</Grid>
) : (
<></>
)}
</Grid>
</Container>
<Divider />
<CustomSnackbar message={snackbarMessage} handleCloseSnackbar={handleCloseSnackbar} />
</Page>
);
};
AnuncioDetails.propTypes = {
className: PropTypes.string,
};
export default AnuncioDetails;
|
jianlexia/assets_front_v2
|
node_modules/@polkadot/x-textdecoder/typeCheck.js
|
<gh_stars>0
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _browser = _interopRequireDefault(require("./browser"));
var _node = _interopRequireDefault(require("./node"));
// Copyright 2020 @polkadot/x-textdecoder authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
console.log(new _browser.default('utf-8').decode(new Uint8Array([1, 2, 3])));
console.log(new _node.default('utf-8').decode(new Uint8Array([1, 2, 3])));
|
kami-lang/madex-redex
|
test/unit/TrueVirtualsTest.cpp
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include "Creators.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "MethodOverrideGraph.h"
#include "RedexTest.h"
#include "ScopeHelper.h"
#include "Show.h"
namespace mog = method_override_graph;
namespace {
//
// Utility to create classes and methods.
//
//
// Scope creation for the different tests.
// they are defined here so we can compose the functions as needed.
// Keep that in mind if making changes.
//
/**
* Make a scope with:
* class A { void final1() {} void final2() {} }
*/
std::vector<DexClass*> create_scope_1() {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto a_t = DexType::make_type("LA;");
auto a_cls = create_internal_class(a_t, obj_t, {});
create_empty_method(a_cls, "final1", void_void);
create_empty_method(a_cls, "final2", void_void);
scope.push_back(a_cls);
return scope;
}
/**
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* abstract class A implements Interf { void final1() {} void intf_meth1() {} }
*/
std::vector<DexClass*> create_scope_2() {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto interf_t = DexType::make_type("LInterf;");
auto interf_cls =
create_internal_class(interf_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf_cls, "intf_meth1", void_void, ACC_PUBLIC);
create_abstract_method(interf_cls, "intf_meth2", void_void, ACC_PUBLIC);
scope.push_back(interf_cls);
auto a_t = DexType::make_type("LA;");
auto a_cls = create_internal_class(a_t, obj_t, {interf_t}, ACC_ABSTRACT);
create_empty_method(a_cls, "final1", void_void);
create_empty_method(a_cls, "intf_meth1", void_void);
scope.push_back(a_cls);
return scope;
}
/**
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* abstract class A implements Interf { void final1() {} void intf_meth1() {} }
* class B extends A { void final2() {} void intf_meth2() {} }
*/
std::vector<DexClass*> create_scope_3() {
auto scope = create_scope_2();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto a_t = DexType::get_type("LA;");
always_assert_log(a_t != nullptr, "class A must be already defined in scope");
auto b_t = DexType::make_type("LB;");
auto b_cls = create_internal_class(b_t, a_t, {});
create_empty_method(b_cls, "final2", void_void);
create_empty_method(b_cls, "intf_meth2", void_void);
scope.push_back(b_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* class A { void final1() {} void intf_meth1() {} }
* class B extends A implements Interf { void intf_meth2() {} }
*/
std::vector<DexClass*> create_scope_4() {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto interf_t = DexType::make_type("LInterf;");
auto interf_cls =
create_internal_class(interf_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf_cls, "intf_meth1", void_void, ACC_PUBLIC);
create_abstract_method(interf_cls, "intf_meth2", void_void, ACC_PUBLIC);
scope.push_back(interf_cls);
auto a_t = DexType::make_type("LA;");
auto a_cls = create_internal_class(a_t, obj_t, {});
create_empty_method(a_cls, "final1", void_void);
create_empty_method(a_cls, "intf_meth1", void_void);
scope.push_back(a_cls);
auto b_t = DexType::make_type("LB;");
auto b_cls = create_internal_class(b_t, a_t, {interf_t});
create_empty_method(b_cls, "intf_meth2", void_void);
scope.push_back(b_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* class A { void override1() {} void intf_meth1() {} }
* class B extends A implements Interf {
* void override1() {} void final1() {} void intf_meth2() {} }
*/
std::vector<DexClass*> create_scope_5() {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto interf_t = DexType::make_type("LInterf;");
auto interf_cls =
create_internal_class(interf_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf_cls, "intf_meth1", void_void, ACC_PUBLIC);
create_abstract_method(interf_cls, "intf_meth2", void_void, ACC_PUBLIC);
scope.push_back(interf_cls);
auto a_t = DexType::make_type("LA;");
auto a_cls = create_internal_class(a_t, obj_t, {});
create_empty_method(a_cls, "override1", void_void);
create_empty_method(a_cls, "intf_meth1", void_void);
scope.push_back(a_cls);
auto b_t = DexType::make_type("LB;");
auto b_cls = create_internal_class(b_t, a_t, {interf_t});
create_empty_method(b_cls, "override1", void_void);
create_empty_method(b_cls, "final1", void_void);
create_empty_method(b_cls, "intf_meth2", void_void);
scope.push_back(b_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* class A { void override1() {} void intf_meth1() {} }
* class B extends A implements Interf {
* void override1() {} void final1() {} void intf_meth2() {} }
* class C extends A implements Interf { void final1() {} void intf_meth2() {} }
*/
std::vector<DexClass*> create_scope_6() {
std::vector<DexClass*> scope = create_scope_5();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto a_t = DexType::get_type("LA;");
always_assert_log(a_t != nullptr, "class A must be defined in scope already");
auto interf_t = DexType::get_type("LInterf;");
always_assert_log(a_t != nullptr,
"interface Interf must be defined in scope already");
auto c_t = DexType::make_type("LC;");
auto c_cls = create_internal_class(c_t, a_t, {interf_t});
create_empty_method(c_cls, "final1", void_void);
create_empty_method(c_cls, "intf_meth2", void_void);
scope.push_back(c_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* class A { void override1() {} void intf_meth1() {} }
* class B extends A implements Interf {
* void override1() {} void final1() {} void intf_meth2() {} }
* class C extends A implements Interf { void final1() {} void intf_meth2() {} }
* class D extends A { void override1() {} }
* class E extends A { void final1() {} }
*/
std::vector<DexClass*> create_scope_7() {
std::vector<DexClass*> scope = create_scope_6();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, args);
auto a_t = DexType::get_type("LA;");
always_assert_log(a_t != nullptr, "class A must be defined in scope already");
auto d_t = DexType::make_type("LD;");
auto d_cls = create_internal_class(d_t, a_t, {});
create_empty_method(d_cls, "override1", void_void);
scope.push_back(d_cls);
auto e_t = DexType::make_type("LE;");
auto e_cls = create_internal_class(e_t, a_t, {});
create_empty_method(e_cls, "final1", void_void);
scope.push_back(e_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* class A { void override1() {} void intf_meth1() {} }
* class B extends A implements Interf {
* void override1() {} void final1() {} void intf_meth2() {} }
* class C extends A implements Interf { void final1() {} void intf_meth2() {} }
* class D extends A { void override1() {} }
* class E extends A { void final1() {} }
* class F extends A { void final1() {} void intf_meth1(int) {} }
* class G extends F { void intf_meth2(int) {} }
* the intf_meth* in F and G are not interface methods but overloads.
*/
std::vector<DexClass*> create_scope_8() {
std::vector<DexClass*> scope = create_scope_7();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto int_t = type::_int();
auto void_args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, void_args);
auto int_args = DexTypeList::make_type_list({int_t});
auto int_void = DexProto::make_proto(void_t, int_args);
auto a_t = DexType::get_type("LA;");
always_assert_log(a_t != nullptr, "class A must be defined in scope already");
auto f_t = DexType::make_type("LF;");
auto f_cls = create_internal_class(f_t, a_t, {});
create_empty_method(f_cls, "final1", void_void);
create_empty_method(f_cls, "intf_meth1", int_void);
scope.push_back(f_cls);
auto g_t = DexType::make_type("LG;");
auto g_cls = create_internal_class(g_t, f_t, {});
create_empty_method(g_cls, "intf_meth2", int_void);
scope.push_back(g_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* interface Interf1 { void intf_meth2(); }
* class A { void override1() {} void intf_meth1() {} }
* class B extends A implements Interf {
* void override1() {} void final1() {} void intf_meth2() {} }
* class C extends A implements Interf { void final1() {} void intf_meth2() {} }
* class D extends A { void override1() {} }
* class E extends A { void final1() {} }
* class F extends A implements Interf1 { void intf_meth2() {} }
*/
std::vector<DexClass*> create_scope_9() {
std::vector<DexClass*> scope = create_scope_7();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto int_t = type::_int();
auto int_args = DexTypeList::make_type_list({int_t});
auto int_void = DexProto::make_proto(void_t, int_args);
auto a_t = DexType::get_type("LA;");
always_assert_log(a_t != nullptr, "class A must be defined in scope already");
auto interf1_t = DexType::make_type("LInterf1;");
auto interf1_cls =
create_internal_class(interf1_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf1_cls, "intf_meth1", int_void, ACC_PUBLIC);
scope.push_back(interf1_cls);
auto f_t = DexType::make_type("LF;");
auto f_cls = create_internal_class(f_t, a_t, {interf1_t});
create_empty_method(f_cls, "intf_meth1", int_void);
scope.push_back(f_cls);
return scope;
}
/*
* Make a scope with:
* interface Interf { void intf_meth1(); void intf_meth2(); }
* interface Interf1 { void intf_meth2(); }
* class A { void override1() {} void final1() {} }
* class AA extends A { void override1() {} void intf_meth1() {} void
* final1(int) {} } class AAA extends AA implements Interf { void final2() {}
* void intf_meth2() {} } class AAB extends AA implements Interf { void final2()
* {} } class AABA extends AAB { void override1() void intf_meth2() {} } class
* AB extends A { void override1() {} void final1(int) {} } class ABA extends AB
* implements Interf { void override1() {} void intf_meth1() {} void final2() {}
* } class ABAA extends ABA implements Interf1 { void intf_meth2() {} void
* final1(int) {} } class ABAB extends AB { void intf_meth2() {} void
* final1(int) {} }
*/
std::vector<DexClass*> create_scope_10() {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto void_t = type::_void();
auto int_t = type::_int();
auto no_args = DexTypeList::make_type_list({});
auto void_void = DexProto::make_proto(void_t, no_args);
auto int_args = DexTypeList::make_type_list({int_t});
auto int_void = DexProto::make_proto(void_t, int_args);
auto interf_t = DexType::make_type("LInterf;");
auto interf1_t = DexType::make_type("LInterf1;");
auto a_t = DexType::make_type("LA;");
auto aa_t = DexType::make_type("LAA;");
auto aaa_t = DexType::make_type("LAAA;");
auto aab_t = DexType::make_type("LAAB;");
auto aaba_t = DexType::make_type("LAABA;");
auto ab_t = DexType::make_type("LAB;");
auto aba_t = DexType::make_type("LABA;");
auto abaa_t = DexType::make_type("LABAA;");
auto abab_t = DexType::make_type("LABAB;");
// push interfaces
auto interf_cls =
create_internal_class(interf_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf_cls, "intf_meth1", void_void, ACC_PUBLIC);
create_abstract_method(interf_cls, "intf_meth2", void_void, ACC_PUBLIC);
scope.push_back(interf_cls);
auto interf1_cls =
create_internal_class(interf1_t, obj_t, {}, ACC_PUBLIC | ACC_INTERFACE);
create_abstract_method(interf1_cls, "intf_meth2", void_void, ACC_PUBLIC);
scope.push_back(interf1_cls);
auto a_cls = create_internal_class(a_t, obj_t, {});
create_empty_method(a_cls, "override1", void_void);
create_empty_method(a_cls, "final1", void_void);
scope.push_back(a_cls);
auto aa_cls = create_internal_class(aa_t, a_t, {});
create_empty_method(aa_cls, "override1", void_void);
create_empty_method(aa_cls, "intf_meth1", void_void);
create_empty_method(aa_cls, "final1", int_void);
scope.push_back(aa_cls);
auto aaa_cls = create_internal_class(aaa_t, aa_t, {interf_t});
create_empty_method(aaa_cls, "final2", void_void);
create_empty_method(aaa_cls, "intf_meth2", void_void);
scope.push_back(aaa_cls);
auto aab_cls = create_internal_class(aab_t, aa_t, {interf_t});
create_empty_method(aab_cls, "final2", void_void);
scope.push_back(aab_cls);
auto aaba_cls = create_internal_class(aaba_t, aab_t, {});
create_empty_method(aaba_cls, "override1", void_void);
create_empty_method(aaba_cls, "intf_meth2", void_void);
scope.push_back(aaba_cls);
auto ab_cls = create_internal_class(ab_t, a_t, {});
create_empty_method(ab_cls, "override1", void_void);
create_empty_method(ab_cls, "final1", int_void);
scope.push_back(ab_cls);
auto aba_cls = create_internal_class(aba_t, ab_t, {interf_t});
create_empty_method(aba_cls, "override1", void_void);
create_empty_method(aba_cls, "intf_meth1", void_void);
create_empty_method(aba_cls, "final2", void_void);
scope.push_back(aba_cls);
auto abaa_cls = create_internal_class(abaa_t, aba_t, {interf1_t});
create_empty_method(abaa_cls, "intf_meth2", void_void);
create_empty_method(abaa_cls, "final1", int_void);
scope.push_back(abaa_cls);
auto abab_cls = create_internal_class(abab_t, aba_t, {});
create_empty_method(abab_cls, "intf_meth2", void_void);
create_empty_method(abab_cls, "final1", int_void);
scope.push_back(abab_cls);
return scope;
}
//
// Utilities for tests
//
std::unordered_set<std::string> get_method_names(
const std::unordered_set<DexMethod*>& methods) {
std::unordered_set<std::string> result;
for (auto* method : methods) {
result.emplace(show(method));
}
return result;
}
} // namespace
//
// Tests
//
class DevirtualizerTest : public RedexTest {};
TEST_F(DevirtualizerTest, OneClass2Finals) {
std::vector<DexClass*> scope = create_scope_1();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(
get_method_names(methods),
::testing::UnorderedElementsAre("LA;.final1:()V", "LA;.final2:()V"));
}
TEST_F(DevirtualizerTest, AbstractClassInterface1Final) {
std::vector<DexClass*> scope = create_scope_2();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre("LA;.final1:()V"));
}
TEST_F(DevirtualizerTest, InterfaceClassInheritance2Final) {
std::vector<DexClass*> scope = create_scope_3();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(
get_method_names(methods),
::testing::UnorderedElementsAre("LA;.final1:()V", "LB;.final2:()V"));
}
TEST_F(DevirtualizerTest, InterfaceWithImplInBase1Final) {
std::vector<DexClass*> scope = create_scope_4();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre("LA;.final1:()V"));
}
TEST_F(DevirtualizerTest, InterfaceWithImplInBaseAndOverride1Final) {
std::vector<DexClass*> scope = create_scope_5();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre("LB;.final1:()V"));
}
TEST_F(DevirtualizerTest, InterfaceWithImplInBase2Classes2Final) {
std::vector<DexClass*> scope = create_scope_6();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(
get_method_names(methods),
::testing::UnorderedElementsAre("LB;.final1:()V", "LC;.final1:()V"));
}
TEST_F(DevirtualizerTest, InterfaceWithImplInBaseMultipleClasses3Final) {
std::vector<DexClass*> scope = create_scope_7();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre(
"LB;.final1:()V", "LC;.final1:()V", "LE;.final1:()V"));
}
TEST_F(DevirtualizerTest,
InterfaceWithImplInBaseMultipleClassesAndOverloads6Final) {
std::vector<DexClass*> scope = create_scope_8();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre(
"LB;.final1:()V", "LC;.final1:()V", "LE;.final1:()V",
"LF;.final1:()V", "LF;.intf_meth1:(I)V",
"LG;.intf_meth2:(I)V"));
}
TEST_F(DevirtualizerTest,
InterfacesWithImplInBaseMultipleClassesAndOverloads3Final) {
std::vector<DexClass*> scope = create_scope_9();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre(
"LB;.final1:()V", "LC;.final1:()V", "LE;.final1:()V"));
}
TEST_F(DevirtualizerTest, GenericRichHierarchy) {
std::vector<DexClass*> scope = create_scope_10();
auto methods = mog::get_non_true_virtuals(*mog::build_graph(scope), scope);
EXPECT_THAT(get_method_names(methods),
::testing::UnorderedElementsAre(
"LA;.final1:()V", "LABA;.final2:()V", "LAA;.final1:(I)V",
"LAAB;.final2:()V", "LAAA;.final2:()V"));
}
|
sturgeons/esfm-server
|
src/main/java/com/esfm/modules/survey/controller/SurveyShceduleController.java
|
package com.esfm.modules.survey.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esfm.extension.api.ApiController;
import com.esfm.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.esfm.modules.survey.entity.SurveyShcedule;
import com.esfm.modules.survey.service.SurveyShceduleService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
/**
* 问卷调查计划(SurveyShcedule)表控制层
*
* @author makejava
* @since 2021-10-31 22:49:45
*/
@RestController
@RequestMapping("surveyShcedule")
public class SurveyShceduleController extends ApiController {
/**
* 服务对象
*/
@Resource
private SurveyShceduleService surveyShceduleService;
/**
* 分页查询所有数据
*/
@GetMapping(value = "list")
public R<?> selectAll(Page<SurveyShcedule> page, SurveyShcedule surveyShcedule) {
return success(this.surveyShceduleService.page(page, new QueryWrapper<>(surveyShcedule)));
}
/**
* 通过主键查询单条数据
*/
@GetMapping("id/{id}")
public R<?> selectOne(@PathVariable Serializable id) {
return success(this.surveyShceduleService.getById(id));
}
/**
* 新增数据
*/
@PostMapping(value = "insert")
public R<?> insert(@RequestBody SurveyShcedule surveyShcedule) {
return success(this.surveyShceduleService.save(surveyShcedule));
}
/**
* 修改数据
*/
@PutMapping(value = "update")
public R<?> update(@RequestBody SurveyShcedule surveyShcedule) {
return success(this.surveyShceduleService.updateById(surveyShcedule));
}
/**
* 删除数据
*/
@DeleteMapping(value = "delete")
public R<?> delete(@RequestParam("idList") List<Long> idList) {
return success(this.surveyShceduleService.removeByIds(idList));
}
}
|
SCS-ASSE-FS21-Group4/tapas
|
tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/handler/TaskExecutedHandler.java
|
package ch.unisg.tapastasks.tasks.application.handler;
import ch.unisg.tapastasks.tasks.application.port.in.TaskExecutedEvent;
import ch.unisg.tapastasks.tasks.application.port.in.TaskExecutedEventHandler;
import ch.unisg.tapascommon.tasks.domain.Task;
import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort;
import ch.unisg.tapastasks.tasks.application.port.out.TaskListLock;
import ch.unisg.tapastasks.tasks.domain.TaskList;
import ch.unisg.tapastasks.tasks.domain.TaskNotFoundException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TaskExecutedHandler implements TaskExecutedEventHandler {
private static final Logger LOGGER = LogManager.getLogger(TaskExecutedHandler.class);
@Autowired
private AddTaskPort addTaskToRepositoryPort;
@Autowired
private TaskListLock taskListLock;
@Override
public Task handleTaskExecuted(TaskExecutedEvent taskExecutedEvent) throws TaskNotFoundException {
TaskList taskList = TaskList.getTapasTaskList();
taskListLock.lockTaskList(taskList.getTaskListName());
var task = taskList.changeTaskStatusToExecuted(taskExecutedEvent.getTaskId(),
taskExecutedEvent.getServiceProvider(), taskExecutedEvent.getOutputData());
addTaskToRepositoryPort.addTask(task);
taskListLock.releaseTaskList(taskList.getTaskListName());
LOGGER.info("Handled Task Executed Event");
return task;
}
}
|
Astrocoders/meteor-easy-testing
|
lib/templates/meteor/method.js
|
<gh_stars>1-10
//
export default ({name, params}) => (
`import { ValidatedMethod } from 'meteor/mdg:validated-method'
import { SimpleSchema } from 'meteor/aldeed:simple-schema'
export default new ValidatedMethod({
name: '${name}',
validate: new SimpleSchema({
${params.map(paramDefToSimpleSchemaDef(params.length)).join('')}
}).validator(),
run({ ${paramsDefToDestructuredArgs(params)} }){
return true
},
})
`)
function paramDefToSimpleSchemaDef() {
return (paramDef, index) => {
const def = paramDef.split(':')
// Doing indentation like this is not ok
return (
`${index > 0 ? '\n' : ''} ${def[0]}: {
type: ${def[1]},
},`
)
}
}
function paramsDefToDestructuredArgs(params) {
return params.map(def => def.split(':')[0]).join(', ')
}
|
AnonymousDeveloper65535/open-toontown
|
toontown/parties/PartyCog.py
|
import math
from direct.actor.Actor import Actor
from direct.interval.ActorInterval import ActorInterval
from direct.interval.MetaInterval import Sequence, Parallel
from direct.interval.FunctionInterval import Func, Wait
from direct.interval.SoundInterval import SoundInterval
from direct.interval.LerpInterval import LerpScaleInterval, LerpFunc
from direct.showbase.PythonUtil import bound as clamp
from direct.task import Task
from direct.fsm.FSM import FSM
from pandac.PandaModules import CollisionTube, CollisionNode, CollisionSphere
from pandac.PandaModules import Point3, Vec4, NodePath, TextNode, Mat4
from toontown.toonbase import ToontownGlobals
from toontown.battle.BattleProps import globalPropPool
from toontown.battle.BattleSounds import globalBattleSoundCache
import PartyGlobals
class PartyCogManager:
def __init__(self):
self.cogs = []
def generateCog(self, parentNode, bounceSpeed = 3, bounceHeight = 1, rotateSpeed = 1, heightShift = 1, xMoveSpeed = 0, xMoveDistance = 0, bounceOffset = 0):
cog = PartyCog(parentNode, len(self.cogs), bounceSpeed, bounceHeight, rotateSpeed, heightShift, xMoveSpeed, xMoveDistance, bounceOffset)
self.cogs.append(cog)
return cog
def unload(self):
for cog in self.cogs:
cog.unload()
def updateDistances(self, distances):
for i in range(len(distances)):
self.cogs[i].updateDistance(distances[i])
class PartyCog(FSM):
notify = directNotify.newCategory('PartyCog')
HpTextGenerator = TextNode('HpTextGenerator')
hpText = None
height = 7
def __init__(self, parentNode, id, bounceSpeed = 3, bounceHeight = 1, rotateSpeed = 1, heightShift = 1, xMoveSpeed = 0, xMoveDistance = 0, bounceOffset = 0):
self.id = id
FSM.__init__(self, 'PartyCogFSM-%d' % self.id)
self.showFacingStatus = False
self.xMoveSpeed = xMoveSpeed
self.xMoveDistance = xMoveDistance
self.heightShift = heightShift
self.bounceSpeed = bounceSpeed
self.bounceHeight = bounceHeight
self.rotateSpeed = rotateSpeed
self.parentNode = parentNode
self.bounceOffset = bounceOffset
self.hitInterval = None
self.kaboomTrack = None
self.resetRollIval = None
self.netTimeSentToStartByHit = 0
self.load()
self.request('Down')
return
def load(self):
self.root = NodePath('PartyCog-%d' % self.id)
self.root.reparentTo(self.parentNode)
path = 'phase_13/models/parties/cogPinata_'
self.actor = Actor(path + 'actor', {'idle': path + 'idle_anim',
'down': path + 'down_anim',
'up': path + 'up_anim',
'bodyHitBack': path + 'bodyHitBack_anim',
'bodyHitFront': path + 'bodyHitFront_anim',
'headHitBack': path + 'headHitBack_anim',
'headHitFront': path + 'headHitFront_anim'})
self.actor.reparentTo(self.root)
self.temp_transform = Mat4()
self.head_locator = self.actor.attachNewNode('temphead')
self.bodyColl = CollisionTube(0, 0, 1, 0, 0, 5.75, 0.75)
self.bodyColl.setTangible(1)
self.bodyCollNode = CollisionNode('PartyCog-%d-Body-Collision' % self.id)
self.bodyCollNode.setCollideMask(ToontownGlobals.PieBitmask)
self.bodyCollNode.addSolid(self.bodyColl)
self.bodyCollNodePath = self.root.attachNewNode(self.bodyCollNode)
self.headColl = CollisionTube(0, 0, 3, 0, 0, 3.0, 1.5)
self.headColl.setTangible(1)
self.headCollNode = CollisionNode('PartyCog-%d-Head-Collision' % self.id)
self.headCollNode.setCollideMask(ToontownGlobals.PieBitmask)
self.headCollNode.addSolid(self.headColl)
self.headCollNodePath = self.root.attachNewNode(self.headCollNode)
self.arm1Coll = CollisionSphere(1.65, 0, 3.95, 1.0)
self.arm1Coll.setTangible(1)
self.arm1CollNode = CollisionNode('PartyCog-%d-Arm1-Collision' % self.id)
self.arm1CollNode.setCollideMask(ToontownGlobals.PieBitmask)
self.arm1CollNode.addSolid(self.arm1Coll)
self.arm1CollNodePath = self.root.attachNewNode(self.arm1CollNode)
self.arm2Coll = CollisionSphere(-1.65, 0, 3.45, 1.0)
self.arm2Coll.setTangible(1)
self.arm2CollNode = CollisionNode('PartyCog-%d-Arm2-Collision' % self.id)
self.arm2CollNode.setCollideMask(ToontownGlobals.PieBitmask)
self.arm2CollNode.addSolid(self.arm2Coll)
self.arm2CollNodePath = self.root.attachNewNode(self.arm2CollNode)
splatName = 'splat-creampie'
self.splat = globalPropPool.getProp(splatName)
self.splat.setBillboardPointEye()
self.splatType = globalPropPool.getPropType(splatName)
self.pieHitSound = globalBattleSoundCache.getSound('AA_wholepie_only.mp3')
self.upSound = globalBattleSoundCache.getSound('AV_jump_to_side.mp3')
self.hole = loader.loadModel('phase_13/models/parties/cogPinataHole')
self.hole.setTransparency(True)
self.hole.setP(-90.0)
self.hole.setScale(3)
self.hole.setBin('ground', 3)
self.hole.reparentTo(self.parentNode)
def unload(self):
self.request('Off')
self.clearHitInterval()
if self.hole is not None:
self.hole.removeNode()
self.hole = None
if self.actor is not None:
self.actor.cleanup()
self.actor.removeNode()
self.actor = None
if self.root is not None:
self.root.removeNode()
self.root = None
if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():
self.kaboomTrack.finish()
self.kaboomTrack = None
if self.resetRollIval is not None and self.resetRollIval.isPlaying():
self.resetRollIval.finish()
self.resetRollIval = None
if self.hitInterval is not None and self.hitInterval.isPlaying():
self.hitInterval.finish()
self.hitInterval = None
del self.upSound
del self.pieHitSound
return
def enterStatic(self):
pass
def exitStatic(self):
pass
def enterActive(self, startTime):
self.root.setR(0.0)
updateTask = Task.Task(self.updateTask)
updateTask.startTime = startTime
taskMgr.add(updateTask, 'PartyCog.update-%d' % self.id)
def exitActive(self):
taskMgr.remove('PartyCog.update-%d' % self.id)
taskMgr.remove('PartyCog.bounceTask-%d' % self.id)
self.clearHitInterval()
self.resetRollIval = self.root.hprInterval(0.5, Point3(self.root.getH(), 0.0, 0.0), blendType='easeInOut')
self.resetRollIval.start()
self.actor.stop()
def enterDown(self):
if self.oldState == 'Off':
downAnimControl = self.actor.getAnimControl('down')
self.actor.pose('down', downAnimControl.getNumFrames() - 1)
return
self.clearHitInterval()
startScale = self.hole.getScale()
endScale = Point3(5, 5, 5)
self.hitInterval = Sequence(LerpFunc(self.setAlongSpline, duration=1.0, fromData=self.currentT, toData=0.0), LerpScaleInterval(self.hole, duration=0.175, scale=endScale, startScale=startScale, blendType='easeIn'), Parallel(SoundInterval(self.upSound, volume=0.6, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), ActorInterval(self.actor, 'down', loop=0)), LerpScaleInterval(self.hole, duration=0.175, scale=Point3(3, 3, 3), startScale=endScale, blendType='easeOut'))
self.hitInterval.start()
def exitDown(self):
self.root.setR(0.0)
self.root.setH(0.0)
self.targetDistance = 0.0
self.targetFacing = 0.0
self.currentT = 0.0
self.setAlongSpline(0.0)
self.clearHitInterval()
startScale = self.hole.getScale()
endScale = Point3(5, 5, 5)
self.hitInterval = Sequence(LerpScaleInterval(self.hole, duration=0.175, scale=endScale, startScale=startScale, blendType='easeIn'), Parallel(SoundInterval(self.upSound, volume=0.6, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), ActorInterval(self.actor, 'up', loop=0)), Func(self.actor.loop, 'idle'), LerpScaleInterval(self.hole, duration=0.175, scale=Point3(3, 3, 3), startScale=endScale, blendType='easeOut'))
self.hitInterval.start()
def filterDown(self, request, args):
if request == 'Down':
return None
else:
return self.defaultFilter(request, args)
return None
def setEndPoints(self, start, end, amplitude = 1.7):
self.sinAmplitude = amplitude
self.sinPeriod = (end.getX() - start.getX()) / 2
self.sinDisplacement = start.getY()
self.startPoint = start
self.endPoint = end
self.currentT = 0.0
self.targetDistance = 0.0
self.currentFacing = 0.0
self.targetFacing = 0.0
self.setAlongSpline(self.currentT)
self.hole.setPos(self.root.getPos())
self.hole.setZ(0.02)
def rockBackAndForth(self, task):
t = task.startTime + task.time
angle = math.sin(t) * 20.0
self.root.setR(angle)
return task.cont
def updateDistance(self, distance):
self.targetDistance = clamp(distance, -1.0, 1.0)
def updateTask(self, task):
self.rockBackAndForth(task)
if self.targetDistance > self.currentT:
self.currentT += min(0.01, self.targetDistance - self.currentT)
self.setAlongSpline(self.currentT)
elif self.targetDistance < self.currentT:
self.currentT += max(-0.01, self.targetDistance - self.currentT)
self.setAlongSpline(self.currentT)
if self.currentT < 0.0:
self.targetFacing = -90.0
elif self.currentT > 0.0:
self.targetFacing = 90.0
else:
self.targetFacing = 0.0
if self.targetFacing > self.currentFacing:
self.currentFacing += min(10, self.targetFacing - self.currentFacing)
elif self.targetFacing < self.currentFacing:
self.currentFacing += max(-10, self.targetFacing - self.currentFacing)
self.root.setH(self.currentFacing)
return task.cont
def setAlongSpline(self, t):
t = t + 1.0
dist = (self.endPoint.getX() - self.startPoint.getX()) / 2.0
x = self.startPoint.getX() + t * dist
y = self.startPoint.getY() - math.sin(t * 2 * math.pi) * self.sinAmplitude
self.root.setPos(x, y, 0)
def startBounce(self):
taskMgr.add(self.bounce, 'PartyCog.bounceTask-%d' % self.id)
def bounce(self, task):
self.root.setZ(math.sin((self.bounceOffset + task.time) * self.bounceSpeed) * self.bounceHeight + self.heightShift)
return task.cont
def setPos(self, position):
self.root.setPos(position)
def respondToPieHit(self, timestamp, position, hot = False, direction = 1.0):
if self.netTimeSentToStartByHit < timestamp:
self.__showSplat(position, direction, hot)
if self.netTimeSentToStartByHit < timestamp:
self.netTimeSentToStartByHit = timestamp
else:
self.notify.debug('respondToPieHit self.netTimeSentToStartByHit = %s' % self.netTimeSentToStartByHit)
def clearHitInterval(self):
if self.hitInterval is not None and self.hitInterval.isPlaying():
self.hitInterval.clearToInitial()
return
def __showSplat(self, position, direction, hot = False):
if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():
self.kaboomTrack.finish()
self.clearHitInterval()
splatName = 'splat-creampie'
self.splat = globalPropPool.getProp(splatName)
self.splat.setBillboardPointEye()
self.splat.reparentTo(render)
self.splat.setPos(self.root, position)
self.splat.setAlphaScale(1.0)
if not direction == 1.0:
self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[0])
if self.currentFacing > 0.0:
facing = 'HitFront'
else:
facing = 'HitBack'
else:
self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[1])
if self.currentFacing > 0.0:
facing = 'HitBack'
else:
facing = 'HitFront'
if hot:
targetscale = 0.75
part = 'head'
else:
targetscale = 0.5
part = 'body'
def setSplatAlpha(amount):
self.splat.setAlphaScale(amount)
self.hitInterval = Sequence(ActorInterval(self.actor, part + facing, loop=0), Func(self.actor.loop, 'idle'))
self.hitInterval.start()
self.kaboomTrack = Parallel(SoundInterval(self.pieHitSound, volume=1.0, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), Sequence(Func(self.splat.showThrough), Parallel(Sequence(LerpScaleInterval(self.splat, duration=0.175, scale=targetscale, startScale=Point3(0.1, 0.1, 0.1), blendType='easeOut'), Wait(0.175)), Sequence(Wait(0.1), LerpFunc(setSplatAlpha, duration=1.0, fromData=1.0, toData=0.0, blendType='easeOut'))), Func(self.splat.cleanup), Func(self.splat.removeNode)))
self.kaboomTrack.start()
return
def showHitScore(self, number, scale = 1):
if number <= 0:
return
if self.hpText:
self.hideHitScore()
self.HpTextGenerator.setFont(ToontownGlobals.getSignFont())
if number < 0:
self.HpTextGenerator.setText(str(number))
else:
self.HpTextGenerator.setText('+' + str(number))
self.HpTextGenerator.clearShadow()
self.HpTextGenerator.setAlign(TextNode.ACenter)
r = 1
g = 1
b = 0
a = 1
self.HpTextGenerator.setTextColor(r, g, b, a)
self.hpTextNode = self.HpTextGenerator.generate()
self.hpText = render.attachNewNode(self.hpTextNode)
self.hpText.setScale(scale)
self.hpText.setBillboardPointEye()
self.hpText.setBin('fixed', 100)
self.hpText.setPos(self.root, 0, 0, self.height / 2)
seq = Task.sequence(self.hpText.lerpPos(Point3(self.root.getX(render), self.root.getY(render), self.root.getZ(render) + self.height + 1.0), 0.25, blendType='easeOut'), Task.pause(0.25), self.hpText.lerpColor(Vec4(r, g, b, a), Vec4(r, g, b, 0), 0.1), Task.Task(self.__hideHitScoreTask))
taskMgr.add(seq, 'PartyCogHpText' + str(self.id))
def __hideHitScoreTask(self, task):
self.hideHitScore()
return Task.done
def hideHitScore(self):
if self.hpText:
taskMgr.remove('PartyCogHpText' + str(self.id))
self.hpText.removeNode()
self.hpText = None
return
def getHeadLocation(self):
self.actor.getJoints(jointName='head')[0].getNetTransform(self.temp_transform)
self.head_locator.setMat(self.temp_transform)
return self.head_locator.getZ(self.root)
|
pchlenski/NeuroSEED
|
tests/multiple_sequence_alignment_tests/test_msa_steiner_training.py
|
import copy
import io
import os
import random
import string
import unittest
from os import path
from contextlib import redirect_stdout
import torch
from multiple_alignment.steiner_string.models.convolutional.model import CNNEncoder, CNNDecoder
from multiple_alignment.steiner_string.models.mlp.model import MLPEncoder, MLPDecoder
from multiple_alignment.steiner_string.models.recurrent.model import GRUEncoder, GRUDecoder
from multiple_alignment.steiner_string.parser import general_arg_parser
from multiple_alignment.steiner_string.task.dataset_generator_genome import MSAPairDatasetGeneratorGenome
from multiple_alignment.steiner_string.train import execute_train
from tests.edit_distance_tests.test_ed_dataset_generation_genomic import generate_random_dna
ALPHABET_SIZE = 4
def generate_dataset_and_parser():
folder_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(10))
dataset_name = folder_name + '/test_msa_model.pkl'
strings = [generate_random_dna(50)] + [generate_random_dna(random.randint(10, 50)) for _ in range(39)]
sequences = {
'train': strings[:10],
'val': strings[10:15],
'val_msa': [strings[15:20], strings[20:25]],
'test': [strings[25:30], strings[30:35], strings[35:]]
}
dataset = MSAPairDatasetGeneratorGenome(strings=sequences, length=50)
dataset.save_as_pickle(dataset_name)
parser = general_arg_parser()
args = parser.parse_args()
args.data = dataset_name
args.epochs = 2
args.print_every = 1
args.distance = "euclidean"
return folder_name, dataset_name, args
def remove_files(folder_name, dataset_name):
if path.exists('0.pkl'): os.remove('0.pkl')
if path.exists('1.pkl'): os.remove('1.pkl')
os.remove(dataset_name)
os.rmdir(folder_name)
class TestMSASteinerTraining(unittest.TestCase):
def test_mlp_model_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=MLPEncoder, decoder_class=MLPDecoder,
encoder_args=dict(hidden_size=5,
layers=2),
decoder_args=dict(hidden_size=5,
layers=2),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_cnn_model_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=CNNEncoder, decoder_class=CNNDecoder,
encoder_args=dict(readout_layers=1,
channels=4,
layers=2,
kernel_size=3,
non_linearity=True),
decoder_args=dict(readout_layers=1,
channels=4,
layers=2,
kernel_size=3,
non_linearity=True),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_gru_model_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=GRUEncoder, decoder_class=GRUDecoder,
encoder_args=dict(recurrent_layers=1,
hidden_size=5),
decoder_args=dict(recurrent_layers=1,
hidden_size=5,
reverse='True'),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_square_distance_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
args = copy.copy(args)
args.distance = 'square'
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=MLPEncoder, decoder_class=MLPDecoder,
encoder_args=dict(hidden_size=5,
layers=2),
decoder_args=dict(hidden_size=5,
layers=2),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_cosine_distance_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
args = copy.copy(args)
args.distance = 'cosine'
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=MLPEncoder, decoder_class=MLPDecoder,
encoder_args=dict(hidden_size=5,
layers=2),
decoder_args=dict(hidden_size=5,
layers=2),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_manhattan_distance_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
args = copy.copy(args)
args.distance = 'manhattan'
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=MLPEncoder, decoder_class=MLPDecoder,
encoder_args=dict(hidden_size=5,
layers=2),
decoder_args=dict(hidden_size=5,
layers=2),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
def test_hyperbolic_distance_output(self):
folder_name, dataset_name, args = generate_dataset_and_parser()
args = copy.copy(args)
args.distance = 'hyperbolic'
args.scaling = True
f = io.StringIO()
with redirect_stdout(f):
execute_train(encoder_class=MLPEncoder, decoder_class=MLPDecoder,
encoder_args=dict(hidden_size=5,
layers=2),
decoder_args=dict(hidden_size=5,
layers=2),
args=args)
out = f.getvalue()
# check correct output
assert "Cost multiple" in out and "Final multiple val" in out and "Final loss_val" in out \
and "Final loss_train" in out, 'Wrong output format'
remove_files(folder_name, dataset_name)
|
Incapture/OG-Platform
|
projects/OG-Analytics/src/test/java/com/opengamma/analytics/math/interpolation/InterpolatorNDDataBundleTest.java
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.math.interpolation;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
import com.opengamma.analytics.math.interpolation.data.InterpolatorNDDataBundle;
import com.opengamma.util.tuple.ObjectsPair;
import com.opengamma.util.tuple.Pair;
/**
*
*/
public class InterpolatorNDDataBundleTest {
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullData() {
new InterpolatorNDDataBundle(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testEmptyData() {
List<Pair<double[], Double>> data = new ArrayList<Pair<double[], Double>>();
new InterpolatorNDDataBundle(data);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testEmptyData2() {
List<Pair<double[], Double>> data = new ArrayList<Pair<double[], Double>>();
double[] temp = new double[] {};
Pair<double[], Double> pair = new ObjectsPair<double[], Double>(temp, 0.0);
data.add(pair);
new InterpolatorNDDataBundle(data);
}
}
|
jdruk/mycroft-for-us
|
app/app/models/kea_lease4.rb
|
<reponame>jdruk/mycroft-for-us
# == Schema Information
#
# Table name: lease4
#
# address :bigint(8) not null, primary key
# expire :datetime
# fqdn_fwd :boolean
# fqdn_rev :boolean
# hostname :string(255)
# hwaddr :binary
# state :bigint(8) default(0)
# user_context :text
# valid_lifetime :bigint(8)
# client_id :binary
# subnet_id :bigint(8)
#
# Indexes
#
# lease4_by_client_id_subnet_id (client_id,subnet_id)
# lease4_by_hwaddr_subnet_id (hwaddr,subnet_id)
# lease4_by_state_expire (state,expire)
# lease4_by_subnet_id (subnet_id)
#
# Foreign Keys
#
# fk_lease4_state (state => lease_state.state)
#
class KeaLease4 < ApplicationRecord
def self.table_name
'lease4'
end
def self.primary_key
'address'
end
belongs_to :kea_lease_state, class_name: 'KeaLeaseState', foreign_key: 'state', primary_key: 'state'
end
|
SmartSoftAsia/iOS-Fleet-Management-SDK
|
EstimoteFleetManagementSDK/EstimoteFleetManagementSDK.framework/Versions/A/Headers/ESTSettingPowerDarkToSleepThreshold.h
|
// Estimote Fleet Management SDK
// Copyright (c) 2015 Estimote. All rights reserved.
#import <Foundation/Foundation.h>
#import "ESTSettingReadWrite.h"
@class ESTSettingPowerDarkToSleepThreshold;
NS_ASSUME_NONNULL_BEGIN
/**
* Block used as a result of read/write setting DarkToSleepThreshold operation for Power packet.
*
* @param thresholdSetting DarkToSleepThreshold setting carrying value.
* @param error Operation error. No error means success.
*/
typedef void(^ESTSettingPowerDarkToSleepThresholdCompletionBlock)(ESTSettingPowerDarkToSleepThreshold * _Nullable thresholdSetting, NSError * _Nullable error);
/**
* ESTSettingPowerDarkToSleepThreshold represents Power DarkToSleepThreshold value.
*/
@interface ESTSettingPowerDarkToSleepThreshold : ESTSettingReadWrite <NSCopying>
/**
* Designated initializer. Validates provided value internally with +validationErrorForValue:.
*
* @see +[ESTSettingPowerDarkToSleepThreshold validationErrorForValue:]
*
* @param threshold Power DarkToSleepThreshold value in lx.
*
* @return Initialized object. Nil if validation fails.
*/
- (instancetype)initWithValue:(NSUInteger)threshold;
/**
* Returns current value of Power DarkToSleepThreshold setting.
*
* @return DarkToSleepThreshold value in lx.
*/
- (NSUInteger)getValue;
/**
* Method allows to read value of initialized Power DarkToSleepThreshold setting object.
*
* @param completion Block to be invoked when operation is complete.
*/
- (void)readValueWithCompletion:(ESTSettingPowerDarkToSleepThresholdCompletionBlock)completion;
/**
* Method allows to create write operation from already initialized Power DarkToSleepThreshold setting object.
* Value provided during initialization will be used as a desired value.
*
* @param threshold DarkToSleepThreshold value in lx to be written to the device.
* @param completion Block to be invoked when operation is complete.
*/
- (void)writeValue:(NSUInteger)threshold completion:(ESTSettingPowerDarkToSleepThresholdCompletionBlock)completion;
/**
* Method checks if provided value is allowed. Returns nil if validation passes.
*
* @param threshold DarkToSleepThreshold value in lx.
*
* @return Error object describing why validation failed. Nil if validation passes.
*/
+ (NSError * _Nullable)validationErrorForValue:(NSUInteger)threshold;
@end
NS_ASSUME_NONNULL_END
|
eugeis/eej-email
|
ee-email-outlook/src/main/java/ee/email/outlook/base/OlDaysOfWeekEnum.java
|
package ee.email.outlook.base;
/**
* @see <p>
* Type <a href="http://msdn.microsoft.com/en-us/library/aa219371(v=office.11).aspx">OlDaysOfWeek</a>
* </p>
* @author eugeis
*/
public enum OlDaysOfWeekEnum {
olSunday(1), olThursday(16), olFriday(32), olMonday(2), olSaturday(64), olTuesday(4), olWednesday(8);
private final int value;
private OlDaysOfWeekEnum(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static OlDaysOfWeekEnum findEnum(Integer value) {
if (value != null) {
for (OlDaysOfWeekEnum objEnum : values()) {
if (objEnum.value == value) {
return objEnum;
}
}
}
return null;
}
public boolean isValue(int value) {
return this.value == value;
}
public boolean isOlSunday() {
return olSunday == this;
}
public boolean isOlThursday() {
return olThursday == this;
}
public boolean isOlFriday() {
return olFriday == this;
}
public boolean isOlMonday() {
return olMonday == this;
}
public boolean isOlSaturday() {
return olSaturday == this;
}
public boolean isOlTuesday() {
return olTuesday == this;
}
public boolean isOlWednesday() {
return olWednesday == this;
}
}
|
YUCS-Club/Java-OOP-LangFeatures
|
Day07/src/com/csculb/collection/CollectionMapDemo.java
|
package com.csculb.collection;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Stream;
public class CollectionMapDemo {
public static void main(String[] args) {
Map maps = new HashMap<Integer, String>();
maps.put(1, "Mg Mg");
maps.put(2, "Mg Hla");
String name = (String) maps.get(1);
System.out.println(name);
long count = Stream.of(maps)
.filter((map) -> map.containsKey(1))
.count();
}
}
|
groupe-sii/ogham
|
ogham-test-utils/src/main/java/fr/sii/ogham/testing/util/ResourceUtils.java
|
<filename>ogham-test-utils/src/main/java/fr/sii/ogham/testing/util/ResourceUtils.java
package fr.sii.ogham.testing.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
/**
* Contains utility methods to load resources in tests.
*
* @author <NAME>
*
*/
public final class ResourceUtils {
/**
* Utility method that loads a file content from the classpath. UTF-8
* charset is used.
*
* @param path
* the path to the classpath resource
* @return the content of the file
* @throws IOException
* when resource can't be read or doesn't exist
*/
public static String resourceAsString(String path) throws IOException {
return resourceAsString(path, StandardCharsets.UTF_8);
}
/**
* Utility method that loads a file content from the classpath.
*
* @param path
* the path to the classpath resource
* @param charset
* the charset used for reading the file
* @return the content of the file
* @throws IOException
* when resource can't be read or doesn't exist
*/
public static String resourceAsString(String path, Charset charset) throws IOException {
return IOUtils.toString(resource(path), charset.name());
}
/**
* Utility method that loads a file content from the classpath.
*
* @param path
* the path to the classpath resource
* @return the content of the file as byte array
* @throws IOException
* when resource can't be read or doesn't exist
*/
public static byte[] resource(String path) throws IOException {
InputStream resource = ResourceUtils.class.getClassLoader().getResourceAsStream(path.startsWith("/") ? path.substring(1) : path);
if (resource == null) {
throw new FileNotFoundException("No resource found for path '" + path + "'");
}
return IOUtils.toByteArray(resource);
}
private ResourceUtils() {
super();
}
}
|
teco-kit/ModelDrivenGateways
|
src/edu.teco.squery.editor/src-gen/edu/teco/squery/wizards/NewSQueryProjectWizard.java
|
<filename>src/edu.teco.squery.editor/src-gen/edu/teco/squery/wizards/NewSQueryProjectWizard.java
package edu.teco.squery.wizards;
import org.openarchitectureware.xtext.LanguageUtilities;
import org.openarchitectureware.xtext.editor.wizards.AbstractNewProjectWizard;
import edu.teco.squery.SQueryEditorPlugin;
public class NewSQueryProjectWizard extends AbstractNewProjectWizard {
public NewSQueryProjectWizard() {
super();
setLangName("sQuery");
setGeneratorProjectName("edu.teco.squery.generator");
setDslProjectName("edu.teco.squery");
setFileExtension("sqr");
setPackageName("edu/teco/squery/");
}
@Override
protected LanguageUtilities getUtilities() {
return SQueryEditorPlugin.getDefault().getUtilities();
}
}
|
ykomitov/Homeworks-TA
|
14.SPA-AngularJS/TheBigCatProject/TheBigCatProject.Client/scripts/_references.js
|
/// <autosync enabled="true" />
/// <reference path="../cats/add-cat-controller.js" />
/// <reference path="../common/main-controller.js" />
/// <reference path="../common/scripts/app.js" />
/// <reference path="../common/scripts/auth-service.js" />
/// <reference path="../common/scripts/cat-service.js" />
/// <reference path="../common/scripts/identity-service.js" />
/// <reference path="../home/home-controller.js" />
/// <reference path="../identity/login/login-controller.js" />
/// <reference path="../identity/register/register-controller.js" />
/// <reference path="angular.js" />
/// <reference path="angular-mocks.js" />
/// <reference path="jquery-1.6.3.min.js" />
|
ControlTrees/rai
|
rai/KOMO/retired/benchmarks.h
|
/* ------------------------------------------------------------------
Copyright (c) 2017 <NAME>
email: <EMAIL>
This code is distributed under the MIT License.
Please see <root-path>/LICENSE for details.
-------------------------------------------------------------- */
#pragma once
#include <Optim/optimization.h>
struct PR2EndPoseProblem : ConstrainedProblem {
struct sPR2EndPoseProblem& s;
PR2EndPoseProblem();
arr getInitialization();
void setState(const arr&);
void report();
};
|
VertiPub/oozie
|
core/src/test/java/org/apache/oozie/executor/jpa/TestCoordJobGetActionsNotCompletedJPAExecutor.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.oozie.executor.jpa;
import java.util.List;
import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.client.CoordinatorJob;
import org.apache.oozie.local.LocalOozie;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;
public class TestCoordJobGetActionsNotCompletedJPAExecutor extends XDataTestCase {
Services services;
@Override
protected void setUp() throws Exception {
super.setUp();
services = new Services();
services.init();
cleanUpDBTables();
}
@Override
protected void tearDown() throws Exception {
services.destroy();
super.tearDown();
}
/*
* Add a Coordinator action with status WAITING and check for expected column values
*/
public void testCoordActionsNotCompletetedForColumnValues() throws Exception {
int actionNum = 1;
CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
String jobId = job.getId();
CoordinatorActionBean action = addRecordToCoordActionTable(jobId, actionNum++,
CoordinatorAction.Status.WAITING, "coord-action-get.xml", 0);
_testCoordActionForCorrectColumnValues(jobId, action.getId(), action.getStatus(), action.getPending());
}
/*
* Add 2 Coordinator actions which are not completed (status as RUNNING and WAITING) and add 2 Coordinator actions
* which are completed (status as FAILED and KILLED). Then check for expected number of actions retrieved.
*/
public void testCoordActionsNotCompletetedForSize() throws Exception {
int actionNum = 1;
CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
String jobId = job.getId();
addRecordToCoordActionTable(jobId, actionNum++, CoordinatorAction.Status.RUNNING, "coord-action-get.xml", 0);
addRecordToCoordActionTable(jobId, actionNum++, CoordinatorAction.Status.WAITING, "coord-action-get.xml", 0);
addRecordToCoordActionTable(jobId, actionNum++, CoordinatorAction.Status.FAILED, "coord-action-get.xml", 0);
addRecordToCoordActionTable(jobId, actionNum++, CoordinatorAction.Status.KILLED, "coord-action-get.xml", 0);
_testCoordActionsNotCompletedSize(jobId, 2);
}
// test sql projection operator
private void _testCoordActionForCorrectColumnValues(String jobId, String actionId, CoordinatorAction.Status status,
int pending) throws Exception {
JPAService jpaService = Services.get().get(JPAService.class);
assertNotNull(jpaService);
// Call JPAExecutor to get actions which are not completed
CoordJobGetActionsNotCompletedJPAExecutor actionGetCmd = new CoordJobGetActionsNotCompletedJPAExecutor(jobId);
List<CoordinatorActionBean> actionList = jpaService.execute(actionGetCmd);
// check for expected column values
CoordinatorActionBean action = actionList.get(0);
assertEquals(action.getId(), actionId);
assertEquals(action.getStatus(), status);
assertEquals(action.getPending(), pending);
assertEquals(jobId, action.getJobId());
}
// test sql selection operator
private void _testCoordActionsNotCompletedSize(String jobId, int expectedSize) throws Exception {
JPAService jpaService = Services.get().get(JPAService.class);
assertNotNull(jpaService);
// Call JPAExecutor to get actions which are not completed
CoordJobGetActionsNotCompletedJPAExecutor actionGetCmd = new CoordJobGetActionsNotCompletedJPAExecutor(jobId);
List<CoordinatorActionBean> actionList = jpaService.execute(actionGetCmd);
// As two actions are not completed, expected result set is of size 2
assertEquals(actionList.size(), expectedSize);
}
}
|
state303/spring-batch
|
spring-batch-core/src/test/java/org/springframework/batch/core/jsr/configuration/xml/BatchParserTests.java
|
/*
* Copyright 2013 the original author or authors.
*
* 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
*
* https://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.springframework.batch.core.jsr.configuration.xml;
import org.junit.Test;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.configuration.xml.DummyItemProcessor;
import org.springframework.batch.core.scope.StepScope;
import org.springframework.batch.core.scope.context.StepSynchronizationManager;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class BatchParserTests {
@Test
@SuppressWarnings("unchecked")
public void testRoseyScenario() throws Exception {
JsrXmlApplicationContext context = new JsrXmlApplicationContext();
Resource batchXml = new ClassPathResource("/org/springframework/batch/core/jsr/configuration/xml/batch.xml");
context.setValidating(false);
context.load(batchXml);
GenericBeanDefinition stepScope = new GenericBeanDefinition();
stepScope.setBeanClass(StepScope.class);
context.registerBeanDefinition("stepScope", stepScope);
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(AutowiredAnnotationBeanPostProcessor.class);
context.registerBeanDefinition("postProcessor", bd);
context.refresh();
ItemProcessor<String, String> itemProcessor = context.getBean(ItemProcessor.class);
assertNotNull(itemProcessor);
StepSynchronizationManager.register(new StepExecution("step1", new JobExecution(5l)));
assertEquals("Test", itemProcessor.process("Test"));
StepSynchronizationManager.close();
context.close();
}
@Test
@SuppressWarnings("unchecked")
public void testOverrideBeansFirst() throws Exception {
JsrXmlApplicationContext context = new JsrXmlApplicationContext();
Resource overrideXml = new ClassPathResource("/org/springframework/batch/core/jsr/configuration/xml/override_batch.xml");
Resource batchXml = new ClassPathResource("/org/springframework/batch/core/jsr/configuration/xml/batch.xml");
context.setValidating(false);
context.load(overrideXml, batchXml);
context.refresh();
ItemProcessor<String, String> itemProcessor = context.getBean("itemProcessor", ItemProcessor.class);
assertNotNull(itemProcessor);
StepSynchronizationManager.register(new StepExecution("step1", new JobExecution(5l)));
assertEquals("Test", itemProcessor.process("Test"));
StepSynchronizationManager.close();
context.close();
}
@Test
@SuppressWarnings({"resource", "rawtypes"})
public void testOverrideBeansLast() {
JsrXmlApplicationContext context = new JsrXmlApplicationContext();
Resource overrideXml = new ClassPathResource("/org/springframework/batch/core/jsr/configuration/xml/override_batch.xml");
Resource batchXml = new ClassPathResource("/org/springframework/batch/core/jsr/configuration/xml/batch.xml");
context.setValidating(false);
context.load(batchXml, overrideXml);
context.refresh();
ItemProcessor processor = (ItemProcessor) context.getBean("itemProcessor");
assertNotNull(processor);
assertTrue(processor instanceof DummyItemProcessor);
context.close();
}
}
|
JamesLinus/rose
|
src/midend/MDCG/lib/klt/klt.cpp
|
#include "sage3basic.h"
#include "KLT/Language/c-family.hpp"
#include "MDCG/KLT/runtime.hpp"
namespace MDCG {
namespace KLT {
template <> Runtime< ::KLT::Language::C, ::KLT::Language::C>::host_api_t Runtime< ::KLT::Language::C, ::KLT::Language::C>::host_api = Runtime< ::KLT::Language::C, ::KLT::Language::C>::host_api_t();
template <> Runtime< ::KLT::Language::C, ::KLT::Language::C>::kernel_api_t Runtime< ::KLT::Language::C, ::KLT::Language::C>::kernel_api = Runtime< ::KLT::Language::C, ::KLT::Language::C>::kernel_api_t();
template <> Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::host_api_t Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::host_api = Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::host_api_t();
template <> Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::kernel_api_t Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::kernel_api = Runtime< ::KLT::Language::C, ::KLT::Language::OpenCL>::kernel_api_t();
template <> Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::host_api_t Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::host_api = Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::host_api_t();
template <> Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::kernel_api_t Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::kernel_api = Runtime< ::KLT::Language::C, ::KLT::Language::CUDA>::kernel_api_t();
} // namespace MDCG::KLT
} // namespace MDCG
|
berak/opencv_smallfry
|
demo/py/rtree.py
|
import cv2
import numpy as np
import random
import pdb
# https://github.com/opencv/opencv/pull/8004
data = list()
classes = list()
test = np.array([[1,2,3,4,5]]).astype(np.float32)
for i in range(20):
entry = list()
for j in range(5):
entry.append(int(random.random() * 10))
data.append(entry)
data = np.array(data).astype(np.float32)
for i in range(20):
classes.append(int(random.random() * 100) % 3 )
classes = np.array(classes)
#model = cv2.ml.SVM_create()
model = cv2.ml.RTrees_create()
model.train(data , cv2.ml.ROW_SAMPLE , classes)
eval_1 = model.predict(test)[1]
print(eval_1)
#model.save("SVM_test.xml")
model.save("RTrees_test.xml")
model2 = cv2.ml.RTrees_load("RTrees_test.xml")
#model2 = cv2.ml.SVM_load("SVM_test.xml")
eval_2 = model2.predict(test)[1]
print (eval_2 == eval_1)
|
Mozu/mozu-java
|
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/customer/CurrencyAmount.java
|
<reponame>Mozu/mozu-java
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.customer;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;
/**
* The currency code and the total monetary sum of the order. Currently, only USD is supported.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CurrencyAmount implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
protected Double amount;
public Double getAmount() {
return this.amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
protected String currencyCode;
public String getCurrencyCode() {
return this.currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
}
|
fancyremarker/opsworks-cli
|
lib/opsworks/instance.rb
|
<reponame>fancyremarker/opsworks-cli<filename>lib/opsworks/instance.rb<gh_stars>0
require 'opsworks/resource'
module OpsWorks
class Instance < Resource
attr_accessor :id, :hostname, :ec2_instance_id, :instance_type, :status
def self.from_collection_response(response)
response.data[:instances].map do |hash|
new(
id: hash[:instance_id],
hostname: hash[:hostname],
ec2_instance_id: hash[:ec2_instance_id],
instance_type: hash[:instance_type],
status: hash[:status]
)
end
end
def online?
status == 'online'
end
end
end
|
thewizardplusplus/wizard-parser
|
source/thewizardplusplus/wizard_parser/vendor/range/v3/utility/scope_exit.hpp
|
<filename>source/thewizardplusplus/wizard_parser/vendor/range/v3/utility/scope_exit.hpp
/// \file
// Range v3 library
//
// Copyright <NAME> 2017-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_UTILITY_SCOPE_EXIT_HPP
#define RANGES_V3_UTILITY_SCOPE_EXIT_HPP
#include <functional>
#include <type_traits>
#include <utility>
#include "../../../meta/meta.hpp"
namespace ranges
{
inline namespace v3
{
template<typename Fun>
struct scope_exit
{
private:
using nothrow_move_t = std::is_nothrow_move_constructible<Fun>;
using nothrow_copy_t = std::is_nothrow_copy_constructible<Fun>;
Fun fun_;
bool dismissed_{false};
using ref_t = decltype(std::ref(std::declval<Fun const &>()));
using guard = scope_exit<ref_t>;
scope_exit(Fun const &fun, guard &&g)
: fun_(fun)
{
g.dismiss();
}
scope_exit(Fun const &fun, std::false_type)
: scope_exit(fun, guard{std::ref(fun)})
{}
scope_exit(Fun const &fun, std::true_type) noexcept
: fun_(fun)
{}
scope_exit(Fun &&fun, std::true_type) noexcept
: fun_(std::move(fun))
{}
public:
explicit scope_exit(Fun const &fun)
noexcept(noexcept(scope_exit(fun, nothrow_copy_t{})))
: scope_exit(fun, nothrow_copy_t{})
{}
explicit scope_exit(Fun &&fun)
noexcept(noexcept(scope_exit(std::move(fun), nothrow_move_t{})))
: scope_exit(std::move(fun), nothrow_move_t{})
{}
scope_exit(scope_exit const &) = delete;
scope_exit(scope_exit &&that)
noexcept(std::is_nothrow_move_constructible<Fun>::value)
: scope_exit(std::move((that.dismiss(), that)).fun_)
{}
~scope_exit()
{
if(!dismissed_)
fun_();
}
void dismiss() noexcept
{
dismissed_ = true;
}
};
template<typename Fun,
typename ScopeExit = scope_exit<meta::_t<std::decay<Fun>>>>
ScopeExit make_scope_exit(Fun &&fun)
noexcept(noexcept(ScopeExit(ScopeExit((Fun &&) fun))))
{
return ScopeExit((Fun &&) fun);
}
}
}
#endif
|
BelieveSong/fssi
|
wallet/src/main/scala/fssi/wallet/WalletMain.scala
|
<reponame>BelieveSong/fssi
package fssi.wallet
import fssi.wallet.controller.LoginController
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.Scene
import scalafx.Includes._
import scalafx.geometry.Insets
import scalafx.scene.effect.DropShadow
import scalafx.scene.layout.{Region, StackPane}
import scalafx.scene.paint.Color
import scalafx.scene.text.Font
import scalafx.stage.StageStyle
object WalletMain extends JFXApp with LoginFragment with MainFrameFragment {
self =>
fssi.utils.crypto.registerBC()
//load font
Font.loadFont(getClass.getClassLoader.getResource("ui/font/Metropolis-Regular.otf").toExternalForm, 10)
stage = new PrimaryStage
stage.setMinHeight(768)
stage.setMinWidth(1024)
stage.setTitle("FSSI Wallet - A FSSI Block Chain Client")
//stage.initStyle(StageStyle.Transparent)
//gotoLogin(stage)
gotoMainFrame(stage)
}
|
qtxasjo/Foundation
|
src/Foundation.CommerceManager/Apps/Shell/Scripts/BusinessFoundation/TimePickerExtender.js
|
<gh_stars>10-100
Type.registerNamespace("Ibn");
// ---------------------------------
// ------- TimePickerExtender ---------
// ---------------------------------
// TimePickerExtender Constructor
Ibn.TimePickerExtender = function(element)
{
Ibn.TimePickerExtender.initializeBase(this, [element]);
//internals
this._element = element;
this._timeValue = null;
this._enabled = true;
this._isAM = false;
this._divCssClass = "";
this._storeValue = null;
this._isOpen = false;
this._width = 95;
this._height = 120;
this._popupDiv = null;
this._innerContainer = null;
this._updateElement = null;
this._calendar = null;
this._calendarHandler = null;
this._blur = new Ibn.DeferredOperation(((Sys.Browser.agent === Sys.Browser.Safari) ? 1000 : 100), this, this._onBlur);
this._focus = new Ibn.DeferredOperation(((Sys.Browser.agent === Sys.Browser.Safari) ? 1000 : 100), this, this._onFocus);
this._slowScroll = new Ibn.DeferredOperation(((Sys.Browser.agent == Sys.Browser.InternetExplorer) ? 100 : 1), this, this._setScroll);
this._element$delegates = {
focus : Function.createDelegate(this, this._element_onFocus),
focusout : Function.createDelegate(this, this._element_onBlur),
blur : Function.createDelegate(this, this._element_onBlur),
keyup : Function.createDelegate(this, this._element_onkeyup)
}
this._cell$delegates = {
mouseover : Function.createDelegate(this, this._cell_onmouseover),
mouseout : Function.createDelegate(this, this._cell_onmouseout),
click : Function.createDelegate(this, this._cell_onclick)
}
this._popup$delegates = {
activate : Function.createDelegate(this, this._popup_onfocus),
focus : Function.createDelegate(this, this._popup_onfocus),
dragstart: Function.createDelegate(this, this._popup_ondragstart),
select: Function.createDelegate(this, this._popup_onselect)
}
}
Ibn.TimePickerExtender.prototype =
{
// -========= Properties =========-
get_timeValue: function () {
return this._timeValue;
},
set_timeValue: function (value) {
this._timeValue = value;
},
get_enabled: function () {
return this._enabled;
},
set_enabled: function (value) {
this._enabled = value;
},
get_isAM: function () {
return this._isAM;
},
set_isAM: function (value) {
this._isAM = value;
},
get_divCssClass: function () {
return this._divCssClass;
},
set_divCssClass: function (value) {
this._divCssClass = value;
},
get_calendar: function () {
return this._calendar;
},
set_calendar: function (value) {
this._calendar = value;
},
get_storeValue: function () {
return this._storeValue;
},
set_storeValue: function (value) {
this._storeValue = value;
},
//added by DVS
get_updateElement: function () {
return this._updateElement;
},
set_updateElement: function (value) {
this._updateElement = value;
},
// -========= Methods =========-
// ctor()
initialize : function()
{
Ibn.TimePickerExtender.callBaseMethod(this, 'initialize');
if(this._element)
$addHandlers(this._element, this._element$delegates);
if (this._calendar) {
this._calendarHandler = Function.createDelegate(this, this._onCalendarEditHandler);
this._calendar.add_editValue(this._calendarHandler);
}
if(this._timeValue)
this._element.value = this._timeValue;
this._ensureTimeString();
if(this._calendar)
this._calendar._ensureDateString();
},
dispose: function() {
if (this._calendar && this._calendarHandler) {
this._calendar.remove_editValue(this._calendarHandler);
}
if (this._element) {
$clearHandlers(this._element);
}
if(this._innerContainer)
this._innerContainer = null;
if(this._popupDiv)
this._popupDiv = null;
this._calendar = null;
Ibn.TimePickerExtender.callBaseMethod(this, 'dispose');
},
_onCalendarEditHandler : function(obj, args) {
if(!this._enabled)
return;
var elt = obj.get_element();
if(elt && elt.value == "")
{
if(this._element.value != "")
this._storeValue = this._element.value;
this._element.value = "";
this._element.disabled = true;
}
else
{
if (typeof(this._element) == 'undefined' && this._updateElement)
this._element = $get(this._updateElement.replace(/\$/g,'_'));
this._element.disabled = false;
if(this._storeValue != null && this._element.value == "")
{
this._element.value = this._storeValue;
this._ensureTimeString();
}
}
},
_onBlur : function() {
this._focus.cancel();
this._hide();
this._ensureTimeString();
},
_onFocus : function() {
this._blur.cancel();
this._element.focus();
},
_element_onFocus : function(e) {
if (this._enabled) {
this._focus.cancel();
this._blur.cancel();
this._show();
}
},
_element_onBlur : function(e) {
if ((e.type == 'blur' && Sys.Browser.agent != Sys.Browser.InternetExplorer) ||
(e.type == 'focusout' && Sys.Browser.agent == Sys.Browser.InternetExplorer)) {
this._focus.cancel();
this._blur.post();
}
},
_element_onkeyup : function(e) {
if (this._enabled) {
this._focus.cancel();
this._blur.cancel();
var _keyCode = e.keyCode;
if(_keyCode == 38)
{
//todo - move div up
}
else if(_keyCode == 40)
{
//todo - move div down
}
}
},
_show : function() {
this._ensureTicks();
if (!this._isOpen) {
var t = this._getTotalOffset(this._element);
if(t && t.Left)
this._popupDiv.style.left = t.Left + "px";
if(t && t.Top)
this._popupDiv.style.top = t.Top + this._element.offsetHeight + 1 + "px";
this._popupDiv.style.display = "";
this._isOpen = true;
this._ensureSelected();
}
},
_getTotalOffset : function(eSrc) {
var retVal = new Object();
retVal.Top = 0;
retVal.Left = 0;
while (eSrc)
{
retVal.Top += eSrc.offsetTop;
retVal.Left += eSrc.offsetLeft;
eSrc = eSrc.offsetParent;
}
return retVal;
},
_hide : function() {
if(this._popupDiv)
{
this._popupDiv.style.display = "none";
}
this._isOpen = false;
},
_ensureTicks : function() {
if (!this._popupDiv) {
this._buildPopup();
}
},
_isNearest : function(elemValue) {
var retVal = false;
var sH = "";
var sM = "";
var sAM = "";
if(this._element.value != "")
{
var str = this._element.value;
var idouble = str.indexOf(":");
if(idouble > 0)
{
sH = str.substring(0, idouble);
sM = str.substr(idouble + 1, 2);
if(this._isAM)
sAM = str.substr(idouble + 3);
}
}
var sElH = "";
var sElM = "";
var sElAM = "";
if(elemValue != "")
{
var str = elemValue;
var idouble = str.indexOf(":");
if(idouble > 0)
{
sElH = str.substring(0, idouble);
sElM = str.substr(idouble + 1, 2);
if(this._isAM)
sElAM = str.substr(idouble + 3);
}
}
if(sElH == sH && sAM == sElAM)
{
var iM = parseInt(sM, 10);
var iElM = parseInt(sElM, 10);
if(iM - iElM >= 0 && iM - iElM < 30)
retVal = true;
}
return retVal;
},
_ensureSelected : function() {
var iSel = 0;
var iOffHeight = 0;
if(!this._innerContainer)
return;
var s = "";
for (var i = 0; i < this._innerContainer.childNodes.length; i++) {
var d0 = this._innerContainer.childNodes[i];
if(this._isNearest(d0.innerHTML))
{
s = s + " " + i.toString();
iSel = i;
iOffHeight = d0.offsetHeight;
d0.style.backgroundColor = "#0000ff";
d0.style.color = "#ffffff";
}
else
{
d0.style.backgroundColor = "#ffffff";
d0.style.color = "#000000";
}
}
this._slowScroll.post(iSel, iOffHeight);
},
_setScroll : function (x,y){
if(this._popupDiv)
this._popupDiv.scrollTop = x*y;
},
_buildPopup : function() {
/// <summary>
/// Builds the calendar's layout
/// </summary>
this._popupDiv = this._createElementFromTemplate({
nodeName : "div",
events : this._popup$delegates,
visible : true
}, document.body);
if(this._divCssClass != "")
this._popupDiv.className = this._divCssClass;
this._popupDiv.style.backgroundColor = "#ffffff";
this._popupDiv.style.border = "1px solid";
this._popupDiv.style.borderColor = "#000000";
this._popupDiv.style.width = this._width + "px";
this._popupDiv.style.height = this._height + "px";
this._popupDiv.style.overflow = "auto";
this._popupDiv.style.zIndex = "2";
this._popupDiv.style.position = "absolute";
this._popupDiv.style.left = "50px";
this._popupDiv.style.top = "50px";
this._innerContainer = this._createElementFromTemplate({
nodeName : "div",
events : null,
visible : true
}, this._popupDiv);
for(var i=0;i<24;i++)
{
var d0 = this._createElementFromTemplate({
nodeName : "div",
events : this._cell$delegates,
visible : true
}, this._innerContainer);
d0.innerHTML = this._getTimeString(i.toString(),"0");
d0.style.cursor = "pointer";
d0.style.padding = "2px";
d0.style.backgroundColor = "#ffffff";
d0.style.color = "#000000";
var d30 = this._createElementFromTemplate({
nodeName : "div",
events : this._cell$delegates,
visible : true
}, this._innerContainer);
d30.innerHTML = this._getTimeString(i.toString(),"30");
d30.style.cursor = "pointer";
d30.style.padding = "2px";
d30.style.backgroundColor = "#ffffff";
d30.style.color = "#000000";
}
this._popupDiv.style.display = "none";
},
_getTimeString : function(h,m) {
var am = "";
if(!this._isAM && parseInt(h, 10) < 10)
h = "0" + h;
else if(this._isAM)
{
if(parseInt(h, 10) == 0)
{
h = "12";
am = "AM";
}
else if(parseInt(h, 10) < 12)
am = "AM";
else if(parseInt(h, 10) > 12)
{
h = (parseInt(h, 10) - 12).toString();
am = "PM";
}
else
am = "PM";
}
var retVal = h + ":";
var sM = m;
if(parseInt(m, 10)<10)
sM = "0" + sM;
retVal = retVal + sM;
if(this._isAM)
retVal = retVal + am;
return retVal;
},
_ensureTimeString : function() {
if(this._element.value == "")
return;
var str = this._element.value;
var idouble = str.indexOf(":");
if(idouble < 0)
{
this._element.value = "";
return;
}
try {
var sH = str.substring(0, idouble);
if(sH == "")
sH = "0";
var sM = str.substr(idouble + 1, 2);
if(sM == "")
sM = "0";
if(isNaN(parseInt(sM, 10)))
{
this._element.value = "";
return;
}
if(parseInt(sH, 10) > 24 || parseInt(sH, 10)<0)
{
this._element.value = "";
return;
}
if(parseInt(sM, 10)>59 || parseInt(sM, 10)<0)
{
this._element.value = "";
return;
}
if(parseInt(sM, 10)<10)
sM = "0" + parseInt(sM, 10).toString();
var sAM = str.substr(idouble + 3);
sAM = sAM.replace(" ", "");
if(this._isAM)
{
if(parseInt(sH, 10) == 0)
{
sH = "12";
sAM = "AM";
}
if(sAM == "")
{
if(parseInt(sH, 10) < 12)
sAM = "AM";
else
sAM = "PM";
}
if(sAM.toLowerCase() == "am")
sAM = "AM";
else if(sAM.toLowerCase() == "pm")
sAM = "PM";
else
sAM = "AM";
if(parseInt(sH, 10)<10)
sH = parseInt(sH, 10).toString();
if(parseInt(sH, 10)>12)
{
sH = (parseInt(sH, 10) - 12).toString();
sAM = "PM";
}
}
if(!this._isAM)
{
if(sAM.toLowerCase() == "am")
{
if(parseInt(sH, 10) == 12)
sH = "00";
}
if(sAM.toLowerCase() == "pm")
{
if(parseInt(sH, 10) < 12)
sH = (parseInt(sH, 10) + 12).toString();
}
if(parseInt(sH, 10)<10)
sH = "0" + parseInt(sH, 10).toString();
sAM = "";
}
this._element.value = sH + ":" + sM + sAM.toUpperCase();
}
catch(e)
{
this._element.value = "";
return;
}
},
_cell_onmouseover : function(e) {
for (var i = 0; i < this._innerContainer.childNodes.length; i++) {
var d0 = this._innerContainer.childNodes[i];
d0.style.backgroundColor = "#ffffff";
d0.style.color = "#000000";
}
var target = e.target;
target.style.backgroundColor = "#0000ff";
target.style.color = "#ffffff";
e.stopPropagation();
},
_cell_onmouseout : function(e) {
var target = e.target;
target.style.backgroundColor = "#ffffff";
target.style.color = "#000000";
e.stopPropagation();
},
_cell_onclick : function(e) {
if ((Sys.Browser.agent === Sys.Browser.Safari) ||
(Sys.Browser.agent === Sys.Browser.Opera)) {
this._popup_onfocus(e);
}
var target = e.target;
this._element.value = target.innerHTML;
this._focus.cancel();
this._blur.post();
//this._hide();
e.stopPropagation();
e.preventDefault();
if (this._updateElement)
{
__doPostBack(this._updateElement, '');
}
},
_popup_onfocus : function(e) {
if ((e.type == 'focus' && Sys.Browser.agent != Sys.Browser.InternetExplorer) ||
(e.type == 'activate' && Sys.Browser.agent == Sys.Browser.InternetExplorer) ||
(Sys.Browser.agent === Sys.Browser.Safari) ||
(Sys.Browser.agent === Sys.Browser.Opera)) {
if (this._isOpen) {
this._blur.cancel();
this._focus.post();
}
}
},
_popup_ondragstart : function(e) {
e.stopPropagation();
e.preventDefault();
},
_popup_onselect : function(e) {
e.stopPropagation();
e.preventDefault();
},
_createElementFromTemplate : function(template, appendToParent, nameTable) {
// if we wish to override the name table we do so here
if (typeof(template.nameTable)!='undefined') {
var newNameTable = template.nameTable;
if (String.isInstanceOfType(newNameTable)) {
newNameTable = nameTable[newNameTable];
}
if (newNameTable != null) {
nameTable = newNameTable;
}
}
// get a name for the element in the nameTable
var elementName = null;
if (typeof(template.name)!=='undefined') {
elementName = template.name;
}
// create or acquire the element
var elt = document.createElement(template.nodeName);
// if our element is named, add it to the name table
if (typeof(template.name)!=='undefined' && nameTable) {
nameTable[template.name] = elt;
}
// if we wish to supply a default parent we do so here
if (typeof(template.parent)!=='undefined' && appendToParent == null) {
var newParent = template.parent;
if (String.isInstanceOfType(newParent)) {
newParent = nameTable[newParent];
}
if (newParent != null) {
appendToParent = newParent;
}
}
// events are added to the dom element using $addHandlers
if (typeof(template.events)!=='undefined' && template.events != null) {
$addHandlers(elt, template.events);
}
// if the element is visible or not its visibility is set
if (typeof(template.visible)!=='undefined' && template.visible != null) {
if(template.visible)
elt.style.display = "";
else
elt.style.display = "none";
}
// if we have an appendToParent we will now append to it
if (appendToParent) {
appendToParent.appendChild(elt);
}
// if we have child templates, process them
if (typeof(template.children)!=='undefined' && template.children != null) {
for (var i = 0; i < template.children.length; i++) {
var subtemplate = template.children[i];
createElementFromTemplate(subtemplate, elt, nameTable);
}
}
// if we have a content presenter for the element get it (the element itself is the default presenter for content)
var contentPresenter = elt;
if (typeof(template.contentPresenter)!=='undefined' && template.contentPresenter != null) {
contentPresenter = nameTable[contentPresenter];
}
// if we have content, add it
if (typeof(template.content)!=='undefined' && template.content != null) {
var content = template.content;
if (String.isInstanceOfType(content)) {
content = nameTable[content];
}
if (content.parentNode) {
wrapElement(content, elt, contentPresenter);
} else {
contentPresenter.appendChild(content);
}
}
// return the created element
return elt;
},
wrapElement : function(innerElement, newOuterElement, newInnerParentElement) {
var parent = innerElement.parentNode;
parent.replaceChild(newOuterElement, innerElement);
(newInnerParentElement || newOuterElement).appendChild(innerElement);
}
}
Ibn.TimePickerExtender.registerClass("Ibn.TimePickerExtender", Sys.UI.Control);
//Threading
Ibn.DeferredOperation = function(delay, context, callback) {
this._delay = delay;
this._context = context;
this._callback = callback;
this._completeCallback = null;
this._errorCallback = null;
this._timer = null;
this._callArgs = null;
this._isComplete = false;
this._completedSynchronously = false;
this._asyncResult = null;
this._exception = null;
this._throwExceptions = true;
this._oncomplete$delegate = Function.createDelegate(this, this._oncomplete);
// post to ensure that attaching it always gets the port as its context
this.post = Function.createDelegate(this, this.post);
}
Ibn.DeferredOperation.prototype = {
get_isPending : function() {
/// <summary>
/// Gets whether there is an asynchronous operation pending
/// </summary>
/// <returns type="Boolean" />
return (this._timer != null);
},
get_isComplete : function() {
/// <summary>
/// Gets whether the asynchronous operation has completed
/// </summary>
/// <returns type="Boolean" />
return this._isComplete;
},
get_completedSynchronously : function() {
/// <summary>
/// Gets whether the operation completed synchronously
/// </summary>
/// <returns type="Boolean" />
return this._completedSynchronously;
},
get_exception : function() {
/// <summary>
/// Gets the current exception if there is one
/// </summary>
/// <returns type="Error" />
return this._exception;
},
get_throwExceptions : function() {
/// <summary>
/// Gets whether to throw exceptions
/// </summary>
/// <returns type="Boolean" />
return this._throwExceptions;
},
set_throwExceptions : function(value) {
/// <summary>
/// Sets whether to throw exceptions
/// </summary>
/// <param name="value" type="Boolean">True if exceptions should be thrown, otherwise false</param>
this._throwExceptions = value;
},
get_delay : function() {
/// <summary>
/// Gets the current delay in milliseconds
/// </summary>
/// <returns type="Number" integer="true" />
return this._delay;
},
set_delay : function(value) {
/// <summary>
/// Sets the current delay in milliseconds
/// </summary>
/// <param name="value" type="Number" integer="true">The delay in milliseconds</param>
this._delay = value;
},
post : function(args) {
/// <summary>
/// A method that can be directly attached to a delegate
/// </summary>
/// <param name="args" type="Object" parameterArray="true">The arguments to the method</param>
var ar = [];
for (var i = 0; i < arguments.length; i++) {
ar[i] = arguments[i];
}
this.beginPost(ar, null, null);
},
beginPost : function(args, completeCallback, errorCallback) {
/// <summary>
/// Posts a call to an async operation on this port
/// </summary>
/// <param name="args" type="Array">An array of arguments to the method</param>
/// <param name="completeCallback" type="Function" optional="true" mayBeNull="true">The callback to execute after the delayed function completes</param>
/// <param name="errorCallback" type="Function" optional="true" mayBeNull="true">The callback to execute in the event of an exception in the delayed function</param>
// cancel any pending post
this.cancel();
// cache the call arguments
this._callArgs = Array.clone(args || []);
this._completeCallback = completeCallback;
this._errorCallback = errorCallback;
if (this._delay == -1) {
// if there is no delay (-1), complete synchronously
this._oncomplete();
this._completedSynchronously = true;
} else {
// complete the post on a seperate call after a delay
this._timer = setTimeout(this._oncomplete$delegate, this._delay);
}
},
cancel : function() {
/// <summary>
/// Cancels a pending post
/// </summary>
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
this._callArgs = null;
this._isComplete = false;
this._asyncResult = null;
this._completeCallback = null;
this._errorCallback = null;
this._exception = null;
this._completedSynchronously = false;
},
complete : function() {
/// <summary>
/// Completes a pending post synchronously
/// </summary>
if (this._timer) {
try {
this._oncomplete();
} finally {
this._completedSynchronously = true;
}
return this._asyncResult;
} else if (this._isComplete) {
return this._asyncResult;
}
},
_oncomplete : function() {
/// <summary>
/// Completes a pending post asynchronously
/// </summary>
var args = this._callArgs;
var completeCallback = this._completeCallback;
var errorCallback = this._errorCallback;
// clear the post state
this.cancel();
try {
// call the post callback
if (args) {
this._asyncResult = this._callback.apply(this._context, args);
} else {
this._asyncResult = this._callback.call(this._context);
}
this._isComplete = true;
this._completedSynchronously = false;
if (completeCallback) {
completeCallback(this);
}
} catch (e) {
this._isComplete = true;
this._completedSynchronously = false;
this._exception = e;
if (errorCallback) {
if (errorCallback(this)) {
return;
}
}
if (this._throwExceptions) {
throw e;
}
}
}
}
Ibn.DeferredOperation.registerClass("Ibn.DeferredOperation");
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
|
lzhzero/ycsb-c-bang
|
Core/generator/scrambled_zipfian_generator.h
|
//
// scrambled_zipfian_generator.h
// YCSB-C
//
// Created by <NAME> on 12/8/14.
// Copyright (c) 2014 <NAME> <<EMAIL>>.
//
#ifndef YCSB_C_SCRAMBLED_ZIPFIAN_GENERATOR_H_
#define YCSB_C_SCRAMBLED_ZIPFIAN_GENERATOR_H_
#include "generator.h"
#include <cstdint>
#include "zipfian_generator.h"
#include "Util/funcs.h"
namespace Ycsb {
namespace Core {
class ScrambledZipfianGenerator : public Generator<uint64_t> {
public:
ScrambledZipfianGenerator(uint64_t min, uint64_t max,
double zipfian_const = ZipfianGenerator::kZipfianConst) :
base_(min), num_items_(max - min + 1),
generator_(min, max, zipfian_const) { }
ScrambledZipfianGenerator(uint64_t num_items) :
base_(0), num_items_(num_items),
generator_(0, num_items -1 , ZipfianGenerator::kZipfianConst) { }
uint64_t Next();
uint64_t Last() { return last_; }
private:
uint64_t base_;
uint64_t num_items_;
ZipfianGenerator generator_;
uint64_t last_;
};
inline uint64_t ScrambledZipfianGenerator::Next() {
uint64_t value = generator_.Next();
value = base_ + Util::FNVHash64(value) % num_items_;
return last_ = value;
}
} // Core
} // Ycsb
#endif // YCSB_C_SCRAMBLED_ZIPFIAN_GENERATOR_H_
|
gabi62215/Teme
|
apd_tema_2/skel/Result.java
|
import java.util.Hashtable;
import java.util.List;
// class that contains results from the map task
public class Result {
Hashtable<Integer, Integer> dict;
List<String> longest_words;
String doc_name;
public Result(Hashtable<Integer, Integer> dict, List<String> longest_words, String doc_name) {
this.dict = dict;
this.longest_words = longest_words;
this.doc_name = doc_name;
}
}
|
phvu/cebes-server
|
cebes-pipeline-serving/src/test/scala/io/cebes/serving/http/CebesServingSecuredServerSuite.scala
|
/* Copyright 2016 The Cebes Authors. All Rights Reserved.
*
* Licensed under the Apache License, version 2.0 (the "License").
* You may not use this work except in compliance with the License,
* which is available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package io.cebes.serving.http
import io.cebes.http.helper.SecuredTestClient
import io.cebes.http.server.HttpServer
import io.cebes.serving.inject.ServingTestInjector
/**
* Tests for [[CebesServingSecuredServer]].
* All the tests are inherited from [[CebesServingServerSuite]], but with secured server.
*/
class CebesServingSecuredServerSuite extends CebesServingServerSuite with SecuredTestClient {
override protected val server: HttpServer =
ServingTestInjector.injector.getInstance(classOf[CebesServingSecuredServer])
}
|
jorgejesus/soils-revealed
|
api/charts/index.js
|
const getOnTheFlyData = require('./on-the-fly');
const getTimeseriesData = require('./timeseries');
const getChangeData = require('./change');
const { combineTimeseriesData, combineChangeData } = require('./helpers');
module.exports = async (
{
params: { layer, type, boundaries, depth },
query: { scenario },
body: { areaInterest, compareAreaInterest },
},
res
) => {
try {
let resData;
const data =
typeof areaInterest === 'object'
? await getOnTheFlyData({ layer, type, depth, areaInterest, scenario })
: {
timeseries: await getTimeseriesData({
layer,
type,
boundaries,
depth,
areaInterest,
scenario,
}),
change: await getChangeData({ layer, type, boundaries, depth, areaInterest, scenario }),
};
resData = data;
if (compareAreaInterest !== null && compareAreaInterest !== undefined) {
const compareData =
typeof compareAreaInterest === 'object'
? await getOnTheFlyData({
layer,
type,
depth,
areaInterest: compareAreaInterest,
scenario,
})
: {
timeseries: await getTimeseriesData({
layer,
type,
boundaries,
depth,
areaInterest: compareAreaInterest,
scenario,
}),
change: await getChangeData({
layer,
type,
boundaries,
depth,
areaInterest: compareAreaInterest,
scenario,
}),
};
resData = {
timeseries: combineTimeseriesData(data.timeseries, compareData.timeseries),
change: combineChangeData(data.change, compareData.change),
};
}
// We cache the results for 10 minutes
res.set('Cache-Control', `public,max-age=${10 * 60}`);
res.send({ data: resData });
} catch (e) {
console.log(e);
res.status(404).end();
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.