repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
Partmedia/bag | src/bag/layout/util.py | <gh_stars>0
# SPDX-License-Identifier: BSD-3-Clause AND Apache-2.0
# Copyright 2018 Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Copyright 2019 Blue Cheetah Analog Design Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains utility classes used for layout
"""
# noinspection PyUnresolvedReferences
from pybag.core import BBox, BBoxArray, BBoxCollection
class PortSpec(object):
"""Specification of a port.
Parameters
----------
ntr : int
number of tracks the port should occupy
idc : float
DC current the port should support, in Amperes.
"""
def __init__(self, ntr, idc):
self._ntr = ntr
self._idc = idc
@property
def ntr(self):
"""minimum number of tracks the port should occupy"""
return self._ntr
@property
def idc(self):
"""minimum DC current the port should support, in Amperes"""
return self._idc
def __str__(self):
return repr(self)
def __repr__(self):
fmt_str = '%s(%d, %.4g)'
return fmt_str % (self.__class__.__name__, self._ntr, self._idc)
class Pin(object):
"""A layout pin.
Multiple pins can share the same terminal name.
Parameters
----------
pin_name : str
the pin label.
term_name : str
the terminal name.
layer : str
the pin layer name.
bbox : bag.layout.util.BBox
the pin bounding box.
"""
def __init__(self, pin_name, term_name, layer, bbox):
if not bbox.is_physical():
raise Exception('Non-physical pin bounding box: %s' % bbox)
self._pin_name = pin_name
self._term_name = term_name
self._layer = layer
self._bbox = bbox
@property
def pin_name(self):
"""the pin label."""
return self._pin_name
@property
def term_name(self):
"""the terminal name."""
return self._term_name
@property
def layer(self):
"""the pin layer name"""
return self._layer
@property
def bbox(self):
"""the pin bounding box."""
return self._bbox
def __str__(self):
return repr(self)
def __repr__(self):
return '%s(%s, %s, %s, %s)' % (self.__class__.__name__, self._pin_name,
self._term_name, self._layer, self._bbox)
|
sailxjx/DI-engine | dizoo/image_classification/data/sampler.py | import math
import torch
from torch.utils.data import Sampler
from ding.utils import get_rank, get_world_size
class DistributedSampler(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
process can pass a DistributedSampler instance as a DataLoader sampler,
and load a subset of the original dataset that is exclusive to it.
.. note::
Dataset is assumed to be of constant size.
Arguments:
dataset: Dataset used for sampling.
world_size (optional): Number of processes participating in
distributed training.
rank (optional): Rank of the current process within world_size.
"""
def __init__(self, dataset, world_size=None, rank=None, round_up=True):
if world_size is None:
world_size = get_world_size()
if rank is None:
rank = get_rank()
self.dataset = dataset
self.world_size = world_size
self.rank = rank
self.round_up = round_up
self.epoch = 0
self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.world_size))
if self.round_up:
self.total_size = self.num_samples * self.world_size
else:
self.total_size = len(self.dataset)
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = list(torch.randperm(len(self.dataset), generator=g))
# add extra samples to make it evenly divisible
if self.round_up:
indices += indices[:(self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
offset = self.num_samples * self.rank
indices = indices[offset:offset + self.num_samples]
if self.round_up or (not self.round_up and self.rank < self.world_size - 1):
assert len(indices) == self.num_samples
return iter(indices)
def __len__(self):
return self.num_samples
def set_epoch(self, epoch):
self.epoch = epoch
|
Almadanmp/frontend | src/views/GeographicArea/Area.js | <reponame>Almadanmp/frontend<filename>src/views/GeographicArea/Area.js
import React, {Component} from 'react';
import US001 from "./US001";
import US002 from './US002';
import US004 from './US004';
import US006 from './US006';
import US006Redux from './US006Redux/US006Redux';
import US007Redux from './US007Redux/US007Redux';
import US010 from './US010';
import US011 from './US011';
import AreasList from './TableAreas/AreasList';
class Area extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {collapse: false};
}
toggle() {
this.setState(state => ({collapse: !state.collapse}));
}
render() {
return (
<div>
<h2>Welcome to the Geographic Area Menu</h2>
<p></p>
<AreasList/>
<US001/>
<US007Redux/>
</div>
);
}
}
export default Area;
|
viticm/web-pap | server/Common/Packets/CGPlayerShopAskForRecord.h | <filename>server/Common/Packets/CGPlayerShopAskForRecord.h
// CGPlayerShopAskForRecord.h
//
// 向服务器申请创建玩家商店
//
//////////////////////////////////////////////////////
#ifndef __CGPLAYERSHOPASKFORRECORD_H__
#define __CGPLAYERSHOPASKFORRECORD_H__
#include "Type.h"
#include "Packet.h"
#include "PacketFactory.h"
#include "GCPlayerShopError.h"
namespace Packets
{
class CGPlayerShopAskForRecord : public Packet
{
public:
enum
{
TYPE_EXCHANGE_RECORD = 0,
TYPE_MANAGER_RECORD,
};
public:
CGPlayerShopAskForRecord( )
{
m_ShopID.Reset();
m_bType = 0;
m_bPage = 0;
}
virtual ~CGPlayerShopAskForRecord( ){};
//公用继承接口
virtual BOOL Read( SocketInputStream& iStream ) ;
virtual BOOL Write( SocketOutputStream& oStream )const ;
virtual UINT Execute( Player* pPlayer ) ;
virtual PacketID_t GetPacketID()const { return PACKET_CG_PLAYERSHOPASKFORRECORD; }
virtual UINT GetPacketSize()const { return sizeof(BYTE)*2+sizeof(_PLAYERSHOP_GUID);}
BYTE GetType(){return m_bType;}
VOID SetType(BYTE bType){m_bType = bType;}
BYTE GetPage(){return m_bPage;}
VOID SetPage(BYTE bPage){m_bPage = bPage;}
_PLAYERSHOP_GUID GetShopID(VOID) const {return m_ShopID;}
VOID SetShopID(_PLAYERSHOP_GUID nShopID) {m_ShopID = nShopID;}
private:
_PLAYERSHOP_GUID m_ShopID; //商店ID
BYTE m_bType;
BYTE m_bPage;
};
class CGPlayerShopAskForRecordFactory : public PacketFactory
{
public:
Packet* CreatePacket() { return new CGPlayerShopAskForRecord() ; }
PacketID_t GetPacketID()const { return PACKET_CG_PLAYERSHOPASKFORRECORD; };
UINT GetPacketMaxSize()const { return sizeof(BYTE)*2+sizeof(_PLAYERSHOP_GUID);};
};
class CGPlayerShopAskForRecordHandler
{
public:
static UINT Execute( CGPlayerShopAskForRecord* pPacket, Player* pPlayer ) ;
};
}
using namespace Packets;
#endif
|
scjalliance/resourceful | enforcer/properties_windows.go | //go:build windows
// +build windows
package enforcer
import (
"github.com/gentlemanautomaton/winproc"
"github.com/scjalliance/resourceful/lease"
)
// Properties returns the lease properties for p.
func Properties(p winproc.Process, environment lease.Properties) lease.Properties {
props := make(lease.Properties, len(environment)+7)
for k, v := range environment {
props[k] = v
}
props["program.name"] = p.Name
props["program.path"] = p.Path
props["process.id"] = p.ID.String()
props["process.creation"] = p.Times.Creation.String()
props["user.id"] = p.User.SID
props["user.account"] = p.User.Account
props["user.domain"] = p.User.Domain
return props
}
|
setonup/PicoKit | Examples/AWSECommerce/AWSECommerce/com/amazon/webservices/awsecommerceservice/_2011_08_01/Offer.h | <reponame>setonup/PicoKit
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!
#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"
@class OfferListing;
@class Merchant;
@class Promotions;
@class OfferAttributes;
@class LoyaltyPoints;
/**
(public class)
@ingroup AWSECommerceServicePortType
*/
@interface Offer : NSObject <PicoBindable> {
@private
Merchant *_merchant;
OfferAttributes *_offerAttributes;
NSMutableArray *_offerListing;
LoyaltyPoints *_loyaltyPoints;
Promotions *_promotions;
}
/**
(public property)
type : class Merchant
*/
@property (nonatomic, strong) Merchant *merchant;
/**
(public property)
type : class OfferAttributes
*/
@property (nonatomic, strong) OfferAttributes *offerAttributes;
/**
(public property)
entry type : class OfferListing
*/
@property (nonatomic, strong) NSMutableArray *offerListing;
/**
(public property)
type : class LoyaltyPoints
*/
@property (nonatomic, strong) LoyaltyPoints *loyaltyPoints;
/**
(public property)
type : class Promotions
*/
@property (nonatomic, strong) Promotions *promotions;
@end
|
ericbrandwein/CodeforcesAPI | examples/load_hacks_for_contest/main.py | #!/usr/bin/env python3
"""
In this example we are loading hacks for contest by it's id
"""
import os
import sys
from codeforces import CodeforcesAPI
def main(argv):
api = CodeforcesAPI()
contest_id = int(argv[1])
hacks = api.contest_hacks(contest_id)
for h in hacks:
print("[{:^30}] hacked [{:^30}], verdict: {}".format(', '.join(member.handle for member in h.hacker.members),
', '.join(member.handle for member in h.defender.members),
h.verdict.value))
if __name__ == '__main__':
if len(sys.argv) == 2:
main(sys.argv)
else:
print("Invalid number of arguments")
print("Usage: python {} [contest id]".format(os.path.basename(sys.argv[0]))) |
consensusnetworks/accumulate | cmd/cli/cmd/util.go | <filename>cmd/cli/cmd/util.go
package cmd
import (
"context"
"encoding"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"math/big"
"strconv"
"time"
api2 "github.com/AccumulateNetwork/accumulate/internal/api/v2"
url2 "github.com/AccumulateNetwork/accumulate/internal/url"
"github.com/AccumulateNetwork/accumulate/protocol"
"github.com/AccumulateNetwork/accumulate/types"
"github.com/AccumulateNetwork/accumulate/types/api/response"
"github.com/AccumulateNetwork/accumulate/types/api/transactions"
"github.com/AccumulateNetwork/accumulate/types/state"
"github.com/AccumulateNetwork/jsonrpc2/v15"
"github.com/spf13/cobra"
)
func getRecord(url string, rec interface{}) (*api2.MerkleState, error) {
params := api2.UrlQuery{
Url: url,
}
res := new(api2.QueryResponse)
res.Data = rec
if err := Client.Request(context.Background(), "query", ¶ms, res); err != nil {
return nil, err
}
return res.MerkleState, nil
}
func getRecordById(chainId []byte, rec interface{}) (*api2.MerkleState, error) {
params := api2.ChainIdQuery{
ChainId: chainId,
}
res := new(api2.QueryResponse)
res.Data = rec
if err := Client.Request(context.Background(), "query-chain", ¶ms, res); err != nil {
return nil, err
}
return res.MerkleState, nil
}
func prepareSigner(origin *url2.URL, args []string) ([]string, *transactions.SignatureInfo, []byte, error) {
var privKey []byte
var err error
ct := 0
if len(args) == 0 {
return nil, nil, nil, fmt.Errorf("insufficent arguments on comand line")
}
ed := transactions.SignatureInfo{}
ed.URL = origin.String()
ed.KeyPageHeight = 1
ed.KeyPageIndex = 0
if IsLiteAccount(origin.String()) == true {
privKey, err = LookupByLabel(origin.String())
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to find private key for lite account %s %v", origin.String(), err)
}
return args, &ed, privKey, nil
}
if len(args) > 1 {
b, err := pubKeyFromString(args[0])
if err != nil {
privKey, err = LookupByLabel(args[0])
if err != nil {
return nil, nil, nil, fmt.Errorf("invalid public key or wallet label specified on command line")
}
} else {
privKey, err = LookupByPubKey(b)
if err != nil {
return nil, nil, nil, fmt.Errorf("invalid public key, cannot resolve signing key")
}
}
ct++
} else {
return nil, nil, nil, fmt.Errorf("insufficent arguments on comand line")
}
if len(args) > 2 {
if v, err := strconv.ParseInt(args[1], 10, 64); err == nil {
ct++
ed.KeyPageIndex = uint64(v)
}
}
originRec := new(state.ChainHeader)
_, err = getRecord(origin.String(), &originRec)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get %q : %v", origin, err)
}
bookRec := new(protocol.KeyBook)
if originRec.KeyBook == (types.Bytes32{}) {
_, err := getRecord(origin.String(), &bookRec)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get %q : %v", origin, err)
}
} else {
_, err := getRecordById(originRec.KeyBook[:], &bookRec)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get %q : %v", origin, err)
}
}
if ed.KeyPageIndex >= uint64(len(bookRec.Pages)) {
return nil, nil, nil, fmt.Errorf("key page index %d is out of bound of the key book of %q", ed.KeyPageIndex, origin)
}
ms, err := getRecordById(bookRec.Pages[ed.KeyPageIndex][:], nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get chain %x : %v", bookRec.Pages[ed.KeyPageIndex][:], err)
}
ed.KeyPageHeight = ms.Count
return args[ct:], &ed, privKey, nil
}
func signGenTx(binaryPayload []byte, origin *url2.URL, si *transactions.SignatureInfo, privKey []byte, nonce uint64) (*transactions.ED25519Sig, error) {
gtx := new(transactions.GenTransaction)
gtx.Transaction = binaryPayload
gtx.ChainID = origin.ResourceChain()
gtx.Routing = origin.Routing()
si.Nonce = nonce
gtx.SigInfo = si
ed := new(transactions.ED25519Sig)
err := ed.Sign(nonce, privKey, gtx.TransactionHash())
if err != nil {
return nil, err
}
return ed, nil
}
func prepareGenTxV2(jsonPayload, binaryPayload []byte, origin *url2.URL, si *transactions.SignatureInfo, privKey []byte, nonce uint64) (*api2.TxRequest, error) {
ed, err := signGenTx(binaryPayload, origin, si, privKey, nonce)
if err != nil {
return nil, err
}
params := &api2.TxRequest{}
if TxPretend {
params.CheckOnly = true
}
// TODO The payload field can be set equal to the struct, without marshalling first
params.Payload = json.RawMessage(jsonPayload)
params.Signer.PublicKey = privKey[32:]
params.Signer.Nonce = nonce
params.Origin = origin.String()
params.KeyPage.Height = si.KeyPageHeight
params.KeyPage.Index = si.KeyPageIndex
params.Signature = ed.GetSignature()
//The public key needs to be used to verify the signature, however,
//to pass verification, the validator will hash the key and check the
//sig spec group to make sure this key belongs to the identity.
params.Signer.PublicKey = ed.GetPublicKey()
return params, err
}
func IsLiteAccount(url string) bool {
u, err := url2.Parse(url)
if err != nil {
log.Fatal(err)
}
u2, err := url2.Parse(u.Authority)
if err != nil {
log.Fatal(err)
}
return protocol.IsValidAdiUrl(u2) != nil
}
func UnmarshalQuery(src interface{}, dst interface{}) error {
d, err := json.Marshal(src)
if err != nil {
return err
}
err = json.Unmarshal(d, dst)
if err != nil {
return err
}
return nil
}
func GetUrlAs(url string, as interface{}) error {
res, err := GetUrl(url)
if err != nil {
return err
}
return UnmarshalQuery(res, as)
}
func GetUrl(url string) (*api2.QueryResponse, error) {
var res api2.QueryResponse
u, err := url2.Parse(url)
params := api2.UrlQuery{}
params.Url = u.String()
data, err := json.Marshal(¶ms)
if err != nil {
return nil, err
}
if err := Client.Request(context.Background(), "query", json.RawMessage(data), &res); err != nil {
ret, err := PrintJsonRpcError(err)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("%v", ret)
}
return &res, nil
}
func dispatchTxRequest(action string, payload encoding.BinaryMarshaler, origin *url2.URL, si *transactions.SignatureInfo, privKey []byte) (*api2.TxResponse, error) {
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
dataBinary, err := payload.MarshalBinary()
if err != nil {
return nil, err
}
nonce := nonceFromTimeNow()
params, err := prepareGenTxV2(data, dataBinary, origin, si, privKey, nonce)
if err != nil {
return nil, err
}
data, err = json.Marshal(params)
if err != nil {
return nil, err
}
var res api2.TxResponse
if err := Client.Request(context.Background(), action, json.RawMessage(data), &res); err != nil {
_, err := PrintJsonRpcError(err)
return nil, err
}
return &res, nil
}
type ActionResponse struct {
Txid types.Bytes32 `json:"txid"`
Hash types.Bytes32 `json:"hash"`
Log types.String `json:"log"`
Code types.String `json:"code"`
Codespace types.String `json:"codespace"`
Error types.String `json:"error"`
Mempool types.String `json:"mempool"`
}
type ActionDataResponse struct {
EntryHash types.Bytes32 `json:"entryHash"`
ActionResponse
}
func ActionResponseFromData(r *api2.TxResponse, entryHash []byte) *ActionDataResponse {
ar := &ActionDataResponse{}
ar.EntryHash.FromBytes(entryHash)
ar.ActionResponse = *ActionResponseFrom(r)
return ar
}
func (a *ActionDataResponse) Print() (string, error) {
var out string
if WantJsonOutput {
ok := a.Code == "0" || a.Code == ""
if ok {
a.Code = "ok"
}
b, err := json.Marshal(a)
if err != nil {
return "", err
}
out = string(b)
} else {
s, err := a.ActionResponse.Print()
if err != nil {
return "", err
}
out = fmt.Sprintf("\n\tEntry Hash\t\t:%x\n%s", a.EntryHash[:], s[1:])
}
return out, nil
}
func ActionResponseFrom(r *api2.TxResponse) *ActionResponse {
return &ActionResponse{
Txid: types.Bytes(r.Txid).AsBytes32(),
Hash: r.Hash,
Error: types.String(r.Message),
Code: types.String(fmt.Sprint(r.Code)),
}
}
func (a *ActionResponse) Print() (string, error) {
ok := a.Code == "0" || a.Code == ""
var out string
if WantJsonOutput {
if ok {
a.Code = "ok"
}
b, err := json.Marshal(a)
if err != nil {
return "", err
}
out = string(b)
} else {
out += fmt.Sprintf("\n\tTransaction Id\t\t:\t%x\n", a.Txid)
out += fmt.Sprintf("\tTendermint Reference\t:\t%x\n", a.Hash)
if !ok {
out += fmt.Sprintf("\tError code\t\t:\t%s\n", a.Code)
} else {
out += fmt.Sprintf("\tError code\t\t:\tok\n")
}
if a.Error != "" {
out += fmt.Sprintf("\tError\t\t\t:\t%s\n", a.Error)
}
if a.Log != "" {
out += fmt.Sprintf("\tLog\t\t\t:\t%s\n", a.Log)
}
if a.Codespace != "" {
out += fmt.Sprintf("\tCodespace\t\t:\t%s\n", a.Codespace)
}
}
if ok {
return out, nil
}
return "", errors.New(out)
}
type JsonRpcError struct {
Msg string
Err jsonrpc2.Error
}
func (e *JsonRpcError) Error() string { return e.Msg }
func PrintJsonRpcError(err error) (string, error) {
var e jsonrpc2.Error
switch err := err.(type) {
case jsonrpc2.Error:
e = err
default:
return "", fmt.Errorf("error with request, %v", err)
}
if WantJsonOutput {
out, err := json.Marshal(e)
if err != nil {
return "", err
}
return "", &JsonRpcError{Err: e, Msg: string(out)}
} else {
var out string
out += fmt.Sprintf("\n\tMessage\t\t:\t%v\n", e.Message)
out += fmt.Sprintf("\tError Code\t:\t%v\n", e.Code)
out += fmt.Sprintf("\tDetail\t\t:\t%s\n", e.Data)
return "", &JsonRpcError{Err: e, Msg: out}
}
}
func printOutput(cmd *cobra.Command, out string, err error) {
if err != nil {
cmd.PrintErrf("Error: %v\n", err)
DidError = err
} else {
cmd.Println(out)
}
}
var (
ApiToString = map[types.ChainType]string{
types.ChainTypeLiteTokenAccount: "Lite Account",
types.ChainTypeTokenAccount: "ADI Token Account",
types.ChainTypeIdentity: "ADI",
types.ChainTypeKeyBook: "Key Book",
types.ChainTypeKeyPage: "Key Page",
types.ChainTypeDataAccount: "Data Chain",
types.ChainTypeLiteDataAccount: "Lite Data Chain",
}
)
func formatAmount(tokenUrl string, amount *big.Int) (string, error) {
//query the token
tokenData, err := Get(tokenUrl)
if err != nil {
return "", fmt.Errorf("error retrieving token url, %v", err)
}
t := protocol.TokenIssuer{}
err = json.Unmarshal([]byte(tokenData), &t)
if err != nil {
return "", err
}
bf := big.Float{}
bd := big.Float{}
bd.SetFloat64(math.Pow(10.0, float64(t.Precision)))
bf.SetInt(amount)
bal := big.Float{}
bal.Quo(&bf, &bd)
return fmt.Sprintf("%s %s", bal.String(), t.Symbol), nil
}
func printGeneralTransactionParameters(res *api2.QueryResponse) string {
out := fmt.Sprintf("---\n")
out += fmt.Sprintf(" - Transaction : %x\n", res.Txid)
out += fmt.Sprintf(" - Signer Url : %s\n", res.Origin)
out += fmt.Sprintf(" - Signature : %x\n", res.Sig)
if res.Signer != nil {
out += fmt.Sprintf(" - Signer Key : %x\n", res.Signer.PublicKey)
out += fmt.Sprintf(" - Signer Nonce : %d\n", res.Signer.Nonce)
}
out += fmt.Sprintf(" - Key Page : %d (height) / %d (index)\n", res.KeyPage.Height, res.KeyPage.Index)
out += fmt.Sprintf("===\n")
return out
}
func PrintQueryResponseV2(v2 *api2.QueryResponse) (string, error) {
if WantJsonOutput || v2.Type == "dataEntry" || v2.Type == "dataSet" {
data, err := json.Marshal(v2)
if err != nil {
return "", err
}
return string(data), nil
}
out, err := outputForHumans(v2)
if err != nil {
return "", err
}
for i, txid := range v2.SyntheticTxids {
out += fmt.Sprintf(" - Synthetic Transaction %d : %x\n", i, txid)
}
return out, nil
}
func outputForHumans(res *api2.QueryResponse) (string, error) {
switch string(res.Type) {
case types.ChainTypeLiteTokenAccount.String():
ata := protocol.LiteTokenAccount{}
err := UnmarshalQuery(res.Data, &ata)
if err != nil {
return "", err
}
amt, err := formatAmount(ata.TokenUrl, &ata.Balance)
if err != nil {
amt = "unknown"
}
var out string
out += fmt.Sprintf("\n\tAccount Url\t:\t%v\n", ata.ChainUrl)
out += fmt.Sprintf("\tToken Url\t:\t%v\n", ata.TokenUrl)
out += fmt.Sprintf("\tBalance\t\t:\t%s\n", amt)
out += fmt.Sprintf("\tCredits\t\t:\t%s\n", ata.CreditBalance.String())
out += fmt.Sprintf("\tNonce\t\t:\t%d\n", ata.Nonce)
return out, nil
case types.ChainTypeTokenAccount.String():
ata := state.TokenAccount{}
err := UnmarshalQuery(res.Data, &ata)
if err != nil {
return "", err
}
amt, err := formatAmount(*ata.TokenUrl.String.AsString(), &ata.Balance)
if err != nil {
amt = "unknown"
}
kbr, err := resolveKeyBookUrl(ata.KeyBook[:])
if err != nil {
return "", fmt.Errorf("cannot resolve keybook for token account query")
}
var out string
out += fmt.Sprintf("\n\tAccount Url\t:\t%v\n", ata.ChainUrl)
out += fmt.Sprintf("\tToken Url\t:\t%s\n", *ata.TokenUrl.String.AsString())
out += fmt.Sprintf("\tBalance\t\t:\t%s\n", amt)
out += fmt.Sprintf("\tKey Book Url\t:\t%s\n", kbr)
return out, nil
case types.ChainTypeIdentity.String():
adi := state.AdiState{}
err := UnmarshalQuery(res.Data, &adi)
if err != nil {
return "", err
}
kb, err := resolveKeyBookUrl(adi.KeyBook[:])
if err != nil {
return "", fmt.Errorf("cannot resolve keybook for adi query")
}
var out string
out += fmt.Sprintf("\n\tADI url\t\t:\t%v\n", adi.ChainUrl)
out += fmt.Sprintf("\tKey Book url\t:\t%s\n", kb)
return out, nil
case "directory":
dqr := api2.DirectoryQueryResult{}
err := UnmarshalQuery(res.Data, &dqr)
if err != nil {
return "", err
}
var out string
out += fmt.Sprintf("\n\tADI Entries: start = %d, count = %d, total = %d\n", dqr.Start, dqr.Count, dqr.Total)
for _, s := range dqr.ExpandedEntries {
header := state.ChainHeader{}
err = UnmarshalQuery(s.Data, &header)
if err != nil {
return "", err
}
chainDesc := "unknown"
if err == nil {
if v, ok := ApiToString[header.Type]; ok {
chainDesc = v
}
}
out += fmt.Sprintf("\t%v (%s)\n", header.ChainUrl, chainDesc)
}
return out, nil
case types.ChainTypeKeyBook.String():
book := protocol.KeyBook{}
err := UnmarshalQuery(res.Data, &book)
if err != nil {
return "", err
}
var out string
out += fmt.Sprintf("\n\tPage Index\t\tKey Page Url\n")
for i, v := range book.Pages {
s, err := resolveKeyPageUrl(v[:])
if err != nil {
return "", err
}
out += fmt.Sprintf("\t%d\t\t:\t%s\n", i, s)
}
return out, nil
case types.ChainTypeKeyPage.String():
ss := protocol.KeyPage{}
err := UnmarshalQuery(res.Data, &ss)
if err != nil {
return "", err
}
out := fmt.Sprintf("\n\tIndex\tNonce\tPublic Key\t\t\t\t\t\t\t\tKey Name\n")
for i, k := range ss.Keys {
keyName := ""
name, err := FindLabelFromPubKey(k.PublicKey)
if err == nil {
keyName = name
}
out += fmt.Sprintf("\t%d\t%d\t%x\t%s", i, k.Nonce, k.PublicKey, keyName)
}
return out, nil
case types.TxTypeSendTokens.String():
tx := response.TokenTx{}
err := UnmarshalQuery(res.Data, &tx)
if err != nil {
return "", err
}
var out string
for i := range tx.ToAccount {
bi := big.Int{}
bi.SetInt64(int64(tx.ToAccount[i].Amount))
amt, err := formatAmount("acc://ACME", &bi)
if err != nil {
amt = "unknown"
}
out += fmt.Sprintf("Send %s from %s to %s\n", amt, *tx.From.AsString(), tx.ToAccount[i].URL)
out += fmt.Sprintf(" - Synthetic Transaction : %x\n", tx.ToAccount[i].SyntheticTxId)
}
out += printGeneralTransactionParameters(res)
return out, nil
case types.TxTypeSyntheticDepositTokens.String():
deposit := new(protocol.SyntheticDepositTokens)
err := UnmarshalQuery(res.Data, &deposit)
if err != nil {
return "", err
}
out := "\n"
amt, err := formatAmount(deposit.Token, &deposit.Amount)
if err != nil {
amt = "unknown"
}
out += fmt.Sprintf("Receive %s to %s (cause: %X)\n", amt, res.Origin, deposit.Cause)
out += printGeneralTransactionParameters(res)
return out, nil
case types.TxTypeCreateIdentity.String():
id := protocol.IdentityCreate{}
err := UnmarshalQuery(res.Data, &id)
if err != nil {
return "", err
}
out := "\n"
out += fmt.Sprintf("ADI url \t\t:\tacc://%s\n", id.Url)
out += fmt.Sprintf("Key Book \t\t:\tacc://%s/%s\n", id.Url, id.KeyBookName)
out += fmt.Sprintf("Key Page \t\t:\tacc://%s/%s\n", id.Url, id.KeyPageName)
keyName, err := FindLabelFromPubKey(id.PublicKey)
if err != nil {
out += fmt.Sprintf("Public Key \t:\t%x\n", id.PublicKey)
} else {
out += fmt.Sprintf("Public Key (name) \t:\t%x (%s)\n", id.PublicKey, keyName)
}
out += printGeneralTransactionParameters(res)
return out, nil
default:
return "", fmt.Errorf("unknown response type %q", res.Type)
}
}
func getChainHeaderFromChainId(chainId []byte) (*state.ChainHeader, error) {
kb, err := GetByChainId(chainId)
header := state.ChainHeader{}
err = UnmarshalQuery(kb.Data, &header)
if err != nil {
return nil, err
}
return &header, nil
}
func resolveKeyBookUrl(chainId []byte) (string, error) {
kb, err := GetByChainId(chainId)
book := protocol.KeyBook{}
err = UnmarshalQuery(kb.Data, &book)
if err != nil {
return "", err
}
return book.GetChainUrl(), nil
}
func resolveKeyPageUrl(chainId []byte) (string, error) {
res, err := GetByChainId(chainId)
if err != nil {
return "", err
}
kp := protocol.KeyPage{}
err = UnmarshalQuery(res.Data, &kp)
if err != nil {
return "", err
}
return kp.GetChainUrl(), nil
}
func nonceFromTimeNow() uint64 {
t := time.Now()
return uint64(t.Unix()*1e6) + uint64(t.Nanosecond())/1e3
}
|
Pancor/airApp | app/src/main/java/pl/pancor/android/air/nearest_station/NearestStationPresenter.java | <reponame>Pancor/airApp<filename>app/src/main/java/pl/pancor/android/air/nearest_station/NearestStationPresenter.java
package pl.pancor.android.air.nearest_station;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pl.pancor.android.air.base.FragmentScope;
import pl.pancor.android.air.data.RealmService;
import pl.pancor.android.air.models.DataResponse;
import pl.pancor.android.air.models.Station;
import pl.pancor.android.air.models.User;
import pl.pancor.android.air.net.NetService;
import pl.pancor.android.air.utils.OtherUtils;
import pl.pancor.android.air.utils.location.Location;
import pl.pancor.android.air.utils.location.LocationService;
import pl.pancor.android.air.utils.location.LocationUtils;
import retrofit2.Retrofit;
@FragmentScope
public class NearestStationPresenter implements NearestStation.Presenter,
Location.Receiver {
private static final String TAG = NearestStationPresenter.class.getSimpleName();
private static String mRequestToken;
private NearestStation.View mView;
private Retrofit mRetrofit;
private LocationService mLocationService;
private RealmService realmService;
private Disposable disposable;
@Inject
NearestStationPresenter(NearestStation.View view, Retrofit retrofit,
LocationService service, RealmService realmService){
mView = view;
mRetrofit = retrofit;
mLocationService = service;
this.realmService = realmService;
}
@Inject
void setupListeners(){
mView.setPresenter(this);
mLocationService.setupReceiver(this);
}
@Override
public void findNearestStation(@NonNull String token) {
mView.setLoadingIndicator(true);
mRequestToken = token;
mLocationService.getLastKnownLocation();
}
@Override
public void getStation(Double latitude, Double longitude) {
mView.setLoadingIndicator(true);
getNearestStation(latitude, longitude);
}
@Override
public void onActivityResult(int requestCode, int resultCode) {
mLocationService.onActivityResult(requestCode, resultCode);
}
@Override
public void onStart() {
mLocationService.onStart();
}
@Override
public void onStop() {
mLocationService.onStop();
realmService.close();
if (disposable != null && !disposable.isDisposed())
disposable.dispose();
}
@Override
public void lastKnownLocation(double latitude, double longitude) {
getNearestStation(latitude, longitude);
}
@Override
public void userRefusedToSendLocation() {
mView.setLoadingIndicator(false);
mView.userRefusedToGiveLocation();
}
@Override
public void unableToObtainLocation() {
}
private void getNearestStation(Double lat, Double lng){
User user = realmService.getUser();
if (user != null) {
Station station = realmService.getStation();
if (LocationUtils.getDistance(lat, lng,
user.getLatitude(), user.getLongitude()) < 0.3 &&
station != null &&
OtherUtils.isTimeUpToDate(station.getUpdateTime())){
mView.setStation(station);
mView.setLoadingIndicator(false);
} else {
getDataFromServer(lat, lng);
}
} else {
realmService.addUser(lat, lng);
getDataFromServer(lat, lng);
}
}
private void getDataFromServer(Double lat, Double lng){
disposable = mRetrofit.create(NetService.class)
.getNearestStation(mRequestToken, lat, lng)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(dataResponse -> handleData(dataResponse, lat, lng),
throwable -> {throwable.printStackTrace();mView.onConnectionError();},
() -> mView.setLoadingIndicator(false));
}
private void handleData(DataResponse<Station> dataResponse, Double lat, Double lng){
if (!dataResponse.isError()) {
Station station = dataResponse.getData().get(0);
station.setDistance(LocationUtils.getDistance(lat, lng,
station.getLatitude(), station.getLongitude()));
realmService.addStation(station);
mView.setStation(station);
} else
mView.onConnectionError();
}
}
|
FAD95/NEXT.JS-Course | node_modules/@iconify/icons-mdi/src/file-sync.js | let data = {
"body": "<path d=\"M11 17.5c0-3.6 2.9-6.5 6.5-6.5c.9 0 1.7.2 2.5.5V8l-6-6H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h6.8c-1.1-1.2-1.8-2.8-1.8-4.5m2-14L18.5 9H13V3.5m4 8.5v1.5c2.2 0 4 1.8 4 4c0 .8-.2 1.6-.7 2.2l-1.1-1.1c.2-.3.3-.7.3-1.1c0-1.4-1.1-2.5-2.5-2.5v1.5l-2.2-2.2L17 12m0 11v-1.5c-2.2 0-4-1.8-4-4c0-.8.2-1.6.7-2.2l1.1 1.1c-.2.3-.3.7-.3 1.1c0 1.4 1.1 2.5 2.5 2.5v-1.5l2.2 2.2L17 23z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
export default data;
|
ruijis/buildsimhub_python_api | test/hvac_swap_zone_group_test.py | <gh_stars>10-100
import BuildSimHubAPI as bshapi
import pandas as pd
# project_key can be found in every project (click the information icon next to project name)
project_api_key = 'c39dceed-242b-4ea3-9fd4-e2076f89c29b'
# model_key can be found in each model information bar
model_api_key = 'dca5f246-e6b5-44de-8a31-b9e27e28a633'
# initialize the client
bsh = bshapi.BuildSimHubAPIClient()
results = bsh.model_results(project_api_key, model_api_key)
zone_list = results.zone_list()
zone_group = dict()
for zone in zone_list:
zone_group[zone['zone_name']] = dict()
zone_group[zone['zone_name']]['ventilation'] = 'testzone'
floor = zone['floor']
if floor == 2:
zone_group[zone['zone_name']]['heating'] = 'test2zone'
zone_group[zone['zone_name']]['cooling'] = 'test2zone'
else:
zone_group[zone['zone_name']]['heating'] = 'test3zone'
zone_group[zone['zone_name']]['cooling'] = 'test3zone'
print(zone_group)
id = results.hvac_swap('/Users/weilixu/Desktop/doasfancoil.idf', zone_group=zone_group)
sim_update = bsh.new_simulation_job(project_api_key)
update_model = sim_update.run_model_simulation(id, track=True)
print(update_model.net_site_eui())
|
yp2211/javabasics | lesson5/src/com/training/Dog.java | <filename>lesson5/src/com/training/Dog.java
package com.training;
public class Dog extends Animal{
protected String type = "DOG";
public Dog(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(title+ " " + name + " is eating bone.");
}
@Override
public void work() {
System.out.println(title+ " " + name + " is guarding.");
}
}
|
thl/cultural_network | app/models/feature_object_type.rb | class FeatureObjectType < CategoryFeature
#
#
# Associations
#
#
belongs_to :perspective
after_save do |record|
record.feature.update_object_type_positions if !record.skip_update
end
end
# == Schema Info
# Schema version: 20110923232332
#
# Table name: category_features
#
# id :integer not null, primary key
# category_id :integer not null
# feature_id :integer not null
# perspective_id :integer
# label :string(255)
# numeric_value :integer
# position :integer not null, default(0)
# prefix_label :boolean not null, default(TRUE)
# show_parent :boolean not null
# show_root :boolean not null, default(TRUE)
# string_value :string(255)
# type :string(255)
# created_at :timestamp
# updated_at :timestamp |
wizardxz/pythran | pythran/pythonic/types/int.hpp | <gh_stars>0
#ifndef PYTHONIC_TYPES_INT_HPP
#define PYTHONIC_TYPES_INT_HPP
#include "pythonic/include/types/int.hpp"
#include "pythonic/types/attr.hpp"
PYTHONIC_NS_BEGIN
namespace __builtin__
{
template <class T>
typename std::enable_if<std::is_integral<T>::value, T>::type
getattr(types::attr::REAL, T self)
{
return self;
}
template <class T>
typename std::enable_if<std::is_integral<T>::value, T>::type
getattr(types::attr::IMAG, T self)
{
return T(0);
}
}
PYTHONIC_NS_END
#ifdef ENABLE_PYTHON_MODULE
#include "pythonic/python/core.hpp"
#include "numpy/arrayobject.h"
PYTHONIC_NS_BEGIN
namespace details
{
constexpr int signed_int_types[] = {0, NPY_INT8, NPY_INT16, 0, NPY_INT32, 0,
0, 0, NPY_INT64};
constexpr int unsigned_int_types[] = {
0, NPY_UINT8, NPY_UINT16, 0, NPY_UINT32, 0, 0, 0, NPY_UINT64};
}
template <class T>
struct c_type_to_numpy_type
: c_type_to_numpy_type<decltype(std::declval<T>()())> {
};
template <>
struct c_type_to_numpy_type<long double>
: std::integral_constant<int, NPY_LONGDOUBLE> {
};
template <>
struct c_type_to_numpy_type<double> : std::integral_constant<int, NPY_DOUBLE> {
};
template <>
struct c_type_to_numpy_type<float> : std::integral_constant<int, NPY_FLOAT> {
};
template <>
struct c_type_to_numpy_type<std::complex<float>>
: std::integral_constant<int, NPY_CFLOAT> {
};
template <>
struct c_type_to_numpy_type<std::complex<double>>
: std::integral_constant<int, NPY_CDOUBLE> {
};
template <>
struct c_type_to_numpy_type<std::complex<long double>>
: std::integral_constant<int, NPY_CLONGDOUBLE> {
};
template <>
struct c_type_to_numpy_type<signed long long> {
static const int value = details::signed_int_types[sizeof(signed long long)];
};
template <>
struct c_type_to_numpy_type<unsigned long long> {
static const int value =
details::unsigned_int_types[sizeof(unsigned long long)];
};
template <>
struct c_type_to_numpy_type<signed long> {
static const int value = details::signed_int_types[sizeof(signed long)];
};
template <>
struct c_type_to_numpy_type<unsigned long> {
static const int value = details::unsigned_int_types[sizeof(unsigned long)];
};
template <>
struct c_type_to_numpy_type<signed int> {
static const int value = details::signed_int_types[sizeof(signed int)];
};
template <>
struct c_type_to_numpy_type<unsigned int> {
static const int value = details::unsigned_int_types[sizeof(unsigned int)];
};
template <>
struct c_type_to_numpy_type<signed short> {
static const int value = details::signed_int_types[sizeof(signed short)];
};
template <>
struct c_type_to_numpy_type<unsigned short> {
static const int value = details::unsigned_int_types[sizeof(unsigned short)];
};
template <>
struct c_type_to_numpy_type<signed char> {
static const int value = details::signed_int_types[sizeof(signed char)];
};
template <>
struct c_type_to_numpy_type<unsigned char> {
static const int value = details::unsigned_int_types[sizeof(unsigned char)];
};
template <>
struct c_type_to_numpy_type<bool> {
static const int value = NPY_BOOL;
};
#if PY_MAJOR_VERSION >= 3
#ifndef PyInt_FromLong
#define PyInt_FromLong PyLong_FromLong
#endif
#ifndef PyInt_CheckExact
#define PyInt_CheckExact PyLong_CheckExact
#endif
#ifndef PyInt_AsLong
#define PyInt_AsLong PyLong_AsLong
#endif
#endif
#define PYTHONIC_INT_TO_PYTHON(TYPE) \
PyObject *to_python<TYPE>::convert(TYPE l) \
{ \
return PyArray_Scalar( \
&l, PyArray_DescrFromType(c_type_to_numpy_type<TYPE>::value), \
nullptr); \
}
PYTHONIC_INT_TO_PYTHON(unsigned char)
PYTHONIC_INT_TO_PYTHON(signed char)
PYTHONIC_INT_TO_PYTHON(unsigned short)
PYTHONIC_INT_TO_PYTHON(signed short)
PYTHONIC_INT_TO_PYTHON(unsigned int)
PYTHONIC_INT_TO_PYTHON(signed int)
PYTHONIC_INT_TO_PYTHON(unsigned long)
PyObject *to_python<signed long>::convert(signed long l)
{
return PyInt_FromLong(l);
}
PYTHONIC_INT_TO_PYTHON(unsigned long long)
PYTHONIC_INT_TO_PYTHON(signed long long)
#undef PYTHONIC_INT_TO_PYTHON
#define PYTHONIC_INT_FROM_PYTHON(TYPE, NTYPE) \
bool from_python<TYPE>::is_convertible(PyObject *obj) \
{ \
return PyObject_TypeCheck(obj, &Py##NTYPE##ArrType_Type); \
} \
TYPE from_python<TYPE>::convert(PyObject *obj) \
{ \
return PyInt_AsLong(obj); \
}
PYTHONIC_INT_FROM_PYTHON(unsigned char, UByte)
PYTHONIC_INT_FROM_PYTHON(signed char, Byte)
PYTHONIC_INT_FROM_PYTHON(unsigned short, UShort)
PYTHONIC_INT_FROM_PYTHON(signed short, Short)
PYTHONIC_INT_FROM_PYTHON(unsigned int, UInt)
PYTHONIC_INT_FROM_PYTHON(signed int, Int)
PYTHONIC_INT_FROM_PYTHON(unsigned long, ULong)
bool from_python<signed long>::is_convertible(PyObject *obj)
{
return PyInt_CheckExact(obj) || PyObject_TypeCheck(obj, &PyLongArrType_Type);
}
signed long from_python<signed long>::convert(PyObject *obj)
{
return PyLong_AsLong(obj);
}
PYTHONIC_INT_FROM_PYTHON(unsigned long long, ULongLong)
PYTHONIC_INT_FROM_PYTHON(signed long long, LongLong)
#undef PYTHONIC_INT_FROM_PYTHON
PYTHONIC_NS_END
#endif
#endif
|
kxen42/Learn-Python-Programming-Third-Edition | ch09/jwt/claims_time.py | <reponame>kxen42/Learn-Python-Programming-Third-Edition
# jwt/claims_time.py
from datetime import datetime, timedelta, timezone
from time import sleep, time
import jwt
iat = datetime.now(tz=timezone.utc)
nfb = iat + timedelta(seconds=1)
exp = iat + timedelta(seconds=3)
data = {'payload': 'data', 'nbf': nfb, 'exp': exp, 'iat': iat}
def decode(token, secret):
print(time())
try:
print(jwt.decode(token, secret, algorithms=['HS256']))
except (
jwt.ImmatureSignatureError, jwt.ExpiredSignatureError
) as err:
print(err)
print(type(err))
secret = 'secret-key'
token = jwt.encode(data, secret)
decode(token, secret)
sleep(2)
decode(token, secret)
sleep(2)
decode(token, secret)
"""
$ python jwt/claims_time.py
1631043839.6459477
The token is not yet valid (nbf)
<class 'jwt.exceptions.ImmatureSignatureError'>
1631043841.6480813
{'payload': 'data', 'nbf': 1631043840, 'exp': 1631043842, 'iat':
1631043839}
1631043843.6498601
Signature has expired
<class 'jwt.exceptions.ExpiredSignatureError'>
"""
|
specs-feup/matisse | MatlabToCLV2/src/org/specs/matlabtocl/v2/codegen/ssatocrules/OverrideGpuBufferContentsProcessor.java | <filename>MatlabToCLV2/src/org/specs/matlabtocl/v2/codegen/ssatocrules/OverrideGpuBufferContentsProcessor.java
/**
* Copyright 2015 SPeCS.
*
* 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. under the License.
*/
package org.specs.matlabtocl.v2.codegen.ssatocrules;
import org.specs.CIR.FunctionInstance.FunctionInstance;
import org.specs.CIR.FunctionInstance.InstanceProvider;
import org.specs.CIR.FunctionInstance.ProviderData;
import org.specs.CIR.Tree.CInstructionList;
import org.specs.CIR.Tree.CNode;
import org.specs.CIR.Tree.PrecedenceLevel;
import org.specs.CIR.Tree.CNodes.CNodeFactory;
import org.specs.CIR.Tree.CNodes.VariableNode;
import org.specs.CIR.Types.Variable;
import org.specs.CIR.Types.ATypes.Matrix.MatrixType;
import org.specs.MatlabToC.CodeBuilder.SsaToCBuilderService;
import org.specs.MatlabToC.CodeBuilder.SsaToCRules.SsaToCRule;
import org.specs.matisselib.ssa.instructions.SsaInstruction;
import org.specs.matlabtocl.v2.CLServices;
import org.specs.matlabtocl.v2.functions.memory.ReleaseBuffer;
import org.specs.matlabtocl.v2.services.ProfilingOptions;
import org.specs.matlabtocl.v2.ssa.instructions.OverrideGpuBufferContentsInstruction;
import org.specs.matlabtocl.v2.types.api.EventType;
public final class OverrideGpuBufferContentsProcessor implements SsaToCRule {
@Override
public boolean accepts(SsaToCBuilderService builder, SsaInstruction instruction) {
return instruction instanceof OverrideGpuBufferContentsInstruction;
}
@Override
public void apply(SsaToCBuilderService builder, CInstructionList currentBlock, SsaInstruction instruction) {
OverrideGpuBufferContentsInstruction copyToGpu = (OverrideGpuBufferContentsInstruction) instruction;
String buffer = copyToGpu.getBuffer();
String matrix = copyToGpu.getMatrix();
VariableNode bufferNode = builder.generateVariableNodeForSsaName(buffer);
VariableNode matrixNode = builder.generateVariableNodeForSsaName(matrix);
builder.addLiteralVariableIfNotArgument(matrixNode.getVariable());
builder.addLiteralVariableIfNotArgument(bufferNode.getVariable());
MatrixType matrixType = (MatrixType) matrixNode.getVariableType();
InstanceProvider numelProvider = matrixType.functions().numel();
ProviderData numelData = builder.getCurrentProvider().createFromNodes(matrixNode);
FunctionInstance numelInstance = numelProvider.newCInstance(numelData);
CNode numelCall = CNodeFactory.newFunctionCall(numelInstance, matrixNode);
String size = "sizeof(" + matrixType.matrix().getElementType().code().getSimpleType() + ") * "
+ numelCall.getCodeForRightSideOf(PrecedenceLevel.Multiplication);
InstanceProvider dataProvider = matrixType.functions().data();
ProviderData dataData = builder.getCurrentProvider().createFromNodes(matrixNode);
FunctionInstance dataInstance = dataProvider.newCInstance(dataData);
String dataCode = dataInstance.getCallCode(matrixNode);
ProfilingOptions profilingOptions = builder.getPassData()
.get(CLServices.PROFILING_OPTIONS);
Variable evtVariable = null;
StringBuilder copyDataCode = new StringBuilder();
copyDataCode.append("CHECK(clEnqueueWriteBuffer, MATISSE_cl.command_queue, ");
copyDataCode.append(bufferNode.getCode());
copyDataCode.append(", CL_TRUE, 0, ");
copyDataCode.append(size);
copyDataCode.append(", ");
copyDataCode.append(dataCode);
copyDataCode.append(", 0, NULL, ");
if (profilingOptions.isDataTransferProfilingEnabled()) {
evtVariable = builder.generateTemporary("evt", new EventType());
builder.addLiteralVariable(evtVariable);
copyDataCode.append("&");
copyDataCode.append(evtVariable.getName());
} else {
copyDataCode.append("NULL");
}
copyDataCode.append(");");
currentBlock.addLiteralInstruction(copyDataCode.toString());
if (profilingOptions.isDataTransferProfilingEnabled()) {
assert evtVariable != null;
currentBlock
.addLiteralInstruction(
"MATISSE_cl_register_host_to_device_data_transfer_event(" + evtVariable.getName() + ");");
}
builder.addDependency(numelInstance);
builder.addDependency(dataInstance);
builder.addDependencies(
new ReleaseBuffer().newCInstance(builder.getCurrentProvider()).getImplementationInstances());
builder.addDependencies(bufferNode.getVariableType().code().getInstances());
builder.addDependencies(matrixNode.getVariableType().code().getInstances());
}
}
|
sobolevn/putout | packages/plugin-convert-for-to-for-of/lib/n/fixture/remove-useless-arguments-fix.js | <filename>packages/plugin-convert-for-to-for-of/lib/n/fixture/remove-useless-arguments-fix.js
module.exports = async function runTests(tests) {
const total = tests.length;
for (const {
fn,
message,
} of tests) {
await runOneTest({
fn,
message
});
}
}
async function runOneTest({
message,
fn
}) {
formatter.emit('test', {
message,
});
await tryToCatch(fn, t);
}
|
OregonShakespeareFestival/sufia | spec/services/noid_spec.rb | <gh_stars>0
require 'spec_helper'
describe Sufia::Noid do
describe "#namespaceize" do
subject { Sufia::Noid.namespaceize(id) }
context "when the passed in pid doesn't have a namespace" do
let(:id) { 'abc123' }
it { is_expected.to eq 'sufia:abc123' }
end
context "when the passed in pid has a namespace" do
let(:id) { 'ksl:abc123' }
it { is_expected.to eq 'ksl:abc123' }
end
end
end
|
PetrykinVictor/incubator-druid | api/src/main/java/io/druid/data/input/impl/DimensionSchema.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 io.druid.data.input.impl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.base.Strings;
import io.druid.guice.annotations.PublicApi;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.emitter.EmittingLogger;
import java.util.Objects;
/**
*/
@PublicApi
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = StringDimensionSchema.class)
@JsonSubTypes(value = {
@JsonSubTypes.Type(name = DimensionSchema.STRING_TYPE_NAME, value = StringDimensionSchema.class),
@JsonSubTypes.Type(name = DimensionSchema.LONG_TYPE_NAME, value = LongDimensionSchema.class),
@JsonSubTypes.Type(name = DimensionSchema.FLOAT_TYPE_NAME, value = FloatDimensionSchema.class),
@JsonSubTypes.Type(name = DimensionSchema.DOUBLE_TYPE_NAME, value = DoubleDimensionSchema.class),
@JsonSubTypes.Type(name = DimensionSchema.SPATIAL_TYPE_NAME, value = NewSpatialDimensionSchema.class),
})
public abstract class DimensionSchema
{
public static final String STRING_TYPE_NAME = "string";
public static final String LONG_TYPE_NAME = "long";
public static final String FLOAT_TYPE_NAME = "float";
public static final String SPATIAL_TYPE_NAME = "spatial";
public static final String DOUBLE_TYPE_NAME = "double";
private static final EmittingLogger log = new EmittingLogger(DimensionSchema.class);
// main druid and druid-api should really use the same ValueType enum.
// merge them when druid-api is merged back into the main repo
/**
* Should be the same as {@code io.druid.segment.column.ValueType}.
* TODO merge them when druid-api is merged back into the main repo
*/
public enum ValueType
{
FLOAT,
LONG,
STRING,
DOUBLE,
@SuppressWarnings("unused") // used in io.druid.segment.column.ValueType
COMPLEX;
@JsonValue
@Override
public String toString()
{
return StringUtils.toUpperCase(this.name());
}
@JsonCreator
public static ValueType fromString(String name)
{
return valueOf(StringUtils.toUpperCase(name));
}
}
public enum MultiValueHandling
{
SORTED_ARRAY,
SORTED_SET,
ARRAY {
@Override
public boolean needSorting()
{
return false;
}
};
public boolean needSorting()
{
return true;
}
@Override
@JsonValue
public String toString()
{
return StringUtils.toUpperCase(name());
}
@JsonCreator
public static MultiValueHandling fromString(String name)
{
return name == null ? ofDefault() : valueOf(StringUtils.toUpperCase(name));
}
// this can be system configuration
public static MultiValueHandling ofDefault()
{
return SORTED_ARRAY;
}
}
private final String name;
private final MultiValueHandling multiValueHandling;
private final boolean createBitmapIndex;
protected DimensionSchema(String name, MultiValueHandling multiValueHandling, boolean createBitmapIndex)
{
if (Strings.isNullOrEmpty(name)) {
log.warn("Null or Empty Dimension found");
}
this.name = name;
this.multiValueHandling = multiValueHandling == null ? MultiValueHandling.ofDefault() : multiValueHandling;
this.createBitmapIndex = createBitmapIndex;
}
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public MultiValueHandling getMultiValueHandling()
{
return multiValueHandling;
}
@JsonProperty("createBitmapIndex")
public boolean hasBitmapIndex()
{
return createBitmapIndex;
}
@JsonIgnore
public abstract String getTypeName();
@JsonIgnore
public abstract ValueType getValueType();
@Override
public boolean equals(final Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DimensionSchema that = (DimensionSchema) o;
return createBitmapIndex == that.createBitmapIndex &&
Objects.equals(name, that.name) &&
Objects.equals(getTypeName(), that.getTypeName()) &&
Objects.equals(getValueType(), that.getValueType()) &&
multiValueHandling == that.multiValueHandling;
}
@Override
public int hashCode()
{
return Objects.hash(name, multiValueHandling, createBitmapIndex, getTypeName(), getValueType());
}
@Override
public String toString()
{
return "DimensionSchema{" +
"name='" + name + '\'' +
", valueType=" + getValueType() +
", typeName=" + getTypeName() +
", multiValueHandling=" + multiValueHandling +
", createBitmapIndex=" + createBitmapIndex +
'}';
}
}
|
zabrewer/batfish | projects/batfish/src/main/java/org/batfish/bddreachability/BDDReverseFlowTransformationFactory.java | <reponame>zabrewer/batfish
package org.batfish.bddreachability;
import javax.annotation.Nonnull;
import org.batfish.bddreachability.transition.Transition;
interface BDDReverseFlowTransformationFactory {
@Nonnull
Transition reverseFlowIncomingTransformation(String hostname, String iface);
@Nonnull
Transition reverseFlowOutgoingTransformation(String hostname, String iface);
}
|
zayez/galigens | src/components/Rovers/RoverItem.js | import React from "react"
import { Link, useNavigate } from "react-router-dom"
import { getRoverImage } from "../../utils/roverUtils"
import RoverDetails from "../Rover/RoverDetails"
const RoverItem = ({ rover }) => {
const roverLink = `/rover/${rover.name.toLowerCase()}`
const roverImage = getRoverImage(rover.name)
const navigate = useNavigate()
const navigateToRover = () => navigate(roverLink)
return (
<div className="rover-item" onClick={navigateToRover}>
<div className="card">
<div className="card-content">
<div className="card-title">
<h3 className="rover-title">
<Link to={roverLink}>{rover.name}</Link>
</h3>
</div>
<div className="card-body">
<RoverDetails rover={rover} />
</div>
</div>
<div className="card-image">
<Link to={roverLink}>
<img src={roverImage} />
</Link>
</div>
</div>
</div>
)
}
export default RoverItem
|
ricksyuan/heap-overflow | app/models/comment.rb | # == Schema Information
#
# Table name: comments
#
# id :bigint(8) not null, primary key
# author_id :integer not null
# commentable_type :string
# commentable_id :bigint(8)
# body :string not null
# created_at :datetime not null
# updated_at :datetime not null
# score :integer default(0)
#
class Comment < ApplicationRecord
# include Commentable
include Votable
belongs_to :commentable, polymorphic: true
belongs_to :author,
class_name: :User
has_many :votes, as: :votable
end
|
rohansachdeva1990/art-of-code | refactoring/kata-one/src/main/java/com/rohan/aoc/refactoring/kataone/refactored/specs/Specs.java | package com.rohan.aoc.refactoring.kataone.refactored.specs;
import com.rohan.aoc.refactoring.kataone.refactored.EstateMaterial;
import com.rohan.aoc.refactoring.kataone.refactored.EstatePlacement;
import com.rohan.aoc.refactoring.kataone.refactored.EstateType;
import com.rohan.aoc.refactoring.kataone.refactored.Spec;
public class Specs {
private Specs() {
}
public static AreaRangeSpec ofAreaRange(float minArea, float maxArea) {
return new AreaRangeSpec(minArea, maxArea);
}
public static BelowAreaSpec belowArea(float maxBuildingArea) {
return new BelowAreaSpec(maxBuildingArea);
}
public static MaterialSpec ofMaterial(EstateMaterial material) {
return new MaterialSpec(material);
}
public static NotSpec not(Spec spec) {
return new NotSpec(spec);
}
/**
* Here we are following static factory method design pattern
*/
public static PlacementSpec placedIn(EstatePlacement placement) {
return new PlacementSpec(placement);
}
public static TypeSpec ofType(EstateType type) {
return new TypeSpec(type);
}
}
|
ihmcrobotics/acsell | src/main/java/us/ihmc/acsell/hardware/state/AcsellState.java | package us.ihmc.acsell.hardware.state;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumMap;
import org.ejml.data.DenseMatrix64F;
import us.ihmc.acsell.hardware.AcsellActuator;
import us.ihmc.acsell.hardware.AcsellJoint;
import us.ihmc.acsell.hardware.configuration.AcsellRobot;
import us.ihmc.acsell.hardware.configuration.StrainGaugeInformation;
import us.ihmc.acsell.hardware.state.slowSensors.StrainSensor;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoLong;
import us.ihmc.robotics.robotSide.RobotSide;
import us.ihmc.robotics.robotSide.SideDependentList;
import us.ihmc.sensorProcessing.sensors.RawJointSensorDataHolder;
import us.ihmc.steppr.hardware.state.StepprPowerDistributionADCState;
import us.ihmc.wanderer.hardware.state.WandererPowerDistributionADCState;
public abstract class AcsellState<ACTUATOR extends Enum<ACTUATOR> & AcsellActuator, JOINT extends Enum<JOINT> & AcsellJoint>
{
protected final YoVariableRegistry registry;
private final YoLong lastReceivedTime;
private final YoLong timeSincePreviousPacket;
private final YoLong stateCollectionStartTime;
private final YoLong stateCollectionFinishTime;
protected final EnumMap<ACTUATOR, AcsellActuatorState> actuatorStates;
private final AcsellPowerDistributionADCState powerDistributionState;
private final YoDouble totalMotorPower;
protected final AcsellXSensState xsens;
protected final EnumMap<JOINT, AcsellJointState> jointStates;
protected final SideDependentList<DenseMatrix64F> footWrenches = new SideDependentList<>();
public AcsellState(String name, double dt, AcsellRobot robot, YoVariableRegistry parentRegistry)
{
registry = new YoVariableRegistry(name);
lastReceivedTime = new YoLong("lastReceivedTime", registry);
timeSincePreviousPacket = new YoLong("timeSincePreviousPacket", registry);
stateCollectionStartTime = new YoLong("stateCollectionStartTime", registry);
stateCollectionFinishTime = new YoLong("stateCollectionFinishTime", registry);
if(robot==AcsellRobot.WANDERER)
this.powerDistributionState = new WandererPowerDistributionADCState("powerDistribution", registry);
else
this.powerDistributionState = new StepprPowerDistributionADCState("powerDistribution", registry);
totalMotorPower = new YoDouble("totalMotorPower", registry);
xsens = new AcsellXSensState("xsens", robot, registry);
actuatorStates = createActuators();
jointStates = createJoints();
for (RobotSide robotSide : RobotSide.values)
{
footWrenches.put(robotSide, new DenseMatrix64F(6, 1));
}
parentRegistry.addChild(registry);
}
protected StrainSensor getCalibratedJointStrainGauge(StrainGaugeInformation sensorInfo)
{
if (sensorInfo != null)
{
StrainSensor strainSensor = actuatorStates.get(sensorInfo.getStrainSensorBoard()).getStrainGuage(sensorInfo.getStrainSensorConnectorId());
strainSensor.setCalibration(sensorInfo.getStrainSensorGain(), sensorInfo.getStrainSensorOffset());
return strainSensor;
}
else
{
return null;
}
}
protected abstract EnumMap<JOINT, AcsellJointState> createJoints();
protected abstract EnumMap<ACTUATOR, AcsellActuatorState> createActuators();
protected abstract ACTUATOR[] getActuators();
protected abstract JOINT[] getJoints();
public void update(ByteBuffer buffer, long timestamp) throws IOException
{
timeSincePreviousPacket.set(timestamp - lastReceivedTime.getLongValue());
lastReceivedTime.set(timestamp);
stateCollectionStartTime.set(buffer.getLong());
stateCollectionFinishTime.set(buffer.getLong());
for (ACTUATOR actuatorName : getActuators())
{
actuatorStates.get(actuatorName).update(buffer);
}
powerDistributionState.update(buffer);
xsens.update(buffer);
for (JOINT joint : getJoints())
{
jointStates.get(joint).update();
}
updateMotorPower();
}
private void updateMotorPower()
{
double accTotalMotorPower = 0;
for (ACTUATOR actuatorName : getActuators())
{
accTotalMotorPower += actuatorStates.get(actuatorName).getMotorPower();
}
totalMotorPower.set(accTotalMotorPower);
}
public AcsellJointState getJointState(JOINT joint)
{
return jointStates.get(joint);
}
public void updateRawSensorData(JOINT joint, RawJointSensorDataHolder dataHolder)
{
AcsellJointState acsellJointState = jointStates.get(joint);
dataHolder.setQ_raw(acsellJointState.getQ());
dataHolder.setQd_raw(acsellJointState.getQd());
for (int i = 0; i < acsellJointState.getNumberOfActuators(); i++)
{
dataHolder.setMotorAngle(i, acsellJointState.getMotorAngle(i));
}
}
public AcsellXSensState getXSensState()
{
return xsens;
}
public DenseMatrix64F getFootWrench(RobotSide robotSide)
{
return footWrenches.get(robotSide);
}
public AcsellPowerDistributionADCState getPowerDistributionState()
{
return powerDistributionState;
}
}
|
lilsweetcaligula/The-C-Exercises | March-31st-2016/K-and-R/readLines.c | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
/*K&R C (<NAME> & <NAME>)
Exercise 5-7. Rewrite readlines to store lines in an array supplied by main,
rather than calling alloc to maintain storage.
*/
#define BUFFER_SIZE 128
int ReadLines(FILE* stream, char* buffers[], size_t bufferLen, size_t buffersCount);
int main(void) {
char buffer1[BUFFER_SIZE] = { 0 };
char buffer2[BUFFER_SIZE] = { 0 };
char buffer3[BUFFER_SIZE] = { 0 };
const int BUFFER_COUNT = 3;
char* buffers[] = {
buffer1, buffer2, buffer3
};
ReadLines(stdin, buffers, BUFFER_SIZE, BUFFER_COUNT);
for (int i = 0; i < BUFFER_COUNT; ++i) {
puts(buffers[i]);
}
getchar();
return 0;
}
int ReadLines(FILE* stream, char* buffers[], size_t bufferLen, size_t buffersCount) {
if (!stream | !buffers || bufferLen < 1) {
return 1;
}
for (size_t i = 0; i < buffersCount; ++i) {
if (!buffers[i]) {
return 1;
}
fgets(buffers[i], bufferLen, stream);
if (buffers[i][strlen(buffers[i]) - 1] == '\n') {
buffers[i][strlen(buffers[i]) - 1] = '\0';
}
}
return 0;
}
|
szczepix1983/quitsmoker | src/test/java/com/szczepix/quitsmoker/enums/HealthProgressTypeTest.java | package com.szczepix.quitsmoker.enums;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HealthProgressTypeTest {
@Test
public void getDuration() {
HealthProgressType[] types = HealthProgressType.class.getEnumConstants();
for (HealthProgressType type : types) {
assertThat(type.getDuration()).isNotNull();
assertThat(type.getDuration()).isGreaterThan(0);
}
}
@Test
public void getDescription() {
HealthProgressType[] types = HealthProgressType.class.getEnumConstants();
for (HealthProgressType type : types) {
assertThat(type.getDescription()).isNotNull();
assertThat(type.getDescription()).isNotEmpty();
}
}
} |
msrecec/infokarta-backend-spring | web/client/epics/__tests__/mapcatalog-test.js | <filename>web/client/epics/__tests__/mapcatalog-test.js
/**
* Copyright 2020, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import expect from 'expect';
import { testEpic } from './epicTestUtils';
import axios from "../../libs/ajax";
import MockAdapter from "axios-mock-adapter";
import {
SET_FILTER_RELOAD_DELAY,
TRIGGER_RELOAD,
deleteMap,
saveMap
} from '../../actions/mapcatalog';
import {
SHOW_NOTIFICATION
} from '../../actions/notifications';
import {
deleteMapEpic,
saveMapEpic
} from '../mapcatalog';
const testMap = {
id: 10,
metadata: {
name: 'testmap',
description: 'testmap'
}
};
describe('mapcatalog epics', () => {
let mockAxios;
beforeEach(() => {
mockAxios = new MockAdapter(axios);
});
afterEach(() => {
mockAxios.restore();
});
it('deleteMapEpic', (done) => {
mockAxios.onDelete().reply(200, {});
mockAxios.onGet().reply(200, {
AttributeList: {}
});
testEpic(deleteMapEpic, 3, deleteMap(testMap), actions => {
expect(actions.length).toBe(3);
expect(actions[0].type).toBe(SHOW_NOTIFICATION);
expect(actions[0].level).toBe('success');
expect(actions[1].type).toBe(SET_FILTER_RELOAD_DELAY);
expect(actions[2].type).toBe(TRIGGER_RELOAD);
}, {}, done);
});
it('saveMapEpic', (done) => {
mockAxios.onPut().reply(200, {});
testEpic(saveMapEpic, 3, saveMap(testMap), actions => {
expect(actions.length).toBe(3);
expect(actions[0].type).toBe(SHOW_NOTIFICATION);
expect(actions[0].level).toBe('success');
expect(actions[1].type).toBe(SET_FILTER_RELOAD_DELAY);
expect(actions[2].type).toBe(TRIGGER_RELOAD);
}, {}, done);
});
});
|
matvaibhav/pensieve | dash_client/player_code_noMPC/test/js/streaming/Capabilities_Suite.js | // The copyright in this software is being made available under the BSD License, included below. This software may be subject to other third party and contributor rights, including patent rights, and no such rights are granted under this license.
//
// Copyright (c) 2013, Microsoft Open Technologies, Inc.
//
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of the Microsoft Open Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//This class parses the MPDs using DashParser framework.
if(window.location.href.indexOf("runner.html")>0)
{
describe("Capabilities Suite", function () {
var context,
system,
result,
capabilitiesObj,
flag;
beforeEach(function () {
system = new dijon.System();
system.mapValue("system", system);
system.mapOutlet("system");
context = new Dash.di.DashContext();
system.injectInto(context);
capabilitiesObj=system.getObject('capabilities');
var element = document.createElement('video');
video = system.getObject("videoModel");
video.setElement(element);
stream = system.getObject("stream");
});
it("supports Codec", function(){
debugger;
stream.manifestModel.setValue(manifestRes);
stream.manifestExt.getVideoData(manifestRes,0).then(
function (videoData) {
debugger;
stream.manifestExt.getCodec(videoData).then(
function (codec) {
debugger;
var result= stream.capabilities.supportsCodec(stream.videoModel.getElement(), codec)
expect(result).toBe(true);
});
});
});
it("supports Codec with manifestResult.Period_asArray[0].AdaptationSet_asArray as empty", function(){
manifestRes.Period_asArray[0].AdaptationSet_asArray={};
stream.manifestModel.setValue(manifestRes);
stream.manifestExt.getVideoData(manifestRes,0).then(
function (videoData) {
expect(videoData).not.toBe(null);
});
});
it("supports Codec with videoData as null", function(){
stream.manifestModel.setValue(manifestRes);
stream.manifestExt.getVideoData(manifestRes,0).then(
function (videoData) {
videoData = null;
stream.manifestExt.getCodec(videoData).then(
function (codec) {
expect(codec).toBe(null);
});
});
});
it("supports MediaSource", function () {
expect(capabilitiesObj.supportsMediaSource()).not.toBe(null);
});
it("supports MediaKeys", function () {
expect(capabilitiesObj.supportsMediaKeys()).not.toBe(null);
});
it("supports Codec", function () {
expect(function () {
capabilitiesObj.supportsCodec(null, null, null)
}).toThrow();
});
});
} |
kiranrraj/100Days_Of_Coding | Day_20/jump_search_2.py | # Title : Jump search
# Author : <NAME>.
# Date : 03:11:2020
import math
def jump_search(arr, num):
prev =0
jump = int(math.sqrt(len(arr)))
length = len(arr)
for i in range(0, length, jump):
if arr[i] < num:
prev = i
elif arr[i] == num:
return f"Found {arr[i]} at {i+1}"
else:
break
for j in range(prev,length):
if arr[j]== num:
return f"Found {arr[j]} at {j+1}"
j+=1
return "Not found"
print(jump_search([2,4,6,8,9,10,13,16,19], 19))
print(jump_search([2,4,6,8,9,10,13,16,19], 16))
print(jump_search([2,4,6,8,9,10,13,16,19], 29))
print(jump_search([2,4,6,8,9,10,13,16,19], 9))
print(jump_search([2,4,6,8,9,10,13,16,19], 2)) |
YtGz/apexcharts.js | src/modules/Responsive.js | <reponame>YtGz/apexcharts.js
import Config from './settings/Config'
import Utils from '../utils/Utils'
import CoreUtils from './CoreUtils'
/**
* ApexCharts Responsive Class to override options for different screen sizes.
*
* @module Responsive
**/
export default class Responsive {
constructor(ctx) {
this.ctx = ctx
this.w = ctx.w
}
// the opts parameter if not null has to be set overriding everything
// as the opts is set by user externally
checkResponsiveConfig(opts) {
const w = this.w
const cnf = w.config
// check if responsive config exists
if (cnf.responsive.length === 0) return
let res = cnf.responsive.slice()
res
.sort((a, b) =>
a.breakpoint > b.breakpoint ? 1 : b.breakpoint > a.breakpoint ? -1 : 0
)
.reverse()
let config = new Config({})
const iterateResponsiveOptions = (newOptions = {}) => {
let largestBreakpoint = res[0].breakpoint
const width = window.innerWidth > 0 ? window.innerWidth : screen.width
if (width > largestBreakpoint) {
let options = CoreUtils.extendArrayProps(
config,
w.globals.initialConfig,
w
)
newOptions = Utils.extend(options, newOptions)
newOptions = Utils.extend(w.config, newOptions)
this.overrideResponsiveOptions(newOptions)
} else {
for (let i = 0; i < res.length; i++) {
if (width < res[i].breakpoint) {
newOptions = CoreUtils.extendArrayProps(config, res[i].options, w)
newOptions = Utils.extend(w.config, newOptions)
this.overrideResponsiveOptions(newOptions)
}
}
}
}
if (opts) {
let options = CoreUtils.extendArrayProps(config, opts, w)
options = Utils.extend(w.config, options)
options = Utils.extend(options, opts)
iterateResponsiveOptions(options)
} else {
iterateResponsiveOptions({})
}
}
overrideResponsiveOptions(newOptions) {
let newConfig = new Config(newOptions).init({ responsiveOverride: true })
this.w.config = newConfig
}
}
|
EDGEDevInteractive/RenCode | html-src/TL/lastAction.js | <gh_stars>0
// Get Elements
var iconElem = document.getElementById("LastActionImg");
var TextElem = document.getElementById("LastActionText");
// Get Images
var Img_Cancel = "../../Icons1/Cancel.png"
var Img_FileCheck = "../../Icons1/File-Check.png"
var Img_Gear = "../../Icons1/Gear.png"
var Img_Info = "../../Icons1/Info.png"
var Img_Run = "../../Icons1/Run.png"
function lastAction_Cancel(Text){
iconElem.src = Img_Cancel;
TextElem.innerText = Text;
}
function lastAction_Info(Text){
iconElem.src = Img_Info;
TextElem.innerText = Text;
} |
qualitybargain/blightstatus | spec/lib/tasks/foreclosures_rake_spec.rb | <gh_stars>1-10
require "./spec/support/shared_contexts/rake.rb"
describe "foreclosures:load" do
include_context "rake"
describe "foreclosures:load" do
it "creates foreclosures" do
#figure out how to test things here
end
end
end
|
masud-technope/ACER-Replication-Package-ASE2017 | corpus/class/ecf/789.java | <reponame>masud-technope/ACER-Replication-Package-ASE2017<filename>corpus/class/ecf/789.java
/****************************************************************************
* Copyright (c) 2007, 2009 Composent, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Composent, Inc. - initial API and implementation
*****************************************************************************/
package org.eclipse.ecf.docshare2.messages;
import org.eclipse.ecf.core.identity.ID;
/**
* @since 2.1
*
*/
public class StartMessage extends Message {
private static final long serialVersionUID = 4712028336072890912L;
private final ID peerID;
private final String path;
private final String documentContent;
public StartMessage(ID peerID, String content, String path) {
this.peerID = peerID;
this.path = path;
this.documentContent = content;
}
public ID getPeerID() {
return peerID;
}
public String getPath() {
return path;
}
public String getDocumentContent() {
return documentContent;
}
}
|
datphan/moviecrab | tests/unit/mgr/__init__.py | # -*- coding:utf-8 -*-
"""unit tests for manager"""
|
souzamonteiro/guash | src/mpi/mpi.c | /**
* File:
* mpi.c
*
* Package:
* Mpi
*
* Description:
* This file implements a GuaraScript extension.
*
* Copyright:
* Copyright (c) 2019 <NAME>, <NAME>.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* RCS: @(#) $Id: mpi.c,v 1.0 2019/11/21 21:02:00 monteiro Exp $
*
*/
#include <stdlib.h>
#include <string.h>
#include "interp.h"
#include "mpi.h"
#define BUFFER_SIZE 65536
/**
* Group:
* C
*
* Function:
* Gua_Status Mpi_FunctionWrapper(void *nspace, Gua_Short argc, Gua_Object *argv, Gua_Object *object, Gua_String error)
*
* Description:
* Function wrapper.
*
* Arguments:
* nspace, a pointer to a structure Gua_Namespace. Must do a cast before use it;
* argc, the number of arguments to pass to the function;
* argv, an array containing the arguments to the function;
* argv[0] is the function name;
* object, a structure containing the return object of the function;
* error, a pointer to the error message.
*
* Results:
* The return object of the wrapped function.
*/
Gua_Status Mpi_FunctionWrapper(void *nspace, Gua_Short argc, Gua_Object *argv, Gua_Object *object, Gua_String error)
{
int rank;
int num_procs;
int count;
MPI_Status status;
Gua_String buffer;
Gua_String errMessage;
rank = 0;
num_procs = 0;
count = 0;
Gua_ClearPObject(object);
if (argc == 0) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s\n", "no function specified");
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Comm_rank") == 0) {
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
Gua_IntegerToPObject(object, rank);
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Comm_size") == 0) {
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
Gua_IntegerToPObject(object, num_procs);
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Send") == 0) {
if (argc != 4) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "wrong number of arguments for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[1]) != OBJECT_TYPE_STRING) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 1 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[2]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 2 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[3]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 3 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
MPI_Send(Gua_ObjectToString(argv[1]), Gua_ObjectLength(argv[1]) + 1, MPI_CHAR, Gua_ObjectToInteger(argv[2]), Gua_ObjectToInteger(argv[3]), MPI_COMM_WORLD);
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Recv") == 0) {
if (argc != 4) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "wrong number of arguments for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[1]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 1 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[2]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 2 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[3]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 3 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
buffer = (char *)Gua_Alloc(sizeof(char) * (Gua_ObjectToInteger(argv[1]) + 1));
memset(buffer, '\0', Gua_ObjectToInteger(argv[1]) + 1);
MPI_Recv(buffer, Gua_ObjectToInteger(argv[1]), MPI_CHAR, Gua_ObjectToInteger(argv[2]), Gua_ObjectToInteger(argv[3]), MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &count);
if (count > 0) {
Gua_ByteArrayToPObject(object, buffer, count);
}
Gua_Free(buffer);
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Probe") == 0) {
if (argc != 3) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "wrong number of arguments for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[1]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 1 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[2]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 2 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
MPI_Probe(Gua_ObjectToInteger(argv[1]), Gua_ObjectToInteger(argv[2]), MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &count);
Gua_IntegerToPObject(object, count);
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Abort") == 0) {
if (argc != 2) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "wrong number of arguments for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
if (Gua_ObjectType(argv[1]) != OBJECT_TYPE_INTEGER) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "illegal argument 1 for function", Gua_ObjectToString(argv[0]));
strcat(error, errMessage);
Gua_Free(errMessage);
return GUA_ERROR;
}
Gua_IntegerToPObject(object, MPI_Abort(MPI_COMM_WORLD, Gua_ObjectToInteger(argv[1])));
} else if (strcmp(Gua_ObjectToString(argv[0]), "MPI_Finalize") == 0) {
Gua_IntegerToPObject(object, MPI_Finalize());
}
return GUA_OK;
}
/**
* Group:
* C
*
* Function:
* Gua_Status Mpi_Init(void *nspace, int argc, char *argv[], char **env, Gua_String error)
*
* Description:
* Install the extension functions.
*
* Arguments:
* nspace, a pointer to a structure containing the variable and function namespace;
* argc, the number of command line arguments;
* argv, the command line arguments;
* env, a pointer to the environment variables;
* error, a pointer to the error message.
*
* Results:
* Install the extension functions.
*/
Gua_Status Mpi_Init(void *nspace, int argc, char *argv[], char **env, Gua_String error)
{
Gua_Function function;
Gua_Object object;
Gua_String errMessage;
/* Define the function wrapper to each extension function... */
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Comm_rank", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Comm_rank");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Comm_size", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Comm_size");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Send", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Send");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Recv", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Recv");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Probe", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Probe");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Abort", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Abort");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_LinkCFunctionToFunction(function, Mpi_FunctionWrapper);
if (Gua_SetFunction((Gua_Namespace *)nspace, "MPI_Finalize", &function) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set function", "MPI_Finalize");
strcat(error, errMessage);
Gua_Free(errMessage);
}
Gua_IntegerToObject(object, MPI_VERSION);
Gua_SetStoredObject(object);
if (Gua_SetVariable((Gua_Namespace *)nspace, "MPI_VERSION", &object, SCOPE_GLOBAL) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set variable", "MPI_VERSION");
strcat(error, errMessage);
Gua_Free(errMessage);
}
/**
* Group:
* Scripting
*
* Constant:
* GUA_MPI_VERSION
*
* Description:
* Library version.
*/
Gua_LinkStringToObject(object, GUA_MPI_VERSION);
Gua_SetStoredObject(object);
if (Gua_SetVariable((Gua_Namespace *)nspace, "GUA_MPI_VERSION", &object, SCOPE_GLOBAL) != GUA_OK) {
errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
sprintf(errMessage, "%s %-.20s...\n", "can't set variable", "GUA_MPI_VERSION");
strcat(error, errMessage);
Gua_Free(errMessage);
}
/* Call the MPI Initializer. */
MPI_Init(&argc, &argv);
return GUA_OK;
}
|
U-Ar/Cpresto | cpc/sysdep/GNUAssembler.py | from .Assembler import Assembler
from utils.CommandUtils import CommandUtils
class GNUAssembler(Assembler):
def __init__(self,h):
self.error_handler = h
def assemble(self,srcpath,destpath,opts):
cmd = []
cmd.append("as")
cmd += opts.args
cmd.append("-o")
cmd.append(destpath)
cmd.append(srcpath)
CommandUtils.invoke(cmd,self.error_handler,opts.verbose) |
DAKSHSEMWAL/Vegidel | app/src/main/java/app/kurosaki/developer/vegidel/ui/activities/AddAddressActivity.java | <reponame>DAKSHSEMWAL/Vegidel
package app.kurosaki.developer.vegidel.ui.activities;
import android.os.Bundle;
import androidx.databinding.DataBindingUtil;
import java.util.ArrayList;
import app.kurosaki.developer.vegidel.R;
import app.kurosaki.developer.vegidel.core.BaseActivity;
import app.kurosaki.developer.vegidel.databinding.ActivityAddAddressBinding;
import app.kurosaki.developer.vegidel.utils.Common;
public class AddAddressActivity extends BaseActivity {
ActivityAddAddressBinding binding;
ArrayList<String> address = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(mContext, R.layout.activity_add_address);
initView();
implementlisteners();
}
private void implementlisteners() {
binding.proceed.setOnClickListener(v->{
String add = binding.name.getText().toString().trim() + "\n" +
binding.address.getText().toString().trim() + ",\n" +
binding.city.getText().toString().trim() + "," +
binding.phonecode.getText().toString().trim() + "\nPhone: " +
binding.phone.getText().toString().trim() ;
address.add(add);
sp.setString(ADDRESS, gson.toJson(address));
finish();
});
}
private void initView() {
Common.setToolbarWithBackAndTitle(mContext,"",false,R.drawable.ic_arrow);
binding.mToolbar.toolbar.setNavigationOnClickListener(v->{
onBackPressed();
});
address.addAll(Common.getAddresses(sp));
}
} |
ScalablyTyped/SlinkyTyped | j/jquery_dot_fancytree/src/main/scala/typingsSlinky/jqueryFancytree/Fancytree/NodePatch.scala | package typingsSlinky.jqueryFancytree.Fancytree
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/** Data object similar to NodeData, but with additional options.
* May be passed to FancytreeNode#applyPatch (Every property that is omitted (or set to undefined) will be ignored) */
@js.native
trait NodePatch extends StObject {
/** (not yet implemented) */
var appendChildren: js.UndefOr[NodeData] = js.native
/** (not yet implemented) */
var insertChildren: js.UndefOr[NodeData] = js.native
/** (not yet implemented) */
var replaceChildren: js.UndefOr[NodeData] = js.native
}
object NodePatch {
@scala.inline
def apply(): NodePatch = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[NodePatch]
}
@scala.inline
implicit class NodePatchMutableBuilder[Self <: NodePatch] (val x: Self) extends AnyVal {
@scala.inline
def setAppendChildren(value: NodeData): Self = StObject.set(x, "appendChildren", value.asInstanceOf[js.Any])
@scala.inline
def setAppendChildrenUndefined: Self = StObject.set(x, "appendChildren", js.undefined)
@scala.inline
def setInsertChildren(value: NodeData): Self = StObject.set(x, "insertChildren", value.asInstanceOf[js.Any])
@scala.inline
def setInsertChildrenUndefined: Self = StObject.set(x, "insertChildren", js.undefined)
@scala.inline
def setReplaceChildren(value: NodeData): Self = StObject.set(x, "replaceChildren", value.asInstanceOf[js.Any])
@scala.inline
def setReplaceChildrenUndefined: Self = StObject.set(x, "replaceChildren", js.undefined)
}
}
|
sridmad/envoy | source/common/router/config_utility.cc | #include "common/router/config_utility.h"
#include <regex>
#include <string>
#include <vector>
#include "common/common/assert.h"
namespace Envoy {
namespace Router {
bool ConfigUtility::QueryParameterMatcher::matches(
const Http::Utility::QueryParams& request_query_params) const {
auto query_param = request_query_params.find(name_);
if (query_param == request_query_params.end()) {
return false;
} else if (is_regex_) {
return std::regex_match(query_param->second, regex_pattern_);
} else if (value_.length() == 0) {
return true;
} else {
return (value_ == query_param->second);
}
}
Upstream::ResourcePriority
ConfigUtility::parsePriority(const envoy::api::v2::RoutingPriority& priority) {
switch (priority) {
case envoy::api::v2::RoutingPriority::DEFAULT:
return Upstream::ResourcePriority::Default;
case envoy::api::v2::RoutingPriority::HIGH:
return Upstream::ResourcePriority::High;
default:
NOT_IMPLEMENTED;
}
}
bool ConfigUtility::matchHeaders(const Http::HeaderMap& request_headers,
const std::vector<HeaderData>& config_headers) {
bool matches = true;
if (!config_headers.empty()) {
for (const HeaderData& cfg_header_data : config_headers) {
const Http::HeaderEntry* header = request_headers.get(cfg_header_data.name_);
if (cfg_header_data.value_.empty()) {
matches &= (header != nullptr);
} else if (!cfg_header_data.is_regex_) {
matches &= (header != nullptr) && (header->value() == cfg_header_data.value_.c_str());
} else {
matches &= (header != nullptr) &&
std::regex_match(header->value().c_str(), cfg_header_data.regex_pattern_);
}
if (!matches) {
break;
}
}
}
return matches;
}
bool ConfigUtility::matchQueryParams(
const Http::Utility::QueryParams& query_params,
const std::vector<QueryParameterMatcher>& config_query_params) {
for (const auto& config_query_param : config_query_params) {
if (!config_query_param.matches(query_params)) {
return false;
}
}
return true;
}
Http::Code ConfigUtility::parseRedirectResponseCode(
const envoy::api::v2::RedirectAction::RedirectResponseCode& code) {
switch (code) {
case envoy::api::v2::RedirectAction::MOVED_PERMANENTLY:
return Http::Code::MovedPermanently;
case envoy::api::v2::RedirectAction::FOUND:
return Http::Code::Found;
case envoy::api::v2::RedirectAction::SEE_OTHER:
return Http::Code::SeeOther;
case envoy::api::v2::RedirectAction::TEMPORARY_REDIRECT:
return Http::Code::TemporaryRedirect;
case envoy::api::v2::RedirectAction::PERMANENT_REDIRECT:
return Http::Code::PermanentRedirect;
default:
NOT_IMPLEMENTED;
}
}
Http::Code ConfigUtility::parseClusterNotFoundResponseCode(
const envoy::api::v2::RouteAction::ClusterNotFoundResponseCode& code) {
switch (code) {
case envoy::api::v2::RouteAction::SERVICE_UNAVAILABLE:
return Http::Code::ServiceUnavailable;
case envoy::api::v2::RouteAction::NOT_FOUND:
return Http::Code::NotFound;
default:
NOT_IMPLEMENTED;
}
}
} // namespace Router
} // namespace Envoy
|
JeromeGobeil/SENG401Chess | src/main/java/com/leokom/games/chess/player/legal/brain/normalized/NormalizedEvaluatorFactory.java | <reponame>JeromeGobeil/SENG401Chess
package com.leokom.games.chess.player.legal.brain.normalized;
import com.google.common.collect.Maps;
import com.leokom.games.chess.player.legal.brain.common.Evaluator;
import com.leokom.games.chess.player.legal.brain.common.EvaluatorFactory;
import com.leokom.games.chess.player.legal.brain.common.EvaluatorFactoryCreator;
import com.leokom.games.chess.player.legal.brain.common.EvaluatorType;
import com.leokom.games.chess.player.legal.brain.denormalized.DenormalizedEvaluatorFactory;
import java.util.EnumMap;
import java.util.Map;
/**
* Author: Leonid
* Date-time: 27.08.16 13:28
*/
public class NormalizedEvaluatorFactory implements EvaluatorFactory {
private static final Map<EvaluatorType, Evaluator> EVALUATORS;
private static final DenormalizedEvaluatorFactory DENORMALIZED_EVALUATOR_FACTORY = (DenormalizedEvaluatorFactory)EvaluatorFactoryCreator.getEvaluatorFactory("denormalized");
static {
//we keep references to instances of EVALUATORS here
//so they're practically singletons
//any valid Evaluator must be stateless and thread-safe
Map< EvaluatorType, Evaluator > evaluatorsMutable = new EnumMap<>( EvaluatorType.class );
evaluatorsMutable.put( EvaluatorType.ATTACK, new AttackEvaluator() );
evaluatorsMutable.put( EvaluatorType.CENTER_CONTROL, new CenterControlEvaluator() );
evaluatorsMutable.put( EvaluatorType.MATERIAL, new MaterialEvaluator() );
evaluatorsMutable.put( EvaluatorType.MOBILITY, new MobilityEvaluator() );
evaluatorsMutable.put( EvaluatorType.PROTECTION, new ProtectionEvaluator() );
EVALUATORS = Maps.immutableEnumMap( evaluatorsMutable );
}
/**
* @implNote part of EVALUATORS might be reused from denormalized package if they already
* provide the correct values (NOTE: most likely we should move them to normalized package then!)
* @param type type of brain to get brain from
* @return brain that is normalized [ 0, 1 ]
*/
@Override
public Evaluator get( EvaluatorType type ) {
return EVALUATORS.get( type ) != null ? EVALUATORS.get( type ) :
DENORMALIZED_EVALUATOR_FACTORY.get( type );
}
}
|
JaxVanYang/acm | jax/codeforces/uncategorized/cf-714/a.cc | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int maxn = 2e5 + 5;
int a[maxn], b[maxn];
char s[maxn], t[maxn];
void solve() {
int n, k;
cin >> n >> k;
int cnt = (n - 1) / 2;
if (cnt < k) {
puts("-1");
return;
}
int num = n;
for (int i = 0; i < k; ++i) {
a[2 * i + 1] = num--;
}
for (int i = 0; i < k; ++i) {
a[2 * i] = num--;
}
for (int i = 2 * k; i < n; ++i) {
a[i] = num--;
}
for (int i = 0; i < n; ++i) {
printf("%d ", a[i]);
}
puts("");
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
} |
hardfish/justTest | profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/server/ServerInfoResponseHandlerTest.java | <gh_stars>0
/*
* 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.jclouds.profitbricks.http.parser.server;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import org.jclouds.date.DateCodec;
import org.jclouds.date.DateCodecFactory;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.profitbricks.domain.AvailabilityZone;
import org.jclouds.profitbricks.domain.Firewall;
import org.jclouds.profitbricks.domain.Nic;
import org.jclouds.profitbricks.domain.OsType;
import org.jclouds.profitbricks.domain.ProvisioningState;
import org.jclouds.profitbricks.domain.Server;
import org.jclouds.profitbricks.domain.Storage;
import org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
@Test(groups = "unit", testName = "ServerInfoResponseHandlerTest")
public class ServerInfoResponseHandlerTest extends BaseResponseHandlerTest<Server> {
@Override
protected ParseSax<Server> createParser() {
return factory.create(injector.getInstance(ServerInfoResponseHandler.class));
}
protected DateCodecFactory createDateParser() {
return injector.getInstance(DateCodecFactory.class);
}
@Test
public void testParseResponseFromGetServer() {
ParseSax<Server> parser = createParser();
Server actual = parser.parse(payloadFromResource("/server/server.xml"));
assertNotNull(actual, "Parsed content returned null");
DateCodec dateParser = createDateParser().iso8601();
Server expected = Server.builder()
.id("qwertyui-qwer-qwer-qwer-qwertyyuiiop")
.name("facebook-node")
.cores(4)
.ram(4096)
.hasInternetAccess(true)
.state(ProvisioningState.AVAILABLE)
.status(Server.Status.RUNNING)
.creationTime(dateParser.toDate("2014-12-04T07:09:23.138Z"))
.lastModificationTime(dateParser.toDate("2014-12-12T03:08:35.629Z"))
.osType(OsType.LINUX)
.availabilityZone(AvailabilityZone.AUTO)
.isCpuHotPlug(true)
.isRamHotPlug(true)
.isNicHotPlug(true)
.isNicHotUnPlug(true)
.isDiscVirtioHotPlug(true)
.isDiscVirtioHotUnPlug(true)
.activate(true)
.balancedNicId("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh")
.storages(ImmutableList.<Storage>of(
Storage.builder()
.bootDevice(Boolean.TRUE)
.busType(Storage.BusType.VIRTIO)
.deviceNumber(1)
.size(40f)
.id("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh")
.name("facebook-storage")
.build()
)
)
.nics(ImmutableList.<Nic>of(
Nic.builder()
.dataCenterId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
.id("qwqwqwqw-wewe-erer-rtrt-tytytytytyty")
.lanId(1)
.internetAccess(true)
.serverId("qwertyui-qwer-qwer-qwer-qwertyyuiiop")
.ip("172.16.58.3")
.macAddress("02:01:09:cd:f0:b0")
.firewall(Firewall.builder()
.active(false)
.id("wqwqwqwq-ewew-rere-trtr-ytytytytytyt")
.nicId("qwqwqwqw-wewe-erer-rtrt-tytytytytyty")
.state(ProvisioningState.AVAILABLE)
.build())
.dhcpActive(true)
.gatewayIp("192.168.127.12")
.state(ProvisioningState.AVAILABLE)
.build()
))
.build();
assertEquals(actual, expected);
}
}
|
Mananananana/yutou_library | yutou_library/apis/v1/__init__.py | <gh_stars>1-10
from flask import Blueprint
api_v1 = Blueprint("api_v1", __name__)
from yutou_library.apis.v1 import resources
|
jelmerterwal/org.hl7.fhir.core | org.hl7.fhir.convertors/src/main/java/org/hl7/fhir/convertors/conv10_50/datatypes10_50/complextypes10_50/Quantity10_50.java | package org.hl7.fhir.convertors.conv10_50.datatypes10_50.complextypes10_50;
import org.hl7.fhir.convertors.conv10_50.datatypes10_50.Element10_50;
import org.hl7.fhir.convertors.conv10_50.datatypes10_50.primitivetypes10_50.Code10_50;
import org.hl7.fhir.convertors.conv10_50.datatypes10_50.primitivetypes10_50.Decimal10_50;
import org.hl7.fhir.convertors.conv10_50.datatypes10_50.primitivetypes10_50.String10_50;
import org.hl7.fhir.convertors.conv10_50.datatypes10_50.primitivetypes10_50.Uri10_50;
import org.hl7.fhir.exceptions.FHIRException;
public class Quantity10_50 {
public static org.hl7.fhir.r5.model.Quantity convertQuantity(org.hl7.fhir.dstu2.model.Quantity src) throws FHIRException {
if (src == null || src.isEmpty()) return null;
org.hl7.fhir.r5.model.Quantity tgt = new org.hl7.fhir.r5.model.Quantity();
Element10_50.copyElement(src, tgt);
if (src.hasValueElement()) tgt.setValueElement(Decimal10_50.convertDecimal(src.getValueElement()));
if (src.hasComparator()) tgt.setComparatorElement(convertQuantityComparator(src.getComparatorElement()));
if (src.hasUnitElement()) tgt.setUnitElement(String10_50.convertString(src.getUnitElement()));
if (src.hasSystemElement()) tgt.setSystemElement(Uri10_50.convertUri(src.getSystemElement()));
if (src.hasCodeElement()) tgt.setCodeElement(Code10_50.convertCode(src.getCodeElement()));
return tgt;
}
public static org.hl7.fhir.dstu2.model.Quantity convertQuantity(org.hl7.fhir.r5.model.Quantity src) throws FHIRException {
if (src == null || src.isEmpty()) return null;
org.hl7.fhir.dstu2.model.Quantity tgt = new org.hl7.fhir.dstu2.model.Quantity();
Element10_50.copyElement(src, tgt);
if (src.hasValueElement()) tgt.setValueElement(Decimal10_50.convertDecimal(src.getValueElement()));
if (src.hasComparator()) tgt.setComparatorElement(convertQuantityComparator(src.getComparatorElement()));
if (src.hasUnitElement()) tgt.setUnitElement(String10_50.convertString(src.getUnitElement()));
if (src.hasSystemElement()) tgt.setSystemElement(Uri10_50.convertUri(src.getSystemElement()));
if (src.hasCodeElement()) tgt.setCodeElement(Code10_50.convertCode(src.getCodeElement()));
return tgt;
}
static public org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Enumerations.QuantityComparator> convertQuantityComparator(org.hl7.fhir.dstu2.model.Enumeration<org.hl7.fhir.dstu2.model.Quantity.QuantityComparator> src) throws FHIRException {
if (src == null || src.isEmpty()) return null;
org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Enumerations.QuantityComparator> tgt = new org.hl7.fhir.r5.model.Enumeration<>(new org.hl7.fhir.r5.model.Enumerations.QuantityComparatorEnumFactory());
Element10_50.copyElement(src, tgt);
if (src.getValue() == null) {
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.NULL);
} else {
switch (src.getValue()) {
case LESS_THAN:
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.LESS_THAN);
break;
case LESS_OR_EQUAL:
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.LESS_OR_EQUAL);
break;
case GREATER_OR_EQUAL:
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.GREATER_OR_EQUAL);
break;
case GREATER_THAN:
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.GREATER_THAN);
break;
default:
tgt.setValue(org.hl7.fhir.r5.model.Enumerations.QuantityComparator.NULL);
break;
}
}
return tgt;
}
static public org.hl7.fhir.dstu2.model.Enumeration<org.hl7.fhir.dstu2.model.Quantity.QuantityComparator> convertQuantityComparator(org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Enumerations.QuantityComparator> src) throws FHIRException {
if (src == null || src.isEmpty()) return null;
org.hl7.fhir.dstu2.model.Enumeration<org.hl7.fhir.dstu2.model.Quantity.QuantityComparator> tgt = new org.hl7.fhir.dstu2.model.Enumeration<>(new org.hl7.fhir.dstu2.model.Quantity.QuantityComparatorEnumFactory());
Element10_50.copyElement(src, tgt);
if (src.getValue() == null) {
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.NULL);
} else {
switch (src.getValue()) {
case LESS_THAN:
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.LESS_THAN);
break;
case LESS_OR_EQUAL:
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.LESS_OR_EQUAL);
break;
case GREATER_OR_EQUAL:
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.GREATER_OR_EQUAL);
break;
case GREATER_THAN:
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.GREATER_THAN);
break;
default:
tgt.setValue(org.hl7.fhir.dstu2.model.Quantity.QuantityComparator.NULL);
break;
}
}
return tgt;
}
}
|
bhoske/changeGLTF | node_modules/mjs-volume/runtime/scene.js | // Copyright (c) 2013, <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
var Montage = require("montage").Montage;
var Node = require("runtime/node").Node;
var RuntimeTFLoader = require("runtime/runtime-tf-loader").RuntimeTFLoader;
var URL = require("url");
var SceneResourceLoader = require("runtime/scene-resource-loader").SceneResourceLoader;
var Q = require("q");
var Target = require("montage/core/target").Target;
var CSSOM = require("cssom");
var GLTFScene = require("runtime/glTF-scene").glTFScene;
var Material = require("runtime/glTF-material").glTFMaterial;
exports.Scene = Target.specialize( {
constructor: {
value: function Scene() {
this.super();
}
},
_resourcesLoaded: { value: false, writable: true },
_glTFElement: { value: null, writable: true },
shouldBeHitTested: { value: false, writable: true },
glTFElement: {
get: function() {
return this._glTFElement;
},
set: function(value) {
this._glTFElement = value;
}
},
_rootNode: { value: null, writable: true },
rootNode: {
get: function() {
if (this.status === "loaded") {
if (this._rootNode == null) {
this._rootNode = Montage.create(Node);
this._rootNode.scene = this;
this._rootNode.id = this.glTFElement.rootNode.id;
}
}
return this._rootNode;
}
},
sceneResourcesDidPrepare: {
value: function() {
if (!this._resourcesLoaded) {
if (this._prepareToRenderDefer) {
this._prepareToRenderDefer.resolve();
}
this._resourcesLoaded = true;
//FIXME: we should pass { scene:scene webGLContext:webGLContext
//only problem now is pass the webGLContext through the promise properly
this.dispatchEventNamed("resourcesDidLoad", true, false, this);
this.status = "loaded";
}
}
},
isLoaded: {
value: function() {
return this.status == "loaded";
}
},
status: { value: 0, writable: true},
styleSheetsLoaded: { value: false, writable: true},
styleSheets: { value: null, writable: true},
loadCSSStyles: {
value: function() {
if (document.styleSheets == null)
return;
var packages = Object.keys(require.packages);
var styleSheetsLoaded = 0;
var styleSheetsCount = document.styleSheets.length;
var i;
var styleSheet;
var styleSheets = [];
this.styleSheets = {};
for (i = 0; i < styleSheetsCount; i++) {
styleSheet = document.styleSheets[i];
if (styleSheet.href != null) {
if (styleSheet.href.indexOf(packages[0]) != -1) {
//HACK: packages[0] is guaranted to be the entry point
//we just want the CSS from this project but not the ones from its dependencies
if (styleSheet.href.indexOf(packages[0] + "node_modules") == -1) {
styleSheets.push(styleSheet);
}
}
}
}
styleSheetsCount = styleSheets.length;
if (styleSheetsCount === 0) {
this.styleSheetsLoaded = true;
return;
}
styleSheets.forEach(function(styleSheet) {
var self = this;
//FIXME: handle error
var cssPath = styleSheet.href;
var cssXHR = new XMLHttpRequest();
cssXHR.open("GET", cssPath, true);
cssXHR.onreadystatechange = function() {
if (cssXHR.readyState == 4) {
if (cssXHR.status == 200 || cssXHR.status == 0) {
var cssDescription = CSSOM.parse(cssXHR.responseText);
self.styleSheets[styleSheet.href] = cssDescription;
styleSheetsLoaded++;
if (styleSheetsLoaded === styleSheetsCount) {
self.dispatchEventNamed("styleSheetsDidLoad", true, false, self);
}
}
}
}
cssXHR.send(null);
}, this);
return false;
}
},
loadMultipleScenes: {
value: function() {
var paths = [];
paths.push("model/ford/Ford_F150_Test_Texture.json");
var pathsIndex = 0;
var mainScene = Object.create(GLTFScene).init();
var readerDelegate = {};
readerDelegate.loadCompleted = function (scene) {
mainScene.baseURL = scene.baseURL;
mainScene.id = scene.id + pathsIndex;
mainScene.baseId = scene.baseId + pathsIndex;
mainScene.ids = scene.ids;
mainScene._animationManager = scene._animationManager;
mainScene.rootNode.children.push(scene.rootNode);
pathsIndex++;
if (paths.length === pathsIndex) {
this.needsDraw = true;
this.glTFElement = mainScene;
this.status = "loaded";
//following lines are addes to handle config file
mainScene.rootNode.isMaterialSet = false;
mainScene.rootNode.configFile = mainScene.baseURL+"i3d.config";
var rootNode= mainScene.rootNode;
var request = new XMLHttpRequest();
var result;
request.onreadystatechange = function() {
if ((request.readyState == 4) ) {
result = request.responseText;
}
};
request.open("POST", rootNode.configFile, false);
request.send(null);
if(result)
{
if(result.search("ColorNodes") != -1)
{
var idx = result.indexOf("ColorNodes");
var sliced_str = result.substr(idx);
var idx1 = result.indexOf("\n");
sliced_str = sliced_str.substr(idx1+1);
if(result.search("BodyColor") != -1)
{
var idx2 = result.indexOf("BodyColor");
sliced_str = sliced_str.substr(0,idx2);
}
if(sliced_str.length >0)
{
function removeSpaces(str_) //can use trim function instead of this
{
var i;
for(i =0;i<str_.length;i++)
{
if(str_[i]=== " " || str_[i] ==="\t" || str_[i] ==="\n")
{
}
else
{
break;
}
}
var new_str = str_.substr(i);
for(i =new_str.length-1;i>= 0;i--)
{
if(new_str[i]=== " " || new_str[i] ==="\t" || new_str[i] ==="\n")
{
}
else
{
break;
}
}
new_str = new_str.substr(0,i+1);
return new_str;
};
function replaceSpaces(str_)
{
var new_str = "";
for(var i =0;i<str_.length;i++)
{
if(str_[i]==" ")
{
new_str = new_str.concat("_");
}
else
{
new_str = new_str.concat(str_[i]);
}
}
return new_str;
};
function searchNode(node_,name_) {
var return_value = null;
var goForChildren = false;
if(node_.name)
{
var name1_ = (node_.name).toLowerCase();
if(name1_ == name_)
{
return_value = node_;
}
else
goForChildren = true;
}
else
goForChildren = true;
if(goForChildren)
{
for(var i =0 ;i<node_.children.length;i++)
{
return_value = searchNode(node_.children[i],name_);
if(return_value != null)
break;
}
}
return return_value;
};
function searchMaterialNode(node_) {
var return_value = null;
if(node_.children.length ==0)
{
return_value = node_;
}
else
{
for(var i =0 ;i<node_.children.length;i++)
{
return_value = searchMaterialNode(node_.children[i]);
if(return_value != null)
break;
}
}
return return_value;
};
function setMaterialForAllNode(node_,tempMaterial) {
if(node_.children.length ==0)
{
var meshes = node_._properties.meshes;
if(meshes)
{
for(var i = 0;i<meshes.length;i++)
{
var primitives = meshes[i].primitives;
if(primitives)
{
for(var j =0 ;j<primitives.length;j++)
{
primitives[j]._material = tempMaterial;
}
}
}
}
}
else
{
for(var i =0 ;i<node_.children.length;i++)
{
setMaterialForAllNode(node_.children[i],tempMaterial);
}
}
};
var split_lines = sliced_str.split("\n");
for(var j = 0;j<split_lines.length;j=j+4)
{
var part_name = split_lines[j];
//console.log("part_name : "+part_name);
if(part_name.search("BodyColor") != -1)
{
j = split_lines.length;
break;
}
var part_name_no_spaces = removeSpaces(part_name);
var part_name_lowercase = part_name_no_spaces.toLowerCase();
part_name_lowercase = part_name_lowercase.substr(0,part_name_lowercase.length-2);
part_name_lowercase = replaceSpaces(part_name_lowercase);
//console.log("part_name_lowercase : "+part_name_lowercase);
var mynode_ = searchNode(rootNode,part_name_lowercase);
if( mynode_ !== null)
{
var mynode1_ = searchMaterialNode(mynode_);
if(mynode1_)
{
if(mynode1_._properties.meshes[0].primitives[0]._material)
{
var old_mat = mynode1_._properties.meshes[0].primitives[0]._material;
//creating material and applying for all node
/*var diffuse = mat._parameters.diffuse !== undefined ? mat._parameters.diffuse : [0.8,0.8,0.0] ;
var ambient = mat._parameters.ambient !== undefined ? mat._parameters.ambient : [0.0,0.0,0.0] ;
var emission = mat._parameters.emission !== undefined ? mat._parameters.emission : [0.0,0.0,0.0] ;
var specular = mat._parameters.specular !== undefined ? mat._parameters.specular : [0.0,0.0,0.0] ;
var shininess = mat._parameters.shininess !== undefined ? mat._parameters.shininess : 100.0 ;
var reflectivity = mat._parameters.reflectivity !== undefined ? mat._parameters.reflectivity : 0.0 ;
var transparency = mat._parameters.transparency !== undefined ? mat._parameters.transparency : 1.0 ;
*/
var param = old_mat.parameters;
/*var new_prop = {};
for (var key in prop) {
if (prop.hasOwnProperty(key)) {
//alert(prop[key]);
new_prop.key = prop[key];
}
}*/
var new_param = Object.clone(param);
console.log("node_name : "+ part_name_lowercase);
for(var k =1;k<4;k++)
{
var next_line = split_lines[j+k];
var split_ = next_line.split("=");
var property_ = split_[0];
var property_lowercase = property_.toLowerCase();
property_lowercase = removeSpaces(property_lowercase);
//property_lowercase = property_lowercase.substr(0,property_lowercase.length-1);
var property_value = split_[1];
var property_value_lowercase = property_value.toLowerCase();
property_value_lowercase = removeSpaces(property_value_lowercase);
property_value_lowercase = property_value_lowercase.substr(0,property_value_lowercase.length-1);
if(property_lowercase == "diffuse" || property_lowercase == "reflectivity" || property_lowercase == "transparency")
{
console.log("property : "+ property_lowercase + " property_value : "+property_value_lowercase);
if(property_value_lowercase.length>0)
{
if(property_lowercase == "diffuse")
{
var diffuse_new = property_value_lowercase.split(" ");
new_param.diffuse.value[0] = diffuse_new[0];
new_param.diffuse.value[1] = diffuse_new[1];
new_param.diffuse.value[2] = diffuse_new[2];
}
if(property_lowercase == "reflectivity")
{
if(new_param.reflectivity)
new_param.reflectivity.value = property_value_lowercase;
}
}
}
}
var tempMaterial = Object.create(Material).init("mymaterial"+j);
tempMaterial.parameters = new_param;
tempMaterial.technique = old_mat.technique;
setMaterialForAllNode(mynode_,tempMaterial);
}
}
}
}
}
}
}
}
}.bind(this);
paths.forEach( function(path) {
var loader = Object.create(RuntimeTFLoader);
loader.initWithPath(path);
loader.delegate = readerDelegate;
loader.load(null /* userInfo */, null /* options */);
}, this);
}
},
path: {
set: function(value) {
//Work-around until montage implements textfield that do not send continous input..
if (value) {
if (value.indexOf(".json") === -1)
return;
var URLObject = URL.parse(value);
if (!URLObject.scheme) {
var packages = Object.keys(require.packages);
//HACK: for demo, packages[0] is guaranted to be the entry point
value = URL.resolve(packages[0], value);
}
}
if (value !== this._path) {
if (1) {
this.loadMultipleScenes();
}
else {
var self = this;
var readerDelegate = {};
readerDelegate.loadCompleted = function (scene) {
this.totalBufferSize = loader.totalBufferSize;
this.glTFElement = scene;
this.status = "loaded";
console.log("scene loaded:"+this._path);
}.bind(this);
if (value) {
var loader = Object.create(RuntimeTFLoader);
this.status = "loading";
loader.initWithPath(value);
loader.delegate = readerDelegate;
loader.load(null /* userInfo */, null /* options */);
} else {
this.scene = null;
}
this._path = value;
}
}
},
get: function() {
return this._path;
}
},
_prepareToRenderDefer: { value: null, writable: true },
/*
This method doesn't need to be called directly if the rendering is done via a view.
*/
prepareToRender: {
value: function(webGLRenderer) {
if (this._prepareToRenderDefer == null) {
this._prepareToRenderDefer = Q.defer();
var sceneResourceLoader = Object.create(SceneResourceLoader).init(this.glTFElement, webGLRenderer, this);
sceneResourceLoader.loadScene();
}
return this._prepareToRenderDefer.promise;
}
},
init: {
value:function(glTFElement) {
if (glTFElement) {
this.glTFElement = glTFElement;
this.status = "loaded";
}
return this;
}
},
blueprintModuleId:require("montage")._blueprintModuleIdDescriptor,
blueprint:require("montage")._blueprintDescriptor
});
|
alibaba/tsmock | src/main/java/com/alibaba/tsmock/concurrent/HttpMockServerThread.java | <reponame>alibaba/tsmock
/**
* Copyright © 2017 Alibaba Inc . All rights reserved.
*
* @Title: HttpMockServerThread.java
* @Prject: tsmock
* @Package: com.alibaba.tsmock.cocurrent
* @Description: TODO
* @author: qinjun.qj
* @date: 2017年1月9日上午9:56:31
* @version: v1.0
*/
package com.alibaba.tsmock.concurrent;
import com.alibaba.tsmock.core.http.HttpMockServer;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName: HttpMockServerThread
* @Description: TODO
* @author: qinjun.qj
* @date: 2017年1月9日上午9:56:31
*/
public class HttpMockServerThread implements Runnable {
public HttpMockServerThread() {
}
@Override
public void run() {
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
String formatDate = sdf.format(date);
System.out.println("["+formatDate+"] [HTTP] Start the mock server");
HttpMockServer.start();
}
}
|
dolanor-galaxy/ledger-1 | cmd/server_start.go | package cmd
import (
"context"
"github.com/numary/ledger/pkg/api"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/fx"
"net"
"net/http"
)
func NewServerStart() *cobra.Command {
return &cobra.Command{
Use: "start",
RunE: func(cmd *cobra.Command, args []string) error {
app := NewContainer(
viper.GetViper(),
fx.Invoke(func(h *api.API) error {
listener, err := net.Listen("tcp", viper.GetString(serverHttpBindAddressFlag))
if err != nil {
return err
}
go http.Serve(listener, h)
go func() {
select {
case <-cmd.Context().Done():
}
err := listener.Close()
if err != nil {
panic(err)
}
}()
return nil
}),
)
go app.Start(context.Background())
select {
case <-cmd.Context().Done():
return app.Stop(context.Background())
case <-app.Done():
return app.Err()
}
},
}
}
|
svrc/bosh-vsphere-cpi-release | src/vsphere_cpi/lib/nsxt_policy_client/nsxt_policy_client/api/policy_networking_connectivity_tier1_gateways_interfaces_dad_state_api.rb | <gh_stars>10-100
=begin
#NSX-T Data Center Policy API
#VMware NSX-T Data Center Policy REST API
OpenAPI spec version: 3.1.0.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.19
=end
require 'uri'
module NSXTPolicy
class PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Get DAD state for downlink router port on tier-1 router
# Segment ID is the ID of the segment that is connected to the the tier-1
# @param tier_1_id
# @param segment_id
# @param [Hash] opts the optional parameters
# @option opts [String] :enforcement_point_path String Path of the enforcement point
# @option opts [String] :source Data source type.
# @return [InterfaceDADState]
def get_downlink_port_dad_state_for_tier1_segment(tier_1_id, segment_id, opts = {})
data, _status_code, _headers = get_downlink_port_dad_state_for_tier1_segment_with_http_info(tier_1_id, segment_id, opts)
data
end
# Get DAD state for downlink router port on tier-1 router
# Segment ID is the ID of the segment that is connected to the the tier-1
# @param tier_1_id
# @param segment_id
# @param [Hash] opts the optional parameters
# @option opts [String] :enforcement_point_path String Path of the enforcement point
# @option opts [String] :source Data source type.
# @return [Array<(InterfaceDADState, Fixnum, Hash)>] InterfaceDADState data, response status code and response headers
def get_downlink_port_dad_state_for_tier1_segment_with_http_info(tier_1_id, segment_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment ...'
end
# verify the required parameter 'tier_1_id' is set
if @api_client.config.client_side_validation && tier_1_id.nil?
fail ArgumentError, "Missing the required parameter 'tier_1_id' when calling PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment"
end
# verify the required parameter 'segment_id' is set
if @api_client.config.client_side_validation && segment_id.nil?
fail ArgumentError, "Missing the required parameter 'segment_id' when calling PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment"
end
if @api_client.config.client_side_validation && opts[:'source'] && !['realtime', 'cached'].include?(opts[:'source'])
fail ArgumentError, 'invalid value for "source", must be one of realtime, cached'
end
# resource path
local_var_path = '/infra/tier-1s/{tier-1-id}/segments/{segment-id}/gateway-interface-dad-state'.sub('{' + 'tier-1-id' + '}', tier_1_id.to_s).sub('{' + 'segment-id' + '}', segment_id.to_s)
# query parameters
query_params = {}
query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?
query_params[:'source'] = opts[:'source'] if !opts[:'source'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['BasicAuth']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'InterfaceDADState')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi#get_downlink_port_dad_state_for_tier1_segment\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Get DAD state for downlink router port on tier-1 router
# Segment ID is the ID of the segment that is connected to the the tier-1
# @param tier_1_id
# @param segment_id
# @param [Hash] opts the optional parameters
# @option opts [String] :enforcement_point_path String Path of the enforcement point
# @option opts [String] :source Data source type.
# @return [InterfaceDADState]
def get_downlink_port_dad_state_for_tier1_segment_0(tier_1_id, segment_id, opts = {})
data, _status_code, _headers = get_downlink_port_dad_state_for_tier1_segment_0_with_http_info(tier_1_id, segment_id, opts)
data
end
# Get DAD state for downlink router port on tier-1 router
# Segment ID is the ID of the segment that is connected to the the tier-1
# @param tier_1_id
# @param segment_id
# @param [Hash] opts the optional parameters
# @option opts [String] :enforcement_point_path String Path of the enforcement point
# @option opts [String] :source Data source type.
# @return [Array<(InterfaceDADState, Fixnum, Hash)>] InterfaceDADState data, response status code and response headers
def get_downlink_port_dad_state_for_tier1_segment_0_with_http_info(tier_1_id, segment_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment_0 ...'
end
# verify the required parameter 'tier_1_id' is set
if @api_client.config.client_side_validation && tier_1_id.nil?
fail ArgumentError, "Missing the required parameter 'tier_1_id' when calling PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment_0"
end
# verify the required parameter 'segment_id' is set
if @api_client.config.client_side_validation && segment_id.nil?
fail ArgumentError, "Missing the required parameter 'segment_id' when calling PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi.get_downlink_port_dad_state_for_tier1_segment_0"
end
if @api_client.config.client_side_validation && opts[:'source'] && !['realtime', 'cached'].include?(opts[:'source'])
fail ArgumentError, 'invalid value for "source", must be one of realtime, cached'
end
# resource path
local_var_path = '/global-infra/tier-1s/{tier-1-id}/segments/{segment-id}/gateway-interface-dad-state'.sub('{' + 'tier-1-id' + '}', tier_1_id.to_s).sub('{' + 'segment-id' + '}', segment_id.to_s)
# query parameters
query_params = {}
query_params[:'enforcement_point_path'] = opts[:'enforcement_point_path'] if !opts[:'enforcement_point_path'].nil?
query_params[:'source'] = opts[:'source'] if !opts[:'source'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['BasicAuth']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'InterfaceDADState')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PolicyNetworkingConnectivityTier1GatewaysInterfacesDADStateApi#get_downlink_port_dad_state_for_tier1_segment_0\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
|
nemOoO-wang/MMLive | MeMeDa/Entrance/Home/Square/___Root___/cells/SquareHeaderCell.h | <filename>MeMeDa/Entrance/Home/Square/___Root___/cells/SquareHeaderCell.h
//
// SquareHeaderCell.h
// MeMeDa
//
// Created by <NAME> on 5/8/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum : NSUInteger {
SquareHeaderTypeShuRen,
SquareHeaderTypeReMen,
SquareHeaderTypeHuoDong,
SquareHeaderTypeGuanZhu,
SquareHeaderTypeTuJian
} SquareHeaderType;
@interface SquareHeaderCell : UICollectionViewCell
@property (nonatomic,assign) SquareHeaderType type;
@end
|
tsegismont/rhq-metrics | job-scheduler/src/main/java/org/hawkular/metrics/scheduler/api/RepeatingTrigger.java | <reponame>tsegismont/rhq-metrics
/*
* Copyright 2014-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.metrics.scheduler.api;
import static org.hawkular.metrics.datetime.DateTimeService.currentMinute;
import static org.hawkular.metrics.datetime.DateTimeService.getTimeSlice;
import static org.hawkular.metrics.datetime.DateTimeService.now;
import static org.joda.time.Duration.standardMinutes;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.joda.time.Minutes;
/**
* @author jsanda
*/
public class RepeatingTrigger implements Trigger {
private Long triggerTime;
private Long interval;
private Long delay;
private Integer repeatCount;
private Integer executionCount;
public static class Builder {
private Long triggerTime;
private Long interval = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
private Long delay;
private Integer repeatCount;
public Builder withTriggerTime(long time) {
this.triggerTime = time;
return this;
}
public Builder withInterval(int interval, TimeUnit timeUnit) {
this.interval = TimeUnit.MILLISECONDS.convert(interval, timeUnit);
return this;
}
public Builder withDelay(int delay, TimeUnit timeUnit) {
this.delay = TimeUnit.MILLISECONDS.convert(delay, timeUnit);
return this;
}
public Builder withRepeatCount(int count) {
this.repeatCount = count;
return this;
}
public RepeatingTrigger build() {
return new RepeatingTrigger(triggerTime, interval, delay, repeatCount);
}
}
private RepeatingTrigger() {
}
private RepeatingTrigger(Long triggerTime, Long interval, Long delay, Integer repeatCount) {
if (triggerTime != null) {
this.triggerTime = getTimeSlice(triggerTime, standardMinutes(1));
}
else if (interval == null && delay == null) {
this.triggerTime = currentMinute().plusMinutes(1).getMillis();
}
this.interval = interval;
this.delay = delay == null ? Minutes.ONE.toStandardDuration().getMillis() : delay;
this.repeatCount = repeatCount;
this.executionCount = 1;
if (this.triggerTime == null) {
this.triggerTime = getTimeSlice(now.get().getMillis() + this.delay, standardMinutes(1));
}
}
// TODO reduce visibility?
// This is for internal use by TaskSchedulerImpl.
public RepeatingTrigger(long interval, long delay, long triggerTime, int repeatCount, int executionCount) {
this.interval = interval;
this.delay = delay;
this.triggerTime = triggerTime;
this.executionCount = executionCount;
this.repeatCount = repeatCount == 0 ? null : repeatCount;
this.executionCount = executionCount;
}
public long getInterval() {
return interval;
}
public long getDelay() {
return delay;
}
@Override
public long getTriggerTime() {
return triggerTime;
}
public Integer getRepeatCount() {
return repeatCount;
}
public int getExecutionCount() {
return executionCount;
}
@Override
public Trigger nextTrigger() {
// TODO what should we do if interval is null?
if (repeatCount != null && executionCount + 1 > repeatCount) {
return null;
}
RepeatingTrigger next = new RepeatingTrigger();
next.interval = interval;
next.delay = delay;
next.triggerTime = triggerTime + interval;
next.repeatCount = repeatCount;
next.executionCount = executionCount + 1;
return next;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RepeatingTrigger that = (RepeatingTrigger) o;
return Objects.equals(triggerTime, that.triggerTime) &&
Objects.equals(interval, that.interval) &&
Objects.equals(delay, that.delay);
}
@Override
public int hashCode() {
return Objects.hash(triggerTime, interval, delay);
}
@Override
public String toString() {
return "RepeatingTrigger{" +
"triggerTime=" + triggerTime +
", interval=" + interval +
", delay=" + delay +
'}';
}
}
|
zswhcb/portal | web/lib/macro.js | <filename>web/lib/macro.js
/*!
* hnzswh-dolalive
* Copyright(c) 2015 hnzswh-dolalive <<EMAIL>>
* MIT Licensed
*/
'use strict';
var fs = require('fs'),
velocity = require('velocityjs'),
util = require('speedt-utils'),
cwd = process.cwd();
var conf = require('../settings');
module.exports = {
parse: function(file){
var tpl = fs.readFileSync(require('path').join(cwd, 'views', file)).toString();
return this.eval(tpl);
}, include: function(file){
var tpl = fs.readFileSync(require('path').join(cwd, 'views', file)).toString();
return tpl;
}, toMon: function(t){
return util.padLeft(t.getMonth() + 1, '0', 2);
}, toDay: function(t){
return util.padLeft(t.getDate(), '0', 2);
}, formatDate: function(t, type){
switch(type){
case 1: return util.format(t, 'YY-MM-dd hh:mm:ss.S');
case 2: return util.format(t, 'YY-MM-dd hh:mm:ss');
case 3: return util.format(t, 'YY-MM');
case 4: return util.format(t, 'YY-MM-dd');
default: return util.format(t, 'YY-MM-dd hh:mm:ss');
}
}, num2Money: function(n){
return util.currencyformat(n);
}, toSDate: function(t){
var y = t.getFullYear();
var m = util.padLeft(t.getMonth() + 1, '0', 2);
var d = util.padLeft(t.getDate(), '0', 2);
return y +'-'+ m +'-'+ d;
}, toHtml: function(s){
return velocity.render(s);
}, toSex: function(n){
switch(n){
case 1: return '男';
case 2: return '女';
default: return '未知';
}
}, toStatus: function(n){
switch(n){
case 1: return '启用';
case 2: return '禁用';
default: return '未知';
}
}, userState: function(n){
switch(n){
case 0: return '未激活';
case 1: return '邮箱';
case 2: return '短信';
default: return '未知';
}
}, fileServUrlFill: function(href){
return conf.html.fileServ + href;
}, recommendType: function(type){
switch(type){
case 1: return '热门户型';
case 2: return '推荐户型';
}
}
}; |
unaussprechlich/prumpo | app/src/main/java/de/uni_stuttgart/informatik/sopra/sopraapp/app/MainActivityModule.java | <filename>app/src/main/java/de/uni_stuttgart/informatik/sopra/sopraapp/app/MainActivityModule.java<gh_stars>0
package de.uni_stuttgart.informatik.sopra.sopraapp.app;
import dagger.Module;
import dagger.Provides;
import dagger.android.ContributesAndroidInjector;
import de.uni_stuttgart.informatik.sopra.sopraapp.dependencyinjection.scopes.ActivityScope;
import de.uni_stuttgart.informatik.sopra.sopraapp.dependencyinjection.scopes.FragmentScope;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.listview.contract.ContractListFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.listview.contract.ContractListFragmentModule;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.listview.damagecase.DamageCaseListFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.listview.damagecase.DamageCaseListFragmentModule;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.listview.user.UserListFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.map.MapFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.map.MapFragmentModule;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.sidebar.about.AboutFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.sidebar.about.AboutModule;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.sidebar.settings.SettingsFragment;
import de.uni_stuttgart.informatik.sopra.sopraapp.feature.sidebar.settings.SettingsModule;
/**
* Here goes all the stuff provided for the MainActivity, to be injected.
*/
@Module
public abstract class MainActivityModule {
@FragmentScope
@ContributesAndroidInjector(modules = {DamageCaseListFragmentModule.class})
abstract DamageCaseListFragment contributeDamageCaseFragment();
@ActivityScope
@Provides
static DamageCaseListFragment providesDamageCaseListFragment() {
return new DamageCaseListFragment();
}
@FragmentScope
@ContributesAndroidInjector(modules = MapFragmentModule.class)
abstract MapFragment contributeMainFragment();
@ActivityScope
@Provides
static MapFragment providesMainFragment() {
return new MapFragment();
}
@FragmentScope
@ContributesAndroidInjector(modules = {ContractListFragmentModule.class})
abstract ContractListFragment contributeInsuranceListFragment();
@ActivityScope
@Provides
static ContractListFragment providesInsuranceListFragment() {
return new ContractListFragment();
}
@FragmentScope
@ContributesAndroidInjector(modules = {ContractListFragmentModule.class})
abstract UserListFragment contributeUserListFragment();
@ActivityScope
@Provides
static UserListFragment providesUserListFragment() {
return new UserListFragment();
}
@FragmentScope
@ContributesAndroidInjector(modules = {AboutModule.class})
abstract AboutFragment contributeAboutFragment();
@ActivityScope
@Provides
static AboutFragment providesAboutFragment() {
return new AboutFragment();
}
@FragmentScope
@ContributesAndroidInjector(modules = {SettingsModule.class})
abstract SettingsFragment contributeSettingsFragment();
@ActivityScope
@Provides
static SettingsFragment providesSettingsFragment() {
return new SettingsFragment();
}
}
|
jbrandwood/kickc | src/main/kc/include/c64-basic-floats.h | /// @file
/// Library wrapping the BASIC floating point functions
///
/// See https://www.c64-wiki.com/wiki/Floating_point_arithmetic
/// See http://www.pagetable.com/c64rom/c64rom_sc.html
/// Prepare MEM pointers for operations using MEM
inline void prepareMEM(unsigned int mem);
/// FAC = unsigned int
/// Set the FAC (floating point accumulator) to the integer value of a 16bit unsigned int
void setFAC(unsigned int w);
/// unsigned int = FAC
/// Get the value of the FAC (floating point accumulator) as an integer 16bit unsigned int
/// Destroys the value in the FAC in the process
unsigned int getFAC();
/// ARG = FAC
/// Set the ARG (floating point argument) to the value of the FAC (floating point accumulator)
void setARGtoFAC();
/// FAC = ARG
/// Set the FAC (floating point accumulator) to the value of the ARG (floating point argument)
void setFACtoARG();
/// MEM = FAC
/// Stores the value of the FAC to memory
/// Stores 5 chars (means it is necessary to allocate 5 chars to avoid clobbering other data using eg. char[] mem = {0, 0, 0, 0, 0};)
void setMEMtoFAC(char* mem);
/// FAC = MEM
/// Set the FAC to value from MEM (float saved in memory)
/// Reads 5 chars
void setFACtoMEM(char* mem);
/// FAC = PI/2
/// Set the FAC to PI/2
/// Reads 5 chars from the BASIC ROM
void setFACtoPIhalf();
/// FAC = 2*PI
/// Set the FAC to 2*PI
/// Reads 5 chars from the BASIC ROM
void setFACto2PI();
/// ARG = MEM
/// Load the ARG from memory
/// Reads 5 chars
void setARGtoMEM(char* mem);
/// FAC = MEM+FAC
/// Set FAC to MEM (float saved in memory) plus FAC (float accumulator)
/// Reads 5 chars from memory
void addMEMtoFAC(char* mem);
/// FAC = ARG+FAC
/// Add ARG (floating point argument) to FAC (floating point accumulator)
void addARGtoFAC();
/// FAC = MEM-FAC
/// Set FAC to MEM (float saved in memory) minus FAC (float accumulator)
/// Reads 5 chars from memory
void subFACfromMEM(char* mem);
/// FAC = ARG-FAC
/// Set FAC to ARG minus FAC
void subFACfromARG();
/// FAC = MEM/FAC
/// Set FAC to MEM (float saved in memory) divided by FAC (float accumulator)
/// Reads 5 chars from memory
void divMEMbyFAC(char* mem);
/// FAC = MEM*FAC
/// Set FAC to MEM (float saved in memory) multiplied by FAC (float accumulator)
/// Reads 5 chars from memory
void mulFACbyMEM(char* mem);
/// FAC = MEM^FAC
/// Set FAC to MEM (float saved in memory) raised to power of FAC (float accumulator)
/// Reads 5 chars from memory
void pwrMEMbyFAC(char* mem);
/// FAC = int(FAC)
/// Set FAC to integer part of the FAC - int(FAC)
/// The integer part is defined as the next lower integer - like java floor()
void intFAC();
/// FAC = sin(FAC)
/// Set FAC to sine of the FAC - sin(FAC)
/// Sine is calculated on radians (0-2*PI)
void sinFAC();
/// FAC = cos(FAC)
/// Set FAC to cosine of the FAC - cos(FAC)
/// Cosine is calculated on radians (0-2*PI)
void cosFAC();
/// FAC = tan(FAC)
/// Set FAC to the tangens of FAC - tan(FAC)
/// Tangens is calculated on radians (0-2*PI)
void tanFAC();
/// FAC = atn(FAC)
/// Set FAC to the arc tangens of FAC - atn(FAC)
/// Arc Tangens is calculated on radians (0-2*PI)
void atnFAC();
/// FAC = sqr(FAC)
/// Set FAC to the square root of FAC - sqr(FAC)
void sqrFAC();
/// FAC = exp(FAC)
/// Set FAC to the exponential function of FAC - exp(FAC)
/// Exp is based on the natural logarithm e=2.71828183
void expFAC();
/// FAC = log(FAC)
/// Set FAC to the logarithm of FAC - log(FAC)
/// Log is based on the natural logarithm e=2.71828183
void logFAC();
/// FAC = FAC/10
/// Set FAC to FAC divided by 10
void divFACby10();
/// FAC = FAC*10
/// Set FAC to FAC multiplied by 10
void mulFACby10(); |
biker2000on/vue-test | src/plugins/apollo.js | import Vue from 'vue'
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync'
import VueApollo from 'vue-apollo'
import AppSyncConfig from '../aws-exports'
import Amplify from 'aws-amplify'
const configApollo = {
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: {
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
jwtToken: async () => (await Amplify.Auth.currentSession()).getAccessToken().getJwtToken(),
},
complexObjectsCredentials: () => Amplify.Auth.currentCredentials()
}
const configApolloApiKey = {
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: { type: AUTH_TYPE.API_KEY, apiKey: AppSyncConfig.aws_appsync_apiKey},
disableOffline: true,
};
const configApolloIAM = {
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: { type: AUTH_TYPE.AWS_IAM},
disableOffline: true,
};
const options = {
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
}
}
}
const cognito = new AWSAppSyncClient(configApollo, options)
const apikey = new AWSAppSyncClient(configApolloApiKey, options)
const iam = new AWSAppSyncClient(configApolloIAM, options)
export const appsyncProvider = new VueApollo({
clients: {
cognito,
apikey,
iam,
},
defaultClient: cognito
})
Vue.use(VueApollo) |
portocodes/rubygems.org | app/models/ownership.rb | class Ownership < ApplicationRecord
belongs_to :rubygem
belongs_to :user
validates :user_id, uniqueness: { scope: :rubygem_id }
def safe_destroy
rubygem.owners.many? && destroy
end
end
|
FredEscobar/hbfl | scripts/09/helpers.js | <filename>scripts/09/helpers.js
const {
IAMClient,
AttachRolePolicyCommand,
CreateRoleCommand
} = require('@aws-sdk/client-iam')
const { SQSClient } = require('@aws-sdk/client-sqs')
const { KinesisClient } = require('@aws-sdk/client-kinesis')
const { LambdaClient } = require('@aws-sdk/client-lambda')
const archiver = require('archiver')
const path = require('path')
const streamBuffers = require('stream-buffers')
const fs = require('fs')
async function sendSQSCommand (command) {
const client = new SQSClient({ region: process.env.AWS_REGION })
return client.send(command)
}
async function sendKinesisCommand (command) {
const client = new KinesisClient({ region: process.env.AWS_REGION })
return client.send(command)
}
async function sendLambdaCommand (command) {
const client = new LambdaClient({ region: process.env.AWS_REGION })
return client.send(command)
}
async function createLambdaKinesisRole () {
const roleName = 'lambda-kinesis-consumer-role'
const params = {
RoleName: roleName,
Path: '/service-role/',
AssumeRolePolicyDocument: '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }'
}
const client = new IAMClient({ region: process.env.AWS_REGION })
const roleCommand = new CreateRoleCommand(params)
const roleResponse = await client.send(roleCommand)
const kinesisParams = {
PolicyArn: 'arn:aws:iam::aws:policy/AmazonKinesisReadOnlyAccess',
RoleName: roleName
}
const lambdaParams = {
PolicyArn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
RoleName: roleName
}
const dynamoParams = {
PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess',
RoleName: roleName
}
const kinesisPolicyCommand = new AttachRolePolicyCommand(kinesisParams)
await client.send(kinesisPolicyCommand)
const lambdaPolicyCommand = new AttachRolePolicyCommand(lambdaParams)
await client.send(lambdaPolicyCommand)
const dynamoPolicyCommand = new AttachRolePolicyCommand(dynamoParams)
await client.send(dynamoPolicyCommand)
await sleep(10)
return roleResponse.Role.Arn
}
function zipLambdaFile () {
const archive = archiver('zip', {
zlib: { level: 9 }
})
const writableStreamBuffer = new streamBuffers.WritableStreamBuffer({
initialSize: (100 * 1024),
incrementAmount: (10 * 1024)
})
return new Promise((resolve, reject) => {
writableStreamBuffer.on('finish', () => {
resolve(writableStreamBuffer.getContents())
})
archive.on('warning', err => reject(err))
archive.on('error', err => reject(err))
archive.pipe(writableStreamBuffer)
archive.append(fs.createReadStream(path.join(__dirname, 'lambda-kinesis-consumer', 'index.js')), { name: 'index.js' })
archive.finalize()
})
}
// Borrowed from https://www.sitepoint.com/delay-sleep-pause-wait/
function sleep (s) {
return new Promise(resolve => setTimeout(resolve, s * 1000))
}
module.exports = {
createLambdaKinesisRole,
sendKinesisCommand,
sendLambdaCommand,
sendSQSCommand,
zipLambdaFile
}
|
transitanalystisarel/TransitAnalystIsrael | root/transitscore_txt2jsobject_v1.py | <reponame>transitanalystisarel/TransitAnalystIsrael
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# convert transitscore txt grid file - transit_score_yyyymmdd.txt - to js object with gridlatlon as key to look up transitscore property from 1-100
# output ts_lookup.js
#
print('----------------- convert grid file to object with key gridlatlon to look up transitscore --------------------------')
print('convert transitscore txt grid file - transit_score_all_israel.txt - to js object with gridlatlon as key to look up transitscore property from 1-100 ')
print('output ts_lookup.js')
import time
import csv
from pathlib import Path
cwd = Path.cwd()
#
print("Local current time :", time.asctime( time.localtime(time.time()) ))
#
def main(gtfsdate, gtfsdirbase, processedpath):
parent_path = cwd.parent / processedpath
tsfilein = 'transit_score_'+gtfsdirbase+gtfsdate+'.txt'
tsfileout = 'ts_lookup_'+gtfsdirbase+gtfsdate+'.js'
ilminlat = 29.490000 # Israel min lat
ilminlon = 34.280000 # Israel min lon
#
# load file
#
# >>> load transitscore file
transitscore_list = []
max_grid_lat = 0
max_grid_lon = 0
with open(parent_path / tsfilein, newline='', encoding="utf8") as ts_f:
readerts = csv.reader(ts_f)
headerts = next(readerts)
print(headerts)
for row in readerts:
#print row
grid_lat = int(row[0])
grid_lon = int(row[1])
ts = int(float(row[2]))
max_grid_lat = max(max_grid_lat, grid_lat)
max_grid_lon = max(max_grid_lon, grid_lon)
transitscore_list.append([grid_lat, grid_lon, ts])
#print transitscore_list
print('transitscore_list loaded. ts count ', len(transitscore_list))
print('max_grid_lat, max_grid_lon : ', max_grid_lat, max_grid_lon)
#
# output file of ts_lookup as object with gridlatlon as key to look up transitscore from 1-100
#
print(("Saving file: ", parent_path / tsfileout, " ..."))
nf = open(parent_path / tsfileout, "w", encoding="utf8")
postsline = 'var transitScore = {\n' # format as js for load to leaflet
print(postsline)
nf.write(postsline)
i=0
grid_lat = 0
grid_lon = 0
ts = 0
gridlatlon = 10000*grid_lat+grid_lon
postsline = str(gridlatlon)+':'+str(ts)
print(postsline)
nf.write(postsline)
for [grid_lat, grid_lon, ts] in transitscore_list :
gridlatlon = 10000*grid_lat+grid_lon
i += 1
if i%100 == 0 :
postsline = ','+str(gridlatlon)+':'+str(ts)+'\n'
#print postsline
else :
postsline = ','+str(gridlatlon)+':'+str(ts)
nf.write(postsline)
postsline = '\n};'
nf.write(postsline)
nf.close()
print(("Saved file: " + tsfileout))
|
OttoWinter/esphomeyaml | esphome/components/midea_ac/climate.py | import esphome.config_validation as cv
CONFIG_SCHEMA = cv.invalid("This platform has been renamed to midea in 2021.9")
|
soyastudio/kurl | curl-application/src/main/java/soya/framework/curl/application/CurlApplication.java | package soya.framework.curl.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"soya.framework.curl.application"})
public class CurlApplication {
public static void main(String[] args) {
SpringApplication.run(CurlApplication.class, args);
}
}
|
konradkalemba/tabler-icons-react | src/icons/paint.js | <reponame>konradkalemba/tabler-icons-react
import React from 'react';
export default function Paint({
size = 24,
color = 'currentColor',
...restProps
}) {
return (
<svg
xmlns='http://www.w3.org/2000/svg'
className='icon icon-tabler icon-tabler-paint'
width={size}
height={size}
viewBox='0 0 24 24'
stroke={color}
strokeWidth='2'
fill='none'
strokeLinecap='round'
strokeLinejoin='round'
{...restProps}
>
<path stroke='none' d='M0 0h24v24H0z' fill='none' />
<rect x='5' y='3' width='14' height='6' rx='2' />
<path d='M19 6h1a2 2 0 0 1 2 2a5 5 0 0 1 -5 5l-5 0v2' />
<rect x='10' y='15' width='4' height='6' rx='1' />
</svg>
);
}
|
saqsun/overlap2d | src/com/uwsoft/editor/gdx/ui/thumbnailbox/ImageThumbnailBox.java | <gh_stars>1-10
/*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * 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 com.uwsoft.editor.gdx.ui.thumbnailbox;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.uwsoft.editor.gdx.stage.UIStage;
import com.uwsoft.editor.gdx.ui.DropDown;
import com.uwsoft.editor.gdx.ui.SelectionActions;
import com.uwsoft.editor.gdx.ui.payloads.AssetPayloadObject;
import com.uwsoft.editor.renderer.data.SimpleImageVO;
public class ImageThumbnailBox extends DraggableThumbnailBox {
private float scaleSize = 1;
private AtlasRegion region;
public ImageThumbnailBox(UIStage s, AtlasRegion region) {
super(s);
Image img = new Image(region);
this.region = region;
if (img.getWidth() > thumbnailSize || img.getHeight() > thumbnailSize) {
// resizing is needed
float scaleFactor = 1.0f;
if (img.getWidth() > img.getHeight()) {
//scale by width
scaleFactor = 1.0f / (img.getWidth() / thumbnailSize);
} else {
scaleFactor = 1.0f / (img.getHeight() / thumbnailSize);
}
scaleSize = scaleFactor;
img.setScale(scaleFactor);
img.setX((getWidth() - img.getWidth() * img.getScaleX()) / 2);
img.setY((getHeight() - img.getHeight() * img.getScaleY()) / 2);
} else {
// put it in middle
img.setX((getWidth() - img.getWidth()) / 2);
img.setY((getHeight() - img.getHeight()) / 2);
}
addActor(img);
Image payloadImg = new Image(region);
AssetPayloadObject payload = new AssetPayloadObject();
payload.assetName = region.name;
payload.type = AssetPayloadObject.AssetType.Sprite;
DraggableThumbnailEvent event = new DraggableThumbnailEvent() {
@Override
public void drop(AssetPayloadObject pld, float x, float y) {
itemDropped(pld.assetName, x, y);
}
};
initDragDrop(stage, payloadImg, scaleSize, scaleSize, payload, event);
initAdditionalListeners();
}
public void initAdditionalListeners() {
addListener(new InputListener(){
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
if(button == Buttons.RIGHT){
showRightClickDropDown(region.name);
}
super.touchUp(event, x, y, pointer, button);
}
});
}
public float getScaleSize() {
return scaleSize;
}
protected void itemDropped(String assetName, float x, float y) {
stage.getSandbox().getUac().createImage(assetName, x, y);
}
private void showRightClickDropDown(final String regionName) {
DropDown dropDown = stage.mainDropDown;
dropDown.clearItems();
dropDown.addItem(SelectionActions.EDIT_ASSET_PHYSICS, "Edit Physics");
dropDown.initView(Gdx.input.getX(), Gdx.input.getY());
dropDown.setEventListener(new DropDown.SelectionEvent() {
@Override public void doAction (int action) {
switch (action) {
case SelectionActions.EDIT_ASSET_PHYSICS:
stage.editPhysics(regionName);
break;
default:
break;
}
}
});
}
}
|
aburbanol/staart | packages/staart/src/components/forgot-password.js | <reponame>aburbanol/staart
import React, {Component} from 'react'
import {withOoth} from 'ooth-client-react'
import {compose} from 'recompose'
import withI18n from '../hocs/i18n'
const ForgotPasswordComponent = ({__}) => (
<div style={{
maxWidth: '300px',
margin: 'auto'
}}>
<h1>{__('forgot-password.forgot-password')}</h1>
<ForgotPasswordForm/>
<p>{__('forgot-password.back-to')} <a href="/login">{__('forgot-password.login-page')}</a>.</p>
</div>
)
const ForgotPassword = compose(
withI18n,
)(ForgotPasswordComponent)
export default ForgotPassword
class ForgotPasswordFormComponent extends Component {
constructor() {
super()
this.state = {
sent: false,
error: null,
}
}
render() {
const {__} = this.props
if (this.state.sent) {
return <p>{__('forgot-password.password-reset-email-sent')}</p>
} else {
return <form onSubmit={e => {
e.preventDefault()
const username = this.username.value;
this.props.oothClient.method('local', 'forgot-password', {
username
}).then(() => {
this.setState({
sent: true
})
}).catch(e => {
this.setState({
error: e.message
})
})
}}>
{this.state.error &&
<div className="alert alert-danger" role="alert">
{this.state.error}
</div>
}
<div className="form-group">
<label htmlFor="username">{__('forgot-password.username-or-email')}</label>
<input
type="username"
className="form-control"
id="username"
placeholder={__('forgot-password.username-or-email')}
ref={username => {
this.username = username
}}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary btn-block">{__('forgot-password.send-reset-password-email')}</button>
</div>
</form>
}
}
}
const ForgotPasswordForm = compose(
withOoth,
withI18n
)(ForgotPasswordFormComponent)
|
a982338665/multithreading | src/main/java/pers/li/thread/timetask/callablefuture/testCallable.java | package pers.li.thread.timetask.callablefuture;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 异步收集线程执行结果:
* 使用completionService收集callable结果
* @author lishengbo
* @Time 2017年12月2日下午2:34:54
*/
public class testCallable {
public static void main(String[] args) {
try {
completionServiceCount();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
/**
* 使用completionService收集callable结果
* @throws ExecutionException
* @throws InterruptedException
*/
public static void completionServiceCount() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);
int threadNum = 20;
/***开始20次任务提交******************/
for (int i = 0; i < threadNum; i++) {
completionService.submit(getTask(i));
}
int sum = 0;
int temp = 0;
/***进行20次任务提交后的结果收集********/
for(int i=0;i<threadNum;i++){
temp = completionService.take().get();
sum += temp;
System.err.print(temp + "\t");
}
System.out.println("CompletionService all is : " + sum);
executorService.shutdown();
}
public static Callable<Integer> getTask(final int no) {
final Random rand = new Random();
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int time = rand.nextInt(100)*100;
System.out.println(Thread.currentThread().getName()+"||第-"+no+"-次任务 生成的随机数为:"+time);
Thread.sleep(time);
return no;
}
};
return task;
}
}
|
shang1219178163/MapTemplet | MapModule/MapView/NNPOIAnnotation.h | <gh_stars>1-10
//
// NNPOIAnnotation.h
// VehicleBonus
//
// Created by <NAME> on 2019/3/19.
// Copyright © 2019 Xi'an iRain IOT Technology Service CO., Ltd. . All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapCommonObj.h>
typedef NS_ENUM(NSInteger, BNParkAnnotationType){
PAWParkAnnotationTypePark,
PAWParkAnnotationTypeBill
};
/**
商户POI对象
*/
@interface NNPOIAnnotation : NSObject <MAAnnotation>
- (id)initWithPOI:(AMapPOI *)poi;
@property (nonatomic, strong) AMapPOI *poi;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end
|
reels-research/iOS-Private-Frameworks | HealthUI.framework/HKElectrocardiogramTableViewCell.h | <reponame>reels-research/iOS-Private-Frameworks
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI
*/
@interface HKElectrocardiogramTableViewCell : UITableViewCell {
NSLayoutConstraint * _bottomPaddingConstraint;
bool _bottomPaddingDisabled;
HKElectrocardiogramCardView * _cardView;
}
@property (nonatomic, retain) NSLayoutConstraint *bottomPaddingConstraint;
@property (nonatomic) bool bottomPaddingDisabled;
@property (nonatomic, retain) HKElectrocardiogramCardView *cardView;
@property (nonatomic, retain) HKElectrocardiogram *sample;
+ (id)defaultReuseIdentifier;
+ (double)estimatedHeight;
- (void).cxx_destruct;
- (void)_setupConstraints;
- (void)_setupUIWithSample:(id)arg1 dateCache:(id)arg2 onboarding:(bool)arg3;
- (id)bottomPaddingConstraint;
- (bool)bottomPaddingDisabled;
- (id)cardView;
- (id)initWithSample:(id)arg1 dateCache:(id)arg2 onboarding:(bool)arg3;
- (id)sample;
- (void)setBottomPaddingConstraint:(id)arg1;
- (void)setBottomPaddingDisabled:(bool)arg1;
- (void)setCardView:(id)arg1;
- (void)setSample:(id)arg1;
@end
|
KAtana-Karlsruhe/AADC_2015_KAtana | src/adtfBase/AADC_ADTF_BaseFilters/src/helper/AADC_CarVisualization/displaywidget.cpp | <reponame>KAtana-Karlsruhe/AADC_2015_KAtana<gh_stars>1-10
/**
Copyright (c)
Audi Autonomous Driving Cup. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: “This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.”
4. Neither the name of Audi nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AUDI AG AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUDI AG OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************
* $Author:: forchhe#$ $Date:: 2014-09-11 10:10:54#$ $Rev:: 25921 $
**********************************************************************/
#include "stdafx.h"
#include "displaywidget.h"
#include "CarVisualizationFilter.h"
using namespace SensorDefinition;
DisplayWidget::DisplayWidget(QWidget* parent, CarControlFilter* filter_orig) :
QWidget(),
ui(new Ui::DisplayGUI),
filter(filter_orig)
{
m_pWidget = parent;
ui->setupUi(this);
connect(ui->SteeringSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSteering(int)));
//Gearbox
connect(ui->SpeedSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSpeed(int)));
connect(ui->pb_brake, SIGNAL(clicked(bool)), this, SLOT(slotBrake()));
// Headlight signal
connect(ui->HeadLightSwitch, SIGNAL(clicked()), this, SLOT(slotHeadlight()));
// Brakelight signal
connect(ui->rb_bl_on, SIGNAL(clicked(bool)), this, SLOT(slotBrakelight()));
connect(ui->rb_bl_off, SIGNAL(clicked(bool)), this, SLOT(slotBrakelight()));
// connect(ui->rb_bl_emergency, SIGNAL(clicked(bool)), this, SLOT(slotBrakelight()));
// Reverselight signal
connect(ui->RevLightSwitch, SIGNAL(clicked()), this, SLOT(slotReverselight()));
// Turn signal
connect(ui->rb_ts_l_on, SIGNAL(clicked(bool)), this, SLOT(slotTurnSignal()));
// connect(ui->rb_ts_l_3, SIGNAL(clicked(bool)), this, SLOT(slotTurnSignal()));
connect(ui->rb_ts_off, SIGNAL(clicked(bool)), this, SLOT(slotTurnSignal()));
// connect(ui->rb_ts_r_3, SIGNAL(clicked(bool)), this, SLOT(slotTurnSignal()));
connect(ui->rb_ts_r_on, SIGNAL(clicked(bool)), this, SLOT(slotTurnSignal()));
}
void DisplayWidget::slotSteering(int val)
{
filter->slotSteering(val);
}
void DisplayWidget::slotSpeed(int val)
{
ui->rb_backward->setEnabled(val == 0);
ui->rb_forward->setEnabled(val == 0);
if (ui->rb_forward->isChecked())
filter->slotSpeed(val);
else if (ui->rb_backward->isChecked())
filter->slotSpeed(val*(-1)); //multiply with -1 if backward is enabled
}
void DisplayWidget::slotBrake()
{
ui->rb_backward->setEnabled(true);
ui->rb_forward->setEnabled(true);
ui->SpeedSlider->setValue(0);
}
void DisplayWidget::slotHeadlight()
{
QPalette pal;
tHeadLight sHeadLight;
if (ui->HeadLightSwitch->isChecked())
{
pal.setColor(QPalette::Button, QColor(0, 255, 0));
sHeadLight.nState = 2;
}
else
{
pal.setColor(QPalette::Button, QColor(255, 0, 0));
sHeadLight.nState = 0;
}
filter->slotHeadlight(sHeadLight);
}
void DisplayWidget::slotBrakelight()
{
tBrakeLight sBrakeLight;
if (this->sender() == ui->rb_bl_off)
{
sBrakeLight.nState = 0;
}
else if (this->sender() == ui->rb_bl_on)
{
sBrakeLight.nState = 1;
}
//else if (this->sender() == ui->rb_bl_emergency)
//{
// sBrakeLight.nState = 2;
//}
filter->slotBrakelight(sBrakeLight);
}
void DisplayWidget::slotReverselight()
{
tReverseLight sReverseLight;
if (ui->RevLightSwitch->isChecked())
sReverseLight.nState = 1;
else
sReverseLight.nState = 0;
filter->slotReverselight(sReverseLight);
}
void DisplayWidget::slotTurnSignal()
{
tTurnSignal sTurnSignal;
if (this->sender() == ui->rb_ts_l_on)
{
sTurnSignal.nState = 1;
}
/*else if (this->sender() == ui->rb_ts_l_3)
{
sTurnSignal.nState = 2;
}*/
else if (this->sender() == ui->rb_ts_off)
{
sTurnSignal.nState = 0;
}
/*else if (this->sender() == ui->rb_ts_r_3)
{
sTurnSignal.nState = 4;
}*/
else if (this->sender() == ui->rb_ts_r_on)
{
sTurnSignal.nState = 3;
}
/*else if (this->sender() == ui->rb_ts_hazard)
{
sTurnSignal.nState = 5;
}*/
filter->slotTurnSignal(sTurnSignal);
}
void DisplayWidget::slotUpdateUS(const int& nPosition, const float& nDistance, const bool& bObjectDetected)
{
QString dist = QString("%1 cm").arg(nDistance);
if (bObjectDetected)
{
switch(nPosition)
{
case 1:
ui->US_front_left->setText(dist);
break;
case 2:
ui->US_front_right->setText(dist);
break;
case 3:
ui->US_back_right->setText(dist);
break;
case 4:
ui->US_back_left->setText(dist);
break;
}
}
else
{
switch(nPosition)
{
case 1:
ui->US_front_left->setText("---");
break;
case 2:
ui->US_front_right->setText("---");
break;
case 3:
ui->US_back_right->setText("---");
break;
case 4:
ui->US_back_left->setText("---");
break;
}
}
// update();
}
void DisplayWidget::slotUpdateSteeringAngle(const float& steer_angle)
{
ui->lbl_servo_pos->setText(QString::number(steer_angle,'f',2));;
}
void DisplayWidget::slotUpdateLuminosityValue(const float& luminosity_value)
{
//ui->lumi_value->setNum(luminosity_value);
//ui->lumi_value->setText(QString("%1 lux").arg(luminosity_value));
}
void DisplayWidget::slotUpdateACCIndividual(const int& sensor_def, const float& value)
{
switch((ACCSensorDefinition)sensor_def)
{
case ACC_X:
{
float fAcc = floorf(value*1000 + .5)/1000;
ui->lbl_acc_x->setText(QString::number(fAcc,'f',2));
break;
}
case ACC_Y:
{
float fAcc = floorf(value*1000 + .5)/1000;
ui->lbl_acc_y->setText(QString::number(fAcc,'f',2));
break;
}
case ACC_Z:
{
float fAcc = floorf(value*1000 + .5)/1000;
ui->lbl_acc_z->setText(QString::number(fAcc,'f',2));
break;
}
default:
{
break;
}
};
// update();
}
void DisplayWidget::slotUpdateGYROIndividual(const int& sensor_def, const float& value)
{
switch((GYROSensorDefinition)sensor_def)
{
case GYRO_YAW:
{
ui->lbl_gyro_x->setText(QString::number(value,'f',2));
break;
}
case GYRO_PITCH:
{
ui->lbl_gyro_y->setText(QString::number(value,'f',2));
break;
}
case GYRO_ROLL:
{
ui->lbl_gyro_z->setText(QString::number(value,'f',2));
break;
}
case GYRO_TEMP:
{
//ui->lbl_gyro_temp->setText(QString::number(value,'f',2));
break;
}
default:
{
break;
}
};
}
void DisplayWidget::slotUpdateRPMIndividual(const int& sensor_def, const float& value)
{
switch((WheelSensorDefinition)sensor_def)
{
case WHEEL_LEFT:
{
ui->RadEncRPM_links->setText(QString("%1 rpm").arg(int(value)));
break;
}
case WHEEL_RIGHT:
{
ui->RadEncRPM_rechts->setText(QString("%1 rpm").arg(int(value)));
break;
}
default:
{
break;
}
};
}
void DisplayWidget::slotUpdateDistanceIndividual(const int& sensor_def, const float& value)
{
switch((WheelSensorDefinition)sensor_def)
{
case DISTANCE_LEFT:
{
ui->RadEnc_Dist_links->setText(QString("%1 cm").arg(int(value)));
break;
}
case DISTANCE_RIGHT:
{
ui->RadEnc_Dist_rechts->setText(QString("%1 cm").arg(int(value)));
break;
}
default:
{
break;
}
};
}
void DisplayWidget::slotUpdateVoltageIndividual(const int& sensor_def, const float& value)
{
switch((VoltageSensorDefinition)sensor_def)
{
case VOLTAGE_MEASUREMENT:
{
ui->lblVolt1->setNum(floorf(value*100.f + .5f)/100.f);
break;
}
case VOLTAGE_ENGINE:
{
ui->lblVolt2->setNum(floorf(value*100.f + .5f)/100.f);
break;
}
default:
{
break;
}
};
}
void DisplayWidget::slotUpdateStatus(int stat)
{
if (stat == 0)
ui->label_AnfahrW->setPixmap(QPixmap(":/images/AnfahrNoWarn.png"));
else if (stat == 1)
ui->label_AnfahrW->setPixmap(QPixmap(":/images/AnfahrWarn.png"));
else if (stat == 2)
ui->label_Notbremse->setPixmap(QPixmap(":/images/NotbrAn.png"));
else if (stat == 3)
ui->label_Notbremse->setPixmap(QPixmap(":/images/NotbrAus.png"));
}
void DisplayWidget::slotUpdateIRIndividual(const int& sensor_def, const double& value)
{
switch ((IrSensorDefinition)sensor_def)
{
case IR_FRONT_CENTER_LONG:
{
ui->IRvL->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_FRONT_CENTER_SHORT:
{
ui->IRvS->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_FRONT_LEFT_LONG:
{
ui->IRfrontleftL->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_FRONT_LEFT_SHORT:
{
ui->IRfrontleftS->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_FRONT_RIGHT_LONG:
{
ui->IRfrontrightL->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_FRONT_RIGHT_SHORT:
{
ui->IRfrontrightS->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_REAR_CENTER_SHORT:
{
ui->IRbL->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_REAR_LEFT_SHORT:
{
ui->IRbackleft->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
case IR_REAR_RIGHT_SHORT:
{
ui->IRbackright->setText(QString("%1 cm").arg(QString::number(value,'f',2)));
break;
}
};
}
|
vikusss/sub4.3 | node_modules/@subql/common/dist/project/load.js | <reponame>vikusss/sub4.3<filename>node_modules/@subql/common/dist/project/load.js
"use strict";
// Copyright 2020-2021 OnFinality Limited authors & contributors
// SPDX-License-Identifier: Apache-2.0
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseChainTypes = exports.loadProjectManifest = exports.loadChainTypes = exports.loadFromJsonOrYaml = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const x_vm2_1 = require("@subql/x-vm2");
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
const js_yaml_1 = __importDefault(require("js-yaml"));
const models_1 = require("./models");
const versioned_1 = require("./versioned");
function loadFromJsonOrYaml(file) {
const { ext } = path_1.default.parse(file);
if (ext !== '.yaml' && ext !== '.yml' && ext !== '.json') {
throw new Error(`Extension ${ext} not supported`);
}
const rawContent = fs_1.default.readFileSync(file, 'utf-8');
return js_yaml_1.default.load(rawContent);
}
exports.loadFromJsonOrYaml = loadFromJsonOrYaml;
function loadChainTypes(file, projectRoot) {
const { ext } = path_1.default.parse(file);
if (ext === '.js' || ext === '.cjs') {
return loadChainTypesFromJs(file, projectRoot);
}
else {
return loadFromJsonOrYaml(file);
}
}
exports.loadChainTypes = loadChainTypes;
function loadProjectManifest(file) {
let manifestPath = file;
if (fs_1.default.existsSync(file) && fs_1.default.lstatSync(file).isDirectory()) {
const yamlFilePath = path_1.default.join(file, 'project.yaml');
const jsonFilePath = path_1.default.join(file, 'project.json');
if (fs_1.default.existsSync(yamlFilePath)) {
manifestPath = yamlFilePath;
}
else if (fs_1.default.existsSync(jsonFilePath)) {
manifestPath = jsonFilePath;
}
else {
throw new Error(`Could not find project manifest under dir ${file}`);
}
}
const doc = loadFromJsonOrYaml(manifestPath);
const projectManifest = new versioned_1.ProjectManifestVersioned(doc);
projectManifest.validate();
return projectManifest;
}
exports.loadProjectManifest = loadProjectManifest;
function parseChainTypes(raw) {
const chainTypes = (0, class_transformer_1.plainToClass)(models_1.ChainTypes, raw);
const errors = (0, class_validator_1.validateSync)(chainTypes, { whitelist: true, forbidNonWhitelisted: true });
if (errors === null || errors === void 0 ? void 0 : errors.length) {
// TODO: print error details
const errorMsgs = errors.map((e) => e.toString()).join('\n');
throw new Error(`failed to parse chain types.\n${errorMsgs}`);
}
return chainTypes;
}
exports.parseChainTypes = parseChainTypes;
function loadChainTypesFromJs(filePath, requireRoot) {
const { base, ext } = path_1.default.parse(filePath);
const root = requireRoot !== null && requireRoot !== void 0 ? requireRoot : path_1.default.dirname(filePath);
if (ext === '.js' || ext === '.cjs') {
const vm = new x_vm2_1.NodeVM({
console: 'redirect',
wasm: false,
sandbox: {},
require: {
context: 'sandbox',
external: true,
builtin: ['path'],
root: root,
resolve: (moduleName) => {
return require.resolve(moduleName, { paths: [root] });
},
},
wrapper: 'commonjs',
sourceExtensions: ['js', 'cjs'],
});
let rawContent;
try {
const script = new x_vm2_1.VMScript(`module.exports = require('${filePath}').default;`, path_1.default.join(root, 'sandbox')).compile();
rawContent = vm.run(script);
}
catch (err) {
throw new Error(`\n NodeVM error: ${err}`);
}
if (rawContent === undefined) {
throw new Error(`There was no default export found from required ${base} file`);
}
return rawContent;
}
else {
throw new Error(`Extension ${ext} not supported`);
}
}
//# sourceMappingURL=load.js.map |
SXiaoXu/java-unified-sdk | core/src/main/java/cn/leancloud/types/AVNull.java | <filename>core/src/main/java/cn/leancloud/types/AVNull.java<gh_stars>0
package cn.leancloud.types;
public final class AVNull {
private static final AVNull INSTANCE = new AVNull();
public static AVNull getINSTANCE() {
return INSTANCE;
}
}
|
CBIIT/cadsr-cdecurate | src/gov/nih/nci/cadsr/persist/vm/VmVO.java | /*L
* Copyright ScenPro Inc, SAIC-F
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cdecurate/LICENSE.txt for details.
*/
package gov.nih.nci.cadsr.persist.vm;
import java.sql.Timestamp;
import gov.nih.nci.cadsr.persist.common.BaseVO;
@SuppressWarnings("serial")
public class VmVO extends BaseVO {
private String short_meaning;
private String description;
private String comments;
private Timestamp begin_date;
private Timestamp end_date;
private String condr_IDSEQ;
private String vm_IDSEQ;
private String prefferred_name;
private String prefferred_def;
private String long_name;
private String conte_IDSEQ;
private String asl_name;
private double version;
private long vm_ID;
private String latest_version_ind;
private String deleted_ind;
private String origin;
private String change_note;
private String definition_source;
public VmVO(){
super();
}
/**
* @return the short_meaning
*/
public String getShort_meaning() {
return short_meaning;
}
/**
* @param short_meaning the short_meaning to set
*/
public void setShort_meaning(String short_meaning) {
this.short_meaning = short_meaning;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the comments
*/
public String getComments() {
return comments;
}
/**
* @param comments the comments to set
*/
public void setComments(String comments) {
this.comments = comments;
}
/**
* @return the condr_IDSEQ
*/
public String getCondr_IDSEQ() {
return condr_IDSEQ;
}
/**
* @param condr_IDSEQ the condr_IDSEQ to set
*/
public void setCondr_IDSEQ(String condr_IDSEQ) {
this.condr_IDSEQ = condr_IDSEQ;
}
/**
* @return the vm_IDSEQ
*/
public String getVm_IDSEQ() {
return vm_IDSEQ;
}
/**
* @param vm_IDSEQ the vm_IDSEQ to set
*/
public void setVm_IDSEQ(String vm_IDSEQ) {
this.vm_IDSEQ = vm_IDSEQ;
}
/**
* @return the prefferred_name
*/
public String getPrefferred_name() {
return prefferred_name;
}
/**
* @param prefferred_name the prefferred_name to set
*/
public void setPrefferred_name(String prefferred_name) {
this.prefferred_name = prefferred_name;
}
/**
* @return the prefferred_def
*/
public String getPrefferred_def() {
return prefferred_def;
}
/**
* @param prefferred_def the prefferred_def to set
*/
public void setPrefferred_def(String prefferred_def) {
this.prefferred_def = prefferred_def;
}
/**
* @return the long_name
*/
public String getLong_name() {
return long_name;
}
/**
* @param long_name the long_name to set
*/
public void setLong_name(String long_name) {
this.long_name = long_name;
}
/**
* @return the conte_IDSEQ
*/
public String getConte_IDSEQ() {
return conte_IDSEQ;
}
/**
* @param conte_IDSEQ the conte_IDSEQ to set
*/
public void setConte_IDSEQ(String conte_IDSEQ) {
this.conte_IDSEQ = conte_IDSEQ;
}
/**
* @return the asl_name
*/
public String getAsl_name() {
return asl_name;
}
/**
* @param asl_name the asl_name to set
*/
public void setAsl_name(String asl_name) {
this.asl_name = asl_name;
}
/**
* @return the version
*/
public double getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(double version) {
this.version = version;
}
/**
* @return the vm_ID
*/
public long getVm_ID() {
return vm_ID;
}
/**
* @param vm_ID the vm_ID to set
*/
public void setVm_ID(long vm_ID) {
this.vm_ID = vm_ID;
}
/**
* @return the latest_version_ind
*/
public String getLatest_version_ind() {
return latest_version_ind;
}
/**
* @param latest_version_ind the latest_version_ind to set
*/
public void setLatest_version_ind(String latest_version_ind) {
this.latest_version_ind = latest_version_ind;
}
/**
* @return the deleted_ind
*/
public String getDeleted_ind() {
return deleted_ind;
}
/**
* @param deleted_ind the deleted_ind to set
*/
public void setDeleted_ind(String deleted_ind) {
this.deleted_ind = deleted_ind;
}
/**
* @return the origin
*/
public String getOrigin() {
return origin;
}
/**
* @param origin the origin to set
*/
public void setOrigin(String origin) {
this.origin = origin;
}
/**
* @return the change_note
*/
public String getChange_note() {
return change_note;
}
/**
* @param change_note the change_note to set
*/
public void setChange_note(String change_note) {
this.change_note = change_note;
}
/**
* @return the definition_source
*/
public String getDefinition_source() {
return definition_source;
}
/**
* @param definition_source the definition_source to set
*/
public void setDefinition_source(String definition_source) {
this.definition_source = definition_source;
}
/**
* @return the begin_date
*/
public Timestamp getBegin_date() {
return begin_date;
}
/**
* @param begin_date the begin_date to set
*/
public void setBegin_date(Timestamp begin_date) {
this.begin_date = begin_date;
}
/**
* @return the end_date
*/
public Timestamp getEnd_date() {
return end_date;
}
/**
* @param end_date the end_date to set
*/
public void setEnd_date(Timestamp end_date) {
this.end_date = end_date;
}
}
|
bartoszherba/messages-service | app/models/message.js | <filename>app/models/message.js
'use strict';
const mongoose = require('mongoose');
const Status = require('../data/status');
const Type = require('../data/type');
const messageSchema = new mongoose.Schema({
identifier: {
type: String,
required: true,
},
message: {
type: String,
required: true,
},
status: {
type: String,
default: Status.Unread,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
type: {
type: String,
default: Type.Success
},
attributes: {
type: Array,
default: [],
}
});
module.exports = mongoose.model('Message', messageSchema); |
amochtar/adventofcode | 2018/day-02/part2.py | <gh_stars>1-10
from itertools import combinations
def solve(input):
combs = combinations(input, 2)
for (a, b) in combs:
if distance(a,b) == 1:
print(a, b)
result = ""
for (n, m) in zip(a, b):
if n == m:
result += n
print(result)
def distance(a, b):
miss = 0
for (n, m) in zip(a, b):
if miss > 1:
return miss
if n != m:
miss += 1
return miss
with open('input.txt', 'r') as f:
input = f.read().splitlines()
solve(input)
|
RinHizakura/riscv-emulator | src/virtio_blk.c | #include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "cpu.h"
#include "macros.h"
#include "memmap.h"
#define ALIGN_UP(n, m) ((((n) + (m) -1) / (m)) * (m))
static void reset_virtio_blk(riscv_virtio_blk *virtio_blk)
{
/* FIXME: Can't find the content of reset sequence in document...... */
virtio_blk->id = 0;
virtio_blk->queue_sel = 0;
virtio_blk->guest_features[0] = 0;
virtio_blk->guest_features[1] = 0;
virtio_blk->status = 0;
virtio_blk->isr = 0;
virtio_blk->vq[0].desc = 0;
virtio_blk->vq[0].avail = 0;
virtio_blk->vq[0].used = 0;
}
static void virtqueue_update(riscv_virtio_blk *virtio_blk)
{
virtio_blk->vq[0].desc = virtio_blk->queue_pfn
<< virtio_blk->guest_page_shift;
virtio_blk->vq[0].avail = virtio_blk->vq[0].desc +
virtio_blk->vq[0].num * sizeof(riscv_virtq_desc);
virtio_blk->vq[0].used =
ALIGN_UP(virtio_blk->vq[0].avail +
offsetof(riscv_virtq_avail, ring[virtio_blk->vq[0].num]),
virtio_blk->vq[0].align);
}
static inline riscv_virtq_desc load_desc(riscv_cpu *cpu, uint64_t addr)
{
uint64_t desc_addr = read_bus(&cpu->bus, addr, 64, &cpu->exc);
uint64_t tmp = read_bus(&cpu->bus, addr + 8, 64, &cpu->exc);
return (riscv_virtq_desc){.addr = desc_addr,
.len = tmp & 0xffffffff,
.flags = (tmp >> 32) & 0xffff,
.next = (tmp >> 48) & 0xffff};
}
// FIXME: error of read / write bus should be handled
static void access_disk(riscv_virtio_blk *virtio_blk)
{
riscv_cpu *cpu = container_of(
container_of(virtio_blk, riscv_bus, virtio_blk), riscv_cpu, bus);
assert(virtio_blk->queue_sel == 0);
uint64_t desc = virtio_blk->vq[0].desc;
uint64_t avail = virtio_blk->vq[0].avail;
uint64_t used = virtio_blk->vq[0].used;
uint64_t queue_size = virtio_blk->vq[0].num;
/* (for avail) idx field indicates where the driver would put the next
* descriptor entry in the ring (modulo the queue size). This starts at 0,
* and increases. */
int idx = read_bus(&cpu->bus, avail + 2, 16, &cpu->exc);
int desc_offset =
read_bus(&cpu->bus, avail + 4 + (idx % queue_size), 16, &cpu->exc);
/* MUST use a single 8-type descriptor containing type, reserved and sector,
* followed by descriptors for data, then finally a separate 1-byte
* descriptor for status. */
riscv_virtq_desc desc0 =
load_desc(cpu, desc + sizeof(riscv_virtq_desc) * desc_offset);
riscv_virtq_desc desc1 =
load_desc(cpu, desc + sizeof(riscv_virtq_desc) * desc0.next);
riscv_virtq_desc desc2 =
load_desc(cpu, desc + sizeof(riscv_virtq_desc) * desc1.next);
assert(desc0.flags & VIRTQ_DESC_F_NEXT);
assert(desc1.flags & VIRTQ_DESC_F_NEXT);
assert(!(desc2.flags & VIRTQ_DESC_F_NEXT));
// the desc address should map to memory and we can then use memcpy directly
assert(desc1.addr >= DRAM_BASE && desc1.addr < DRAM_END);
assert((desc1.addr + desc1.len) >= DRAM_BASE &&
(desc1.addr + desc1.len) < DRAM_END);
// take value of type and sector in field of struct virtio_blk_req
int blk_req_type = read_bus(&cpu->bus, desc0.addr, 32, &cpu->exc);
int blk_req_sector = read_bus(&cpu->bus, desc0.addr + 8, 64, &cpu->exc);
// write device
if (blk_req_type == VIRTIO_BLK_T_OUT) {
assert(!(desc1.flags & VIRTQ_DESC_F_WRITE));
memcpy(cpu->bus.virtio_blk.rfsimg + (blk_req_sector * SECTOR_SIZE),
cpu->bus.memory.mem + (desc1.addr - DRAM_BASE), desc1.len);
}
// read device
else {
assert(desc1.flags & VIRTQ_DESC_F_WRITE);
memcpy(cpu->bus.memory.mem + (desc1.addr - DRAM_BASE),
cpu->bus.virtio_blk.rfsimg + (blk_req_sector * SECTOR_SIZE),
desc1.len);
}
assert(desc2.flags & VIRTQ_DESC_F_WRITE);
/* The final status byte is written by the device: VIRTIO_BLK_S_OK for
* success */
write_bus(&cpu->bus, desc2.addr, 8, VIRTIO_BLK_S_OK, &cpu->exc);
/* (for used) idx field indicates where the device would put the next
* descriptor entry in the ring (modulo the queue size). This starts at 0,
* and increases */
write_bus(&cpu->bus, used + 4 + ((virtio_blk->id % queue_size) * 8), 16,
desc_offset, &cpu->exc);
virtio_blk->id++;
write_bus(&cpu->bus, used + 2, 16, virtio_blk->id, &cpu->exc);
}
bool init_virtio_blk(riscv_virtio_blk *virtio_blk, const char *rfs_name)
{
memset(virtio_blk, 0, sizeof(riscv_virtio_blk));
// notify is set to -1 for no event happen
virtio_blk->queue_notify = 0xFFFFFFFF;
// default the align of virtqueue to 4096
virtio_blk->vq[0].align = VIRTQUEUE_ALIGN;
virtio_blk->config[1] = 0x20;
virtio_blk->config[2] = 0x03;
if (rfs_name[0] == '\0') {
virtio_blk->rfsimg = NULL;
return true;
}
FILE *fp = fopen(rfs_name, "rb");
if (!fp) {
LOG_ERROR("Invalid root filesystem path.\n");
return false;
}
fseek(fp, 0, SEEK_END);
size_t sz = ftell(fp) * sizeof(uint8_t);
rewind(fp);
virtio_blk->rfsimg = malloc(sz);
size_t read_size = fread(virtio_blk->rfsimg, sizeof(uint8_t), sz, fp);
if (read_size != sz) {
LOG_ERROR("Error when reading binary through fread.\n");
fclose(fp);
return false;
}
fclose(fp);
return true;
}
uint64_t read_virtio_blk(riscv_virtio_blk *virtio_blk,
uint64_t addr,
uint8_t size,
riscv_exception *exc)
{
uint64_t offset = addr - VIRTIO_BASE;
// support only byte size access for VIRTIO_MMIO_CONFIG
if (offset >= VIRTIO_MMIO_CONFIG) {
int index = offset - VIRTIO_MMIO_CONFIG;
if (index >= 8)
goto read_virtio_fail;
return virtio_blk->config[index];
}
// support only word-aligned and word size access for other registers
if ((size != 32) || (addr & 0x3))
goto read_virtio_fail;
switch (offset) {
case VIRTIO_MMIO_MAGIC_VALUE:
return VIRT_MAGIC;
case VIRTIO_MMIO_VERSION:
return VIRT_VERSION_LEGACY;
case VIRTIO_MMIO_DEVICE_ID:
return VIRT_BLK_DEV;
case VIRTIO_MMIO_VENDOR_ID:
return VIRT_VENDOR;
case VIRTIO_MMIO_DEVICE_FEATURES:
return virtio_blk->host_features[virtio_blk->host_features_sel];
case VIRTIO_MMIO_QUEUE_NUM_MAX:
return VIRTQUEUE_MAX_SIZE;
case VIRTIO_MMIO_QUEUE_PFN:
assert(virtio_blk->queue_sel == 0);
return virtio_blk->queue_pfn;
case VIRTIO_MMIO_INTERRUPT_STATUS:
return virtio_blk->isr;
case VIRTIO_MMIO_STATUS:
return virtio_blk->status;
default:
goto read_virtio_fail;
}
read_virtio_fail:
LOG_ERROR("read virtio addr %lx for size %d failed\n", addr, size);
exc->exception = LoadAccessFault;
return -1;
}
bool write_virtio_blk(riscv_virtio_blk *virtio_blk,
uint64_t addr,
uint8_t size,
uint64_t value,
riscv_exception *exc)
{
uint64_t offset = addr - VIRTIO_BASE;
// support only byte size access for VIRTIO_MMIO_CONFIG
if (offset >= VIRTIO_MMIO_CONFIG) {
int index = offset - VIRTIO_MMIO_CONFIG;
if (index >= 8)
goto write_virtio_fail;
virtio_blk->config[index] = (value >> (index * 8)) & 0xFF;
return true;
}
value &= 0xFFFFFFFF;
// support only word-aligned and word size access for other registers
if ((size != 32) || (addr & 0x3))
goto write_virtio_fail;
switch (offset) {
case VIRTIO_MMIO_DEVICE_FEATURES_SEL:
virtio_blk->host_features_sel = value ? 1 : 0;
break;
case VIRTIO_MMIO_DRIVER_FEATURES:
virtio_blk->guest_features[virtio_blk->guest_features_sel] = value;
break;
case VIRTIO_MMIO_DRIVER_FEATURES_SEL:
virtio_blk->guest_features_sel = value ? 1 : 0;
break;
case VIRTIO_MMIO_GUEST_PAGE_SIZE:
assert(value != 0);
virtio_blk->guest_page_shift = __builtin_ctz(value);
break;
case VIRTIO_MMIO_QUEUE_SEL:
if (value != 0) {
LOG_ERROR("Support only on virtio queue now \n");
goto write_virtio_fail;
}
break;
case VIRTIO_MMIO_QUEUE_NUM:
assert(virtio_blk->queue_sel == 0);
virtio_blk->vq[0].num = value;
break;
case VIRTIO_MMIO_QUEUE_ALIGN:
assert(virtio_blk->queue_sel == 0);
virtio_blk->vq[0].align = value;
break;
case VIRTIO_MMIO_QUEUE_PFN:
assert(virtio_blk->queue_sel == 0);
virtio_blk->queue_pfn = value;
virtqueue_update(virtio_blk);
break;
case VIRTIO_MMIO_QUEUE_NOTIFY:
assert(value == 0);
virtio_blk->queue_notify = value;
virtio_blk->notify_clock = virtio_blk->clock;
break;
case VIRTIO_MMIO_INTERRUPT_ACK:
/* clear bits by given bitmask to represent that the events causing
* the interrupt have been handled */
virtio_blk->isr &= ~(value & 0xff);
break;
case VIRTIO_MMIO_STATUS:
virtio_blk->status = value & 0xff;
// Writing zero (0x0) to this register triggers a device reset.
if (virtio_blk->status == 0)
reset_virtio_blk(virtio_blk);
if (virtio_blk->status & 0x4)
virtqueue_update(virtio_blk);
/* FIXME: we may have to do something for the indicating driver
* progress? */
break;
default:
goto write_virtio_fail;
}
return true;
write_virtio_fail:
LOG_ERROR("write virtio addr %lx for size %d failed\n", addr, size);
exc->exception = StoreAMOAccessFault;
return false;
}
bool virtio_is_interrupt(riscv_virtio_blk *virtio_blk)
{
return (virtio_blk->isr & 0x1) == 1;
}
void tick_virtio_blk(riscv_virtio_blk *virtio_blk)
{
if (virtio_blk->queue_notify != 0xFFFFFFFF &&
virtio_blk->clock == virtio_blk->notify_clock + DISK_DELAY) {
/* the interrupt was asserted because the device has used a buffer
* in at least one of the active virtual queues. */
virtio_blk->isr |= 0x1;
access_disk(virtio_blk);
virtio_blk->queue_notify = 0xFFFFFFFF;
}
virtio_blk->clock++;
}
void free_virtio_blk(riscv_virtio_blk *virtio_blk)
{
free(virtio_blk->rfsimg);
}
|
jkennaly/ft-api-lb | common/models/intention.js | <filename>common/models/intention.js
// intention.js
const _ = require('lodash')
module.exports = function(Intention){
Intention.batchCreate = function(req, data, cb) {
//console.log('Intention.batchCreate')
//console.log(data)
const userId = req && req.user && req.user.ftUserId
data
.filter(elData => elData && elData.subject && elData.subjectType)
.map(elData => Intention.upsertWithWhere({
subject: elData.subject,
subject_type: elData.subjectType,
user: userId
},
elData,
(err, el) => {
if(err) {
//console.log('err')
console.log(err)
}
}
))
cb(null, 'OK');
// the files are available as req.files.
// the body fields are available in req.body
}
Intention.batchDelete = function(req, data, cb) {
//console.log('Intention.batchDelete')
//console.log(data)
data
.filter(_.isNumber)
.map(elData => Intention.deleteById(elData,
(err, el) => {
if(err) {
//console.log('err')
console.log(err)
}
}
))
// the files are available as req.files.
// the body fields are available in req.body
cb(null, 'OK');
}
Intention.remoteMethod('batchCreate', {
accepts: [
{arg: 'req', type: 'object', 'http': {source: 'req'}},
{ arg: 'data', type: 'array', http: { source: 'body' } }],
http: {path: '/batchCreate'}
});
Intention.remoteMethod('batchDelete', {
accepts: [
{arg: 'req', type: 'object', 'http': {source: 'req'}},
{ arg: 'data', type: 'array', http: { source: 'body' } }],
http: {path: '/batchDelete'}
});
};
|
mufty/Framework | vendors/galaxy/Docs/GalaxyExport_8h.js | var GalaxyExport_8h =
[
[ "GALAXY_CALLTYPE", "GalaxyExport_8h.html#a8b1c00d8c18fa44e1762e7e7163e5065", null ],
[ "GALAXY_DLL_EXPORT", "GalaxyExport_8h.html#ad4fe29abd38af8e52004db26ea275486", null ]
]; |
brickviking/TinkersConstruct | src/main/java/slimeknights/tconstruct/library/data/material/package-info.java | <reponame>brickviking/TinkersConstruct<filename>src/main/java/slimeknights/tconstruct/library/data/material/package-info.java
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package slimeknights.tconstruct.library.data.material;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
|
isabelleh/atlas | src/test/java/org/openstreetmap/atlas/tags/oneway/OneWayTagTest.java | <reponame>isabelleh/atlas
package org.openstreetmap.atlas.tags.oneway;
import org.junit.Assert;
import org.junit.Test;
import org.openstreetmap.atlas.tags.HighwayTag;
import org.openstreetmap.atlas.tags.Taggable;
import org.openstreetmap.atlas.tags.oneway.bicycle.BicycleOneWayTag;
import org.openstreetmap.atlas.tags.oneway.bicycle.CyclewayLeftOneWayTag;
import org.openstreetmap.atlas.tags.oneway.bicycle.CyclewayOneWayTag;
import org.openstreetmap.atlas.tags.oneway.bicycle.CyclewayRightOneWayTag;
import org.openstreetmap.atlas.tags.oneway.bicycle.OneWayBicycleTag;
import org.openstreetmap.atlas.tags.oneway.motor.OneWayMotorVehicleTag;
import org.openstreetmap.atlas.tags.oneway.motor.OneWayMotorcarTag;
import org.openstreetmap.atlas.tags.oneway.motor.OneWayVehicleTag;
/**
* @author matthieun
*/
public class OneWayTagTest
{
// Un-tagged
public static final Taggable UNTAGGED = Taggable.with(HighwayTag.KEY,
HighwayTag.MOTORWAY.toString());
// OneWay tags
public static final Taggable ONE_WAY_YES = Taggable.with(OneWayTag.KEY,
OneWayTag.YES.toString());
public static final Taggable ONE_WAY_NO = Taggable.with(OneWayTag.KEY, OneWayTag.NO.toString());
public static final Taggable ONE_WAY_REVERSIBLE = Taggable.with(OneWayTag.KEY,
OneWayTag.REVERSIBLE.toString());
public static final Taggable ONE_WAY_TRUE = Taggable.with(OneWayTag.KEY,
OneWayTag.TRUE.toString());
public static final Taggable ONE_WAY_FALSE = Taggable.with(OneWayTag.KEY,
OneWayTag.FALSE.toString());
public static final Taggable ONE_WAY_ONE = Taggable.with(OneWayTag.KEY,
OneWayTag.ONE.toString());
public static final Taggable ONE_WAY_ZERO = Taggable.with(OneWayTag.KEY,
OneWayTag.ZERO.toString());
public static final Taggable ONE_WAY_MINUS_ONE = Taggable.with(OneWayTag.KEY,
OneWayTag.MINUS_1.toString());
public static final Taggable ONE_WAY_REVERSE = Taggable.with(OneWayTag.KEY,
OneWayTag.REVERSE.toString());
// OneWayMotorVehicle
public static final Taggable ONE_WAY_MOTOR_VEHICLE_YES = Taggable
.with(OneWayMotorVehicleTag.KEY, OneWayMotorVehicleTag.YES.toString());
public static final Taggable ONE_WAY_MOTOR_VEHICLE_NO = Taggable.with(OneWayMotorVehicleTag.KEY,
OneWayMotorVehicleTag.NO.toString());
public static final Taggable ONE_WAY_MOTOR_VEHICLE_MINUS_ONE = Taggable
.with(OneWayMotorVehicleTag.KEY, OneWayMotorVehicleTag.MINUS_1.toString());
// OneWayVehicle
public static final Taggable ONE_WAY_VEHICLE_YES = Taggable.with(OneWayVehicleTag.KEY,
OneWayVehicleTag.YES.toString());
public static final Taggable ONE_WAY_VEHICLE_NO = Taggable.with(OneWayVehicleTag.KEY,
OneWayVehicleTag.NO.toString());
public static final Taggable ONE_WAY_VEHICLE_MINUS_ONE = Taggable.with(OneWayVehicleTag.KEY,
OneWayVehicleTag.MINUS_1.toString());
// OneWayMotorcar
public static final Taggable ONE_WAY_MOTORCAR_YES = Taggable.with(OneWayMotorcarTag.KEY,
OneWayMotorcarTag.YES.toString());
public static final Taggable ONE_WAY_MOTORCAR_NO = Taggable.with(OneWayMotorcarTag.KEY,
OneWayMotorcarTag.NO.toString());
public static final Taggable ONE_WAY_MOTORCAR_MINUS_ONE = Taggable.with(OneWayMotorcarTag.KEY,
OneWayMotorcarTag.MINUS_1.toString());
// BicycleOneWay
public static final Taggable BICYCLE_ONE_WAY_YES = Taggable.with(BicycleOneWayTag.KEY,
BicycleOneWayTag.YES.toString());
public static final Taggable BICYCLE_ONE_WAY_NO = Taggable.with(BicycleOneWayTag.KEY,
BicycleOneWayTag.NO.toString());
public static final Taggable BICYCLE_ONE_WAY_MINUS_ONE = Taggable.with(BicycleOneWayTag.KEY,
BicycleOneWayTag.MINUS_1.toString());
// OneWayBicycle
public static final Taggable ONE_WAY_BICYCLE_YES = Taggable.with(OneWayBicycleTag.KEY,
OneWayBicycleTag.YES.toString());
public static final Taggable ONE_WAY_BICYCLE_NO = Taggable.with(OneWayBicycleTag.KEY,
OneWayBicycleTag.NO.toString());
public static final Taggable ONE_WAY_BICYCLE_ONE = Taggable.with(OneWayBicycleTag.KEY,
OneWayBicycleTag.ONE.toString());
public static final Taggable ONE_WAY_BICYCLE_MINUS_ONE = Taggable.with(OneWayBicycleTag.KEY,
OneWayBicycleTag.MINUS_1.toString());
public static final Taggable ONE_WAY_BICYCLE_OPPOSITE = Taggable.with(OneWayBicycleTag.KEY,
OneWayBicycleTag.OPPOSITE.toString());
// CyclewayOneWay
public static final Taggable CYCLEWAY_ONE_WAY_YES = Taggable.with(CyclewayOneWayTag.KEY,
CyclewayOneWayTag.YES.toString());
public static final Taggable CYCLEWAY_ONE_WAY_NO = Taggable.with(CyclewayOneWayTag.KEY,
CyclewayOneWayTag.NO.toString());
public static final Taggable CYCLEWAY_ONE_WAY_MINUS_ONE = Taggable.with(CyclewayOneWayTag.KEY,
CyclewayOneWayTag.MINUS_1.toString());
// CyclewayRightOneWay
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_YES = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.YES.toString());
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_NO = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.NO.toString());
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_ONE = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.ONE.toString());
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_MINUS_ONE = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.MINUS_1.toString());
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_LANE = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.LANE.toString());
public static final Taggable CYCLEWAY_RIGHT_ONE_WAY_DESIGNATED = Taggable
.with(CyclewayRightOneWayTag.KEY, CyclewayRightOneWayTag.DESIGNATED.toString());
// CyclewayLeftOneWay
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_YES = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.YES.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_NO = Taggable.with(CyclewayLeftOneWayTag.KEY,
CyclewayLeftOneWayTag.NO.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_ONE = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.ONE.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_MINUS_ONE = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.MINUS_1.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_LANE = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.LANE.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_OPPOSITE = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.OPPOSITE.toString());
public static final Taggable CYCLEWAY_LEFT_ONE_WAY_FALSE = Taggable
.with(CyclewayLeftOneWayTag.KEY, CyclewayLeftOneWayTag.FALSE.toString());
@Test
public void testOneWayBicycleForwardFalse()
{
// Splitting between true and false methods for Sonar
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(UNTAGGED));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(BICYCLE_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(BICYCLE_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(ONE_WAY_BICYCLE_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(ONE_WAY_BICYCLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(ONE_WAY_BICYCLE_OPPOSITE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_OPPOSITE));
Assert.assertFalse(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_FALSE));
}
@Test
public void testOneWayBicycleForwardTrue()
{
// Splitting between true and false methods for Sonar
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(ONE_WAY_TRUE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(ONE_WAY_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(BICYCLE_ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(ONE_WAY_BICYCLE_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(ONE_WAY_BICYCLE_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_LANE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_RIGHT_ONE_WAY_DESIGNATED));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayForward(CYCLEWAY_LEFT_ONE_WAY_LANE));
}
@Test
public void testOneWayBicycleReverseFalse()
{
// Splitting between true and false methods for Sonar
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(UNTAGGED));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(BICYCLE_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(BICYCLE_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(ONE_WAY_BICYCLE_YES));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(ONE_WAY_BICYCLE_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(ONE_WAY_BICYCLE_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_LANE));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_DESIGNATED));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_LANE));
Assert.assertFalse(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_FALSE));
}
@Test
public void testOneWayBicycleReverseTrue()
{
// Splitting between true and false methods for Sonar
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(BICYCLE_ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(ONE_WAY_BICYCLE_MINUS_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(ONE_WAY_BICYCLE_OPPOSITE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_RIGHT_ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isBicycleOneWayReversed(CYCLEWAY_LEFT_ONE_WAY_OPPOSITE));
}
@Test
public void testOneWayBicycleTwoWay()
{
Assert.assertTrue(OneWayTag.isBicycleTwoWay(UNTAGGED));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(BICYCLE_ONE_WAY_NO));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(ONE_WAY_BICYCLE_NO));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(CYCLEWAY_ONE_WAY_NO));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_NO));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_NO));
Assert.assertTrue(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_FALSE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(BICYCLE_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(BICYCLE_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(ONE_WAY_BICYCLE_YES));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(ONE_WAY_BICYCLE_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(ONE_WAY_BICYCLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(ONE_WAY_BICYCLE_OPPOSITE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_LANE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_RIGHT_ONE_WAY_DESIGNATED));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_LANE));
Assert.assertFalse(OneWayTag.isBicycleTwoWay(CYCLEWAY_LEFT_ONE_WAY_OPPOSITE));
}
@Test
public void testOneWayMotorTagsForward()
{
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(UNTAGGED));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_TRUE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_ONE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTOR_VEHICLE_YES));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_VEHICLE_YES));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTORCAR_YES));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTOR_VEHICLE_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTOR_VEHICLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_VEHICLE_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_VEHICLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTORCAR_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayForward(ONE_WAY_MOTORCAR_MINUS_ONE));
}
@Test
public void testOneWayMotorTagsReverse()
{
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(UNTAGGED));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_REVERSE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTOR_VEHICLE_MINUS_ONE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_VEHICLE_MINUS_ONE));
Assert.assertTrue(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTORCAR_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTOR_VEHICLE_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTOR_VEHICLE_YES));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_VEHICLE_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_VEHICLE_YES));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTORCAR_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleOneWayReversed(ONE_WAY_MOTORCAR_YES));
}
@Test
public void testOneWayMotorTagsTwoWay()
{
Assert.assertTrue(OneWayTag.isMotorVehicleTwoWay(UNTAGGED));
Assert.assertTrue(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTOR_VEHICLE_NO));
Assert.assertTrue(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_VEHICLE_NO));
Assert.assertTrue(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTORCAR_NO));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTOR_VEHICLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTOR_VEHICLE_YES));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_VEHICLE_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_VEHICLE_YES));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTORCAR_MINUS_ONE));
Assert.assertFalse(OneWayTag.isMotorVehicleTwoWay(ONE_WAY_MOTORCAR_YES));
}
@Test
public void testOneWayRegularForward()
{
Assert.assertFalse(OneWayTag.isOneWayForward(UNTAGGED));
Assert.assertTrue(OneWayTag.isOneWayForward(ONE_WAY_YES));
Assert.assertTrue(OneWayTag.isOneWayForward(ONE_WAY_TRUE));
Assert.assertTrue(OneWayTag.isOneWayForward(ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_REVERSIBLE));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_FALSE));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_ZERO));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isOneWayForward(ONE_WAY_REVERSE));
}
@Test
public void testOneWayRegularReverse()
{
Assert.assertFalse(OneWayTag.isOneWayReversed(UNTAGGED));
Assert.assertTrue(OneWayTag.isOneWayReversed(ONE_WAY_MINUS_ONE));
Assert.assertTrue(OneWayTag.isOneWayReversed(ONE_WAY_REVERSE));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_TRUE));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_NO));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_REVERSIBLE));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_FALSE));
Assert.assertFalse(OneWayTag.isOneWayReversed(ONE_WAY_ZERO));
}
@Test
public void testOneWayRegularTwoWay()
{
Assert.assertTrue(OneWayTag.isTwoWay(UNTAGGED));
Assert.assertTrue(OneWayTag.isTwoWay(ONE_WAY_NO));
Assert.assertTrue(OneWayTag.isTwoWay(ONE_WAY_FALSE));
Assert.assertTrue(OneWayTag.isTwoWay(ONE_WAY_ZERO));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_YES));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_TRUE));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_ONE));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_REVERSIBLE));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_MINUS_ONE));
Assert.assertFalse(OneWayTag.isTwoWay(ONE_WAY_REVERSE));
}
}
|
cineris/wro4j | wro4j-core/src/test/java/ro/isdc/wro/model/resource/processor/decorator/TestSupportAwareProcessorDecorator.java | <reponame>cineris/wro4j
package ro.isdc.wro.model.resource.processor.decorator;
import static org.junit.Assert.assertTrue;
import java.io.Reader;
import java.io.Writer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
import ro.isdc.wro.model.resource.processor.SupportAware;
import ro.isdc.wro.model.resource.processor.impl.js.JSMinProcessor;
/**
* @author <NAME>
*/
public class TestSupportAwareProcessorDecorator {
@Mock
private MockProcessor mockProcessor;
@Mock
private Resource mockResource;
@Mock
private Reader mockReader;
@Mock
private Writer mockWriter;
private SupportAwareProcessorDecorator victim;
private static interface MockProcessor
extends ResourcePreProcessor, SupportAware {
}
@Before
public void setUp() {
Context.set(Context.standaloneContext());
MockitoAnnotations.initMocks(this);
victim = new SupportAwareProcessorDecorator(mockProcessor);
}
@After
public void tearDown() {
Context.unset();
}
@Test(expected = NullPointerException.class)
public void cannotDecorateNullProcessor() {
new SupportAwareProcessorDecorator(null);
}
@Test
public void shouldCorrectlyDetectSupportOfDeepNestedProcessor() {
victim = new SupportAwareProcessorDecorator(new ProcessorDecorator(new ProcessorDecorator(new JSMinProcessor())));
assertTrue(victim.isSupported());
}
@Test
public void shouldInvokeDecoratedProcessorWhenProcessorIsSupported()
throws Exception {
Mockito.when(mockProcessor.isSupported()).thenReturn(true);
victim = new SupportAwareProcessorDecorator(mockProcessor);
victim.process(mockResource, mockReader, mockWriter);
Mockito.verify(mockProcessor).process(Mockito.any(Resource.class), Mockito.any(Reader.class),
Mockito.any(Writer.class));
}
@Test(expected = WroRuntimeException.class)
public void shouldThrowExceptionWhenProcessorIsNotSupported()
throws Exception {
Mockito.when(mockProcessor.isSupported()).thenReturn(false);
victim = new SupportAwareProcessorDecorator(mockProcessor);
victim.process(mockResource, mockReader, mockWriter);
}
}
|
pranavsadavarte221b/xv6 | doxygen/html/search/files_f.js | <reponame>pranavsadavarte221b/xv6
var searchData=
[
['uart_2ec_846',['uart.c',['../d1/d87/uart_8c.html',1,'']]],
['uart_2ed_847',['uart.d',['../d3/de3/uart_8d.html',1,'']]],
['ulib_2ec_848',['ulib.c',['../db/d8a/ulib_8c.html',1,'']]],
['ulib_2ed_849',['ulib.d',['../d8/d0c/ulib_8d.html',1,'']]],
['umalloc_2ec_850',['umalloc.c',['../df/d5d/umalloc_8c.html',1,'']]],
['umalloc_2ed_851',['umalloc.d',['../de/dd3/umalloc_8d.html',1,'']]],
['user_2eh_852',['user.h',['../d8/ddb/user_8h.html',1,'']]],
['usertests_2ed_853',['usertests.d',['../d7/d62/usertests_8d.html',1,'']]]
];
|
etkeys/cs417-in-python | python/tests/solvers/__init__.py | import pytest
import src.matrix_operations as matops
from src.solvers import Result, ResultAttributes
from tests.utils import create_matrix
def assert_iterations_count(act_count, exp_count):
if isinstance(exp_count, int):
assert act_count == exp_count
elif isinstance(exp_count, list):
assert exp_count[0] <= act_count <= exp_count[1]
else:
pytest.fail("exp_count should be int or list of ints.")
def common_test_solve(data, exception, solver):
"""
Paramerters
-----
data : the namespace representation of the yaml data for the test
exception : the context manager to trap expected exceptions
solver : static refernce (not instance) of what solver type to test
"""
inputs = vars(data.input)
for k, v in inputs.items():
if k.startswith("mat"):
inputs[k] = create_matrix(v)
with exception:
actor = solver(**inputs)
act_fresult = actor.solve()
act_result = actor.result
exp_fresult = data.expect.func_result
assert act_fresult == exp_fresult
assert isinstance(act_result, Result)
if act_result.has_error:
raise act_result[ResultAttributes.ERROR]
exp_vec = matops.reshape(create_matrix(data.expect.vec_result), (-1, 1))
assert ResultAttributes.RESULT_VECTOR in act_result
assert matops.almost_equal(act_result[ResultAttributes.RESULT_VECTOR], exp_vec)
if not "iter_count" in data.expect:
return
exp_iter_count = data.expect.iter_count
assert ResultAttributes.ITERATIONS in act_result
assert_iterations_count(act_result[ResultAttributes.ITERATIONS], exp_iter_count)
|
WinterChenS/photography-site | common/src/main/java/com/winterchen/common/base/ResponseCodeInterface.java | <filename>common/src/main/java/com/winterchen/common/base/ResponseCodeInterface.java<gh_stars>0
package com.winterchen.common.base;
/**
* @author winterchen
* @version 1.0
* @date 2021/1/19 3:52 下午
* @description 异常代码接口
**/
public interface ResponseCodeInterface {
int getCode();
String getMessage();
}
|
lawrencejones/pg2pubsub | pkg/sinks/bigquery/schema_builders.go | <reponame>lawrencejones/pg2pubsub
package bigquery
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/lawrencejones/pgsink/pkg/changelog"
"github.com/lawrencejones/pgsink/pkg/decode"
bq "cloud.google.com/go/bigquery"
"github.com/alecthomas/template"
)
// buildRawMetadata generates a BigQuery schema from an avro-ish changelog entry. This schema
// is for the raw tables, those that contain each changelog entry. This table is what
// we'll query with our view to display only the most recent row.
//
// {
// timestamp: "2020-02-15 19:33:32+00:00",
// lsn: 0/19EC9B8,
// payload: {
// id: "PA123",
// ...,
// },
// }
func buildRaw(tableName string, schema *changelog.Schema, decoder decode.Decoder) (*bq.TableMetadata, error) {
fields := bq.Schema{}
for _, column := range schema.Spec.Columns {
_, dest, err := decoder.ScannerFor(column.Type)
if err != nil {
return nil, err
}
externalType, repeated, err := fieldTypeFor(dest)
if err != nil {
return nil, err
}
fieldSchema := &bq.FieldSchema{
Name: column.Name,
Type: externalType,
Repeated: repeated,
Required: false,
}
fields = append(fields, fieldSchema)
}
// Sort the schema columns just in case BigQuery is sensitive to column order
sort.Slice(fields, func(i, j int) bool {
return fields[i].Name < fields[j].Name
})
bqSchema := bq.Schema{
&bq.FieldSchema{
Name: "timestamp",
Type: bq.TimestampFieldType,
Description: "Timestamp at which the row was read from database",
Required: true,
},
&bq.FieldSchema{
Name: "lsn",
Type: bq.IntegerFieldType,
Description: "Database log sequence number at time of read, optional",
Required: false,
},
&bq.FieldSchema{
Name: "operation",
Type: bq.StringFieldType,
Description: "Either IMPORT, INSERT, UPDATE or DELETE",
Required: true,
},
&bq.FieldSchema{
Name: "payload",
Type: bq.RecordFieldType,
Description: "Contents of database row",
Schema: fields,
},
}
keys := schema.GetPrimaryKey()
if len(keys) == 0 {
return nil, fmt.Errorf("table %s has no detected primary key columns", tableName)
}
md := &bq.TableMetadata{
Name: tableName,
Schema: bqSchema,
// Mark the origin as pgsink so users know where the table originates from.
Labels: map[string]string{
"origin": "pgsink",
},
// Clustering the table by the primary key makes it much more efficient to fetch just
// a single row from the table. It helps support the use case where BigQuery is
// replacing your legacy 'databox', a Postgres clone that people might use for ad-hoc
// analytic queries.
Clustering: &bq.Clustering{
Fields: keys,
},
// Time partitioning enables us to drop old data, and to efficiently compute views
// from a given time period (time-travelling, how awesome!).
TimePartitioning: &bq.TimePartitioning{
Field: "timestamp",
},
}
return md, nil
}
// buildView creates a BigQuery view that presents only the most recent row content in the
// raw table to the user. We expect the rawTableName to be in projectID:datasetID.tableID
// form.
func buildView(tableName, rawTableName string, schema *changelog.Schema) (*bq.TableMetadata, error) {
keys := schema.GetPrimaryKey()
if len(keys) == 0 {
return nil, fmt.Errorf("table %s has no detected primary key columns", tableName)
}
var buffer bytes.Buffer
err := viewQueryTemplate.Execute(
&buffer, struct {
EscapedRawTableIdentifier string
PrimaryKeyColumns []string
}{
fmt.Sprintf("`%s`", strings.Replace(rawTableName, ":", ".", 1)),
keys,
},
)
if err != nil {
return nil, err
}
md := &bq.TableMetadata{
Name: tableName,
ViewQuery: buffer.String(),
Schema: nil, // we don't use schema for a view
}
return md, nil
}
// TODO: Support composite primary keys
var viewQueryTemplate = template.Must(template.New("view_query_template").Parse(
`select payload.*, from (
select *, row_number() over (
partition by
{{ $select := "" }}
{{ range $index, $column := .PrimaryKeyColumns }}
{{ if $index}},{{end}}
payload.{{ $column }}
{{ end }}
order by timestamp desc
) as row_number
from {{.EscapedRawTableIdentifier}}
)
where row_number = 1
and operation != 'DELETE'
`))
|
greifentor/blueprints | java-code-parser-antlr/src/main/java/de/ollie/blueprints/codereader/java/model/CompilationUnit.java | package de.ollie.blueprints.codereader.java.model;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.Generated;
import lombok.experimental.Accessors;
/**
* A container for the compilation unit information.
*
* @author ollie (13.04.2020)
*/
@Accessors(chain = true)
@Data
@Generated
public class CompilationUnit {
private String packageName;
private List<ImportDeclaration> importDeclarations = new ArrayList<>();
private List<TypeDeclaration> typeDeclarations = new ArrayList<>();
public CompilationUnit addImportDeclarations(ImportDeclaration... importDeclarations) {
for (ImportDeclaration importDeclaration : importDeclarations) {
this.importDeclarations.add(importDeclaration);
}
return this;
}
public CompilationUnit addTypeDeclarations(TypeDeclaration... typeDeclarations) {
for (TypeDeclaration typeDeclaration : typeDeclarations) {
this.typeDeclarations.add(typeDeclaration);
}
return this;
}
} |
KimJinYounga/SNS_gooroomee | src/main/java/com/gooroomee/api/error/entity/ErrorLogService.java | <filename>src/main/java/com/gooroomee/api/error/entity/ErrorLogService.java
package com.gooroomee.api.error.entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ErrorLogService {
@Autowired
private ErrorLogRepository errorLogRepository;
@Transactional
public void save(ErrorLog errorLog) {
errorLogRepository.save(errorLog);
}
}
|
nulab/backlog-migration-common | core/src/main/scala/com/nulabinc/backlog/migration/common/service/PriorityService.scala | <gh_stars>1-10
package com.nulabinc.backlog.migration.common.service
import com.nulabinc.backlog4j.Priority
/**
* @author
* uchida
*/
trait PriorityService {
def allPriorities(): Seq[Priority]
}
|
zephyriot/zephyr-bluetooth | drivers/clock_control/stm32f107xx_clock.c | /*
* Copyright (c) 2016 RnDity Sp. z o.o.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @brief Driver for Reset & Clock Control of STM32F10x family processor.
*
* Based on reference manual:
* STM32F101xx, STM32F102xx, STM32F103xx, STM32F105xx and STM32F107xx
* advanced ARM ® -based 32-bit MCUs
*
* Chapter 8: Connectivity line devices: reset and clock control (RCC)
*/
#include <soc.h>
#include <soc_registers.h>
#include <clock_control.h>
#include <misc/util.h>
#include <clock_control/stm32_clock_control.h>
struct stm32f10x_rcc_data {
u8_t *base;
};
static inline int stm32f10x_clock_control_on(struct device *dev,
clock_control_subsys_t sub_system)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
u32_t subsys = POINTER_TO_UINT(sub_system);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
subsys &= ~(STM32F10X_CLOCK_APB2_BASE);
rcc->apb2enr |= subsys;
} else {
rcc->apb1enr |= subsys;
}
return 0;
}
static inline int stm32f10x_clock_control_off(struct device *dev,
clock_control_subsys_t sub_system)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
u32_t subsys = POINTER_TO_UINT(sub_system);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
subsys &= ~(STM32F10X_CLOCK_APB2_BASE);
rcc->apb2enr &= ~subsys;
} else {
rcc->apb1enr &= ~subsys;
}
return 0;
}
/**
* @brief helper for mapping a setting to register value
*/
struct regval_map {
int val;
int reg;
};
static int map_reg_val(const struct regval_map *map, size_t cnt, int val)
{
for (int i = 0; i < cnt; i++) {
if (map[i].val == val) {
return map[i].reg;
}
}
return 0;
}
/**
* @brief map APB prescaler setting to register value
*/
static int apb_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_RCC_CFG_HCLK_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_RCC_CFG_HCLK_DIV_0},
{2, STM32F10X_RCC_CFG_HCLK_DIV_2},
{4, STM32F10X_RCC_CFG_HCLK_DIV_4},
{8, STM32F10X_RCC_CFG_HCLK_DIV_8},
{16, STM32F10X_RCC_CFG_HCLK_DIV_16},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
/**
* @brief map AHB prescaler setting to register value
*/
static int ahb_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_RCC_CFG_SYSCLK_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_RCC_CFG_SYSCLK_DIV_0},
{2, STM32F10X_RCC_CFG_SYSCLK_DIV_2},
{4, STM32F10X_RCC_CFG_SYSCLK_DIV_4},
{8, STM32F10X_RCC_CFG_SYSCLK_DIV_8},
{16, STM32F10X_RCC_CFG_SYSCLK_DIV_16},
{64, STM32F10X_RCC_CFG_SYSCLK_DIV_64},
{128, STM32F10X_RCC_CFG_SYSCLK_DIV_128},
{256, STM32F10X_RCC_CFG_SYSCLK_DIV_256},
{512, STM32F10X_RCC_CFG_SYSCLK_DIV_512},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
/**
* @brief select PREDIV division factor
*/
static int prediv_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_0},
{2, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_2},
{3, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_3},
{4, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_4},
{5, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_5},
{6, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_6},
{7, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_7},
{8, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_8},
{9, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_9},
{10, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_10},
{11, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_11},
{12, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_12},
{13, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_13},
{14, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_14},
{15, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_15},
{16, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_16},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER
/**
* @brief map PLL multiplier setting to register value
*/
static int pllmul(int mul)
{
/* x4 -> 0x2
* x5 -> 0x3
* x6 -> 0x4
* x7 -> 0x5
* x8 -> 0x6
* x9 -> 0x7
* x6.5 -> 0xd
*/
if (mul == 13) {
/* ToDo: do something with 6.5 multiplication */
return 0xd;
} else {
return mul - 2;
}
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER
static int pll2mul(int mul)
{
/* x8 -> 0x6
* x9 -> 0x7
* x10 -> 0x8
* x11 -> 0x9
* x12 -> 0xa
* x13 -> 0xb
* x14 -> 0xc
* x16 -> 0xe
* x20 -> 0xf
*/
if (mul == 20) {
return 0xf;
} else {
return mul - 2;
}
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER */
static u32_t get_ahb_clock(u32_t sysclk)
{
/* AHB clock is generated based on SYSCLK */
u32_t sysclk_div =
CONFIG_CLOCK_STM32F10X_CONN_LINE_AHB_PRESCALER;
if (sysclk_div == 0) {
sysclk_div = 1;
}
return sysclk / sysclk_div;
}
static u32_t get_apb_clock(u32_t ahb_clock, u32_t prescaler)
{
if (prescaler == 0) {
prescaler = 1;
}
return ahb_clock / prescaler;
}
static
int stm32f10x_clock_control_get_subsys_rate(struct device *clock,
clock_control_subsys_t sub_system,
u32_t *rate)
{
ARG_UNUSED(clock);
u32_t subsys = POINTER_TO_UINT(sub_system);
u32_t prescaler =
CONFIG_CLOCK_STM32F10X_CONN_LINE_APB1_PRESCALER;
/* assumes SYSCLK is SYS_CLOCK_HW_CYCLES_PER_SEC */
u32_t ahb_clock =
get_ahb_clock(CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
prescaler =
CONFIG_CLOCK_STM32F10X_CONN_LINE_APB2_PRESCALER;
}
*rate = get_apb_clock(ahb_clock, prescaler);
return 0;
}
static const struct clock_control_driver_api stm32f10x_clock_control_api = {
.on = stm32f10x_clock_control_on,
.off = stm32f10x_clock_control_off,
.get_rate = stm32f10x_clock_control_get_subsys_rate,
};
/**
* @brief setup embedded flash controller
*
* Configure flash access time latency depending on SYSCLK.
*/
static inline void setup_flash(void)
{
volatile struct stm32f10x_flash *flash =
(struct stm32f10x_flash *)(FLASH_R_BASE);
if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 24000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_0;
} else if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 48000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_1;
} else if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 72000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_2;
}
}
static int stm32f10x_clock_control_init(struct device *dev)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
/* SYSCLK source defaults to HSI */
int sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSI;
u32_t hpre =
ahb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_AHB_PRESCALER);
u32_t ppre1 =
apb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_APB1_PRESCALER);
u32_t ppre2 =
apb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_APB2_PRESCALER);
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER
u32_t pll_mul =
pllmul(CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER
u32_t pll2_mul =
pll2mul(CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1
u32_t prediv1 =
prediv_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1 */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV2
u32_t prediv2 =
prediv_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV2);
#endif /* CLOCK_STM32F10X_CONN_LINE_PREDIV2 */
/* disable PLLs */
rcc->cr.bit.pllon = 0;
rcc->cr.bit.pll2on = 0;
rcc->cr.bit.pll3on = 0;
/* disable HSE */
rcc->cr.bit.hseon = 0;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_HSE_BYPASS
/* HSE is disabled, HSE bypass can be enabled*/
rcc->cr.bit.hsebyp = 1;
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_HSE_BYPASS */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_HSI
/* enable HSI clock */
rcc->cr.bit.hsion = 1;
/* this should end after one test */
while (rcc->cr.bit.hsirdy != 1) {
}
/* HSI oscillator clock / 2 selected as PLL input clock */
rcc->cfgr.bit.pllsrc = STM32F10X_RCC_CFG_PLL_SRC_HSI;
#endif /* CONFIG_CLOCK_STM32F10X_PLL_SRC_HSI */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_PREDIV1
/* wait for to become ready */
rcc->cr.bit.hseon = 1;
while (rcc->cr.bit.hserdy != 1) {
}
rcc->cfgr2.bit.prediv1 = prediv1;
/* Clock from PREDIV1 selected as PLL input clock */
rcc->cfgr.bit.pllsrc = STM32F10X_RCC_CFG_PLL_SRC_PREDIV1;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1_SRC_HSE
/* HSE oscillator clock selected as PREDIV1 clock entry */
rcc->cfgr2.bit.prediv1src = STM32F10X_RCC_CFG2_PREDIV1_SRC_HSE;
#else
/* PLL2 selected as PREDIV1 clock entry */
rcc->cfgr2.bit.prediv1src = STM32F10X_RCC_CFG2_PREDIV1_SRC_PLL2;
rcc->cfgr2.bit.prediv2 = prediv2;
rcc->cfgr2.bit.pll2mul = pll2_mul;
/* enable PLL2 */
rcc->cr.bit.pll2on = 1;
/* wait for PLL to become ready */
while (rcc->cr.bit.pll2rdy != 1) {
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1_SRC_HSE */
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_PREDIV1 */
/* setup AHB prescaler */
rcc->cfgr.bit.hpre = hpre;
/* setup APB1, must not exceed 36MHz */
rcc->cfgr.bit.ppre1 = ppre1;
/* setup APB2 */
rcc->cfgr.bit.ppre2 = ppre2;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_HSI
/* enable HSI clock */
rcc->cr.bit.hsion = 1;
/* this should end after one test */
while (rcc->cr.bit.hsirdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSI;
#elif defined(CONFIG_CLOCK_STM32F10X_SYSCLK_SRC_HSE)
/* enable HSE clock */
rcc->cr.bit.hseon = 1;
/* wait for to become ready */
while (rcc->cr.bit.hserdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSE;
#elif defined(CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_PLLCLK)
/* setup PLL multiplication (PLL must be disabled) */
rcc->cfgr.bit.pllmul = pll_mul;
/* enable PLL */
rcc->cr.bit.pllon = 1;
/* wait for PLL to become ready */
while (rcc->cr.bit.pllrdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_PLL;
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_HSI */
/* configure flash access latency before SYSCLK source
* switch
*/
setup_flash();
/* set SYSCLK clock value */
rcc->cfgr.bit.sw = sysclk_src;
/* wait for SYSCLK to switch the source */
while (rcc->cfgr.bit.sws != sysclk_src) {
}
return 0;
}
static struct stm32f10x_rcc_data stm32f10x_rcc_data = {
.base = (u8_t *)RCC_BASE,
};
/* FIXME: move prescaler/multiplier defines into device config */
/**
* @brief RCC device, note that priority is intentionally set to 1 so
* that the device init runs just after SOC init
*/
DEVICE_AND_API_INIT(rcc_stm32f10x, STM32_CLOCK_CONTROL_NAME,
&stm32f10x_clock_control_init,
&stm32f10x_rcc_data, NULL,
PRE_KERNEL_1,
CONFIG_CLOCK_CONTROL_STM32F10X_CONN_LINE_DEVICE_INIT_PRIORITY,
&stm32f10x_clock_control_api);
|
chowdud/intrigue-ident | checks/ip/ganglia.rb | <gh_stars>0
module Intrigue
module Ident
module IpCheck
class Ganglia < Intrigue::Ident::IpCheck::Base
def generate_checks
[
{
type: 'fingerprint',
category: 'application',
tags: %w[Network Tcp Ganglia],
vendor: 'Ganglia',
product: 'Ganglia',
description: 'match via protocol response string',
references: [
'http://ganglia.info/'
],
request_type: :plain,
protocol: :tcp,
request_content: "\r\n",
# match_type: :content_banner, we don't have a match_type because we can only match whatever we get in the response
match_content: /^.*<!DOCTYPE\sGANGLIA_XML.*$/i
}
]
end
end
end
end
end
|
phetsims/scenery-phet | js/sceneryPhetQueryParameters.js | // Copyright 2016-2020, University of Colorado Boulder
/**
* Query parameters for the scenery-phet demo application.
*
* @author <NAME> (PixelZoom, Inc.)
*/
import sceneryPhet from './sceneryPhet.js';
const sceneryPhetQueryParameters = QueryStringMachine.getAll( {
// background color of the screens
backgroundColor: {
type: 'string', // CSS color format, e.g. 'green', 'ff8c00', 'rgb(255,0,255)'
defaultValue: 'white'
},
// initial selection on the Sliders screen, values are the same as the labels on combo box items
slider: {
type: 'string',
defaultValue: null
},
// initial selection on the Components screen, values are the same as the labels on combo box items
component: {
type: 'string',
defaultValue: null
}
} );
sceneryPhet.register( 'sceneryPhetQueryParameters', sceneryPhetQueryParameters );
export default sceneryPhetQueryParameters; |
rgm93/CleanersDApp | origin-dapp/src/components/modals/offer-modals.js | import React from 'react'
import { Link } from 'react-router-dom'
import { FormattedMessage } from 'react-intl'
import Modal from 'components/modal'
export const WithdrawModal = ({ isOpen = false, onCancel, onSubmit }) => (
<Modal
className="offer-modal withdraw"
isOpen={isOpen}
handleToggle={onCancel}
>
<p className="heading">
<FormattedMessage
id={'offerModals.withdrawHeading'}
defaultMessage={'Withdraw Offer'}
/>
</p>
<div className="text">
<span>
<FormattedMessage
id={'offerModals.withdrawText'}
defaultMessage={
'Are you sure you want to withdraw your offer? Your escrowed payment wil be returned to your wallet.'
}
/>
</span>
</div>
<div className="d-flex button-container">
<button className="btn btn-clear" onClick={onCancel}>
<FormattedMessage
id={'offerModals.withdrawCancel'}
defaultMessage={'Cancel'}
/>
</button>
<button className="btn btn-clear" onClick={onSubmit}>
<FormattedMessage
id={'offerModals.withdrawSubmit'}
defaultMessage={'Withdraw'}
/>
</button>
</div>
</Modal>
)
export const RejectionModal = ({ isOpen = false, handleToggle }) => (
<Modal
className="arbitration-modal rejection"
isOpen={isOpen}
handleToggle={handleToggle}
>
<div className="image-container">
<img src="images/reject-icon.svg" role="presentation" />
</div>
<p className="heading">
<FormattedMessage
id={'offerModals.rejectionHeading'}
defaultMessage={'This offer has been rejected.'}
/>
</p>
<span className="text">
<FormattedMessage
id={'offerModals.rejectionText'}
defaultMessage={
'Your listing is now available for other buyers to purchase.'
}
/>
</span>
<div className="button-container">
<Link to="/my-listings">
<button className="btn btn-clear">
<FormattedMessage
id={'arbitrationModals.rejectionListings'}
defaultMessage={'View Listings'}
/>
</button>
</Link>
</div>
</Modal>
)
|
kylinmac/leetCode | src/main/java/com/mc/code/MedianOfTwoSortedArrays.java | <reponame>kylinmac/leetCode
package com.mc.code;
/**
* @author macheng
* @date 2020/11/25 10:20
* @desc 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
*/
public class MedianOfTwoSortedArrays {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
return find(nums1, nums2);
}
public double find(int[] nums1, int[] nums2) {
return findForSameLengthArrays(nums1, nums2);
}
public double findForSameLengthArrays(int[] nums1, int[] nums2) {
double result = 0;
return result;
}
public static void main(String[] args) {
System.out.println(test(new int[]{4},new int[]{3}));
}
public static double test(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length==0) {
if (nums2 == null || nums2.length==0) {
return 0;
}
if (nums2.length % 2 == 0) {
return (((double)(nums2[nums2.length / 2 - 1] + nums2[nums2.length / 2])) / 2);
} else {
return (nums2[nums2.length / 2]);
}
}
if (nums2 == null || nums2.length==0) {
if (nums1.length % 2 == 0) {
return (((double) (nums1[nums1.length / 2 - 1] + nums1[nums1.length / 2])) / 2);
} else {
return (nums1[nums1.length / 2]);
}
}
int num = nums1.length + nums2.length;
if (num % 2 == 0) {
int index = num / 2;
int n1 = 0;
int n2 = 0;
int[] l = nums1.length >= nums2.length ? nums1 : nums2;
int[] s = nums1.length >= nums2.length ? nums2 : nums1;
int cindex = 0;
int li = -1;
int si = -1;
while (cindex <= index) {
if (si+1 < s.length && li+1 <l.length) {
if (l[li + 1] <= s[si + 1]) {
li++;
if (cindex == (index - 1)) {
n1 = l[li];
}
if (cindex == index) {
n2 = l[li];
}
} else {
si++;
if (cindex == (index - 1)) {
n1 = s[si];
}
if (cindex == index) {
n2 = s[si];
}
}
} else if ( li+1 <l.length){
li++;
if (cindex == (index - 1)) {
n1 = l[li];
}
if (cindex == index) {
n2 = l[li];
}
}else{
si++;
if (cindex == index-1) {
n1 = s[si];
}
if (cindex == index) {
n2 = s[si];
}
}
cindex++;
}
return (((double) (n1 + n2) )/ 2);
} else {
int index = num / 2;
int n = 0;
int[] l = nums1.length >= nums2.length ? nums1 : nums2;
int[] s = nums1.length >= nums2.length ? nums2 : nums1;
int cindex = 0;
int li = -1;
int si = -1;
while (cindex <= index) {
if (si+1 < s.length && li+1 <l.length) {
if (l[li + 1] <= s[si + 1]) {
li++;
if (cindex == index) {
n = l[li];
}
} else {
si++;
if (cindex == index) {
n = s[si];
}
}
} else if ( li+1 <l.length){
li++;
if (cindex == index) {
n = l[li];
}
}else {
si++;
if (cindex == index) {
n = s[si];
}
}
cindex++;
}
return n;
}
}
}
|
FengYen-Chang/dldt | inference-engine/src/mkldnn_plugin/nodes/mkldnn_eltwise_node.cpp | // Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "mkldnn_eltwise_node.h"
#include <ie_layers.h>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <cmath>
#include <mkldnn_types.h>
#include <mkldnn_extension_utils.h>
#include "ie_parallel.hpp"
#include <map>
using namespace mkldnn;
using namespace MKLDNNPlugin;
using namespace InferenceEngine;
MKLDNNEltwiseNode::MKLDNNEltwiseNode(const InferenceEngine::CNNLayerPtr& layer, const mkldnn::engine& eng) : MKLDNNNode(layer, eng) {
op = EltwiseLayer::Sum;
}
bool MKLDNNEltwiseNode::isSum() {
auto * eltwiseLayer = dynamic_cast<EltwiseLayer*>(getCnnLayer().get());
return eltwiseLayer->_operation == EltwiseLayer::Sum;
}
bool MKLDNNEltwiseNode::isUnitScales() {
auto * eltwiseLayer = dynamic_cast<EltwiseLayer*>(getCnnLayer().get());
if (eltwiseLayer->coeff.empty())
return true;
for (auto scale : eltwiseLayer->coeff) {
if (scale != 1.0f)
return false;
}
return true;
}
void MKLDNNEltwiseNode::getSupportedDescriptors() {
auto * eltwiseLayer = dynamic_cast<EltwiseLayer*>(getCnnLayer().get());
if (eltwiseLayer == nullptr)
THROW_IE_EXCEPTION << "Cannot convert eltwise layer.";
op = eltwiseLayer->_operation;
if (getParentEdges().size() < 2)
THROW_IE_EXCEPTION << "Incorrect number of input edges for layer " << getName();
if (getChildEdges().empty())
THROW_IE_EXCEPTION << "Incorrect number of output edges for layer " << getName();
if (op == EltwiseLayer::Squared_diff)
if (getParentEdges().size() != 2)
THROW_IE_EXCEPTION << "Incorrect number of input edges for layer " << getName() << " for operation squared_diff.\n"
<< "Expected: 2\n" << "Actual: " << getParentEdges().size();
auto outDims = getChildEdgeAt(0)->getDims();
for (size_t i = 0; i < getParentEdges().size(); i++) {
auto inDims = getParentEdgeAt(i)->getDims();
for (size_t j = 1; j <= inDims.ndims(); j++) {
if (outDims[outDims.ndims() - j] != inDims[inDims.ndims() - j]) {
if (inDims[inDims.ndims() - j] == 1) {
broadcast = true;
} else {
THROW_IE_EXCEPTION << "Incorrect dimentions for broadcasting for " << eltwiseLayer->name;
}
}
}
}
if (broadcast) {
auto outDims = getChildEdgeAt(0)->getDims();
for (size_t i = 0; i < getParentEdges().size(); i++) {
auto inDims = getParentEdgeAt(i)->getDims();
if (inDims.ndims() > 5 || outDims.ndims() > 5)
THROW_IE_EXCEPTION << "Eltwise node in broadcasting mode doesn't support more than 5 dims for blobs";
}
}
bool with_coeffs = !eltwiseLayer->coeff.empty();
if (op != EltwiseLayer::Sum && with_coeffs)
THROW_IE_EXCEPTION << "Only sum operation supports operands coefficients";
if (with_coeffs && eltwiseLayer->coeff.size() != getParentEdges().size())
THROW_IE_EXCEPTION << "Number of provided coefficients is not equal to number of operands";
if (with_coeffs && eltwiseLayer->precision != Precision::FP32)
THROW_IE_EXCEPTION << "Sum with coefficients supports only FP32 precision";
sum_scales.clear();
for (int i = 0; i < getParentEdges().size(); i++)
sum_scales.push_back(with_coeffs ? eltwiseLayer->coeff[i] : 1.0f);
}
void MKLDNNEltwiseNode::initSupportedPrimitiveDescriptors() {
if (!supportedPrimitiveDescriptors.empty())
return;
auto initDesc = [&] (mkldnn::memory::data_type inputDT, mkldnn::memory::data_type outputDT, memory::format format) -> PrimitiveDescInfo {
InferenceEngine::LayerConfig config;
config.dynBatchSupport = true;
for (size_t i = 0; i < getParentEdges().size(); i++) {
InferenceEngine::DataConfig dataConfig;
dataConfig.inPlace = (!i && canBeInPlace()) ? 0 : -1;
dataConfig.constant = false;
if (getParentEdgeAt(i)->getDims().ndims() == getChildEdgeAt(0)->getDims().ndims()) {
dataConfig.desc = MKLDNNMemoryDesc(getParentEdgeAt(i)->getDims(), inputDT, format);
config.inConfs.push_back(dataConfig);
} else {
// Broadcasting support
if (MKLDNNMemory::IsPlainFormat(format)) {
dataConfig.desc = MKLDNNMemoryDesc(getParentEdgeAt(i)->getDims(), inputDT, MKLDNNMemory::GetPlainFormat(getParentEdgeAt(i)->getDims()));
config.inConfs.push_back(dataConfig);
}
}
}
InferenceEngine::DataConfig dataConfig;
dataConfig.inPlace = -1;
dataConfig.constant = false;
dataConfig.desc = MKLDNNMemoryDesc(getChildEdgeAt(0)->getDims(), outputDT, format);
config.outConfs.push_back(dataConfig);
return {config, impl_desc_type::ref};
};
for (const auto& format : getAvailableFormatsForDims(getChildEdgeAt(0)->getDims())) {
mkldnn::memory::data_type inputDT = MKLDNNExtensionUtils::IEPrecisionToDataType(getCnnLayer()->precision);
mkldnn::memory::data_type outputDT = MKLDNNExtensionUtils::IEPrecisionToDataType(getCnnLayer()->precision);
supportedPrimitiveDescriptors.push_back(initDesc(inputDT, outputDT, format));
}
}
void MKLDNNEltwiseNode::createPrimitive() {
if (prim)
return;
auto& dstMemPtr = getChildEdgeAt(0)->getMemoryPtr();
if (!dstMemPtr || !dstMemPtr->GetPrimitivePtr())
THROW_IE_EXCEPTION << "Destination memory didn't allocate.";
if (getSelectedPrimitiveDescriptor() == nullptr)
THROW_IE_EXCEPTION << "Preferable primitive descriptor does not set.";
std::vector<memory::primitive_desc> srcs_pd;
std::vector<primitive::at> srcs_p;
for (size_t i = 0; i < getParentEdges().size(); i++) {
auto& srcMemPtr = getParentEdgeAt(i)->getMemoryPtr();
if (!srcMemPtr || !srcMemPtr->GetPrimitivePtr()) {
auto parent = getParentEdgeAt(i)->getParent();
THROW_IE_EXCEPTION << "Source memory from " << parent->getName() << " didn't allocate.";
}
if (op == EltwiseLayer::Sum) {
srcs_pd.push_back(srcMemPtr->GetPrimitiveDescriptor());
srcs_p.emplace_back(srcMemPtr->GetPrimitive());
}
}
if (op == EltwiseLayer::Sum && !broadcast) {
try {
auto primitive_desc = mkldnn::sum::primitive_desc(dstMemPtr->GetDescriptor(), sum_scales, srcs_pd);
prim = std::shared_ptr<mkldnn::sum>(new mkldnn::sum(primitive_desc, srcs_p, dstMemPtr->GetPrimitive()));
} catch (...) {
std::cerr << "Handle this problem correctly!" << std::endl;
prim = nullptr;
}
}
}
void MKLDNNEltwiseNode::initOptimalPrimitiveDescriptor() {
auto config = getSelectedPrimitiveDescriptor()->getConfig();
if (isInitConfig(config))
return;
MKLDNNNode::initOptimalPrimitiveDescriptor();
auto* selectedPD = getSelectedPrimitiveDescriptor();
if (!selectedPD) {
return;
}
auto& selectedConfig = getSelectedPrimitiveDescriptor()->getConfig();
for (size_t i = 1; i < selectedConfig.inConfs.size(); i++) {
if (selectedConfig.inConfs[0].desc.getPrecision() != selectedConfig.inConfs[i].desc.getPrecision()) {
selectedConfig.inConfs[i].desc.setPrecision(selectedConfig.inConfs[0].desc.getPrecision());
}
}
}
void MKLDNNEltwiseNode::dims_calc(int *dims, const MKLDNNDims &edge_dims) {
for (int i = 0; i < 5; i++)
dims[i] = 1;
int ndims = edge_dims.ndims();
if (ndims > 5) {
THROW_IE_EXCEPTION << "ndims should be less then 5";
}
for (int i = 0; i < ndims; i++) {
dims[4 - i] = edge_dims[ndims - 1 - i];
}
dims[5 - ndims] = std::min(dims[5 - ndims], batchToProcess());
}
void MKLDNNEltwiseNode::offset_out_calc(int *offset, int *dims) {
int k = 1;
for (int i = 4; i >= 0; i--) {
offset[i] = k;
k *= dims[i];
}
}
void MKLDNNEltwiseNode::offset_in_calc(int *offset, int *dims_in, int *dims_out) {
int k = 1;
for (int i = 4; i >= 0; i--) {
offset[i] = (dims_in[i] == dims_out[i]) ? k : 0;
k *= dims_in[i];
}
}
// Intel C++ Compiler 18.0 for Windows contains bug that doesn't allow to use templates to generate eltwise implementations
// and to avoid all copypaste below
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_add(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] + src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] + src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] + src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] + src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] + src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] + src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] + src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] + src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_prod(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] * src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] * src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] * src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] * src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] * src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] * src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] * src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] * src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_max(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::max(src0_ptr[i], (T0)src1_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::max(src0_ptr[i], (T0)src1_ptr[i]);
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::max(dst_ptr[i], (T0)src_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::max(dst_ptr[i], (T0)src_ptr[i]);
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::max(src0_ptr[index_in0], (T0)src1_ptr[index_in1]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::max(src0_ptr[index_in0], (T0)src1_ptr[index_in1]);
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::max(dst_ptr[index_out], (T0)src_ptr[index_in]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::max(dst_ptr[index_out], (T0)src_ptr[index_in]);
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_sub(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] - src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] - src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] - src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] - src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] - src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] - src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] - src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] - src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_min(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::min(src0_ptr[i], (T0)src1_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::min(src0_ptr[i], (T0)src1_ptr[i]);
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::min(dst_ptr[i], (T0)src_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::min(dst_ptr[i], (T0)src_ptr[i]);
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::min(src0_ptr[index_in0], (T0)src1_ptr[index_in1]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::min(src0_ptr[index_in0], (T0)src1_ptr[index_in1]);
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::min(dst_ptr[index_out], (T0)src_ptr[index_in]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::min(dst_ptr[index_out], (T0)src_ptr[index_in]);
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_div(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] / src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] / src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] / src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] / src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] / src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] / src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] / src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] / src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_squared_diff(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = (src0_ptr[i] - src1_ptr[i]) * (src0_ptr[i] - src1_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = (src0_ptr[i] - src1_ptr[i]) * (src0_ptr[i] - src1_ptr[i]);
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = (dst_ptr[i] - src_ptr[i]) * (dst_ptr[i] - src_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = (dst_ptr[i] - src_ptr[i]) * (dst_ptr[i] - src_ptr[i]);
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (src0_ptr[index_in0] - src1_ptr[index_in1]) * (src0_ptr[index_in0] - src1_ptr[index_in1]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (src0_ptr[index_in0] - src1_ptr[index_in1]) * (src0_ptr[index_in0] - src1_ptr[index_in1]);
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (dst_ptr[index_out] - src_ptr[index_in]) * (dst_ptr[index_out] - src_ptr[index_in]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (dst_ptr[index_out] - src_ptr[index_in]) * (dst_ptr[index_out] - src_ptr[index_in]);
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_floor_mod(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] - src0_ptr[i] / src1_ptr[i] * src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] - src0_ptr[i] / src1_ptr[i] * src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] - dst_ptr[i] / src_ptr[i] * src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] - dst_ptr[i] / src_ptr[i] * src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] - src0_ptr[index_in1] / src1_ptr[index_in0] * src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] - src0_ptr[index_in1] / src1_ptr[index_in0] * src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] - dst_ptr[index_in] / src_ptr[index_out] * src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] - dst_ptr[index_in] / src_ptr[index_out] * src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_pow(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::pow(src0_ptr[i], src1_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::pow(src0_ptr[i], src1_ptr[i]);
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = std::pow(dst_ptr[i], src_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = std::pow(dst_ptr[i], src_ptr[i]);
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::pow(src0_ptr[index_in0], src1_ptr[index_in1]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::pow(src0_ptr[index_in0], src1_ptr[index_in1]);
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::pow(dst_ptr[index_out], src_ptr[index_in]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = std::pow(dst_ptr[index_out], src_ptr[index_in]);
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_equal(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] == src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] == src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] == src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] == src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] == src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] == src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] == src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] == src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_not_equal(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] != src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] != src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] != src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] != src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] != src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] != src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] != src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] != src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_less(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] < src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] < src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] < src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] < src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] < src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] < src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] < src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] < src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_less_equal(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] <= src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] <= src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] <= src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] <= src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] <= src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] <= src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] <= src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] <= src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_greater(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] > src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] > src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] > src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] > src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] > src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] > src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] > src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] > src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_greater_equal(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] >= src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] >= src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] >= src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] >= src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] >= src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] >= src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] >= src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] >= src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_logical_and(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] && src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] && src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] && src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] && src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] && src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] && src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] && src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] && src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_logical_or(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = src0_ptr[i] || src1_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = src0_ptr[i] || src1_ptr[i];
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = dst_ptr[i] || src_ptr[i];
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = dst_ptr[i] || src_ptr[i];
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] || src1_ptr[index_in1];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = src0_ptr[index_in0] || src1_ptr[index_in1];
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] || src_ptr[index_in];
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = dst_ptr[index_out] || src_ptr[index_in];
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::eltwise_logical_xor(
const T0 *src0_ptr, const T1 *src1_ptr, T0 *dst_ptr, const size_t dst_data_size) {
if (!broadcast) {
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = (src0_ptr[i] || src1_ptr[i]) - (src0_ptr[i] && src1_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = (src0_ptr[i] || src1_ptr[i]) - (src0_ptr[i] && src1_ptr[i]);
});
#endif
for (int j = 2; j < getParentEdges().size(); j++) {
const T1 *src_ptr = reinterpret_cast<const T1*>(getParentEdgeAt(j)->getMemory().GetData()) +
getParentEdgeAt(j)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
#ifdef _WIN32
for (size_t i = 0; i < dst_data_size; i++) {
dst_ptr[i] = (dst_ptr[i] || src_ptr[i]) - (dst_ptr[i] && src_ptr[i]);
}
#else
parallel_for(dst_data_size, [&](size_t i) {
dst_ptr[i] = (dst_ptr[i] || src_ptr[i]) - (dst_ptr[i] && src_ptr[i]);
});
#endif
}
} else {
int dims_out[5], dims_in0[5], dims_in1[5];
int offset_out[5], offset_in0[5], offset_in1[5];
auto& child_edge_dims = getChildEdgeAt(0)->getDims();
auto& parent0_edge_dims = getParentEdgeAt(0)->getDims();
auto& parent1_edge_dims = getParentEdgeAt(1)->getDims();
dims_calc(dims_out, child_edge_dims);
dims_calc(dims_in0, parent0_edge_dims);
dims_calc(dims_in1, parent1_edge_dims);
offset_out_calc(offset_out, dims_out);
offset_in_calc(offset_in0, dims_in0, dims_out);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (src0_ptr[index_in0] || src1_ptr[index_in1]) - (src0_ptr[index_in0] && src1_ptr[index_in1]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in0 = i0 * offset_in0[0] + i1 * offset_in0[1] + i2 * offset_in0[2] + i3 * offset_in0[3] + i4 * offset_in0[4];
size_t index_in1 = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (src0_ptr[index_in0] || src1_ptr[index_in1]) - (src0_ptr[index_in0] && src1_ptr[index_in1]);
});
#endif
for (size_t n = 2; n < getParentEdges().size(); n++) {
const T1 *src_ptr = reinterpret_cast<const T1 *>(getParentEdgeAt(n)->getMemory().GetData()) +
getParentEdgeAt(n)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
auto& parent_edge_dims = getParentEdgeAt(n)->getDims();
dims_calc(dims_in1, parent_edge_dims);
offset_in_calc(offset_in1, dims_in1, dims_out);
#ifdef _WIN32
for (size_t i0 = 0; i0 < dims_out[0]; i0++) {
for (size_t i1 = 0; i1 < dims_out[1]; i1++) {
for (size_t i2 = 0; i2 < dims_out[2]; i2++) {
for (size_t i3 = 0; i3 < dims_out[3]; i3++) {
for (size_t i4 = 0; i4 < dims_out[4]; i4++) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (dst_ptr[index_out] || src_ptr[index_in]) - (dst_ptr[index_out] && src_ptr[index_in]);
}
}
}
}
}
#else
parallel_for5d(dims_out[0], dims_out[1], dims_out[2], dims_out[3], dims_out[4], [&](size_t i0, size_t i1, size_t i2, size_t i3, size_t i4) {
size_t index_out = i0 * offset_out[0] + i1 * offset_out[1] + i2 * offset_out[2] + i3 * offset_out[3] + i4 * offset_out[4];
size_t index_in = i0 * offset_in1[0] + i1 * offset_in1[1] + i2 * offset_in1[2] + i3 * offset_in1[3] + i4 * offset_in1[4];
dst_ptr[index_out] = (dst_ptr[index_out] || src_ptr[index_in]) - (dst_ptr[index_out] && src_ptr[index_in]);
});
#endif
}
}
}
template <typename T0, typename T1> void MKLDNNEltwiseNode::ref_eltwise(int in0, int in1) {
IE_ASSERT(getParentEdges().size() > 1);
auto& srcMemory0 = getParentEdgeAt(in0)->getMemory();
auto& srcMemory1 = getParentEdgeAt(in1)->getMemory();
const T0 *src0_ptr = reinterpret_cast<const T0*>(srcMemory0.GetData()) +
srcMemory0.GetDescriptor().data.layout_desc.blocking.offset_padding;
const T1 *src1_ptr = reinterpret_cast<const T1*>(srcMemory1.GetData()) +
srcMemory1.GetDescriptor().data.layout_desc.blocking.offset_padding;
T0 *dst_ptr = reinterpret_cast<T0*>(getChildEdgeAt(0)->getMemory().GetData()) +
getChildEdgeAt(0)->getMemory().GetDescriptor().data.layout_desc.blocking.offset_padding;
const size_t dst_data_size = srcMemory0.GetSize() / sizeof(T0) / srcMemory0.GetDims()[0] * batchToProcess();
switch (op) {
case EltwiseLayer::eOperation::Sum: eltwise_add(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Prod: eltwise_prod(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Max: eltwise_max(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Sub: eltwise_sub(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Min: eltwise_min(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Div: eltwise_div(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Squared_diff: eltwise_squared_diff(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Floor_mod: eltwise_floor_mod(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Pow: eltwise_pow(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Equal: eltwise_equal(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Not_equal: eltwise_not_equal(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Less: eltwise_less(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Less_equal: eltwise_less_equal(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Greater: eltwise_greater(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Greater_equal: eltwise_greater_equal(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Logical_AND: eltwise_logical_and(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Logical_OR: eltwise_logical_or(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
case EltwiseLayer::eOperation::Logical_XOR: eltwise_logical_xor(src0_ptr, src1_ptr, dst_ptr, dst_data_size); break;
default: THROW_IE_EXCEPTION << "Unsupported operation type for Eltwise node";
}
}
void MKLDNNEltwiseNode::execute(mkldnn::stream strm) {
if (prim) {
MKLDNNNode::execute(strm);
} else {
if (op == EltwiseLayer::Floor_mod) {
for (size_t i = 0; i < getParentEdges().size(); i++)
if (getParentEdgeAt(i)->getDesc().getPrecision() != Precision::I32)
THROW_IE_EXCEPTION << "Floor_mod supports only I32 precision of inputs";
if (getChildEdgeAt(0)->getDesc().getPrecision() != Precision::I32)
THROW_IE_EXCEPTION << "Floor_mod supports only I32 precision of output";
}
if (getParentEdges().size() > 2) {
Precision pi = getParentEdgeAt(0)->getDesc().getPrecision();
Precision po = getChildEdgeAt(0)->getDesc().getPrecision();
for (int i = 1; i < getParentEdges().size(); i++) {
if (getParentEdgeAt(i)->getDesc().getPrecision() != pi)
THROW_IE_EXCEPTION << "If Eltwise node has more than 2 inputs, all inputs must have same precision";
}
if (pi != po) {
THROW_IE_EXCEPTION << "If Eltwise node has more than 2 inputs, all inputs and output must have same precision";
}
if (pi == Precision::FP32)
ref_eltwise<float, float>(0, 1);
else if (pi == Precision::I32)
ref_eltwise<int32_t, int32_t>(0, 1);
else if (pi == Precision::I8)
ref_eltwise<int8_t, int8_t>(0, 1);
else if (pi == Precision::U8)
ref_eltwise<uint8_t, uint8_t>(0, 1);
else
THROW_IE_EXCEPTION << "If Eltwise node has more than 2 inputs, only FP32, I32, I8, U8 are supported";
return;
}
Precision pi0 = getParentEdgeAt(0)->getDesc().getPrecision();
Precision pi1 = getParentEdgeAt(1)->getDesc().getPrecision();
Precision po = getChildEdgeAt(0)->getDesc().getPrecision();
IE_ASSERT(getParentEdges().size() > 1);
if (po == Precision::FP32 && pi0 == po && pi1 == po) {
ref_eltwise<float, float>(0, 1);
} else if (po == Precision::FP32 && pi0 == po && pi1 == Precision::I8) {
ref_eltwise<float, int8_t>(0, 1);
} else if (po == Precision::FP32 && pi1 == po && pi0 == Precision::I8) {
ref_eltwise<float, int8_t>(1, 0);
} else if (po == Precision::FP32 && pi0 == po && pi1 == Precision::U8) {
ref_eltwise<float, uint8_t>(0, 1);
} else if (po == Precision::FP32 && pi1 == po && pi0 == Precision::U8) {
ref_eltwise<float, uint8_t>(1, 0);
} else if (po == Precision::I8 && pi0 == po && pi1 == po) {
ref_eltwise<int8_t, int8_t>(0, 1);
} else if (po == Precision::I8 && pi0 == po && pi1 == Precision::U8) {
ref_eltwise<int8_t, uint8_t>(0, 1);
} else if (po == Precision::I8 && pi1 == po && pi0 == Precision::U8) {
ref_eltwise<int8_t, uint8_t>(1, 0);
} else if (po == Precision::I32 && pi0 == po && pi1 == po) {
ref_eltwise<int32_t, int32_t>(0, 1);
}
}
}
bool MKLDNNEltwiseNode::created() const {
return getType() == Eltwise;
}
bool MKLDNNEltwiseNode::canBeInPlace() const {
size_t inPlaceWithParent = getParentEdges().size();
for (size_t i = 0; i < inPlaceWithParent; i++) {
auto parentEdge = getParentEdgeAt(i);
if (!parentEdge->getParent()->isConstant() &&
parentEdge->getParent()->getChildEdges().size() == 1) {
inPlaceWithParent = i;
break;
}
}
// This is WA for MKLDNN implementation
if (inPlaceWithParent != 0)
return false;
MKLDNNDims dims = getParentEdgeAt(0)->getDims();
for (size_t cIdx = 0; cIdx < getChildEdges().size(); cIdx++) {
if (getChildEdgeAt(cIdx)->getDims() != dims) {
return false;
}
}
return true;
}
|
phumoonlight/ossuary | university-c-training/HwLab/HwLab2.1_353.c | #include<stdio.h>
int main ()
{
char pro[20];
float price,total,dis,amount;
int unit;
printf("Enter product = ");
scanf("%s",pro);
printf("Enter price = ");
scanf("%f",&price);
printf("Enter unit = ");
scanf("%d",&unit);
total=price*unit;
if(total>=1&&total<=100)
{
dis=total*0.05;
}else if(total>=101&&total<=500)
{
dis=total*0.1;
}else if(total>=501&&total<=1000)
{
dis=total*0.15;
}else if(total>=1001)
{
dis=total*0.2;
}else{
printf("Error");
}
amount=total-dis;
printf("\n---------------------------------------------\n");
printf("Product = %s \n",pro);
printf("Discount = %.2f\n",dis);
printf("Amount = %.2f\n",amount);
system("pause");
return 0;
}
|
andBrandCo/AMA-txtdata | react-src/src/redux/actions/recordsActions.js | <reponame>andBrandCo/AMA-txtdata
export const types = {
GET_ALL_RECORD: "GET_ALL_RECORD",
GET_ALL_RECORD_CSV: "GET_ALL_RECORD_CSV",
SEND_REPORT_TO_SERVER: "SEND_REPORT_TO_SERVER"
};
const getAllRecordRequest = payload => ({
type: `${types.GET_ALL_RECORD}_REQUEST`,
payload
});
const getAllRecordSuccess = payload => ({
type: `${types.GET_ALL_RECORD}_SUCCESS`,
payload
});
const getAllRecordFailed = error => ({
type: `${types.GET_ALL_RECORD}_FAILED`,
payload: error
});
const getAllRecordCSVRequest = payload => ({
type: `${types.GET_ALL_RECORD_CSV}_REQUEST`,
payload
});
const getAllRecordCSVSuccess = payload => ({
type: `${types.GET_ALL_RECORD_CSV}_SUCCESS`,
payload
});
const getAllRecordCSVFailed = error => ({
type: `${types.GET_ALL_RECORD_CSV}_FAILED`,
payload: error
});
const sendReportRequest = payload => ({
type: `${types.SEND_REPORT_TO_SERVER}_REQUEST`,
payload
});
const sendReportSuccess = payload => ({
type: `${types.SEND_REPORT_TO_SERVER}_SUCCESS`,
payload
});
const sendReportFailed = error => ({
type: `${types.SEND_REPORT_TO_SERVER}_FAILED`,
payload: error
});
export const actions = {
getAllRecordRequest,
getAllRecordSuccess,
getAllRecordFailed,
getAllRecordCSVRequest,
getAllRecordCSVSuccess,
getAllRecordCSVFailed,
sendReportRequest,
sendReportSuccess,
sendReportFailed
};
|
Zenitram-Oriaj/Room-Finder-And-Scheduler | server/applications/Controllers/services/monitor.js | <gh_stars>0
/**
* Created by <NAME> on 10/13/14.
*/
var async = require('async');
var xml2js = require('xml2js');
var log = {};
var cfg = {};
function XmlToJson(xml, cb) {
var parser = new xml2js.Parser({
mergeAttrs: true
});
parser.parseString(xml, function (err, result) {
if (err) {
cb(null, err);
} else {
cb(null, result);
}
});
}
function SendReq(url, cb) {
var req = require('request');
var e = {
code: 0,
message: '',
xml: '',
err: {}
};
var opts = {
url: url,
timeout: 5000
};
req(opts, function (err, res, body) {
if (err) {
e.code = err.code;
e.xml = '<IPSensorError>\n<Failed reason="' + e.code + '"></Failed>\n</IPSensorError>';
e.err = err;
e.message = 'Failed';
cb(e, null);
} else {
var str = body.replace(/(\r\n|\n|\r)/gm, "");
str = str.replace(/\s+/gm, " ");
cb(null, str);
}
});
}
function CheckController(ct, cb) {
var url = 'http://' + ct.ip + '/settings_m2m?';
try {
SendReq(url, function (err, res) {
if (err) {
cb(null, err.xml);
} else {
cb(null, res);
}
});
}
catch(ex){
ex.xml = '<IPSensorError>\n<Failed reason="Exception"></Failed>\n</IPSensorError>';
cb(null,ex.xml)
}
}
function CheckState(ct, cb) {
var url = 'http://' + ct.ip + '/setoutputs?password=' + ct.password + '&value=x';
SendReq(url, function (err, res) {
if (err) {
cb(null, null);
} else {
XmlToJson(res, function (err, jsn) {
if (err) {
cb(err, null);
} else {
var i = parseInt(jsn.IPSensorResponse.GPIOOutputs[0].state[0], 10);
if (ct.state != i) {
ct.state = i;
ct.save();
}
cb(null, jsn);
}
});
}
});
}
function CheckHeartbeat(ct) {
var dt = new Date();
if (ct.heartbeatAt) {
var offset = dt.getTime() - ct.heartbeatAt.getTime();
var refVal = (6 * 60 * 1000);
return (offset > refVal);
} else {
return false;
}
}
function RebootCtrl(ct, cb) {
var url = 'http://' + ct.ip + '/reboot?password=' + ct.password;
SendReq(url, function (err, res) {
cb(err, res);
});
}
function CheckAutoReboot(ct) {
if (ct.autoReboot == 1 || ct.uptime > cfg.ctrl.maxUpTime) {
var dt = new Date();
if (dt.getHours() < 5 || dt.getHours >= 22) {
RebootCtrl(ct, function (err, res) {
if (err) {
console.error(err);
}
});
}
}
}
function UpdateDiscoverStatus(cb) {
CollectControllers(function (err, cts) {
if (err) {
cb(err, null);
} else {
CollectDiscover(function (err, dsc) {
if (err) {
cb(err, null);
} else {
for (var i in dsc) {
if (dsc[i].added == 'no') {
for (var j in cts) {
if (cts[j].uuid == dsc[i].uuid && cts[j].workspaceUuid && cts[j].workspaceUuid.length > 0) {
dsc[i].added = 'yes';
dsc[i].addedAt = new Date();
dsc[i].save();
break;
}
}
}
}
cb(null, 'OK');
}
});
}
});
}
function CollectDiscover(cb) {
db.Discover.findAll({where: {typeDev: 'IPS'}}).then(
function (ds) {
if (ds) {
cb(null, ds);
} else {
cb('No Discovered Controllers Found', null);
}
},
function (err) {
cb(err, null);
});
}
function CollectControllers(cb) {
db.Controller.findAll().then(
function (cts) {
cb(null, cts);
},
function (err) {
cb(err, null);
});
}
/////////////////////////////////////////////////////////////////////////////
// Module Exports
module.exports.config = function(c){
cfg = c || {};
};
module.exports.check = function (cb) {
try {
UpdateDiscoverStatus(function (err, res) {
cb(err, res);
});
}
catch (ex) {
cb(ex, null);
}
};
module.exports.init = function (cb) {
try {
CollectControllers(function (err, cts) {
if (err) {
console.error(err);
cb(err, null);
} else {
var Ctrls = [];
for (var i in cts) {
if (cts[i].status == 'ONLINE') Ctrls.push(cts[i]);
}
if (Ctrls.length > 0) {
async.mapSeries(Ctrls, CheckState, function (err, res) {
cb(err, res);
});
}
}
});
}
catch (ex) {
cb(ex, null);
}
};
module.exports.run = function () {
try {
CollectControllers(function (err, cts) {
if (err) {
console.error(err);
} else {
var Ctrls = [];
if (cts && cts.length > 0) {
cts.forEach(function (ct) {
CheckAutoReboot(ct);
if (CheckHeartbeat(ct)) {
if (ct.status == 'ONLINE') {
log = new po.SysLog('controller', 'error', 'Controller OFFLINE :: ' + ct.uuid);
updateSysLog(log);
ct.status = 'OFFLINE';
ct.save();
}
Ctrls.push(ct);
} else {
if (ct.status == 'OFFLINE') {
log = new po.SysLog('controller', 'info', 'Controller is now ONLINE :: ' + ct.uuid);
updateSysLog(log);
ct.status = 'ONLINE';
ct.save();
}
}
});
}
if (Ctrls.length > 0) {
async.mapSeries(Ctrls, CheckController, function (err, results) {
if (err) {
} else {
async.mapSeries(results, XmlToJson, function (err, json) {
});
}
});
}
}
});
}
catch (ex) {
log = new po.SysLog('controller', 'error', 'Monitor Run Service Had Exception :: ' + JSON.stringify(ex));
updateSysLog(log);
}
}; |
huangbop/seadroid-build | seadroid/src/main/java/com/seafile/seadroid2/ui/activity/AccountDetailActivity.java | <filename>seadroid/src/main/java/com/seafile/seadroid2/ui/activity/AccountDetailActivity.java
package com.seafile.seadroid2.ui.activity;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.seafile.seadroid2.CertsManager;
import com.seafile.seadroid2.ConcurrentAsyncTask;
import com.seafile.seadroid2.R;
import com.seafile.seadroid2.SeafConnection;
import com.seafile.seadroid2.SeafException;
import com.seafile.seadroid2.account.Account;
import com.seafile.seadroid2.account.AccountManager;
import com.seafile.seadroid2.ui.CustomClearableEditText;
import com.seafile.seadroid2.ui.dialog.SslConfirmDialog;
import com.seafile.seadroid2.util.Utils;
public class AccountDetailActivity extends SherlockFragmentActivity {
private static final String DEBUG_TAG = "AccountDetailActivity";
private static final String HTTP_PREFIX = "http://";
private static final String HTTPS_PREFIX = "https://";
private TextView statusView;
private Button loginButton;
private EditText serverText;
private CustomClearableEditText emailText;
private CustomClearableEditText passwdText;
private CheckBox httpsCheckBox;
private TextView seahubUrlHintText;
private AccountManager accountManager;
private Account account = null;
private boolean isFromEdit = false;
private boolean serverTextHasFocus;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This has to be called before setContentView and you must use the
//class in com.actionbarsherlock.view and NOT android.view
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.account_detail);
statusView = (TextView) findViewById(R.id.status_view);
loginButton = (Button) findViewById(R.id.login_button);
httpsCheckBox = (CheckBox) findViewById(R.id.https_checkbox);
serverText = (EditText) findViewById(R.id.server_url);
emailText = (CustomClearableEditText) findViewById(R.id.email_address);
emailText.setInputType(CustomClearableEditText.INPUT_TYPE_EMAIL);
passwdText = (CustomClearableEditText) findViewById(R.id.password);
passwdText.setInputType(CustomClearableEditText.INPUT_TYPE_PASSWORD);
seahubUrlHintText = (TextView) findViewById(R.id.seahub_url_hint);
setupServerText();
accountManager = new AccountManager(this);
// email address auto complete when login in
ArrayList<String> accounts = accountManager.getAccountAutoCompleteTexts();
if (accounts != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, accounts);
emailText.setEmailAddressAutoCompleteAdapter(adapter);
}
Intent intent = getIntent();
String server = intent.getStringExtra("server");
String email = intent.getStringExtra("email");
isFromEdit = intent.getBooleanExtra("isEdited", false);
if (server != null) {
if (email == null) email = "";
account = new Account(server, email);
if (account.isHttps())
httpsCheckBox.setChecked(true);
serverText.setText(account.getServer());
emailText.setText(account.getEmail());
emailText.requestFocus();
seahubUrlHintText.setVisibility(View.GONE);
} else {
serverText.setText(HTTP_PREFIX);
int prefixLen = HTTP_PREFIX.length();
serverText.setSelection(prefixLen, prefixLen);
}
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("email", emailText.getText().toString());
savedInstanceState.putString("password", passwdText.getText().toString());
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
emailText.setText((String) savedInstanceState.get("email"));
passwdText.setText((String) savedInstanceState.get("password"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
/* FYI {@link http://stackoverflow.com/questions/13293772/how-to-navigate-up-to-the-same-parent-state?rq=1} */
Intent upIntent = new Intent(this, AccountsActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is NOT part of this app's task, so create a new task
// when navigating up, with a synthesized back stack.
TaskStackBuilder.create(this)
// Add all of this activity's parents to the back stack
.addNextIntentWithParentStack(upIntent)
// Navigate up to the closest parent
.startActivities();
} else {
// This activity is part of this app's task, so simply
// navigate up to the logical parent activity.
// NavUtils.navigateUpTo(this, upIntent);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(upIntent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void onHttpsCheckboxClicked(View view) {
refreshServerUrlPrefix();
}
private void refreshServerUrlPrefix() {
boolean isHttps = httpsCheckBox.isChecked();
String url = serverText.getText().toString();
String prefix = isHttps ? HTTPS_PREFIX : HTTP_PREFIX;
String urlWithoutScheme = url.replace(HTTPS_PREFIX, "").replace(HTTP_PREFIX, "");
int oldOffset = serverText.getSelectionStart();
// Change the text
serverText.setText(prefix + urlWithoutScheme);
if (serverTextHasFocus) {
// Change the cursor position since we changed the text
if (isHttps) {
int offset = oldOffset + 1;
serverText.setSelection(offset, offset);
} else {
int offset = Math.max(0, oldOffset - 1);
serverText.setSelection(offset, offset);
}
}
}
private void setupServerText() {
serverText.setOnFocusChangeListener(new View.OnFocusChangeListener () {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d(DEBUG_TAG, "serverText has focus: " + (hasFocus ? "yes" : "no"));
serverTextHasFocus = hasFocus;
}
});
serverText.addTextChangedListener(new TextWatcher() {
private String old;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
old = serverText.getText().toString();
}
@Override
public void afterTextChanged(Editable s) {
// Don't allow the user to edit the "https://" or "http://" part of the serverText
String url = serverText.getText().toString();
boolean isHttps = httpsCheckBox.isChecked();
String prefix = isHttps ? HTTPS_PREFIX : HTTP_PREFIX;
if (!url.startsWith(prefix)) {
int oldOffset = Math.max(prefix.length(), serverText.getSelectionStart());
serverText.setText(old);
serverText.setSelection(oldOffset, oldOffset);
}
}
});
}
/** Called when the user clicks the Login button */
public void login(View view) {
String serverURL = serverText.getText().toString().trim();
String email = emailText.getText().toString().trim();
String passwd = passwdText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (serverURL.length() == 0) {
statusView.setText(R.string.err_server_andress_empty);
return;
}
if (email.length() == 0) {
emailText.setError(getResources().getString(R.string.err_email_empty));
return;
}
if (passwd.length() == 0) {
passwdText.setError(getResources().getString(R.string.err_passwd_empty));
return;
}
try {
serverURL = Utils.cleanServerURL(serverURL);
} catch (MalformedURLException e) {
statusView.setText(R.string.invalid_server_address);
Log.d(DEBUG_TAG, "Invalid URL " + serverURL);
return;
}
loginButton.setEnabled(false);
Account tmpAccount = new Account(serverURL, email, passwd);
ConcurrentAsyncTask.execute(new LoginTask(tmpAccount));
} else {
statusView.setText(R.string.network_down);
}
}
private void startFilesActivity(Account account) {
Intent intent = new Intent(this, BrowserActivity.class);
intent.putExtra("server", account.server);
intent.putExtra("email", account.email);
intent.putExtra("token", account.token);
startActivity(intent);
finish(); // so the user will not return to this activity when press 'back'
}
private class LoginTask extends AsyncTask<Void, Void, String> {
Account loginAccount;
SeafException err = null;
public LoginTask(Account loginAccount) {
this.loginAccount = loginAccount;
}
@Override
protected void onPreExecute() {
//super.onPreExecute();
setSupportProgressBarIndeterminateVisibility(true);
}
@Override
protected String doInBackground(Void... params) {
if (params.length != 0)
return "Error number of parameter";
return doLogin();
}
private void resend() {
ConcurrentAsyncTask.execute(new LoginTask(loginAccount));
}
@Override
protected void onPostExecute(final String result) {
if (err == SeafException.sslException) {
SslConfirmDialog dialog = new SslConfirmDialog(loginAccount,
new SslConfirmDialog.Listener() {
@Override
public void onAccepted(boolean rememberChoice) {
CertsManager.instance().saveCertForAccount(loginAccount, rememberChoice);
resend();
}
@Override
public void onRejected() {
statusView.setText(result);
loginButton.setEnabled(true);
}
});
dialog.show(getSupportFragmentManager(), SslConfirmDialog.FRAGMENT_TAG);
return;
}
if (result != null && result.equals("Success")) {
if (isFromEdit) {
accountManager.updateAccountFromDB(account, loginAccount);
isFromEdit = false;
} else {
accountManager.saveAccountToDB(loginAccount);
}
// save account to SharedPreference
accountManager.saveCurrentAccount(loginAccount);
startFilesActivity(loginAccount);
} else {
statusView.setText(result);
}
setSupportProgressBarIndeterminateVisibility(false);
loginButton.setEnabled(true);
}
private String doLogin() {
SeafConnection sc = new SeafConnection(loginAccount);
try {
if (!sc.doLogin())
return getString(R.string.err_login_failed);
return "Success";
} catch (SeafException e) {
err = e;
if (e == SeafException.sslException) {
return getString(R.string.ssl_error);
}
switch (e.getCode()) {
case HttpURLConnection.HTTP_BAD_REQUEST:
return getString(R.string.err_wrong_user_or_passwd);
case HttpURLConnection.HTTP_NOT_FOUND:
return getString(R.string.invalid_server_address);
default:
return e.getMessage();
}
}
}
}
}
|
koty08/JAVA_PBP | week8-lambda_stream/hw/com/fm/unit/Player.java | <reponame>koty08/JAVA_PBP
public class Player {
public static int ID = 0;
public static int NAME = 1;
public static int HEIGHT = 2;
public static int NATIONALITY = 3;
public static int CLUB = 4;
public static int OVERALL = 5;
public static int POSITION = 6;
private final int id;
private final String name;
private final int height;
private final String nationality;
private final String club;
private final int overall;
private final List<String> positions;
public Player(int id, String name, int height, String nationality, String club, int overall, List<String> positions){
this.id = id;
this.name = name;
this.height = height;
this.nationality = nationality;
this.club = club;
this.overall = overall;
this.positions = positions;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getHeight() {
return height;
}
public String getNationality() {
return nationality;
}
public String getClub() {
return club;
}
public int getOverall() {
return overall;
}
public List<String> getPositions() {
return positions;
}
@Override
public String toString() {
return String.valueOf(id);
}
} |
givanse/ember-simple-auth | packages/ember-simple-auth/tests/simple-auth/utils/objects-are-equal-test.js | import objectsAreEqual from 'simple-auth/utils/objects-are-equal';
describe('Utils.objectsAreEqual', function() {
it('is true for equal objects', function() {
expect(objectsAreEqual({ a: 'b', c: 'd' }, { a: 'b', c: 'd' })).to.be.true;
});
it('is true for equal objects regardless of property order', function() {
expect(objectsAreEqual({ a: 'b', c: 'd' }, { c: 'd', a: 'b' })).to.be.true;
});
it('is true for equal nested objects regardless of property order', function() {
expect(objectsAreEqual({ a: 'b', c: 'd', e: { f: 'g' } }, { e: { f: 'g' }, a: 'b', c: 'd' })).to.be.true;
});
it('is false for unequal objects', function() {
expect(objectsAreEqual({ a: 'b' }, { c: 'd' })).to.be.false;
});
});
|
LigthWarrior/frontend-course-2020 | homeworks/daria.zahrebelna_Angel-88/4-modules/script.js | import {
getFridaysOfMonth,
isMonthLong,
fullWeeksNumberInMonth,
shortestWeekDaysNumber,
} from './time.js';
const date = document.querySelector('[data-date]');
const buttonGetMonthFridays = document.querySelector('[data-button-get-month-fridays]');
const fridaysInMonth = document.querySelector('[data-fridays-in-month]');
const buttonIsMonthLong = document.querySelector('[data-button-is-month-long]');
const lengthInMonth = document.querySelector('[data-length-in-month]');
const buttonFullWeeks = document.querySelector('[data-button-full-weeks]');
const fullWeeks = document.querySelector('[data-full-weeks]');
const buttonDayOfShortestWeek = document.querySelector('[data-button-day-of-shortest-week]');
const dayOfShortestWeek = document.querySelector('[data-day-of-shortest-week]');
buttonGetMonthFridays.addEventListener('click', () => {
if (!date.value) return;
fridaysInMonth.innerText = getFridaysOfMonth(new Date(date.value));
});
buttonIsMonthLong.addEventListener('click', () => {
if (!date.value) return;
lengthInMonth.innerText = isMonthLong(new Date(date.value));
});
buttonDayOfShortestWeek.addEventListener('click', () => {
if (!date.value) return;
dayOfShortestWeek.innerText = shortestWeekDaysNumber(new Date(date.value));
});
buttonFullWeeks.addEventListener('click', () => {
if (!date.value) return;
fullWeeks.innerText = fullWeeksNumberInMonth(new Date(date.value));
});
|
saqsham/one | src/fireedge/src/public/containers/Application/Deploy.js | /* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import React, { useEffect } from 'react';
import {
makeStyles,
Card,
Chip,
CardContent,
Typography,
LinearProgress,
Box
} from '@material-ui/core';
import useGeneral from 'client/hooks/useGeneral';
import useOpennebula from 'client/hooks/useOpennebula';
const useStyles = makeStyles({
card: {
minWidth: 275,
marginBottom: '2em'
},
title: {
fontSize: 14
}
});
function ApplicationDeploy() {
const classes = useStyles();
const { isLoading } = useGeneral();
const { groups, getUsers } = useOpennebula();
useEffect(() => {
if (!isLoading) {
getUsers();
}
}, [getUsers]);
const getGroupById = findId => groups?.find(({ ID }) => ID === findId);
return (
<>
{isLoading && <LinearProgress style={{ width: '100%' }} />}
Deploy
</>
);
}
ApplicationDeploy.propTypes = {};
ApplicationDeploy.defaultProps = {};
export default ApplicationDeploy;
|
hamidgasmi/training.computerscience.algorithms-datastructures | 02-data-sructures-fundamentals/5_binary_search_trees/is_bst.py | <reponame>hamidgasmi/training.computerscience.algorithms-datastructures
import sys, threading
# In Order Traversal of the Tree:
# Time Complexity: O(n)
# Space Complxity: O(height)
def IsBinarySearchTree(tree, v, inOrderTraversal):
if len(tree) < 2:
return True
if tree[v][1] != -1 and not IsBinarySearchTree(tree, tree[v][1], inOrderTraversal):
return False
if len(inOrderTraversal) == 1 and inOrderTraversal[0] >= tree[v][0]:
return False
if len(inOrderTraversal) == 0:
inOrderTraversal.append(tree[v][0])
else:
inOrderTraversal[0] = tree[v][0]
if tree[v][2] == -1:
return True
else:
return IsBinarySearchTree(tree, tree[v][2], inOrderTraversal)
def main():
nodes = int(sys.stdin.readline().strip())
tree = []
for i in range(nodes):
tree.append(list(map(int, sys.stdin.readline().strip().split())))
inOrderTraversal = []
if IsBinarySearchTree(tree, 0, inOrderTraversal):
print("CORRECT")
else:
print("INCORRECT")
if __name__ == '__main__':
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()
|
plbogen/MinorThird | src/main/java/LBJ2/classify/RealReferrer.java | <filename>src/main/java/LBJ2/classify/RealReferrer.java
package LBJ2.classify;
import LBJ2.learn.ChildLexicon;
import LBJ2.learn.Lexicon;
import LBJ2.util.ByteString;
import LBJ2.util.ExceptionlessInputStream;
import LBJ2.util.ExceptionlessOutputStream;
/**
* A referring real feature is one that has its own identifier, but whose
* value comes from a separate feature that it refers to.
*
* @author <NAME>
**/
public abstract class RealReferrer extends RealFeature
{
/** The feature being referred to. */
protected RealFeature referent;
/**
* For internal use only.
*
* @see Feature#readFeature(ExceptionlessInputStream)
**/
protected RealReferrer() { }
/**
* Sets both the identifier and the referent.
*
* @param c The classifier that produced this feature.
* @param r The real feature referred to by this new feature.
**/
public RealReferrer(Classifier c, RealFeature r) {
this(c.containingPackage, c.name, r);
}
/**
* Sets both the identifier and the referent.
*
* @param p The new real feature's package.
* @param c The name of the classifier that produced this feature.
* @param r The real feature referred to by this new feature.
**/
public RealReferrer(String p, String c, RealFeature r) {
super(p, c);
referent = r;
}
/**
* Determines if this feature is a referring feature.
*
* @return <code>true</code> iff this feature is a referring feature.
**/
public boolean isReferrer() { return true; }
/** Returns the value of {@link #referent}. */
public RealFeature getReferent() { return referent; }
/**
* The depth of a feature is one more than the maximum depth of any of its
* children, or 0 if it has no children.
*
* @return The depth of this feature as described above.
**/
public int depth() { return referent.depth() + 1; }
/** Simply returns the strength of {@link #referent}. */
public double getStrength() { return referent.getStrength(); }
/**
* Takes care of any feature-type-specific tasks that need to be taken care
* of when removing a feature of this type from a {@link ChildLexicon}, in
* particular updating parent counts and removing children of this feature
* if necessary.
*
* @param lex The child lexicon this feature is being removed from.
**/
public void removeFromChildLexicon(ChildLexicon lex) {
lex.decrementParentCounts(referent);
}
/**
* Does a feature-type-specific lookup of this feature in the given
* {@link ChildLexicon}.
*
* @param lex The child lexicon this feature is being looked up in.
* @param label The label of the example containing this feature, or -1 if
* we aren't doing per class feature counting.
* @return The index of <code>f</code> in this lexicon.
**/
public int childLexiconLookup(ChildLexicon lex, int label) {
return lex.childLexiconLookup(this, label);
}
/**
* The hash code of a <code>RealReferrer</code> is the sum of the hash
* codes of the containing package, the identifier, and the referent
* feature.
*
* @return The hash code for this feature.
**/
public int hashCode() {
return 17 * super.hashCode() + referent.hashCode();
}
/**
* Used to sort features into an order that is convenient both to page
* through and for the lexicon to read off disk.
*
* @param o An object to compare with.
* @return Integers appropriate for sorting features first by package, then
* by identifier, then by value.
**/
public int compareTo(Object o) {
int d = compareNameStrings(o);
if (d != 0) return d;
RealReferrer r = (RealReferrer) o;
if (d != 0) return d;
return referent.compareTo(r.referent);
}
/**
* Writes a string representation of this <code>Feature</code> to the
* specified buffer.
*
* @param buffer The buffer to write to.
**/
public void write(StringBuffer buffer) {
writeNameString(buffer);
buffer.append("->");
referent.write(buffer);
}
/**
* Writes a string representation of this <code>Feature</code> to the
* specified buffer, omitting the package name.
*
* @param buffer The buffer to write to.
**/
public void writeNoPackage(StringBuffer buffer) {
String p = containingPackage;
containingPackage = null;
writeNameString(buffer);
buffer.append("->");
referent.writeNoPackage(buffer);
containingPackage = p;
}
/**
* Writes a complete binary representation of the feature.
*
* @param out The output stream.
**/
public void write(ExceptionlessOutputStream out) {
super.write(out);
referent.write(out);
}
/**
* Reads the representation of a feaeture with this object's run-time type
* from the given stream, overwriting the data in this object.
*
* @param in The input stream.
**/
public void read(ExceptionlessInputStream in) {
super.read(in);
referent = (RealFeature) Feature.readFeature(in);
}
/**
* Writes a binary representation of the feature intended for use by a
* lexicon, omitting redundant information when possible.
*
* @param out The output stream.
* @param lex The lexicon out of which this feature is being written.
* @param c The fully qualified name of the assumed class. The runtime
* class of this feature won't be written if it's equivalent to
* <code>c</code>.
* @param p The assumed package string. This feature's package string
* won't be written if it's equivalent to <code>p</code>.
* @param g The assumed classifier name string. This feature's
* classifier name string won't be written if it's equivalent
* to <code>g</code>.
* @param si The assumed identifier as a string. If this feature has a
* string identifier, it won't be written if it's equivalent to
* <code>si</code>.
* @param bi The assumed identifier as a byte string. If this feature
* has a byte string identifier, it won't be written if it's
* equivalent to <code>bi</code>.
* @return The name of the runtime type of this feature.
**/
public String lexWrite(ExceptionlessOutputStream out, Lexicon lex, String c,
String p, String g, String si, ByteString bi) {
String result = super.lexWrite(out, lex, c, p, g, si, bi);
out.writeInt(lex.lookupChild(referent));
return result;
}
/**
* Reads the representation of a feature with this object's run-time type
* as stored by a lexicon, overwriting the data in this object.
*
* <p> This method is appropriate for reading features as written by
* {@link #lexWrite(ExceptionlessOutputStream,Lexicon,String,String,String,String,ByteString)}.
*
* @param in The input stream.
* @param lex The lexicon we are reading in to.
* @param p The assumed package string. If no package name is given in
* the input stream, the instantiated feature is given this
* package.
* @param g The assumed classifier name string. If no classifier name
* is given in the input stream, the instantiated feature is
* given this classifier name.
* @param si The assumed identifier as a string. If the feature being
* read has a string identifier field and no identifier is
* given in the input stream, the feature is given this
* identifier.
* @param bi The assumed identifier as a byte string. If the feature
* being read has a byte string identifier field and no
* identifier is given in the input stream, the feature is
* given this identifier.
**/
public void lexRead(ExceptionlessInputStream in, Lexicon lex, String p,
String g, String si, ByteString bi) {
super.lexRead(in, lex, p, g, si, bi);
referent = (RealFeature) lex.lookupKey(in.readInt());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.