repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
f-cazzola/hypermedia-2019-alterio-antichi-cazzola | api/v1/routes/company.js | <filename>api/v1/routes/company.js<gh_stars>0
const express = require('express');
const router = express.Router();
const companyController = require('../controller/company');
router.get('/', companyController.getCompanies);
router.post('/', companyController.postCompany);
router.get('/event/:eventId', companyController.getCompaniesByEvent);
router.get('/:companyId', companyController.getCompanyById);
module.exports = router; |
luispc111/Competitive-Programming-2019 | 2019_SemanaiCompetitiveProgramming/ProblemC_PetyaAndOrigami.cpp | <reponame>luispc111/Competitive-Programming-2019<filename>2019_SemanaiCompetitiveProgramming/ProblemC_PetyaAndOrigami.cpp
// PROBLEM
// http://codeforces.com/problemset/problem/1080/A
#include <iostream>
using namespace std;
int main(){
long long int invitados, sheets, total=0;
cin >> invitados >> sheets;
int red = 2*invitados/sheets;
int blue = 5*invitados/sheets;
int green = 8*invitados/sheets;
total = red+blue+green;
if(2*invitados % sheets != 0){
total++;
}
if(5*invitados % sheets != 0){
total++;
}
if(8*invitados % sheets != 0){
total++;
}
cout << total << endl;
return 0;
}
|
pralphv/stripe_color_system_clone | src/components/ColorGradient/ColorGradient.js | <filename>src/components/ColorGradient/ColorGradient.js
import React from "react";
import PropTypes from "prop-types";
import ColorBox from "../ColorBox";
import { ID_DELIMITER } from "../../constants/colorGradient";
const ColorGradient = ({ colorGradient, handleOnClick, onClick, id }) => {
const oneLineStyle = { display: "flex", flexDirection: "row" };
return (
<div style={oneLineStyle}>
{Object.entries(colorGradient).map(([key, value]) => (
<ColorBox
lch={value.lch}
key={`${key}-gradient`}
active={value.active}
onClick={onClick}
id={`${id}${ID_DELIMITER}${key}`}
contrast={value.contrast}
/>
))}
</div>
);
};
ColorGradient.propTypes = {
colorGradient: PropTypes.object,
handleOnClick: PropTypes.func,
onClick: PropTypes.func.isRequired,
id: PropTypes.string.isRequired
};
export default ColorGradient;
|
Imperi13/cp-library | lib/UnionFind/PotentialUnionFind.hpp | <reponame>Imperi13/cp-library
#pragma once
#include <cassert>
#include <numeric>
#include <vector>
template <typename Group>
class PotentialUnionFind {
public:
using value_t = typename Group::value_t;
using size_t = std::size_t;
private:
size_t group;
std::vector<size_t> par, sz;
std::vector<value_t> df; // val[par]=val[x]+df[x]
value_t fold_to_root(size_t x) {
value_t ret = Group::id;
while (par[x] != x) {
df[x] = Group::op(df[x], df[par[x]]);
par[x] = par[par[x]];
ret = Group::op(ret, df[x]);
x = par[x];
}
return ret;
}
public:
PotentialUnionFind(size_t n = 0)
: group(n), par(n), sz(n, 1), df(n, Group::id) {
std::iota(par.begin(), par.end(), 0);
}
size_t root(size_t x) {
while (par[x] != x) {
df[x] = Group::op(df[x], df[par[x]]);
par[x] = par[par[x]];
x = par[x];
}
return x;
}
bool same(size_t a, size_t b) { return root(a) == root(b); }
size_t size() { return par.size(); }
size_t groups() { return group; }
size_t group_size(size_t x) { return sz[root(x)]; }
// unite A=B+value
bool unite(size_t a, size_t b, value_t value) {
size_t aroot = root(a), broot = root(b);
if (aroot == broot) return false;
group--;
if (sz[aroot] < sz[broot]) {
std::swap(aroot, broot);
std::swap(a, b);
value = Group::inv(value);
}
sz[aroot] += sz[broot];
value = Group::op(value, fold_to_root(a));
value = Group::op(Group::inv(fold_to_root(b)), value);
df[broot] = value;
par[broot] = aroot;
return true;
}
// return diff such as A=B+diff
value_t diff(size_t a, size_t b) {
assert(same(a, b));
return Group::op(fold_to_root(b), Group::inv(fold_to_root(a)));
}
}; |
Vithujan19/REEX_MERN_Stack | server/src/routers/news.js | const express = require('express');
const auth = require('../middleware/auth');
const News = require('../models/news');
const router = new express.Router();
router.post('/news', [auth.authUser, auth.isAdmin], async (req, res) => {
const news = new News({
...req.body,
postedBy: req.user._id,
});
try {
await news.save();
res.status(201).send(news);
} catch (e) {
res.status(400).send(e);
}
});
router.patch('/news/:id', [auth.authUser, auth.isAdmin], async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = [
'viewers',
'title',
'news',
'startDisplayOn',
'endDisplayOn',
];
const isValidOperation = updates.every((update) =>
allowedUpdates.includes(update)
);
if (!isValidOperation) {
return res.status(400).send({ error: 'Invalid updates!' });
}
try {
const news = await News.findOne({
_id: req.params.id,
postedBy: req.user._id,
});
if (!news) {
return res.status(404).send();
}
updates.forEach((update) => (news[update] = req.body[update]));
await news.save();
res.send(news);
} catch (e) {
res.status(400).send(e);
}
});
router.delete('/news/:id', [auth.authUser, auth.isAdmin], async (req, res) => {
try {
const news = await News.findOneAndDelete({
_id: req.params.id,
postedBy: req.user._id,
});
if (!news) {
res.status(404).send();
}
res.send(news);
} catch (e) {
res.status(500).send();
}
});
router.get('/news', [auth.authUser], async (req, res) => {
try {
const role = req.user.role;
if (role === 'manager') {
const wholeNews = await News.find({
viewers: { $in: ['manager'] },
});
res.send(wholeNews);
}
if (role === 'employee') {
const wholeNews = await News.find({
viewers: { $in: ['employee'] },
});
res.send(wholeNews);
}
if (role === 'admin') {
const wholeNews = await News.find({});
res.send(wholeNews);
}
} catch (e) {
res.status(500).send();
}
});
module.exports = router;
|
cls688/GrainCollege | guli_parent/service/service_vod/src/test/java/com/atguigu/vodtest/TestVod.java | package com.atguigu.vodtest;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import java.util.List;
/**
* @author chenglongsheng
* @create 2021-08-11 22:05
*/
public class TestVod {
public static void main(String[] args) {
// 上传视频的方法
String accessKeyId = "LTAI5t7zEyNP7cPU7tbaiUrm";
String accessKeySecret = "<KEY>";
String title = "6 - What If I Want to Move Faster - upload by sdk";
String fileName = "F:\\guli_edu\\6 - What If I Want to Move Faster.mp4";
UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
/* 可指定分片上传时每个分片的大小,默认为2M字节 */
request.setPartSize(2 * 1024 * 1024L);
/* 可指定分片上传时的并发线程数,默认为1,(注:该配置会占用服务器CPU资源,需根据服务器情况指定)*/
request.setTaskNum(1);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadVideoResponse response = uploader.uploadVideo(request);
System.out.print("RequestId=" + response.getRequestId() + "\n"); //请求视频点播服务的请求ID
if (response.isSuccess()) {
System.out.print("VideoId=" + response.getVideoId() + "\n");
} else {
/* 如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因 */
System.out.print("VideoId=" + response.getVideoId() + "\n");
System.out.print("ErrorCode=" + response.getCode() + "\n");
System.out.print("ErrorMessage=" + response.getMessage() + "\n");
}
}
public static void getVideoAuth() throws Exception {
// 根据视频id获取视频播放凭证
// 创建初始化对象
DefaultAcsClient client = InitObject.initVodClient("LTAI5t7zEyNP7cPU7tbaiUrm", "Sw1YLSKSHUdD14dyPvfBKaCDvoMByU");
// 创建获取视频凭证request和response
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
// 向request对象里面设置视频id
request.setVideoId("05328dd149e84e389ab6fb8fdd5c02c6");
// 调用初始化对象里面的方法传递request对象,获取数据
response = client.getAcsResponse(request);
System.out.println("PlayAuth:" + response.getPlayAuth());
}
public static void getVideoPlayURL() throws Exception {
// 根据视频id获取视频播放地址
// 创建初始化对象
DefaultAcsClient client = InitObject.initVodClient("LTAI5t7zEyNP7cPU7tbaiUrm", "Sw1YLSKSHUdD14dyPvfBKaCDvoMByU");
// 创建获取视频地址request和response
GetPlayInfoRequest request = new GetPlayInfoRequest();
GetPlayInfoResponse response = new GetPlayInfoResponse();
// 向request对象里面设置视频id
request.setVideoId("05328dd149e84e389ab6fb8fdd5c02c6");
// 调用初始化对象里面的方法传递request对象,获取数据
response = client.getAcsResponse(request);
List<GetPlayInfoResponse.PlayInfo> playInfosList = response.getPlayInfoList();
// 播放地址
for (GetPlayInfoResponse.PlayInfo playInfo : playInfosList) {
System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
}
// Base信息
System.out.println("VideoBase.Title = " + response.getVideoBase().getTitle() + "\n");
}
}
|
johannespischinger/senti_anal | opensentiment/models/train_model.py | <filename>opensentiment/models/train_model.py<gh_stars>1-10
import logging
import os
from collections import defaultdict
from typing import Any, Dict, Tuple
import hydra
import numpy as np
import torch
import transformers
from omegaconf import DictConfig
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
import wandb
from opensentiment.gcp.storage_utils import save_to_model_gs
from opensentiment.models.bert_model import SentimentClassifier
from opensentiment.utils import get_project_root
logger = logging.getLogger(__name__)
def train_model(
model: nn.Module,
data_loader: DataLoader,
criterion: Any,
optimizer: Any,
scheduler: Any,
max_norm: float = 1.0,
) -> [torch.Tensor, np.float64]:
model.train()
train_loss = []
correct_pred = 0
total_pred = 0
for d in tqdm(data_loader):
input_ids = d["input_id"]
attention_masks = d["attention_mask"]
targets = d["target"]
# forward prop
predictions = model(input_ids, attention_masks)
loss = criterion(predictions, targets)
_, pred_classes = torch.max(predictions, dim=1)
# backprop
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
# training loss and number of correct prediction
train_loss.append(loss.item())
correct_pred += torch.sum(pred_classes == targets)
total_pred += targets.shape[0]
return correct_pred / total_pred, np.mean(train_loss)
def eval_model(
model: nn.Module,
data_loader: DataLoader,
criterion: Any,
) -> [torch.Tensor, float]:
model.eval()
eval_loss = []
correct_pred = 0
total_pred = 0
with torch.no_grad():
for d in tqdm(data_loader):
input_ids = d["input_id"]
attention_masks = d["attention_mask"]
targets = d["target"]
# forward prop
predictions = model(input_ids, attention_masks)
loss = criterion(predictions, targets)
_, pred_classes = torch.max(predictions, dim=1)
eval_loss.append(loss.item())
correct_pred += torch.sum(pred_classes == targets)
total_pred += targets.shape[0]
return correct_pred / total_pred, np.mean(eval_loss)
@hydra.main(config_path="config", config_name="default_config.yaml")
def train(cfg: DictConfig) -> Tuple[Dict, str]:
if cfg.wandb_key_api:
os.environ["WANDB_API_KEY"] = cfg.wandb_key_api
wandb.init(
project="BERT",
entity="senti_anal",
name=os.getcwd().split("/")[-1],
job_type="train",
)
config = cfg.experiments
torch.manual_seed(config.seed)
train_set = torch.load(
os.path.join(get_project_root(), f"{config.data_path}/train_dataset.pt")
)
val_set = torch.load(
os.path.join(get_project_root(), f"{config.data_path}/val_dataset.pt")
)
train_loader = DataLoader(train_set, batch_size=config.batch_size)
val_loader = DataLoader(val_set, batch_size=config.batch_size)
model = SentimentClassifier()
wandb.watch(model, log_freq=100)
total_steps = len(train_loader) * config.epochs
criterion = torch.nn.CrossEntropyLoss()
optimizer = transformers.AdamW(
params=model.parameters(), lr=config.learning_rate, correct_bias=False
)
scheduler = transformers.get_linear_schedule_with_warmup(
optimizer=optimizer,
num_warmup_steps=config.num_warmup_steps,
num_training_steps=total_steps,
)
history = defaultdict(list)
best_accuracy = 0
best_model_name = "untrained_model.pt"
logger.info("Start training:")
for epoch in range(config.epochs):
# training part
print(f"epoch : {epoch + 1}/{config.epochs}")
train_acc, train_loss = train_model(
model,
train_loader,
criterion,
optimizer,
scheduler,
config.max_norm,
)
# validation part
val_acc, val_loss = eval_model(model, val_loader, criterion)
# saving training logs
history["train_acc"].append(train_acc)
history["train_loss"].append(train_loss)
history["val_acc"].append(val_acc)
history["val_loss"].append(val_loss)
wandb.log(
{
"train_loss": train_loss,
"train_acc": train_acc,
"val_loss": val_loss,
"val_acc": val_acc,
}
)
logger.info(
f"train_loss: {train_loss}, train_acc: {train_acc} ,val_loss: {val_loss}, val_acc: {val_acc}"
)
# saving model if performance improved
if val_acc > best_accuracy:
best_model_name = f"best_model_state_{val_acc:.2}.pt"
best_accuracy = val_acc
torch.save(model.state_dict(), os.path.join(os.getcwd(), best_model_name))
if cfg.job_dir_gs:
logger.info(f"Uploading model google bucket: {cfg.job_dir_gs}")
save_to_model_gs(cfg.job_dir_gs, best_model_name)
return history, best_model_name
if __name__ == "__main__":
train()
|
jaskier07/trend-miner | src/main/java/pl/kania/trendminer/dataparser/parser/preproc/Receiver.java | package pl.kania.trendminer.dataparser.parser.preproc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import pl.kania.trendminer.dataparser.Tweet;
import pl.kania.trendminer.dataparser.input.CsvReader;
import pl.kania.trendminer.dataparser.input.TweetAnalysisData;
import pl.kania.trendminer.dataparser.parser.ImproveResults;
import pl.kania.trendminer.dataparser.parser.preproc.replacing.TweetContentPreprocessor;
import pl.kania.trendminer.dataparser.parser.preproc.filtering.ValidEnglishWordThresholdProvider;
import pl.kania.trendminer.dataparser.parser.preproc.filtering.ValidEnglishWordsCounter;
import pl.kania.trendminer.util.NumberFormatter;
import pl.kania.trendminer.util.ProgressLogger;
import java.util.Iterator;
import java.util.List;
@Slf4j
@Service
public class Receiver {
private final ValidEnglishWordsCounter validEnglishWordsCounter;
private final ValidEnglishWordThresholdProvider validEnglishWordThresholdProvider;
private final Environment environment;
private final ImproveResults improveResults;
public Receiver(@Autowired ValidEnglishWordsCounter validEnglishWordsCounter, @Autowired ValidEnglishWordThresholdProvider validEnglishWordThresholdProvider,
@Autowired Environment environment, @Autowired ImproveResults improveResults) {
this.validEnglishWordsCounter = validEnglishWordsCounter;
this.validEnglishWordThresholdProvider = validEnglishWordThresholdProvider;
this.environment = environment;
this.improveResults = improveResults;
}
public TweetAnalysisData getTweetsInEnglish() {
TweetAnalysisData tweetAnalysisData = new CsvReader().readFile(environment.getProperty("pl.kania.path.dataset"));
List<Tweet> tweets = tweetAnalysisData.getTweets();
performPreprocessing(tweets);
filterOutNonEnglishTweets(tweets);
return new TweetAnalysisData(tweets, tweetAnalysisData.getStart(), tweetAnalysisData.getEnd());
}
private void performPreprocessing(List<Tweet> tweets) {
tweets.forEach(t -> new TweetContentPreprocessor().performPreprocessing(t, improveResults.get()));
}
private void filterOutNonEnglishTweets(List<Tweet> tweets) {
log.info("Filtering non-English tweets started.");
int tweetsBeforeFilteringOut = tweets.size();
int counter = 0;
Iterator<Tweet> iterator = tweets.iterator();
while (iterator.hasNext()) {
Tweet tweet = iterator.next();
int percentageOfEnglishWords = validEnglishWordsCounter.getPercentageOfEnglishWords(tweet);
if (percentageOfEnglishWords < validEnglishWordThresholdProvider.getThresholdInPercentage(tweet)) {
iterator.remove();
log.debug("Removed non-English tweet: " + tweet.getContent());
}
ProgressLogger.log(counter++);
}
ProgressLogger.done("Filtering non-English tweets. % of preserved tweets: " +
NumberFormatter.formatPercentage(tweets.size(), tweetsBeforeFilteringOut));
log.info("Percentage of tweets with location: " + NumberFormatter.formatPercentage(
ValidEnglishWordThresholdProvider.getTweetsWithLocation(), tweetsBeforeFilteringOut));
}
}
|
PJB2TY/hbase | hbase-it/src/test/java/org/apache/hadoop/hbase/chaos/monkies/ChaosMonkey.java | <reponame>PJB2TY/hbase
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.chaos.monkies;
import org.apache.hadoop.hbase.Stoppable;
/**
* A utility to injects faults in a running cluster.
* <p>
* ChaosMonkey defines Action's and Policy's. Actions are sequences of events, like - Select a
* random server to kill - Sleep for 5 sec - Start the server on the same host Actions can also be
* complex events, like rolling restart of all of the servers.
* <p>
* Policies on the other hand are responsible for executing the actions based on a strategy. The
* default policy is to execute a random action every minute based on predefined action weights.
* ChaosMonkey executes predefined named policies until it is stopped. More than one policy can be
* active at any time.
* <p>
* Chaos monkey can be run from the command line, or can be invoked from integration tests. See
* {@link org.apache.hadoop.hbase.IntegrationTestIngest} or other integration tests that use chaos
* monkey for code examples.
* <p>
* ChaosMonkey class is indeed inspired by the Netflix's same-named tool:
* http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html
*/
public abstract class ChaosMonkey implements Stoppable {
public abstract void start() throws Exception;
@Override
public abstract void stop(String why);
@Override
public abstract boolean isStopped();
public abstract void waitForStop() throws InterruptedException;
/**
* Returns whether the CM does destructive actions (killing servers) so that a cluster restore is
* needed after CM is stopped. Otherwise cluster will be left as it is
*/
public abstract boolean isDestructive();
}
|
asimzsaeed/mongod_node_multi_tenancy_startup | app/common/services/index.js | <reponame>asimzsaeed/mongod_node_multi_tenancy_startup<gh_stars>100-1000
'use strict';
// Services and Factories have their first letter capitalized like Controllers
module.exports = angular.module('common.services', [])
.factory('APIService', require('./APIService.js'))
.factory('RESTService', require('./RESTService.js'))
.factory('CustomerService', require('./CustomerService.js'))
.factory('AuthenticationFactory', require('./AuthenticationFactory.js'))
.factory('AuthInterceptor', require('./AuthInterceptor.js'))
.factory('SignupService', require('./SignupService.js'))
; |
cndoit18/Dragonfly2 | pkg/rpc/dfdaemon/dfdaemon.pb.go | //
// Copyright 2020 The Dragonfly Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.17.3
// source: pkg/rpc/dfdaemon/dfdaemon.proto
package dfdaemon
import (
base "d7y.io/dragonfly/v2/pkg/rpc/base"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
emptypb "google.golang.org/protobuf/types/known/emptypb"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type DownRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// identify one downloading, the framework will fill it automatically
Uuid string `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"`
// download file from the url, not only for http
Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"`
// pieces will be written to output path directly,
// at the same time, dfdaemon workspace also makes soft link to the output
Output string `protobuf:"bytes,3,opt,name=output,proto3" json:"output,omitempty"`
// timeout duration
Timeout uint64 `protobuf:"varint,4,opt,name=timeout,proto3" json:"timeout,omitempty"`
// rate limit in bytes per second
Limit float64 `protobuf:"fixed64,5,opt,name=limit,proto3" json:"limit,omitempty"`
DisableBackSource bool `protobuf:"varint,6,opt,name=disable_back_source,json=disableBackSource,proto3" json:"disable_back_source,omitempty"`
UrlMeta *base.UrlMeta `protobuf:"bytes,7,opt,name=url_meta,json=urlMeta,proto3" json:"url_meta,omitempty"`
// p2p/cdn/source, default is p2p
Pattern string `protobuf:"bytes,8,opt,name=pattern,proto3" json:"pattern,omitempty"`
// call system
Callsystem string `protobuf:"bytes,9,opt,name=callsystem,proto3" json:"callsystem,omitempty"`
// user id
Uid int64 `protobuf:"varint,10,opt,name=uid,proto3" json:"uid,omitempty"`
// group id
Gid int64 `protobuf:"varint,11,opt,name=gid,proto3" json:"gid,omitempty"`
}
func (x *DownRequest) Reset() {
*x = DownRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DownRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DownRequest) ProtoMessage() {}
func (x *DownRequest) ProtoReflect() protoreflect.Message {
mi := &file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DownRequest.ProtoReflect.Descriptor instead.
func (*DownRequest) Descriptor() ([]byte, []int) {
return file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescGZIP(), []int{0}
}
func (x *DownRequest) GetUuid() string {
if x != nil {
return x.Uuid
}
return ""
}
func (x *DownRequest) GetUrl() string {
if x != nil {
return x.Url
}
return ""
}
func (x *DownRequest) GetOutput() string {
if x != nil {
return x.Output
}
return ""
}
func (x *DownRequest) GetTimeout() uint64 {
if x != nil {
return x.Timeout
}
return 0
}
func (x *DownRequest) GetLimit() float64 {
if x != nil {
return x.Limit
}
return 0
}
func (x *DownRequest) GetDisableBackSource() bool {
if x != nil {
return x.DisableBackSource
}
return false
}
func (x *DownRequest) GetUrlMeta() *base.UrlMeta {
if x != nil {
return x.UrlMeta
}
return nil
}
func (x *DownRequest) GetPattern() string {
if x != nil {
return x.Pattern
}
return ""
}
func (x *DownRequest) GetCallsystem() string {
if x != nil {
return x.Callsystem
}
return ""
}
func (x *DownRequest) GetUid() int64 {
if x != nil {
return x.Uid
}
return 0
}
func (x *DownRequest) GetGid() int64 {
if x != nil {
return x.Gid
}
return 0
}
type DownResult struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
TaskId string `protobuf:"bytes,2,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
PeerId string `protobuf:"bytes,3,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
CompletedLength uint64 `protobuf:"varint,4,opt,name=completed_length,json=completedLength,proto3" json:"completed_length,omitempty"`
Done bool `protobuf:"varint,5,opt,name=done,proto3" json:"done,omitempty"`
}
func (x *DownResult) Reset() {
*x = DownResult{}
if protoimpl.UnsafeEnabled {
mi := &file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DownResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DownResult) ProtoMessage() {}
func (x *DownResult) ProtoReflect() protoreflect.Message {
mi := &file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DownResult.ProtoReflect.Descriptor instead.
func (*DownResult) Descriptor() ([]byte, []int) {
return file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescGZIP(), []int{1}
}
func (x *DownResult) GetTaskId() string {
if x != nil {
return x.TaskId
}
return ""
}
func (x *DownResult) GetPeerId() string {
if x != nil {
return x.PeerId
}
return ""
}
func (x *DownResult) GetCompletedLength() uint64 {
if x != nil {
return x.CompletedLength
}
return 0
}
func (x *DownResult) GetDone() bool {
if x != nil {
return x.Done
}
return false
}
var File_pkg_rpc_dfdaemon_dfdaemon_proto protoreflect.FileDescriptor
var file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDesc = []byte{
0x0a, 0x1f, 0x70, 0x6b, 0x67, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x64, 0x66, 0x64, 0x61, 0x65, 0x6d,
0x6f, 0x6e, 0x2f, 0x64, 0x66, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x08, 0x64, 0x66, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x1a, 0x17, 0x70, 0x6b, 0x67,
0x2f, 0x72, 0x70, 0x63, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2f, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x17, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x2f, 0x76, 0x61, 0x6c, 0x69,
0x64, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x85, 0x03, 0x0a, 0x0b, 0x44,
0x6f, 0x77, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x0a, 0x04, 0x75, 0x75,
0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x72, 0x03, 0xb0,
0x01, 0x01, 0x52, 0x04, 0x75, 0x75, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x08, 0xfa, 0x42, 0x05, 0x72, 0x03, 0x88, 0x01, 0x01, 0x52,
0x03, 0x75, 0x72, 0x6c, 0x12, 0x1f, 0x0a, 0x06, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x18, 0x03,
0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x06, 0x6f,
0x75, 0x74, 0x70, 0x75, 0x74, 0x12, 0x21, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74,
0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x32, 0x02, 0x28, 0x00, 0x52,
0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x24, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69,
0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x42, 0x0e, 0xfa, 0x42, 0x0b, 0x12, 0x09, 0x29, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x2e,
0x0a, 0x13, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x5f, 0x73,
0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x64, 0x69, 0x73,
0x61, 0x62, 0x6c, 0x65, 0x42, 0x61, 0x63, 0x6b, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x28,
0x0a, 0x08, 0x75, 0x72, 0x6c, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x0d, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x55, 0x72, 0x6c, 0x4d, 0x65, 0x74, 0x61, 0x52,
0x07, 0x75, 0x72, 0x6c, 0x4d, 0x65, 0x74, 0x61, 0x12, 0x34, 0x0a, 0x07, 0x70, 0x61, 0x74, 0x74,
0x65, 0x72, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x42, 0x1a, 0xfa, 0x42, 0x17, 0x72, 0x15,
0x52, 0x03, 0x70, 0x32, 0x70, 0x52, 0x03, 0x63, 0x64, 0x6e, 0x52, 0x06, 0x73, 0x6f, 0x75, 0x72,
0x63, 0x65, 0xd0, 0x01, 0x01, 0x52, 0x07, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x1e,
0x0a, 0x0a, 0x63, 0x61, 0x6c, 0x6c, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x18, 0x09, 0x20, 0x01,
0x28, 0x09, 0x52, 0x0a, 0x63, 0x61, 0x6c, 0x6c, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x12, 0x10,
0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x75, 0x69, 0x64,
0x12, 0x10, 0x0a, 0x03, 0x67, 0x69, 0x64, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x67,
0x69, 0x64, 0x22, 0x98, 0x01, 0x0a, 0x0a, 0x44, 0x6f, 0x77, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c,
0x74, 0x12, 0x20, 0x0a, 0x07, 0x74, 0x61, 0x73, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01,
0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x06, 0x74, 0x61, 0x73,
0x6b, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x07, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03,
0x20, 0x01, 0x28, 0x09, 0x42, 0x07, 0xfa, 0x42, 0x04, 0x72, 0x02, 0x10, 0x01, 0x52, 0x06, 0x70,
0x65, 0x65, 0x72, 0x49, 0x64, 0x12, 0x32, 0x0a, 0x10, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x74,
0x65, 0x64, 0x5f, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x42,
0x07, 0xfa, 0x42, 0x04, 0x32, 0x02, 0x28, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65,
0x74, 0x65, 0x64, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x6f, 0x6e,
0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x04, 0x64, 0x6f, 0x6e, 0x65, 0x32, 0xbe, 0x01,
0x0a, 0x06, 0x44, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x12, 0x39, 0x0a, 0x08, 0x44, 0x6f, 0x77, 0x6e,
0x6c, 0x6f, 0x61, 0x64, 0x12, 0x15, 0x2e, 0x64, 0x66, 0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x2e,
0x44, 0x6f, 0x77, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x64, 0x66,
0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x2e, 0x44, 0x6f, 0x77, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c,
0x74, 0x30, 0x01, 0x12, 0x3a, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x50, 0x69, 0x65, 0x63, 0x65, 0x54,
0x61, 0x73, 0x6b, 0x73, 0x12, 0x16, 0x2e, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x50, 0x69, 0x65, 0x63,
0x65, 0x54, 0x61, 0x73, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x11, 0x2e, 0x62,
0x61, 0x73, 0x65, 0x2e, 0x50, 0x69, 0x65, 0x63, 0x65, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x12,
0x3d, 0x0a, 0x0b, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x16,
0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x26,
0x5a, 0x24, 0x64, 0x37, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x64, 0x72, 0x61, 0x67, 0x6f, 0x6e, 0x66,
0x6c, 0x79, 0x2f, 0x76, 0x32, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x64, 0x66,
0x64, 0x61, 0x65, 0x6d, 0x6f, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescOnce sync.Once
file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescData = file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDesc
)
func file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescGZIP() []byte {
file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescOnce.Do(func() {
file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescData = protoimpl.X.CompressGZIP(file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescData)
})
return file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDescData
}
var file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pkg_rpc_dfdaemon_dfdaemon_proto_goTypes = []interface{}{
(*DownRequest)(nil), // 0: dfdaemon.DownRequest
(*DownResult)(nil), // 1: dfdaemon.DownResult
(*base.UrlMeta)(nil), // 2: base.UrlMeta
(*base.PieceTaskRequest)(nil), // 3: base.PieceTaskRequest
(*emptypb.Empty)(nil), // 4: google.protobuf.Empty
(*base.PiecePacket)(nil), // 5: base.PiecePacket
}
var file_pkg_rpc_dfdaemon_dfdaemon_proto_depIdxs = []int32{
2, // 0: dfdaemon.DownRequest.url_meta:type_name -> base.UrlMeta
0, // 1: dfdaemon.Daemon.Download:input_type -> dfdaemon.DownRequest
3, // 2: dfdaemon.Daemon.GetPieceTasks:input_type -> base.PieceTaskRequest
4, // 3: dfdaemon.Daemon.CheckHealth:input_type -> google.protobuf.Empty
1, // 4: dfdaemon.Daemon.Download:output_type -> dfdaemon.DownResult
5, // 5: dfdaemon.Daemon.GetPieceTasks:output_type -> base.PiecePacket
4, // 6: dfdaemon.Daemon.CheckHealth:output_type -> google.protobuf.Empty
4, // [4:7] is the sub-list for method output_type
1, // [1:4] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_pkg_rpc_dfdaemon_dfdaemon_proto_init() }
func file_pkg_rpc_dfdaemon_dfdaemon_proto_init() {
if File_pkg_rpc_dfdaemon_dfdaemon_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DownRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DownResult); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_pkg_rpc_dfdaemon_dfdaemon_proto_goTypes,
DependencyIndexes: file_pkg_rpc_dfdaemon_dfdaemon_proto_depIdxs,
MessageInfos: file_pkg_rpc_dfdaemon_dfdaemon_proto_msgTypes,
}.Build()
File_pkg_rpc_dfdaemon_dfdaemon_proto = out.File
file_pkg_rpc_dfdaemon_dfdaemon_proto_rawDesc = nil
file_pkg_rpc_dfdaemon_dfdaemon_proto_goTypes = nil
file_pkg_rpc_dfdaemon_dfdaemon_proto_depIdxs = nil
}
|
kulbhushan-skf/go-tests-utility | users/create_user.go | <filename>users/create_user.go
package users
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"time"
"github.com/pkg/errors"
disposable_emails "github.com/SKF/go-tests-utility/disposable-emails"
)
const identityMgmtBaseURL = "https://sso-api.%s.users.enlight.skf.com"
func Create(accessToken, stage, companyID, email string) (_ User, password string, err error) {
startedAt := time.Now().Add(-1 * time.Second)
requestBody := struct {
Email string `json:"email"`
GivenName string `json:"givenName"`
Surname string `json:"surname"`
}{
Email: email,
GivenName: "Foo",
Surname: "Bar",
}
jsonBody, err := json.Marshal(requestBody)
if err != nil {
err = errors.Wrap(err, "json.Marshal failed")
return
}
url := fmt.Sprintf(identityMgmtBaseURL+"/companies/%s/users", stage, companyID)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonBody))
if err != nil {
err = errors.Wrap(err, "http.NewRequest failed")
return
}
req.Header.Set("Authorization", accessToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
err = errors.Wrap(err, "client.Do failed")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
err = errors.Wrap(err, "ioutil.ReadAll failed")
return
}
var respBody struct {
Data User `json:"data"`
}
if err = json.Unmarshal(body, &respBody); err != nil {
err = errors.Wrapf(err, "json.Unmarshal failed, body: %s", string(body))
return
}
if resp.StatusCode != http.StatusOK {
err = errors.Errorf("Wrong status: %q, req: %+v", resp.Status, req)
return
}
temporaryPassword, err := PollForTemporaryPassword(email, startedAt)
if err != nil {
return
}
return respBody.Data, temporaryPassword, nil
}
func PollForTemporaryPassword(email string, startedAt time.Time) (string, error) {
const subject = "Welcome to SKF Digital Services"
actualEmail, err := disposable_emails.PollForMessageWithSubject(email, subject, startedAt)
if err != nil {
return "", err
}
temporaryPassword, err := getTemporaryPassword(actualEmail)
if err != nil {
return "", err
}
return temporaryPassword, nil
}
func getTemporaryPassword(emailMessage string) (string, error) {
subMatches := temporaryPasswordRegexp.FindAllStringSubmatch(emailMessage, -1)
if len(subMatches) == 0 {
return "", errors.Errorf("couldn't retrieve temporary password from email: [%s]", emailMessage)
}
return subMatches[0][1], nil
}
var temporaryPasswordRegexp = regexp.MustCompile(`password=(\S+)\" style`)
type User struct {
ID string `json:"id"`
CompanyID string `json:"companyId"`
Email string `json:"email"`
GivenName string `json:"givenName"`
Surname string `json:"surname"`
Language string `json:"language"`
Status string `json:"status"`
}
|
pickupst/hezarfen | gradle/wrapper/gradle-3.0/src/tooling-api/org/gradle/tooling/internal/protocol/InternalCompositeAwareConnection.java | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.tooling.internal.protocol;
import org.gradle.tooling.internal.protocol.exceptions.InternalUnsupportedBuildArgumentException;
import org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection;
public interface InternalCompositeAwareConnection extends InternalTestExecutionConnection, InternalCancellableConnection {
/**
* Performs some action against a composite and returns the requested model.
*
* <p>Consumer compatibility: This method is used by all consumer versions from 2.13-rc-1.</p>
* <p>Provider compatibility: This method is implemented by all provider versions from 2.13-rc-1.</p>
*
* @param modelIdentifier The identifier of the model to build.
* @param cancellationToken The token to propagate cancellation.
* @throws BuildExceptionVersion1 On build failure.
* @throws InternalUnsupportedModelException When the requested model is not supported.
* @throws InternalUnsupportedBuildArgumentException When the specified command-line options are not supported.
* @throws InternalBuildCancelledException When the operation was cancelled before it could complete.
* @throws IllegalStateException When this connection has been stopped.
* @since 2.13-rc-1
*/
BuildResult<?> getModels(ModelIdentifier modelIdentifier, InternalCancellationToken cancellationToken,
BuildParameters operationParameters) throws
BuildExceptionVersion1,
InternalUnsupportedModelException,
InternalUnsupportedBuildArgumentException,
InternalBuildCancelledException,
IllegalStateException;
}
|
intesight/Panorama4AIWAYS | s32v234_sdk/libs/apexcv_pro/gftt_corners/graphs/harris_b3n5_compute_extract_graph.hpp | <reponame>intesight/Panorama4AIWAYS<gh_stars>0
/*****************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright (c) 2014-2016 Freescale Semiconductor
* Copyright 2017-2018 NXP
* All Rights Reserved
*
******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS 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.
*
****************************************************************************/
/*!*********************************************************************************
* @file
* @brief ACF graph for the \ref secHarrisCorner "Harris Corner Detect".
***********************************************************************************/
#ifndef HARRISCOMPUTEEXTRACTGRAPH_HPP
#define HARRISCOMPUTEEXTRACTGRAPH_HPP
#include <acf_graph.hpp>
#include "harris_acf.h"
#include "apexcv_pro_gftt_harris_common.h"
/*!*********************************************************************************
* \brief ACF graph for the \ref secHarrisCornerDetector "Harris Corner Detect" using a 3x3 linear filter,
* a 3x3 box filter, and a 5x5 non-maxima suppression.
*
* \image html harris_corners_detect_graph.jpg "ACF Graph for the harris corner detect."
* \image latex harris_corners_detect_graph.pdf "ACF Graph for the harris corner detect." width = 14cm
***********************************************************************************/
class harris_b3n5_compute_extract_graph : public ACF_Graph
{
public:
harris_b3n5_compute_extract_graph() : ACF_Graph()
{
XREGISTER_ACF_KERNEL(HARRIS_CORNERS_BOX3_NMS5_K)
XREGISTER_ACF_KERNEL(HARRIS_EXTRACT_K)
XREGISTER_ACF_KERNEL(HARRIS_SORT_AND_FILTER_K)
}
/*!*********************************************************************************
* \brief Create the ACF graph.
*
* In this function we
* - set the graph's unique identifier.
* - add the kernels
* - add graph ports for the source image , corner coefficient and destination image
* - connect graph ports to kernel ports
***********************************************************************************/
void Create()
{
// Set identifier for graph
SetIdentifier("harris_b3n5_compute_extract_graph");
// add kernels
AddKernel("HARRIS", HARRIS_CORNERS_BOX3_NMS5_KN);
AddKernel("EXTRACT", HARRIS_EXTRACT_KN);
AddKernel("SORT", HARRIS_SORT_AND_FILTER_KN);
SetKernelPortOutputDelay("HARRIS", "OUTPUT", PORT_OUTPUT_DELAY_BOX3_NMS5);
// add graph port
AddInputPort("INPUT");
AddInputPort("PARAMS");
AddOutputPort("OUTPUT_IMAGE");
AddOutputPort("OUTPUT_CORNERLIST");
AddOutputPort("OUTPUT_COUNT");
// specify connections
// harris
Connect( GraphPort("INPUT"), KernelPort("HARRIS", "INPUT"));
Connect( GraphPort("PARAMS"), KernelPort("HARRIS", "PARAMS"));
// extract
Connect( GraphPort("PARAMS"), KernelPort("EXTRACT", "PARAMS"));
Connect( KernelPort("HARRIS", "OUTPUT"), KernelPort("EXTRACT", "SRC"));
// sort
Connect( GraphPort("PARAMS"), KernelPort("SORT", "PARAMS"));
Connect( KernelPort("EXTRACT", "COORD"), KernelPort("SORT", "COORD"));
Connect( KernelPort("EXTRACT", "STREN"), KernelPort("SORT", "STREN"));
Connect( KernelPort("EXTRACT", "COUNT"), KernelPort("SORT", "COUNT"));
// graph out
Connect( KernelPort("HARRIS", "OUTPUT"), GraphPort("OUTPUT_IMAGE"));
Connect( KernelPort("SORT", "FEATURE"), GraphPort("OUTPUT_CORNERLIST"));
Connect( KernelPort("SORT", "FEAT_OUT"), GraphPort("OUTPUT_COUNT"));
}
};
#endif /* HARRISCOMPUTEEXTRACTGRAPH_HPP */
|
BlizzardHero/Arduino-Source | SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.h | /* Game Entry
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#ifndef PokemonAutomation_PokemonLA_GameEntry_H
#define PokemonAutomation_PokemonLA_GameEntry_H
#include "CommonFramework/Tools/ProgramEnvironment.h"
#include "CommonFramework/Tools/ConsoleHandle.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonLA{
bool gamemenu_to_ingame(
ProgramEnvironment& env, ConsoleHandle& console,
uint16_t mash_duration, uint16_t enter_game_timeout
);
bool openedgame_to_ingame(
ProgramEnvironment& env, ConsoleHandle& console,
uint16_t load_game_timeout,
uint16_t mash_duration, uint16_t enter_game_timeout,
uint16_t post_wait_time = 125
);
bool reset_game_from_home(
ProgramEnvironment& env, ConsoleHandle& console,
bool tolerate_update_menu,
uint16_t post_wait_time = 125
);
void save_game_from_overworld(ProgramEnvironment& env, ConsoleHandle& console);
}
}
}
#endif
|
wangsenyuan/learn-go | src/leetcode/set1000/set2000/set2200/set2220/p2220/solution.go | package p2220
func minBitFlips(start int, goal int) int {
num := start ^ goal
var cnt int
for num > 0 {
cnt++
num -= num & -num
}
return cnt
}
|
manasdebashiskar/geoshield | src/src/java/ch/supsi/ist/geoshield/utils/FiltersUtils.java | /**
* Copyright (c) 2010 Istituto Scienze della Terra - SUPSI
* 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 Istituto Scienze della Terra - SUPSI 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 ISTITUTO SCIENZE DELLA TERRA - SUPSI BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.supsi.ist.geoshield.utils;
// GEOTOOLS --------------------------------------------------------------------
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.opengis.filter.*;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.filter.AndImpl;
import org.geotools.filter.FilterTransformer;
import org.geotools.filter.GeometryFilterImpl;
import org.geotools.filter.OrImpl;
/**
*
* @author <NAME> - <EMAIL>
*/
public class FiltersUtils {
public static int getPriorityFilter(String cqlFilter) throws CQLException {
int ret = 0;
if (cqlFilter.equalsIgnoreCase("INCLUDE")) {
ret = 4;
} else if (cqlFilter.equalsIgnoreCase("EXCLUDE")) {
ret = 1;
} else {
List<Filter> f = getSpatialFilter(CQL.toFilter(cqlFilter));
if (f.size() > 0) {
ret = 2;
}else{
ret = 3;
}
}
return ret;
}
public static synchronized List<Filter> getSpatialFilter(Filter filter) {
List<Filter> ret = new LinkedList<Filter>();
if (filter instanceof AndImpl) {
List<Filter> tmp = new LinkedList<Filter>();
for (Iterator it2 = ((AndImpl) filter).getFilterIterator(); it2.hasNext();) {
tmp.add((Filter) it2.next());
}
ret.addAll(getSpatialFilter(tmp));
} else if (filter instanceof OrImpl) {
List<Filter> tmp = new LinkedList<Filter>();
for (Iterator it2 = ((OrImpl) filter).getFilterIterator(); it2.hasNext();) {
tmp.add((Filter) it2.next());
}
ret.addAll(getSpatialFilter(tmp));
} else if (filter instanceof GeometryFilterImpl) {
ret.add(filter);
}
return ret;
}
public static synchronized List<Filter> getSpatialFilter(List<Filter> flts) {
List<Filter> ret = new LinkedList<Filter>();
for (Iterator<Filter> it = flts.iterator(); it.hasNext();) {
ret.addAll(getSpatialFilter(it.next()));
}
return ret;
}
public static void main(String[] args) throws Exception {
int p = 0;
String cql = "INCLUDE";
p = FiltersUtils.getPriorityFilter(cql);
System.out.println(cql+" PRIORITY="+p);
cql = "EXCLUDE";
p = FiltersUtils.getPriorityFilter(cql);
System.out.println(cql+" PRIORITY="+p);
cql = "val=4";
p = FiltersUtils.getPriorityFilter(cql);
System.out.println(cql+" PRIORITY="+p);
cql = "BBOX(the_geom, 147.15,-43, 147.5,-42.75)";
p = FiltersUtils.getPriorityFilter(cql);
System.out.println(cql+" PRIORITY="+p);
cql = "val=4 AND BBOX(the_geom, 147.15,-43, 147.5,-42.75)";
p = FiltersUtils.getPriorityFilter(cql);
System.out.println(cql+" PRIORITY="+p);
}
}
|
xj361685640/ParaView | Qt/ApplicationComponents/pqChangePipelineInputReaction.cxx | /*=========================================================================
Program: ParaView
Module: pqChangePipelineInputReaction.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqChangePipelineInputReaction.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqChangeInputDialog.h"
#include "pqCoreUtilities.h"
#include "pqOutputPort.h"
#include "pqPipelineFilter.h"
#include "pqPipelineModel.h"
#include "pqServerManagerModel.h"
#include "pqUndoStack.h"
#include "vtkSMInputProperty.h"
#include "vtkSMProxy.h"
#include "vtkSMTrace.h"
#include <QDebug>
//-----------------------------------------------------------------------------
pqChangePipelineInputReaction::pqChangePipelineInputReaction(QAction* parentObject)
: Superclass(parentObject)
{
QObject::connect(&pqActiveObjects::instance(), SIGNAL(sourceChanged(pqPipelineSource*)), this,
SLOT(updateEnableState()));
// nameChanged() is fired even when modified state is changed ;).
QObject::connect(pqApplicationCore::instance()->getServerManagerModel(),
SIGNAL(modifiedStateChanged(pqServerManagerModelItem*)), this, SLOT(updateEnableState()));
this->updateEnableState();
}
//-----------------------------------------------------------------------------
void pqChangePipelineInputReaction::updateEnableState()
{
pqPipelineFilter* filter =
qobject_cast<pqPipelineFilter*>(pqActiveObjects::instance().activeSource());
if (filter == nullptr || filter->modifiedState() == pqProxy::UNINITIALIZED)
{
this->parentAction()->setEnabled(false);
return;
}
this->parentAction()->setEnabled(true);
}
//-----------------------------------------------------------------------------
void pqChangePipelineInputReaction::changeInput()
{
pqPipelineFilter* filter =
qobject_cast<pqPipelineFilter*>(pqActiveObjects::instance().activeSource());
if (!filter)
{
qCritical() << "No active filter.";
return;
}
pqChangeInputDialog dialog(filter->getProxy(), pqCoreUtilities::mainWidget());
dialog.setObjectName("ChangeInputDialog");
if (dialog.exec() != QDialog::Accepted)
{
return;
}
BEGIN_UNDO_SET(QString("Change Input for %1").arg(filter->getSMName()));
SM_SCOPED_TRACE(PropertiesModified).arg("proxy", filter->getProxy());
const QMap<QString, QList<pqOutputPort*>> input_map = dialog.selectedInputs();
QMap<QString, QList<pqOutputPort*>>::const_iterator iter;
for (iter = input_map.begin(); iter != input_map.end(); iter++)
{
const QString& inputPortName = iter.key();
const QList<pqOutputPort*>& inputs = iter.value();
std::vector<vtkSMProxy*> inputPtrs;
std::vector<unsigned int> inputPorts;
Q_FOREACH (pqOutputPort* opport, inputs)
{
inputPtrs.push_back(opport->getSource()->getProxy());
inputPorts.push_back(opport->getPortNumber());
}
vtkSMInputProperty* ip = vtkSMInputProperty::SafeDownCast(
filter->getProxy()->GetProperty(inputPortName.toUtf8().data()));
ip->SetProxies(static_cast<unsigned int>(inputPtrs.size()), &inputPtrs[0], &inputPorts[0]);
}
filter->getProxy()->UpdateVTKObjects();
END_UNDO_SET();
// render all views
pqApplicationCore::instance()->render();
}
|
henrypan/titan | titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/FaunusPropertyKey.java | <reponame>henrypan/titan
package com.thinkaurelius.titan.hadoop;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.core.Cardinality;
import com.thinkaurelius.titan.core.Multiplicity;
import com.thinkaurelius.titan.core.PropertyKey;
import com.thinkaurelius.titan.graphdb.schema.EdgeLabelDefinition;
import com.thinkaurelius.titan.graphdb.schema.PropertyKeyDefinition;
import javax.annotation.Nullable;
/**
* @author <NAME> (<EMAIL>)
*/
public class FaunusPropertyKey<T> extends FaunusRelationType implements PropertyKey {
public static final FaunusPropertyKey<Long> COUNT = new FaunusPropertyKey<Long>(
new PropertyKeyDefinition(Tokens._COUNT, FaunusElement.NO_ID,Cardinality.SINGLE,Long.class),
new Function<FaunusElement, Long>() {
@Nullable
@Override
public Long apply(@Nullable FaunusElement element) {
if (element instanceof FaunusPathElement)
return Long.valueOf(((FaunusPathElement)element).pathCount());
else return 0l;
}
}
);
public static final FaunusPropertyKey<Object> ID = new FaunusPropertyKey<Object>(
new PropertyKeyDefinition(Tokens.ID, FaunusElement.NO_ID,Cardinality.SINGLE,Long.class),
new Function<FaunusElement, Object>() {
@Nullable
@Override
public Object apply(@Nullable FaunusElement element) {
return element.getId();
}
}
);
public static final FaunusPropertyKey<Long> _ID = new FaunusPropertyKey<Long>(
new PropertyKeyDefinition(Tokens._ID, FaunusElement.NO_ID,Cardinality.SINGLE,Long.class),
new Function<FaunusElement, Long>() {
@Nullable
@Override
public Long apply(@Nullable FaunusElement element) {
return element.getLongId();
}
}
);
public static final FaunusPropertyKey<String> LABEL = new FaunusPropertyKey<String>(
new PropertyKeyDefinition(Tokens.LABEL, FaunusElement.NO_ID,Cardinality.SINGLE,String.class),
new Function<FaunusElement, String>() {
@Nullable
@Override
public String apply(@Nullable FaunusElement element) {
if (element instanceof FaunusVertex) return ((FaunusVertex)element).getLabel();
else if (element instanceof FaunusRelation) return ((FaunusRelation)element).getType().getName();
else return null;
}
}
);
public static final FaunusPropertyKey VALUE = new FaunusPropertyKey(
new PropertyKeyDefinition(Tokens._VALUE, FaunusElement.NO_ID, Cardinality.SINGLE, Object.class),false);
private final PropertyKeyDefinition definition;
private final Function<FaunusElement,T> implicitFunction;
public FaunusPropertyKey(PropertyKeyDefinition definition, boolean isHidden) {
super(definition,isHidden);
this.definition = definition;
this.implicitFunction = null;
}
public FaunusPropertyKey(PropertyKeyDefinition definition, Function<FaunusElement,T> implicitFunction) {
super(definition,false);
Preconditions.checkArgument(definition.getCardinality()==Cardinality.SINGLE);
this.definition = definition;
this.implicitFunction = implicitFunction;
}
@Override
public Class<?> getDataType() {
return definition.getDataType();
}
@Override
public Cardinality getCardinality() {
return definition.getCardinality();
}
@Override
public boolean isPropertyKey() {
return true;
}
@Override
public boolean isEdgeLabel() {
return false;
}
public boolean isImplicit() {
return implicitFunction!=null;
}
public T computeImplicit(FaunusElement element) {
Preconditions.checkArgument(isImplicit());
return implicitFunction.apply(element);
}
}
|
jcalderaio/synzi-mobile-web-app | react/synzi/_shared/src/molecules/AvatarRelated/styles.js | <filename>react/synzi/_shared/src/molecules/AvatarRelated/styles.js
import { createStyleSheet } from '../../../../../features/base/styles';
import { SynziColor } from '../../../Color';
export default createStyleSheet({
mainContainerStyle: {
flexDirection: 'row',
backgroundColor: 'rgba(23, 37, 67, 1)',
width: 300,
height: 150,
borderRadius : 75,
marginBottom: 35,
borderColor: 'black',
borderWidth: 2.0,
},
primaryImageContainer: {
flex:1,
justifyContent: 'center'
},
incomingPrimaryAvatarStyle: {
width:150,
height:150,
borderRadius : 75,
borderColor: 'white',
borderWidth: 1.0,
opacity:1.0
},
incomingSecondaryAvatarStyle: {
width: 70,
height: 70,
borderRadius : 35,
borderColor: 'white',
borderWidth: 1.0,
opacity:1.0,
},
incomingCallTextStyle: {
color: SynziColor.SYNZI_BLUE,
fontSize: 16,
marginTop: 3
},
callerNameTextStyle:{
color: 'white',
width: 130,
fontSize: 16,
fontWeight: '400',
marginTop: 3
},
secondaryContainer: {
flex :1,
flexDirection: 'column'
},
secondaryImageContainer: {
flex: 1,
marginLeft: 40,
justifyContent: 'flex-end'
}
});
|
cmarincia/defold | engine/dlib/src/dmsdk/dlib/dstrings.h | <filename>engine/dlib/src/dmsdk/dlib/dstrings.h<gh_stars>0
// Copyright 2020-2022 The Defold Foundation
// Copyright 2014-2020 King
// Copyright 2009-2014 <NAME>, <NAME>
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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.
#ifndef DMSDK_DSTRINGS_H
#define DMSDK_DSTRINGS_H
#include <stdio.h>
/*# String functions.
*
* SDK Defold String Utils API documentation
*
* @document
* @namespace dmStringFunc
* @name DStrings
* @path engine/dlib/src/dmsdk/dlib/dstrings.h
*/
/*# Size-bounded string formating.
*
* Size-bounded string formating. Resulting string is guaranteed to be 0-terminated.
*
* @name dmSnPrintf
* @param buffer Buffer to write to
* @param count Size of the buffer
* @param format String format
* @return Size of the resulting string (excl terminating 0) if it fits, -1 otherwise
* @examples
*
* ```cpp
* char path[64];
* dmSnPrintf(path, 64, PATH_FORMAT, filename);
* ```
*/
#ifdef __GNUC__
int dmSnPrintf(char *buffer, size_t count, const char *format, ...) __attribute__ ((format (printf, 3, 4)));
#else
int dmSnPrintf(char *buffer, size_t count, const char *format, ...);
#endif
/*# Tokenize strings.
*
* Tokenize strings. Equivalent to BSD strsep_r. Thread-save version of strtok.
*
* @name dmStrTok
* @param string Pointer to string. For the first call string is the string to tokenize. Subsequent should pass NULL.
* @param delim Delimiter string
* @param lasts Internal state pointer
* @return Each call to dmStrTok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, dmStrTok() returns NULL
* @examples
*
* ```cpp
* char* string = strdup("a b c");
* char* s, *last;
* s = dmStrTok(string, " ", &last); // a
* s = dmStrTok(0, " ", &last); // b
* s = dmStrTok(0, " ", &last); // c
* ```
*/
char* dmStrTok(char *string, const char *delim, char **lasts);
/*# Size-bounded string copying.
*
* Size-bounded string copying. Same as OpenBSD 2.4 [strlcpy](http://www.manpagez.com/man/3/strlcpy/).
* Copy src to string dst of size siz. At most siz-1 characters will be copied.
* Always NUL terminates (unless siz == 0).Returns strlen(src); if retval >= siz, truncation occurred.
*
* @name dmStrlCpy
* @param dst Destination string
* @param src Source string
* @param size Max size
* @return Total length of the created string
* @examples
*
* ```cpp
* const char* src = "foo";
* char dst[3];
* dmStrlCpy(dst, src, sizeof(dst)); // dst = "fo"
* ```
*/
size_t dmStrlCpy(char *dst, const char *src, size_t size);
/*# Size-bounded string concatenation.
*
* Size-bounded string concatenation. Same as OpenBSD 2.4 [strlcat](http://www.manpagez.com/man/3/strlcat).
* Appends src to string dst of size siz (unlike strncat, siz is the full size of dst, not space left).
* At most siz-1 characters will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*
* @name dmStrlCat
* @param dst Destination string
* @param src Source string
* @param size Max size
* @return Total length of the created string
* @examples
*
* ```cpp
* const char* src = "foo";
* char dst[3] = { 0 };
* dmStrlCat(dst, src, sizeof(dst)); // dst = "fo"
* ```
*/
size_t dmStrlCat(char *dst, const char *src, size_t size);
/*# Case-insensitive string comparison
*
* Case-insensitive string comparison
*
* @name dmStrCaseCmp
* @param s1 First string to compare
* @param s2 Second string to compare
* @return an integer greater than, equal to, or less than 0 after lexicographically comparison of s1 and s2
* @examples
*
* ```cpp
* dmStrCaseCmp("a", "b"); // <0
* dmStrCaseCmp("b", "a"); // >0
* dmStrCaseCmp("a", "a"); // 0
* ```
*/
int dmStrCaseCmp(const char *s1, const char *s2);
#endif //DMSDK_DSTRINGS_H
|
nickbrandt/gitlab-ui | src/directives/outside/get_event_like_time_stamp.js | <reponame>nickbrandt/gitlab-ui
/**
* This file is based on Vue's scheduler code:
* https://github.com/vuejs/vue/blob/v2.6.12/src/core/observer/scheduler.js#L44-L66
*
* See the LICENSE file in this directory.
*/
const { performance } = window;
/**
* Get a current timestamp that can be meaningfully compared to an event's
* `timeStamp` property.
*
* Event timestamps can be a DOMHighResTimeStamp (if supported), otherwise
* a DOMTimeStamp (used by jsdom and older browsers).
*
* This function will return a current timestamp of the same type used by the
* underlying environment when it creates DOM events.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/Event/timeStamp for
* more details.
*
* @returns {number}
*/
export const getEventLikeTimeStamp =
// If the event timestamp, although evaluated AFTER the Date.now(), is
// smaller, it means the event is using a hi-res timestamp, and we need to
// use the hi-res version for event listener timestamps as well.
typeof performance?.now === 'function' && Date.now() > document.createEvent('Event').timeStamp
? () => performance.now()
: () => Date.now();
|
mjenrungrot/algorithm | UVa Online Judge/v4/410.cc | /*=============================================================================
# Author: <NAME> - https://github.com/mjenrungrot/
# FileName: 410.cc
# Description: UVa Online Judge - 410
=============================================================================*/
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, K;
int n_test = 0;
while (cin >> K >> N) {
cout << "Set #" << (++n_test) << endl;
vector<int> vi;
double avg = 0.0;
for (int i = 1; i <= N; i++) {
int tmp;
cin >> tmp;
vi.push_back(tmp);
avg += (double)tmp;
}
avg /= (double)K;
for (int i = N + 1; i <= 2 * K; i++) vi.push_back(0);
sort(vi.begin(), vi.end());
double ans = 0.0;
for (int i = 0, j = 2 * K - 1; i < j; i++, j--) {
ans += fabs((double)(vi[i] + vi[j]) - avg);
cout << " " << i << ":";
if (vi[i] > 0) cout << " " << vi[i];
if (vi[j] > 0) cout << " " << vi[j];
cout << endl;
}
cout << "IMBALANCE = " << fixed << setprecision(5) << ans << endl;
cout << endl;
}
return 0;
} |
Capeia/capeia | src/public/Nav.js | // @flow
import React from 'react'
import Link from 'found/lib/Link'
import appConfig from 'config-app'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './Nav.scss'
const Nav = () => {
const items = Object.keys(appConfig.sections).map(slug => (
<NavItem key={slug} name={appConfig.sections[slug].name} img={appConfig.sections[slug].icon} linkTo={`/${slug}`} />
))
return (
<nav className={s['main-nav']} role='navigation'>
<ul>
{items}
</ul>
</nav>
)
}
export default withStyles(s)(Nav)
const NavItem = ({name, img, linkTo}: {name: string, img: string, linkTo: string}) => {
return (
<li>
<Link to={linkTo} activeClassName={s.active}>
<img src={img} alt='' />
{name}
</Link>
</li>
)
}
|
NGliese/Embedded | linux/RPI/OutDoorMain_CCTV/LibraryModule-1.0-Source/docs/html/search/functions_7.js | var searchData=
[
['hal_5fesp32_881',['HAL_ESP32',['../d4/dc1/class_h_a_l___e_s_p32.html#a8417734fbdb0f7129285f042e484977e',1,'HAL_ESP32']]],
['handle_882',['handle',['../dd/d84/class_fault___handler.html#a7d2101d68cd182ddd66b389ddf83aa35',1,'Fault_Handler']]],
['handle_5fevent_883',['handle_event',['../d5/de7/classmqtt__api__v2.html#a05889dd05c9903e733f8a6aff7d555dd',1,'mqtt_api_v2']]],
['handlefault_884',['handleFault',['../dd/d84/class_fault___handler.html#a8d16396cdc318f240c1b626c84a342aa',1,'Fault_Handler']]],
['handlesensor_885',['handleSensor',['../d1/da4/class_sensor___base.html#a3a16a7ed0a2e7441182f54ebd088cbcb',1,'Sensor_Base']]],
['http_5finterface_886',['http_interface',['../dc/dc2/classhttp__interface.html#a6bb433e5107687e03ed0e47bd28a7ca8',1,'http_interface']]]
];
|
TaoWang4446/WeChatEnterprise-master | WeChatEnterprise/src/wx/menu/package-info.java | /**
* WeChatEnterprise框架菜单创建、生成包
* <p>
* 注意:该包下所有get、set的方法名,请不要随意改动
* <p>
* 因为net.sf.json.JSONObject类将bean转成json的时候,会根据class内的方法名等属性作为json的key名称
* <p>
* 所以请不要随意改动该包下的所有get、set方法名
*
* @author <a href="https://github.com/Mr-Jiang">Mr-Jiang</a>
* @date 2018.08.27 15:35
*/
package wx.menu; |
Terebinth/freefalcon-central | src/ui95/soundrsc.h | #ifndef _SOUND_RSC_H_
#define _SOUND_RSC_H_
//
// This class is TIED to the C_Resmgr class (which holds the actual sound data)
//
// (So you need both to actually be able to play a sound)
//
// First item MUST be short Type
class SoundHeader
{
#ifdef USE_SH_POOLS
public:
// Overload new/delete to use a SmartHeap pool
void *operator new(size_t size)
{
return MemAllocPtr(UI_Pools[UI_SOUND_POOL], size, FALSE);
};
void operator delete(void *mem)
{
if (mem) MemFreePtr(mem);
};
#endif
public:
long Type;
char ID[32];
long flags;
short Channels;
short SoundType;
long offset;
long headersize;
};
class SOUND_RSC
{
#ifdef USE_SH_POOLS
public:
// Overload new/delete to use a SmartHeap pool
void *operator new(size_t size)
{
return MemAllocPtr(UI_Pools[UI_SOUND_POOL], size, FALSE);
};
void operator delete(void *mem)
{
if (mem) MemFreePtr(mem);
};
#endif
public:
long ID;
C_Resmgr *Owner;
SoundHeader *Header;
BOOL Play(int Stream);
BOOL Loop(int Stream);
BOOL Stream(int Stream);
};
#endif
|
lichanghong/CHBaseUtil | FLEXInspector/Classes/log/VZLogInspector.h | <reponame>lichanghong/CHBaseUtil
//
// VZLogInspector.h
// VZInspector
//
// Created by moxin.xt on 14-12-16.
// Copyright (c) 2014年 VizLab. All rights reserved.
//
#import <Foundation/Foundation.h>
#define kVZDefaultNumberOfLogs 20
@class VZLogInspectorEntity;
@protocol VZLogInspectorDelegate <NSObject>
- (void)logMessage:(VZLogInspectorEntity *)message;
@end
@interface VZLogInspectorEntity:NSObject
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, copy) NSString *sender;
@property (nonatomic, copy) NSString *messageText;
@property (nonatomic, assign) long long messageID;
@property (nonatomic, assign) NSUInteger level;
@end
@interface VZLogInspector : NSObject
@property(nonatomic,copy) NSArray *searchList;
+ (instancetype) sharedInstance;
@property (nonatomic, strong) NSMutableArray *observers;
@property (nonatomic, assign) id<VZLogInspectorDelegate> delegate;
+ (void)setNumberOfLogs:(NSUInteger)num;
+ (NSArray* )logs;
+ (NSAttributedString* )logsString:(NSString *)searchkey;
+(NSAttributedString *)formatLog:(VZLogInspectorEntity *)entity searchkey:(NSString *)searchKey;
+ (void)start;
+ (void)stop;
- (void)addObserver:(id<VZLogInspectorDelegate>)observer;
- (void)removeObserver:(id<VZLogInspectorDelegate>)observer;
@end
|
ZRY551-DevelopGroup/MCMod_IKnowIt | build/tmp/expandedArchives/forge-1.16.5-36.2.19_mapped_official_1.16.5-sources.jar_96953985799bf045b80c10dc6b54685a/net/minecraft/entity/ai/controller/DolphinLookController.java | <filename>build/tmp/expandedArchives/forge-1.16.5-36.2.19_mapped_official_1.16.5-sources.jar_96953985799bf045b80c10dc6b54685a/net/minecraft/entity/ai/controller/DolphinLookController.java
package net.minecraft.entity.ai.controller;
import net.minecraft.entity.MobEntity;
import net.minecraft.util.math.MathHelper;
public class DolphinLookController extends LookController {
private final int maxYRotFromCenter;
public DolphinLookController(MobEntity p_i48942_1_, int p_i48942_2_) {
super(p_i48942_1_);
this.maxYRotFromCenter = p_i48942_2_;
}
public void tick() {
if (this.hasWanted) {
this.hasWanted = false;
this.mob.yHeadRot = this.rotateTowards(this.mob.yHeadRot, this.getYRotD() + 20.0F, this.yMaxRotSpeed);
this.mob.xRot = this.rotateTowards(this.mob.xRot, this.getXRotD() + 10.0F, this.xMaxRotAngle);
} else {
if (this.mob.getNavigation().isDone()) {
this.mob.xRot = this.rotateTowards(this.mob.xRot, 0.0F, 5.0F);
}
this.mob.yHeadRot = this.rotateTowards(this.mob.yHeadRot, this.mob.yBodyRot, this.yMaxRotSpeed);
}
float f = MathHelper.wrapDegrees(this.mob.yHeadRot - this.mob.yBodyRot);
if (f < (float)(-this.maxYRotFromCenter)) {
this.mob.yBodyRot -= 4.0F;
} else if (f > (float)this.maxYRotFromCenter) {
this.mob.yBodyRot += 4.0F;
}
}
} |
RomanSechin/C_Projects | 12_03_loc_stat.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
void trystat(void);
int main()
{
setlocale(0,"RUS");
int count;
for( count = 1; count <= 3; ++count)
{
printf("The iteration %d:\n", count);
trystat();
}
return 0;
}
void trystat(void)
{
int fade = 1;
static int stay = 1;
printf("fade = %d and stay = %d\n", fade, stay++);
}
|
commsen/EM | demos/demo.command/src/main/java/com/commsen/em/demo/command/gogo/HelloCommand.java | <reponame>commsen/EM
package com.commsen.em.demo.command.gogo;
import org.apache.felix.service.command.Descriptor;
import org.apache.felix.service.command.Parameter;
import org.osgi.service.component.annotations.Component;
import com.commsen.em.annotations.RequiresLocalConsole;
@Component( //
property = { //
"osgi.command.function=hello", //
"osgi.command.function=greet", //
"osgi.command.scope=em" //
}, //
service = Object.class //
)
@RequiresLocalConsole
public class HelloCommand {
@Descriptor("Says hello")
public void hello () {
System.out.println("Hello there!");
}
@Descriptor("Greets someone")
public void greet (@Parameter(names="-n", absentValue="stranger") String name) {
System.out.println("Hello " + name + "!");
}
}
|
ShafranEugene/irida-telegrambot | src/test/java/com/github/iridatelegrambot/test/service/sendlers/SendMessageServiceImplTest.java | package com.github.iridatelegrambot.test.service.sendlers;
import com.github.iridatelegrambot.bot.IridaBot;
import com.github.iridatelegrambot.service.senders.SendMessageService;
import com.github.iridatelegrambot.service.senders.SendMessageServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.*;
class SendMessageServiceImplTest {
private SendMessageService sendMessageService;
private IridaBot mIridaBot;
@BeforeEach
void init(){
mIridaBot = Mockito.mock(IridaBot.class);
sendMessageService = new SendMessageServiceImpl(mIridaBot);
}
@Test
void shouldSendMessage() throws TelegramApiException {
//given
String chatId = "test_id";
String message = "test_message";
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId);
sendMessage.setText(message);
sendMessage.enableHtml(true);
//when
sendMessageService.sendMessage(chatId,message);
//then
Mockito.verify(mIridaBot).execute(sendMessage);
}
@Test
void shouldSendMessageWithButtons() throws TelegramApiException {
//given
String chatId = "test_id";
String message = "test_message";
List<List<InlineKeyboardButton>> rows = new ArrayList<>();
rows.add(new ArrayList<>());
InlineKeyboardButton button = new InlineKeyboardButton();
button.setText("test_button");
button.setText("/test_button");
rows.get(0).add(button);
InlineKeyboardMarkup markup = new InlineKeyboardMarkup();
markup.setKeyboard(rows);
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId);
sendMessage.setText(message);
sendMessage.enableHtml(true);
sendMessage.setReplyMarkup(markup);
//when
sendMessageService.sendMessage(chatId,message,markup);
//then
Mockito.verify(mIridaBot).execute(sendMessage);
}
@Test
void shouldProperlyDeleteMessage() throws TelegramApiException {
//given
Long chatId = 12345678L;
Integer idMessage = 20;
DeleteMessage deleteMessage = new DeleteMessage();
deleteMessage.setMessageId(idMessage);
deleteMessage.setChatId(chatId.toString());
//when
sendMessageService.deleteMessage(chatId,idMessage);
//then
Mockito.verify(mIridaBot).execute(deleteMessage);
}
} |
tianxiaogu/r8 | src/test/java/com/android/tools/r8/regress/b69825683/Regress69825683Test.java | <filename>src/test/java/com/android/tools/r8/regress/b69825683/Regress69825683Test.java<gh_stars>0
// Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.regress.b69825683;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.android.tools.r8.DexIndexedConsumer;
import com.android.tools.r8.R8Command;
import com.android.tools.r8.TestBase;
import com.android.tools.r8.ToolHelper;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.utils.AndroidApp;
import com.android.tools.r8.utils.DexInspector;
import com.android.tools.r8.utils.DexInspector.FoundClassSubject;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.junit.Test;
public class Regress69825683Test extends TestBase {
@Test
public void outerConstructsInner() throws Exception {
Class mainClass = com.android.tools.r8.regress.b69825683.outerconstructsinner.Outer.class;
R8Command.Builder builder = R8Command.builder();
builder.addProgramFiles(ToolHelper.getClassFilesForTestPackage(mainClass.getPackage()));
builder.addProguardConfiguration(ImmutableList.of(
"-keep class " + mainClass.getCanonicalName() + " {",
" public static void main(java.lang.String[]);",
"}",
"-dontobfuscate"),
Origin.unknown());
builder.setProgramConsumer(DexIndexedConsumer.emptyConsumer());
AndroidApp app = ToolHelper.runR8(builder.build());
DexInspector inspector = new DexInspector(app);
List<FoundClassSubject> classes = inspector.allClasses();
// Check that the synthetic class is still present.
assertEquals(3, classes.size());
assertEquals(1,
classes.stream()
.map(FoundClassSubject::getOriginalName)
.filter(name -> name.endsWith("$1"))
.count());
// Run code to check that the constructor with synthetic class as argument is present.
Class innerClass =
com.android.tools.r8.regress.b69825683.outerconstructsinner.Outer.Inner.class;
String innerName = innerClass.getCanonicalName();
int index = innerName.lastIndexOf('.');
innerName = innerName.substring(0, index) + "$" + innerName.substring(index + 1);
assertTrue(runOnArt(app, mainClass).startsWith(innerName));
}
@Test
public void innerConstructsOuter() throws Exception {
Class mainClass = com.android.tools.r8.regress.b69825683.innerconstructsouter.Outer.class;
R8Command.Builder builder = R8Command.builder();
builder.addProgramFiles(ToolHelper.getClassFilesForTestPackage(mainClass.getPackage()));
builder.addProguardConfiguration(ImmutableList.of(
"-keep class " + mainClass.getCanonicalName() + " {",
" public static void main(java.lang.String[]);",
"}",
"-dontobfuscate"),
Origin.unknown());
builder.setProgramConsumer(DexIndexedConsumer.emptyConsumer());
AndroidApp app = ToolHelper.runR8(builder.build());
DexInspector inspector = new DexInspector(app);
List<FoundClassSubject> classes = inspector.allClasses();
// Check that the synthetic class is still present.
assertEquals(3, classes.size());
assertEquals(1,
classes.stream()
.map(FoundClassSubject::getOriginalName)
.filter(name -> name.endsWith("$1"))
.count());
// Run code to check that the constructor with synthetic class as argument is present.
assertTrue(runOnArt(app, mainClass).startsWith(mainClass.getCanonicalName()));
}
}
|
lechium/iOS1351Headers | System/Library/PrivateFrameworks/SetupAssistant.framework/BFFSettingsManager.h | <filename>System/Library/PrivateFrameworks/SetupAssistant.framework/BFFSettingsManager.h<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.5
* on Friday, April 30, 2021 at 11:36:17 AM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/SetupAssistant.framework/SetupAssistant
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
@class NSMutableArray, NSMutableDictionary, NSNumber, NSData, NSArray, NSDictionary;
@interface BFFSettingsManager : NSObject {
NSMutableArray* _stashedPaths;
NSMutableDictionary* _stashedPreferences;
NSMutableDictionary* _stashedManagedConfigurationSettings;
NSMutableArray* _stashedButtonHaptics;
NSNumber* _stashedAssistantEnabled;
NSNumber* _stashedAssistantVoiceTriggerEnabled;
NSNumber* _stashedSiriDataSharingOptInStatus;
NSNumber* _stashedLocationServicesEnabled;
NSData* _stashedLocationServicesSettings;
NSData* _stashedWatchData;
NSArray* _stashedFlowSkipIdentifiers;
NSNumber* _stashedScreenTimeEnabled;
NSNumber* _stashedAutoUpdateEnabled;
NSData* _stashedAccessibilityData;
NSDictionary* _stashedDeviceToDeviceMigrationSuccessInfo;
NSNumber* _stashedUserInterfaceStyleMode;
}
+(id)sharedManager;
-(id)init;
-(void)reset;
-(BOOL)hasStashedValuesOnDisk;
-(BOOL)removeSafeHaven;
-(void)postDidRestoreSafeHavenNotification;
-(void)setScreenTimeEnabled:(BOOL)arg1 ;
-(void)setAutoUpdateEnabled:(BOOL)arg1 ;
-(void)setUserInterfaceStyleMode:(long long)arg1 ;
-(void)_reset:(BOOL)arg1 ;
-(id)loadConfigurationFromDisk;
-(void)setObject:(id)arg1 forDomain:(id)arg2 key:(id)arg3 ;
-(id)_preferencesForDomain:(id)arg1 ;
-(void)stashPath:(id)arg1 ;
-(void)clearHapticTypeForButtonKind:(long long)arg1 ;
-(BOOL)hideStashInSafeHavenAsProvisional:(BOOL)arg1 ;
-(void)populatePathsToStash;
-(BOOL)hasStashedValues;
-(long long)stashConfigurationType;
-(BOOL)_stashConfiguration:(BOOL)arg1 ;
-(BOOL)_stashPaths;
-(BOOL)_commitStash;
-(id)stashProductVersion;
-(id)stashBuildVersion;
-(unsigned long long)_restoreConfiguration;
-(void)_applyStashedPreferences;
-(void)_applyStashedManagedConfiguration;
-(void)_applyStashedButtonHaptics;
-(void)_applyAssistantPreferences;
-(void)_applyLocationServices;
-(void)_applyLocationServicesSettings;
-(void)_restoreWatchData;
-(void)_applyStashedFlowSkipIdentifiers;
-(void)_applyScreenTimePreferences;
-(void)_applyAutoUpdatePreferences;
-(void)_restoreAccessibilityData;
-(void)_applyUserInterfaceStyleMode;
-(void)_restoreStashedFiles;
-(id)_shovePath:(id)arg1 toPath:(id)arg2 ;
-(unsigned long long)stashVersion;
-(void)setBool:(BOOL)arg1 forManagedConfigurationSetting:(id)arg2 ;
-(void)removeBoolSettingForManagedConfigurationSetting:(id)arg1 ;
-(void)setBool:(BOOL)arg1 forDomain:(id)arg2 key:(id)arg3 ;
-(void)stashHapticType:(long long)arg1 forButtonKind:(long long)arg2 ;
-(void)stashLocationServicesChoice:(BOOL)arg1 ;
-(void)stashLocationServicesSettings:(id)arg1 ;
-(void)stashWatchData:(id)arg1 ;
-(void)setAssistantEnabled:(BOOL)arg1 ;
-(void)setAssistantVoiceTriggerEnabled:(BOOL)arg1 ;
-(void)stashDeviceToDeviceMigrationSuccessInfo:(id)arg1 ;
-(void)stashFlowSkipIdentifiers:(id)arg1 ;
-(void)stashAccessibilityData:(id)arg1 ;
-(BOOL)hideStashInSafeHaven;
-(void)applySafeHavenStash;
@end
|
ligangty/scalajsoup | src/main/scala/com/github/ligangty/scala/jsoup/parser/Tag.scala | package com.github.ligangty.scala.jsoup.parser
import com.github.ligangty.scala.jsoup.helper.Validator._
/**
* HTML Tag capabilities.
*
* @constructor default constructor
* @param tagName tag name
* @param block block or inline
* @param containBlock Can this tag hold block level tags?
* @param formatAsBlock should be formatted as a block
*
*/
class Tag private(private var tagName: String, private var block: Boolean, private var containBlock: Boolean, private var formatAsBlock: Boolean) {
tagName = tagName.toLowerCase
// only pcdata if not
private var canContainInline: Boolean = true
// can hold nothing; e.g. img
private var empty: Boolean = false
// can self close (<foo />). used for unknown tags that self close, without forcing them as empty.
private var selfClosing: Boolean = false
// for pre, textarea, script etc
private var preserveWhitespace: Boolean = false
// a control that appears in forms: input, textarea, output etc
private var formList: Boolean = false
// a control that can be submitted in a form: input etc
private var formSubmit: Boolean = false
private def this(tagName: String) {
this(tagName, true, true, true)
}
private def this(tagName: String, block: Boolean, containBlock: Boolean) {
this(tagName, block, containBlock, true)
}
/**
* Get this tag's name.
*
* @return the tag's name
*/
def getName: String = tagName
/**
* If this is a block tag.
*/
def isBlock: Boolean = block
/**
* if this tag should be formatted as a block (or as inline)
*/
def isFormatAsBlock: Boolean = formatAsBlock
/**
* if this tag can contain block tags.
*/
def canContainBlock: Boolean = containBlock
/**
* if this is an empty tag
*/
def isEmpty: Boolean = empty
/**
* Gets if this tag is an inline tag.
*
* @return if this tag is an inline tag.
*/
def isInline: Boolean = !isBlock
/**
* Gets if this tag is a data only tag.
*
* @return if this tag is a data only tag
*/
def isData: Boolean = !canContainInline && !isEmpty
/**
* Get if this tag is self closing.
*
* @return if this tag should be output as self closing.
*/
def isSelfClosing: Boolean = {
isEmpty || selfClosing
}
/**
* Get if this is a pre-defined tag, or was auto created on parsing.
*
* @return if a known tag
*/
def isKnownTag: Boolean = {
Tag.tags.contains(tagName)
}
/**
* Check if this tagname is a known tag.
*
* @param tagName name of tag
* @return if known HTML tag
*/
def isKnownTag(tagName: String): Boolean = {
Tag.tags.contains(tagName)
}
/**
* Get if this tag should preserve whitespace within child text nodes.
*
* @return if preserve whitepace
*/
def isPreserveWhitespace: Boolean = preserveWhitespace
/**
* Get if this tag represents a control associated with a form. E.g. input, textarea, output
* @return if associated with a form
*/
def isFormListed: Boolean = {
formList
}
/**
* Get if this tag represents an element that should be submitted with a form. E.g. input, option
* @return if submittable with a form
*/
def isFormSubmittable: Boolean = {
formSubmit
}
private[parser] def setSelfClosing(): Tag = {
selfClosing = true
this
}
override def equals(o: Any): Boolean = o match {
case that: Tag =>
that.tagName == this.tagName &&
that.canContainBlock == this.canContainBlock &&
that.canContainInline == this.canContainInline &&
that.isEmpty == this.isEmpty &&
that.isFormatAsBlock == this.isFormatAsBlock &&
that.isBlock == this.isBlock &&
that.preserveWhitespace == this.preserveWhitespace &&
that.selfClosing == this.selfClosing &&
that.formList == this.formList &&
that.formSubmit == this.formSubmit
case _ => false
}
import scala.language.implicitConversions
implicit private def booleanToInt(boolVal: Boolean): Int = if (boolVal) {
1
} else {
0
}
override def hashCode: Int = {
var result: Int = tagName.hashCode
result = 31 * result + block
result = 31 * result + formatAsBlock
result = 31 * result + containBlock
result = 31 * result + canContainInline
result = 31 * result + empty
result = 31 * result + selfClosing
result = 31 * result + preserveWhitespace
result = 31 * result + formList
result = 31 * result + formSubmit
result
}
override def toString: String = {
tagName
}
}
object Tag {
private val blockTags: Array[String] = Array("html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame", "noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins", "del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th", "td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main", "svg", "math")
private val inlineTags: Array[String] = Array("object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q", "sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup", "option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track", "summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track", "data", "bdi")
private val emptyTags: Array[String] = Array("meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track")
private val formatAsInlineTags: Array[String] = Array("title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style", "ins", "del", "s")
private val preserveWhitespaceTags: Array[String] = Array("pre", "plaintext", "title", "textarea")
private val formListedTags: Array[String] = Array("button", "fieldset", "input", "keygen", "object", "output", "select", "textarea")
private val formSubmitTags: Array[String] = Array("input", "keygen", "object", "select", "textarea")
// creates
private val tags: Map[String, Tag] = initTags()
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". Case insensitive.
* @return The tag, either defined or new generic.
*/
def apply(tagName: String): Tag = {
notNull(tagName)
tags.get(tagName) match {
case Some(find1: Tag) => find1
case None =>
notEmpty(tagName.trim.toLowerCase)
tags.get(tagName.trim.toLowerCase) match {
case Some(find2: Tag) => find2
case None => new Tag(tagName, false, true)
}
}
}
private def initTags(): Map[String, Tag] = {
import scala.collection.mutable
val tagsV: mutable.Map[String, Tag] = new mutable.HashMap()
for (tagName <- blockTags) {
tagsV += (tagName -> new Tag(tagName))
}
for (tagName <- inlineTags) {
tagsV += (tagName -> new Tag(tagName, false, false, false))
}
// mods:
for (tagName <- emptyTags) {
val tag = tagsV(tagName)
notNull(tag)
tag.containBlock = false
tag.canContainInline = false
tag.empty = true
tagsV(tagName) = tag
}
for (tagName <- formatAsInlineTags) {
val tag = tagsV(tagName)
notNull(tag)
tag.formatAsBlock = false
tagsV(tagName) = tag
}
for (tagName <- preserveWhitespaceTags) {
val tag = tagsV(tagName)
notNull(tag)
tag.preserveWhitespace = true
tagsV(tagName) = tag
}
for (tagName <- formListedTags) {
val tag = tagsV(tagName)
notNull(tag)
tag.formList = true
tagsV(tagName) = tag
}
for (tagName <- formSubmitTags) {
val tag = tagsV(tagName)
notNull(tag)
tag.formSubmit = true
tagsV(tagName) = tag
}
tagsV.toMap
}
} |
jlpedrosa/accumulo | server/master/src/main/java/org/apache/accumulo/master/replication/WorkDriver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.master.replication;
import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.util.Daemon;
import org.apache.accumulo.master.Master;
import org.apache.accumulo.server.replication.WorkAssigner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Driver for a {@link WorkAssigner}
*/
public class WorkDriver extends Daemon {
private static final Logger log = LoggerFactory.getLogger(WorkDriver.class);
private Master master;
private AccumuloClient client;
private AccumuloConfiguration conf;
private WorkAssigner assigner;
private String assignerImplName;
public WorkDriver(Master master) {
super();
this.master = master;
this.client = master.getContext();
this.conf = master.getConfiguration();
configureWorkAssigner();
}
protected void configureWorkAssigner() {
String workAssignerClass = conf.get(Property.REPLICATION_WORK_ASSIGNER);
if (assigner == null || !assigner.getClass().getName().equals(workAssignerClass)) {
log.info("Initializing work assigner implementation of {}", workAssignerClass);
try {
Class<?> clz = Class.forName(workAssignerClass);
Class<? extends WorkAssigner> workAssignerClz = clz.asSubclass(WorkAssigner.class);
this.assigner = workAssignerClz.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
log.error("Could not instantiate configured work assigner {}", workAssignerClass, e);
throw new RuntimeException(e);
}
this.assigner.configure(conf, client);
this.assignerImplName = assigner.getClass().getName();
this.setName(assigner.getName());
}
}
@Override
public void run() {
log.info("Starting replication work assignment thread using {}", assignerImplName);
while (master.stillMaster()) {
// Assign the work using the configured implementation
try {
assigner.assignWork();
} catch (Exception e) {
log.error("Error while assigning work", e);
}
long sleepTime = conf.getTimeInMillis(Property.REPLICATION_WORK_ASSIGNMENT_SLEEP);
log.debug("Sleeping {} ms before next work assignment", sleepTime);
sleepUninterruptibly(sleepTime, TimeUnit.MILLISECONDS);
// After each loop, make sure that the WorkAssigner implementation didn't change
configureWorkAssigner();
}
}
}
|
ShekharPaatni/SDK | atom/nucleus/javascript/test/api/ModelApi.spec.js | <filename>atom/nucleus/javascript/test/api/ModelApi.spec.js
/*
* Hydrogen Nucleus API
* The Hydrogen Nucleus API
*
* OpenAPI spec version: 1.9.4
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.19
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.HydrogenNucleusApi);
}
}(this, function(expect, HydrogenNucleusApi) {
'use strict';
var instance;
beforeEach(function() {
instance = new HydrogenNucleusApi.ModelApi();
});
describe('(package)', function() {
describe('ModelApi', function() {
describe('createModelAssetSizeUsingPost', function() {
it('should call createModelAssetSizeUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelAssetSizeUsingPost call and complete the assertions
/*
var req = new HydrogenNucleusApi.ModelAssetSize();
req.assetSize = 0.9;
req.currencyCode = "USD";
req._date = 2018-01-09'T'12:00:00;
req.isReconciled = true;
req.modelId = "62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d";
instance.createModelAssetSizeUsingPost(req, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelAssetSize);
expect(data.assetSize).to.be.a('number');
expect(data.assetSize).to.be(0.9);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isReconciled).to.be.a('boolean');
expect(data.isReconciled).to.be(true);
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('createModelChangeUsingPost', function() {
it('should call createModelChangeUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelChangeUsingPost call and complete the assertions
/*
var changeRequest = new HydrogenNucleusApi.OrderReconcileRequest();
changeRequest.accountId = """00000000-0000-0000-0000-000000000000";
changeRequest.nonFractional = false;
changeRequest.orderTrackIds = ["""00000000-0000-0000-0000-000000000000"];
changeRequest.portfolioId = """00000000-0000-0000-0000-000000000000";
changeRequest.tenantId = """00000000-0000-0000-0000-000000000000";
var modelId = "modelId_example";
instance.createModelChangeUsingPost(changeRequest, modelId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
let dataCtr = data;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.ModelTransaction);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.price).to.be.a('number');
expect(data.price).to.be(100.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.shares).to.be.a('number');
expect(data.shares).to.be(100.0);
expect(data.transactionCodeId).to.be.a('string');
expect(data.transactionCodeId).to.be("f5af397b-7d22-433f-b01e-8202184a6386");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('createModelCommentUsingPost', function() {
it('should call createModelCommentUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelCommentUsingPost call and complete the assertions
/*
var modelCommentRequest = new HydrogenNucleusApi.ModelComment();
modelCommentRequest.comment = "sample";
modelCommentRequest._date = 2018-01-09'T'12:00:00;
modelCommentRequest.metadata = {key: ""};
modelCommentRequest.modelId = "62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d";
instance.createModelCommentUsingPost(modelCommentRequest, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelComment);
expect(data.comment).to.be.a('string');
expect(data.comment).to.be("sample");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('createModelHoldingUsingPost', function() {
it('should call createModelHoldingUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelHoldingUsingPost call and complete the assertions
/*
var modelHoldingRequest = new HydrogenNucleusApi.ModelHolding();
modelHoldingRequest.currentWeight = 0.88;
modelHoldingRequest._date = 2018-01-09'T'12:00:00;
modelHoldingRequest.driftFactor = 0.9;
modelHoldingRequest.isCash = true;
modelHoldingRequest.isInitialHolding = true;
modelHoldingRequest.isSafeSecurity = true;
modelHoldingRequest.modelDescription = "";
modelHoldingRequest.modelId = "62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d";
modelHoldingRequest.modelName = "";
modelHoldingRequest.modelWeight = 0.0;
modelHoldingRequest.secPrice = 0.0;
modelHoldingRequest.securityId = "29c3f995-bd45-4346-aea2-fd4476568d4c";
modelHoldingRequest.strategicWeight = 0.89;
instance.createModelHoldingUsingPost(modelHoldingRequest, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelHolding);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currentWeight).to.be.a('number');
expect(data.currentWeight).to.be(0.88);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.driftFactor).to.be.a('number');
expect(data.driftFactor).to.be(0.9);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isCash).to.be.a('boolean');
expect(data.isCash).to.be(true);
expect(data.isInitialHolding).to.be.a('boolean');
expect(data.isInitialHolding).to.be(true);
expect(data.isSafeSecurity).to.be.a('boolean');
expect(data.isSafeSecurity).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelDescription).to.be.a('string');
expect(data.modelDescription).to.be("");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.modelName).to.be.a('string');
expect(data.modelName).to.be("");
expect(data.modelWeight).to.be.a('number');
expect(data.modelWeight).to.be(0.0);
expect(data.secPrice).to.be.a('number');
expect(data.secPrice).to.be(0.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.strategicWeight).to.be.a('number');
expect(data.strategicWeight).to.be(0.89);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('createModelTransactionUsingPost', function() {
it('should call createModelTransactionUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelTransactionUsingPost call and complete the assertions
/*
var modelTransactionRequest = new HydrogenNucleusApi.ModelTransaction();
modelTransactionRequest._date = 2018-01-09'T'12:00:00;
modelTransactionRequest.modelId = "62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d";
modelTransactionRequest.price = 100.0;
modelTransactionRequest.securityId = "29c3f995-bd45-4346-aea2-fd4476568d4c";
modelTransactionRequest.shares = 100.0;
modelTransactionRequest.transactionCodeId = "f5af397b-7d22-433f-b01e-8202184a6386";
instance.createModelTransactionUsingPost(modelTransactionRequest, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelTransaction);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.price).to.be.a('number');
expect(data.price).to.be(100.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.shares).to.be.a('number');
expect(data.shares).to.be(100.0);
expect(data.transactionCodeId).to.be.a('string');
expect(data.transactionCodeId).to.be("f5af397b-7d22-433f-b01e-8202184a6386");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('createModelUsingPost', function() {
it('should call createModelUsingPost successfully', function(done) {
// TODO: uncomment, update parameter values for createModelUsingPost call and complete the assertions
/*
var modelInfoRequest = new HydrogenNucleusApi.Model();
modelInfoRequest.benchmarkId = "f3c384dd-5895-4da8-a356-61f266269082";
modelInfoRequest.cashSec = "1";
modelInfoRequest.category = "tech";
modelInfoRequest.clientId = "2035f52d-2c5b-4e07-8904-cb037bad7aff";
modelInfoRequest.currencyCode = "USD";
modelInfoRequest.defaultDriftFactor = 0.55;
modelInfoRequest.description = "consists of tech ETFs";
modelInfoRequest.downside = true;
modelInfoRequest.driftRebal = true;
modelInfoRequest.isActive = true;
modelInfoRequest.metadata = {key: ""};
modelInfoRequest.name = "Tech model";
modelInfoRequest.nodeMap = [new HydrogenNucleusApi.AllocationNodeMap()];
modelInfoRequest.nodeMap[0].nodeId = "6e14259a-9a68-4593-9e6d-8fcd0d05cf44";
modelInfoRequest.periodRebal = true;
modelInfoRequest.rebalancePeriod = 12;
modelInfoRequest.safeSec = "1";
modelInfoRequest.secRotation = true;
modelInfoRequest.taxEfficiencyId = 1;
instance.createModelUsingPost(modelInfoRequest, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.Model);
expect(data.benchmarkId).to.be.a('string');
expect(data.benchmarkId).to.be("f3c384dd-5895-4da8-a356-61f266269082");
expect(data.cashSec).to.be.a('string');
expect(data.cashSec).to.be("1");
expect(data.category).to.be.a('string');
expect(data.category).to.be("tech");
expect(data.clientId).to.be.a('string');
expect(data.clientId).to.be("2035f52d-2c5b-4e07-8904-cb037bad7aff");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data.defaultDriftFactor).to.be.a('number');
expect(data.defaultDriftFactor).to.be(0.55);
expect(data.description).to.be.a('string');
expect(data.description).to.be("consists of tech ETFs");
expect(data.downside).to.be.a('boolean');
expect(data.downside).to.be(true);
expect(data.driftRebal).to.be.a('boolean');
expect(data.driftRebal).to.be(true);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isActive).to.be.a('boolean');
expect(data.isActive).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.name).to.be.a('string');
expect(data.name).to.be("Tech model");
{
let dataCtr = data.nodeMap;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.AllocationNodeMap);
expect(data.nodeId).to.be.a('string');
expect(data.nodeId).to.be("6e14259a-9a68-4593-9e6d-8fcd0d05cf44");
}
}
expect(data.periodRebal).to.be.a('boolean');
expect(data.periodRebal).to.be(true);
expect(data.rebalancePeriod).to.be.a('number');
expect(data.rebalancePeriod).to.be(12);
expect(data.safeSec).to.be.a('string');
expect(data.safeSec).to.be("1");
expect(data.secRotation).to.be.a('boolean');
expect(data.secRotation).to.be(true);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.taxEfficiencyId).to.be.a('number');
expect(data.taxEfficiencyId).to.be(1);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('deleteModelAssetSizeUsingDelete', function() {
it('should call deleteModelAssetSizeUsingDelete successfully', function(done) {
// TODO: uncomment, update parameter values for deleteModelAssetSizeUsingDelete call
/*
var modelAssetSizeId = "modelAssetSizeId_example";
instance.deleteModelAssetSizeUsingDelete(modelAssetSizeId, function(error, data, response) {
if (error) {
done(error);
return;
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('deleteModelCommentUsingDelete', function() {
it('should call deleteModelCommentUsingDelete successfully', function(done) {
// TODO: uncomment, update parameter values for deleteModelCommentUsingDelete call
/*
var modelCommentId = "modelCommentId_example";
instance.deleteModelCommentUsingDelete(modelCommentId, function(error, data, response) {
if (error) {
done(error);
return;
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('deleteModelHoldingUsingDelete', function() {
it('should call deleteModelHoldingUsingDelete successfully', function(done) {
// TODO: uncomment, update parameter values for deleteModelHoldingUsingDelete call
/*
var modelHoldingId = "modelHoldingId_example";
instance.deleteModelHoldingUsingDelete(modelHoldingId, function(error, data, response) {
if (error) {
done(error);
return;
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('deleteModelTransactionUsingDelete', function() {
it('should call deleteModelTransactionUsingDelete successfully', function(done) {
// TODO: uncomment, update parameter values for deleteModelTransactionUsingDelete call
/*
var modelTransactionId = "modelTransactionId_example";
instance.deleteModelTransactionUsingDelete(modelTransactionId, function(error, data, response) {
if (error) {
done(error);
return;
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('deleteModelUsingDelete', function() {
it('should call deleteModelUsingDelete successfully', function(done) {
// TODO: uncomment, update parameter values for deleteModelUsingDelete call
/*
var modelId = "modelId_example";
instance.deleteModelUsingDelete(modelId, function(error, data, response) {
if (error) {
done(error);
return;
}
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelAllUsingGet', function() {
it('should call getModelAllUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelAllUsingGet call and complete the assertions
/*
var opts = {};
opts.ascending = false;
opts.filter = "filter_example";
opts.orderBy = "update_date";
opts.page = 0;
opts.size = 25;
instance.getModelAllUsingGet(opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.PageModel);
{
let dataCtr = data.content;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Model);
expect(data.benchmarkId).to.be.a('string');
expect(data.benchmarkId).to.be("f3c384dd-5895-4da8-a356-61f266269082");
expect(data.cashSec).to.be.a('string');
expect(data.cashSec).to.be("1");
expect(data.category).to.be.a('string');
expect(data.category).to.be("tech");
expect(data.clientId).to.be.a('string');
expect(data.clientId).to.be("2035f52d-2c5b-4e07-8904-cb037bad7aff");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data.defaultDriftFactor).to.be.a('number');
expect(data.defaultDriftFactor).to.be(0.55);
expect(data.description).to.be.a('string');
expect(data.description).to.be("consists of tech ETFs");
expect(data.downside).to.be.a('boolean');
expect(data.downside).to.be(true);
expect(data.driftRebal).to.be.a('boolean');
expect(data.driftRebal).to.be(true);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isActive).to.be.a('boolean');
expect(data.isActive).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.name).to.be.a('string');
expect(data.name).to.be("Tech model");
{
let dataCtr = data.nodeMap;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.AllocationNodeMap);
expect(data.nodeId).to.be.a('string');
expect(data.nodeId).to.be("6e14259a-9a68-4593-9e6d-8fcd0d05cf44");
}
}
expect(data.periodRebal).to.be.a('boolean');
expect(data.periodRebal).to.be(true);
expect(data.rebalancePeriod).to.be.a('number');
expect(data.rebalancePeriod).to.be(12);
expect(data.safeSec).to.be.a('string');
expect(data.safeSec).to.be("1");
expect(data.secRotation).to.be.a('boolean');
expect(data.secRotation).to.be(true);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.taxEfficiencyId).to.be.a('number');
expect(data.taxEfficiencyId).to.be(1);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
}
expect(data.first).to.be.a('boolean');
expect(data.first).to.be(false);
expect(data.last).to.be.a('boolean');
expect(data.last).to.be(false);
expect(data._number).to.be.a('number');
expect(data._number).to.be(0);
expect(data.numberOfElements).to.be.a('number');
expect(data.numberOfElements).to.be(0);
expect(data.size).to.be.a('number');
expect(data.size).to.be(0);
{
let dataCtr = data.sort;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Sort);
expect(data.ascending).to.be.a('boolean');
expect(data.ascending).to.be(true);
expect(data.descending).to.be.a('boolean');
expect(data.descending).to.be(false);
expect(data.direction).to.be.a('string');
expect(data.direction).to.be("DESC");
expect(data.ignoreCase).to.be.a('boolean');
expect(data.ignoreCase).to.be(false);
expect(data.nullHandling).to.be.a('string');
expect(data.nullHandling).to.be("NATIVE");
expect(data.property).to.be.a('string');
expect(data.property).to.be("updateDate");
}
}
expect(data.totalElements).to.be.a('number');
expect(data.totalElements).to.be("0");
expect(data.totalPages).to.be.a('number');
expect(data.totalPages).to.be(0);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelAssetSizeAllUsingGet', function() {
it('should call getModelAssetSizeAllUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelAssetSizeAllUsingGet call and complete the assertions
/*
var opts = {};
opts.ascending = false;
opts.currencyConversion = "currencyConversion_example";
opts.filter = "filter_example";
opts.orderBy = "update_date";
opts.page = 0;
opts.size = 25;
instance.getModelAssetSizeAllUsingGet(opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.PageModelAssetSize);
{
let dataCtr = data.content;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.ModelAssetSize);
expect(data.assetSize).to.be.a('number');
expect(data.assetSize).to.be(0.9);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isReconciled).to.be.a('boolean');
expect(data.isReconciled).to.be(true);
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
}
expect(data.first).to.be.a('boolean');
expect(data.first).to.be(false);
expect(data.last).to.be.a('boolean');
expect(data.last).to.be(false);
expect(data._number).to.be.a('number');
expect(data._number).to.be(0);
expect(data.numberOfElements).to.be.a('number');
expect(data.numberOfElements).to.be(0);
expect(data.size).to.be.a('number');
expect(data.size).to.be(0);
{
let dataCtr = data.sort;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Sort);
expect(data.ascending).to.be.a('boolean');
expect(data.ascending).to.be(true);
expect(data.descending).to.be.a('boolean');
expect(data.descending).to.be(false);
expect(data.direction).to.be.a('string');
expect(data.direction).to.be("DESC");
expect(data.ignoreCase).to.be.a('boolean');
expect(data.ignoreCase).to.be(false);
expect(data.nullHandling).to.be.a('string');
expect(data.nullHandling).to.be("NATIVE");
expect(data.property).to.be.a('string');
expect(data.property).to.be("updateDate");
}
}
expect(data.totalElements).to.be.a('number');
expect(data.totalElements).to.be("0");
expect(data.totalPages).to.be.a('number');
expect(data.totalPages).to.be(0);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelAssetSizeUsingGet', function() {
it('should call getModelAssetSizeUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelAssetSizeUsingGet call and complete the assertions
/*
var modelAssetSizeId = "modelAssetSizeId_example";
var opts = {};
opts.currencyConversion = "currencyConversion_example";
instance.getModelAssetSizeUsingGet(modelAssetSizeId, opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelAssetSize);
expect(data.assetSize).to.be.a('number');
expect(data.assetSize).to.be(0.9);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isReconciled).to.be.a('boolean');
expect(data.isReconciled).to.be(true);
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelCommentAllUsingGet', function() {
it('should call getModelCommentAllUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelCommentAllUsingGet call and complete the assertions
/*
var opts = {};
opts.ascending = false;
opts.filter = "filter_example";
opts.orderBy = "update_date";
opts.page = 0;
opts.size = 25;
instance.getModelCommentAllUsingGet(opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.PageModelComment);
{
let dataCtr = data.content;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.ModelComment);
expect(data.comment).to.be.a('string');
expect(data.comment).to.be("sample");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
}
expect(data.first).to.be.a('boolean');
expect(data.first).to.be(false);
expect(data.last).to.be.a('boolean');
expect(data.last).to.be(false);
expect(data._number).to.be.a('number');
expect(data._number).to.be(0);
expect(data.numberOfElements).to.be.a('number');
expect(data.numberOfElements).to.be(0);
expect(data.size).to.be.a('number');
expect(data.size).to.be(0);
{
let dataCtr = data.sort;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Sort);
expect(data.ascending).to.be.a('boolean');
expect(data.ascending).to.be(true);
expect(data.descending).to.be.a('boolean');
expect(data.descending).to.be(false);
expect(data.direction).to.be.a('string');
expect(data.direction).to.be("DESC");
expect(data.ignoreCase).to.be.a('boolean');
expect(data.ignoreCase).to.be(false);
expect(data.nullHandling).to.be.a('string');
expect(data.nullHandling).to.be("NATIVE");
expect(data.property).to.be.a('string');
expect(data.property).to.be("updateDate");
}
}
expect(data.totalElements).to.be.a('number');
expect(data.totalElements).to.be("0");
expect(data.totalPages).to.be.a('number');
expect(data.totalPages).to.be(0);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelCommentUsingGet', function() {
it('should call getModelCommentUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelCommentUsingGet call and complete the assertions
/*
var modelCommentId = "modelCommentId_example";
instance.getModelCommentUsingGet(modelCommentId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelComment);
expect(data.comment).to.be.a('string');
expect(data.comment).to.be("sample");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelHoldingAllUsingGet', function() {
it('should call getModelHoldingAllUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelHoldingAllUsingGet call and complete the assertions
/*
var opts = {};
opts.ascending = false;
opts.filter = "filter_example";
opts.orderBy = "update_date";
opts.page = 0;
opts.size = 25;
instance.getModelHoldingAllUsingGet(opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.PageModelHolding);
{
let dataCtr = data.content;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.ModelHolding);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currentWeight).to.be.a('number');
expect(data.currentWeight).to.be(0.88);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.driftFactor).to.be.a('number');
expect(data.driftFactor).to.be(0.9);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isCash).to.be.a('boolean');
expect(data.isCash).to.be(true);
expect(data.isInitialHolding).to.be.a('boolean');
expect(data.isInitialHolding).to.be(true);
expect(data.isSafeSecurity).to.be.a('boolean');
expect(data.isSafeSecurity).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelDescription).to.be.a('string');
expect(data.modelDescription).to.be("");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.modelName).to.be.a('string');
expect(data.modelName).to.be("");
expect(data.modelWeight).to.be.a('number');
expect(data.modelWeight).to.be(0.0);
expect(data.secPrice).to.be.a('number');
expect(data.secPrice).to.be(0.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.strategicWeight).to.be.a('number');
expect(data.strategicWeight).to.be(0.89);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
}
expect(data.first).to.be.a('boolean');
expect(data.first).to.be(false);
expect(data.last).to.be.a('boolean');
expect(data.last).to.be(false);
expect(data._number).to.be.a('number');
expect(data._number).to.be(0);
expect(data.numberOfElements).to.be.a('number');
expect(data.numberOfElements).to.be(0);
expect(data.size).to.be.a('number');
expect(data.size).to.be(0);
{
let dataCtr = data.sort;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Sort);
expect(data.ascending).to.be.a('boolean');
expect(data.ascending).to.be(true);
expect(data.descending).to.be.a('boolean');
expect(data.descending).to.be(false);
expect(data.direction).to.be.a('string');
expect(data.direction).to.be("DESC");
expect(data.ignoreCase).to.be.a('boolean');
expect(data.ignoreCase).to.be(false);
expect(data.nullHandling).to.be.a('string');
expect(data.nullHandling).to.be("NATIVE");
expect(data.property).to.be.a('string');
expect(data.property).to.be("updateDate");
}
}
expect(data.totalElements).to.be.a('number');
expect(data.totalElements).to.be("0");
expect(data.totalPages).to.be.a('number');
expect(data.totalPages).to.be(0);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelHoldingUsingGet', function() {
it('should call getModelHoldingUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelHoldingUsingGet call and complete the assertions
/*
var modelHoldingId = "modelHoldingId_example";
instance.getModelHoldingUsingGet(modelHoldingId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelHolding);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currentWeight).to.be.a('number');
expect(data.currentWeight).to.be(0.88);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.driftFactor).to.be.a('number');
expect(data.driftFactor).to.be(0.9);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isCash).to.be.a('boolean');
expect(data.isCash).to.be(true);
expect(data.isInitialHolding).to.be.a('boolean');
expect(data.isInitialHolding).to.be(true);
expect(data.isSafeSecurity).to.be.a('boolean');
expect(data.isSafeSecurity).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelDescription).to.be.a('string');
expect(data.modelDescription).to.be("");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.modelName).to.be.a('string');
expect(data.modelName).to.be("");
expect(data.modelWeight).to.be.a('number');
expect(data.modelWeight).to.be(0.0);
expect(data.secPrice).to.be.a('number');
expect(data.secPrice).to.be(0.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.strategicWeight).to.be.a('number');
expect(data.strategicWeight).to.be(0.89);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelTransactionAllUsingGet', function() {
it('should call getModelTransactionAllUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelTransactionAllUsingGet call and complete the assertions
/*
var opts = {};
opts.ascending = false;
opts.filter = "filter_example";
opts.orderBy = "update_date";
opts.page = 0;
opts.size = 25;
instance.getModelTransactionAllUsingGet(opts, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.PageModelTransaction);
{
let dataCtr = data.content;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.ModelTransaction);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.price).to.be.a('number');
expect(data.price).to.be(100.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.shares).to.be.a('number');
expect(data.shares).to.be(100.0);
expect(data.transactionCodeId).to.be.a('string');
expect(data.transactionCodeId).to.be("f5af397b-7d22-433f-b01e-8202184a6386");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
}
}
expect(data.first).to.be.a('boolean');
expect(data.first).to.be(false);
expect(data.last).to.be.a('boolean');
expect(data.last).to.be(false);
expect(data._number).to.be.a('number');
expect(data._number).to.be(0);
expect(data.numberOfElements).to.be.a('number');
expect(data.numberOfElements).to.be(0);
expect(data.size).to.be.a('number');
expect(data.size).to.be(0);
{
let dataCtr = data.sort;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.Sort);
expect(data.ascending).to.be.a('boolean');
expect(data.ascending).to.be(true);
expect(data.descending).to.be.a('boolean');
expect(data.descending).to.be(false);
expect(data.direction).to.be.a('string');
expect(data.direction).to.be("DESC");
expect(data.ignoreCase).to.be.a('boolean');
expect(data.ignoreCase).to.be(false);
expect(data.nullHandling).to.be.a('string');
expect(data.nullHandling).to.be("NATIVE");
expect(data.property).to.be.a('string');
expect(data.property).to.be("updateDate");
}
}
expect(data.totalElements).to.be.a('number');
expect(data.totalElements).to.be("0");
expect(data.totalPages).to.be.a('number');
expect(data.totalPages).to.be(0);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelTransactionUsingGet', function() {
it('should call getModelTransactionUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelTransactionUsingGet call and complete the assertions
/*
var modelTransactionId = "modelTransactionId_example";
instance.getModelTransactionUsingGet(modelTransactionId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelTransaction);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.price).to.be.a('number');
expect(data.price).to.be(100.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.shares).to.be.a('number');
expect(data.shares).to.be(100.0);
expect(data.transactionCodeId).to.be.a('string');
expect(data.transactionCodeId).to.be("f5af397b-7d22-433f-b01e-8202184a6386");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('getModelUsingGet', function() {
it('should call getModelUsingGet successfully', function(done) {
// TODO: uncomment, update parameter values for getModelUsingGet call and complete the assertions
/*
var modelId = "modelId_example";
instance.getModelUsingGet(modelId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.Model);
expect(data.benchmarkId).to.be.a('string');
expect(data.benchmarkId).to.be("f3c384dd-5895-4da8-a356-61f266269082");
expect(data.cashSec).to.be.a('string');
expect(data.cashSec).to.be("1");
expect(data.category).to.be.a('string');
expect(data.category).to.be("tech");
expect(data.clientId).to.be.a('string');
expect(data.clientId).to.be("2035f52d-2c5b-4e07-8904-cb037bad7aff");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data.defaultDriftFactor).to.be.a('number');
expect(data.defaultDriftFactor).to.be(0.55);
expect(data.description).to.be.a('string');
expect(data.description).to.be("consists of tech ETFs");
expect(data.downside).to.be.a('boolean');
expect(data.downside).to.be(true);
expect(data.driftRebal).to.be.a('boolean');
expect(data.driftRebal).to.be(true);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isActive).to.be.a('boolean');
expect(data.isActive).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.name).to.be.a('string');
expect(data.name).to.be("Tech model");
{
let dataCtr = data.nodeMap;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.AllocationNodeMap);
expect(data.nodeId).to.be.a('string');
expect(data.nodeId).to.be("6e14259a-9a68-4593-9e6d-8fcd0d05cf44");
}
}
expect(data.periodRebal).to.be.a('boolean');
expect(data.periodRebal).to.be(true);
expect(data.rebalancePeriod).to.be.a('number');
expect(data.rebalancePeriod).to.be(12);
expect(data.safeSec).to.be.a('string');
expect(data.safeSec).to.be("1");
expect(data.secRotation).to.be.a('boolean');
expect(data.secRotation).to.be(true);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.taxEfficiencyId).to.be.a('number');
expect(data.taxEfficiencyId).to.be(1);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('updateModelAssetSizeUsingPut', function() {
it('should call updateModelAssetSizeUsingPut successfully', function(done) {
// TODO: uncomment, update parameter values for updateModelAssetSizeUsingPut call and complete the assertions
/*
var modelAssetSize = null;
var modelAssetSizeId = "modelAssetSizeId_example";
instance.updateModelAssetSizeUsingPut(modelAssetSize, modelAssetSizeId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelAssetSize);
expect(data.assetSize).to.be.a('number');
expect(data.assetSize).to.be(0.9);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isReconciled).to.be.a('boolean');
expect(data.isReconciled).to.be(true);
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('updateModelCommentUsingPut', function() {
it('should call updateModelCommentUsingPut successfully', function(done) {
// TODO: uncomment, update parameter values for updateModelCommentUsingPut call and complete the assertions
/*
var modelComment = null;
var modelCommentId = "modelCommentId_example";
instance.updateModelCommentUsingPut(modelComment, modelCommentId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelComment);
expect(data.comment).to.be.a('string');
expect(data.comment).to.be("sample");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('updateModelHoldingUsingPut', function() {
it('should call updateModelHoldingUsingPut successfully', function(done) {
// TODO: uncomment, update parameter values for updateModelHoldingUsingPut call and complete the assertions
/*
var modelHolding = null;
var modelHoldingId = "modelHoldingId_example";
instance.updateModelHoldingUsingPut(modelHolding, modelHoldingId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelHolding);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currentWeight).to.be.a('number');
expect(data.currentWeight).to.be(0.88);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.driftFactor).to.be.a('number');
expect(data.driftFactor).to.be(0.9);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isCash).to.be.a('boolean');
expect(data.isCash).to.be(true);
expect(data.isInitialHolding).to.be.a('boolean');
expect(data.isInitialHolding).to.be(true);
expect(data.isSafeSecurity).to.be.a('boolean');
expect(data.isSafeSecurity).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.modelDescription).to.be.a('string');
expect(data.modelDescription).to.be("");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.modelName).to.be.a('string');
expect(data.modelName).to.be("");
expect(data.modelWeight).to.be.a('number');
expect(data.modelWeight).to.be(0.0);
expect(data.secPrice).to.be.a('number');
expect(data.secPrice).to.be(0.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.strategicWeight).to.be.a('number');
expect(data.strategicWeight).to.be(0.89);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('updateModelTransactionUsingPut', function() {
it('should call updateModelTransactionUsingPut successfully', function(done) {
// TODO: uncomment, update parameter values for updateModelTransactionUsingPut call and complete the assertions
/*
var modelTransaction = null;
var modelTransactionId = "modelTransactionId_example";
instance.updateModelTransactionUsingPut(modelTransaction, modelTransactionId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.ModelTransaction);
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data._date).to.be.a(Date);
expect(data._date).to.be(2018-01-09'T'12:00:00);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.modelId).to.be.a('string');
expect(data.modelId).to.be("62fd0a9f-4bac-4b1d-94d2-2c5ea2adca3d");
expect(data.price).to.be.a('number');
expect(data.price).to.be(100.0);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.securityId).to.be.a('string');
expect(data.securityId).to.be("29c3f995-bd45-4346-aea2-fd4476568d4c");
expect(data.shares).to.be.a('number');
expect(data.shares).to.be(100.0);
expect(data.transactionCodeId).to.be.a('string');
expect(data.transactionCodeId).to.be("f5af397b-7d22-433f-b01e-8202184a6386");
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
describe('updateModelUsingPut', function() {
it('should call updateModelUsingPut successfully', function(done) {
// TODO: uncomment, update parameter values for updateModelUsingPut call and complete the assertions
/*
var model = null;
var modelId = "modelId_example";
instance.updateModelUsingPut(model, modelId, function(error, data, response) {
if (error) {
done(error);
return;
}
// TODO: update response assertions
expect(data).to.be.a(HydrogenNucleusApi.Model);
expect(data.benchmarkId).to.be.a('string');
expect(data.benchmarkId).to.be("f3c384dd-5895-4da8-a356-61f266269082");
expect(data.cashSec).to.be.a('string');
expect(data.cashSec).to.be("1");
expect(data.category).to.be.a('string');
expect(data.category).to.be("tech");
expect(data.clientId).to.be.a('string');
expect(data.clientId).to.be("2035f52d-2c5b-4e07-8904-cb037bad7aff");
expect(data.createDate).to.be.a(Date);
expect(data.createDate).to.be(2018-06-28T18:17:23.579+0000);
expect(data.currencyCode).to.be.a('string');
expect(data.currencyCode).to.be("USD");
expect(data.defaultDriftFactor).to.be.a('number');
expect(data.defaultDriftFactor).to.be(0.55);
expect(data.description).to.be.a('string');
expect(data.description).to.be("consists of tech ETFs");
expect(data.downside).to.be.a('boolean');
expect(data.downside).to.be(true);
expect(data.driftRebal).to.be.a('boolean');
expect(data.driftRebal).to.be(true);
expect(data.id).to.be.a('string');
expect(data.id).to.be("000183ac-2288-4564-a76b-119f4694be98");
expect(data.isActive).to.be.a('boolean');
expect(data.isActive).to.be(true);
{
let dataCtr = data.metadata;
expect(dataCtr).to.be.an(Object);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a('string');
expect(data).to.be("");
}
}
expect(data.name).to.be.a('string');
expect(data.name).to.be("Tech model");
{
let dataCtr = data.nodeMap;
expect(dataCtr).to.be.an(Array);
expect(dataCtr).to.not.be.empty();
for (let p in dataCtr) {
let data = dataCtr[p];
expect(data).to.be.a(HydrogenNucleusApi.AllocationNodeMap);
expect(data.nodeId).to.be.a('string');
expect(data.nodeId).to.be("6e14259a-9a68-4593-9e6d-8fcd0d05cf44");
}
}
expect(data.periodRebal).to.be.a('boolean');
expect(data.periodRebal).to.be(true);
expect(data.rebalancePeriod).to.be.a('number');
expect(data.rebalancePeriod).to.be(12);
expect(data.safeSec).to.be.a('string');
expect(data.safeSec).to.be("1");
expect(data.secRotation).to.be.a('boolean');
expect(data.secRotation).to.be(true);
expect(data.secondaryId).to.be.a('string');
expect(data.secondaryId).to.be("7289243787238");
expect(data.taxEfficiencyId).to.be.a('number');
expect(data.taxEfficiencyId).to.be(1);
expect(data.updateDate).to.be.a(Date);
expect(data.updateDate).to.be(2018-06-28T18:17:23.579+0000);
done();
});
*/
// TODO: uncomment and complete method invocation above, then delete this line and the next:
done();
});
});
});
});
}));
|
hemantt/pcq-frontend | test/end-to-end/helpers/PuppeteerHelper.js | 'use strict';
const Helper = codecept_helper;
const helperName = 'Puppeteer';
class PuppeteerHelper extends Helper {
clickBrowserBackButton() {
const page = this.helpers[helperName].page;
return page.goBack();
}
async waitForNavigationToComplete(locator) {
const page = this.helpers[helperName].page;
await Promise.all([
page.waitForNavigation(), // The promise resolves after navigation has finished
page.click(locator) // Clicking the link will indirectly cause a navigation
])
.catch((err) => err);
}
}
module.exports = PuppeteerHelper;
|
SuperV1234/vrm_core | test/core/type_traits/remove_rvalue_reference.cpp | <filename>test/core/type_traits/remove_rvalue_reference.cpp
#include "../../utils/test_utils.hpp"
#include <vrm/core/assert.hpp>
#include <vrm/core/type_traits/remove_rvalue_reference.hpp>
using namespace vrm::core;
SA_SAME((remove_rvalue_reference_t<int>), (int));
SA_SAME((remove_rvalue_reference_t<int&>), (int&));
SA_SAME((remove_rvalue_reference_t<int&&>), (int));
SA_SAME((remove_rvalue_reference_t<const int>), (const int));
SA_SAME((remove_rvalue_reference_t<const int&>), (const int&));
SA_SAME((remove_rvalue_reference_t<const int&&>), (const int));
SA_SAME((remove_rvalue_reference_t<volatile int>), (volatile int));
SA_SAME((remove_rvalue_reference_t<volatile int&>), (volatile int&));
SA_SAME((remove_rvalue_reference_t<volatile int&&>), (volatile int));
SA_SAME((remove_rvalue_reference_t<const volatile int>), (const volatile int));
SA_SAME(
(remove_rvalue_reference_t<const volatile int&>), (const volatile int&));
SA_SAME(
(remove_rvalue_reference_t<const volatile int&&>), (const volatile int));
TEST_MAIN()
{
return 0;
}
|
SolidDesignNet/j1939-84 | src-test/org/etools/j1939_84/controllers/part03/Part03Step02ControllerTest.java | <gh_stars>1-10
/*
* Copyright (c) 2021. Equipment & Tool Institute
*/
package org.etools.j1939_84.controllers.part03;
import static net.soliddesign.j1939tools.j1939.packets.LampStatus.OFF;
import static net.soliddesign.j1939tools.j1939.packets.LampStatus.ON;
import static org.etools.j1939_84.J1939_84.NL;
import static org.etools.j1939_84.controllers.QuestionListener.AnswerType.NO;
import static org.etools.j1939_84.controllers.ResultsListener.MessageType.QUESTION;
import static org.etools.j1939_84.model.Outcome.ABORT;
import static org.etools.j1939_84.model.Outcome.FAIL;
import static org.etools.j1939_84.model.Outcome.WARN;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.concurrent.Executor;
import org.etools.j1939_84.controllers.DataRepository;
import org.etools.j1939_84.controllers.QuestionListener;
import org.etools.j1939_84.controllers.ResultsListener;
import org.etools.j1939_84.controllers.StepController;
import org.etools.j1939_84.controllers.TestResultsListener;
import org.etools.j1939_84.model.OBDModuleInformation;
import org.etools.j1939_84.modules.BannerModule;
import org.etools.j1939_84.modules.EngineSpeedModule;
import org.etools.j1939_84.modules.ReportFileModule;
import org.etools.j1939_84.modules.TestDateTimeModule;
import org.etools.j1939_84.modules.VehicleInformationModule;
import org.etools.j1939_84.utils.AbstractControllerTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import net.soliddesign.j1939tools.bus.RequestResult;
import net.soliddesign.j1939tools.j1939.J1939;
import net.soliddesign.j1939tools.j1939.packets.AcknowledgmentPacket;
import net.soliddesign.j1939tools.j1939.packets.DM6PendingEmissionDTCPacket;
import net.soliddesign.j1939tools.j1939.packets.DiagnosticTroubleCode;
import net.soliddesign.j1939tools.modules.CommunicationsModule;
import net.soliddesign.j1939tools.modules.DateTimeModule;
@RunWith(MockitoJUnitRunner.class)
public class Part03Step02ControllerTest extends AbstractControllerTest {
private static final int PART_NUMBER = 3;
private static final int STEP_NUMBER = 2;
@Mock
private BannerModule bannerModule;
@Mock
private CommunicationsModule communicationsModule;
@Mock
private EngineSpeedModule engineSpeedModule;
@Mock
private Executor executor;
@Mock
private J1939 j1939;
private TestResultsListener listener;
@Mock
private ResultsListener mockListener;
@Mock
private ReportFileModule reportFileModule;
@Mock
private VehicleInformationModule vehicleInformationModule;
private DataRepository dataRepository;
private DateTimeModule dateTimeModule;
private StepController instance;
@Before
public void setUp() throws Exception {
dateTimeModule = new TestDateTimeModule();
dataRepository = DataRepository.newInstance();
listener = new TestResultsListener(mockListener);
instance = new Part03Step02Controller(executor,
bannerModule,
dateTimeModule,
dataRepository,
engineSpeedModule,
vehicleInformationModule,
communicationsModule);
setup(instance,
listener,
j1939,
executor,
reportFileModule,
engineSpeedModule,
vehicleInformationModule,
communicationsModule);
}
@After
public void tearDown() throws Exception {
verifyNoMoreInteractions(executor,
engineSpeedModule,
bannerModule,
vehicleInformationModule,
mockListener);
}
@Test
public void testGetDisplayName() {
assertEquals("Part " + PART_NUMBER + " Step " + STEP_NUMBER, instance.getDisplayName());
}
@Test
public void testGetPartNumber() {
assertEquals(PART_NUMBER, instance.getPartNumber());
}
@Test
public void testGetStepNumber() {
assertEquals(STEP_NUMBER, instance.getStepNumber());
}
@Test
public void testGetTotalSteps() {
assertEquals(0, instance.getTotalSteps());
}
@Test
public void testHappyPathNoFailures() {
dataRepository.putObdModule(new OBDModuleInformation(0));
dataRepository.putObdModule(new OBDModuleInformation(1));
var nack = AcknowledgmentPacket.create(0, AcknowledgmentPacket.Response.NACK);
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, nack));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6_1 = DM6PendingEmissionDTCPacket.create(1, OFF, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any(), eq(1))).thenReturn(new RequestResult<>(false, dm6_1));
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6_1));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(1));
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
}
@Test
public void testNoResponses() throws InterruptedException {
when(communicationsModule.requestDM6(any())).thenReturn(RequestResult.empty());
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER, STEP_NUMBER, FAIL, "6.3.2.2.a - No OBD ECU supports DM6");
}
@Test
public void testNoDTCs() {
dataRepository.putObdModule(new OBDModuleInformation(0));
var dm6 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6));
String promptMsg = "No ECU has reported a Pending Emission DTC." + NL + NL + "Do you wish to continue?";
String promptTitle = "No Pending Emission DTCs Found";
doAnswer(invocationOnMock -> {
QuestionListener questionListener = invocationOnMock.getArgument(3);
questionListener.answered(NO);
return null;
}).when(mockListener).onUrgentMessage(eq(promptMsg), eq(promptTitle), eq(QUESTION), any());
runTest();
StringBuilder expectedMessages = new StringBuilder();
for (int i = 1; i <= 300; i++) {
expectedMessages.append("Step 6.3.2.1.a - Requesting DM6 Attempt ").append(i).append(NL);
}
expectedMessages.append("User cancelled testing at Part 3 Step 2");
assertEquals(expectedMessages.toString(), listener.getMessages());
StringBuilder expectedResults = new StringBuilder();
for (int i = 1; i <= 300; i++) {
expectedResults.append(NL).append("Attempt ").append(i).append(NL);
}
assertEquals(expectedResults.toString(), listener.getResults());
verify(mockListener).onUrgentMessage(eq(promptMsg), eq(promptTitle), eq(QUESTION), any());
verify(communicationsModule, times(300)).requestDM6(any());
verify(mockListener).onUrgentMessage(eq(promptMsg), eq(promptTitle), eq(QUESTION), any());
verify(mockListener, times(2)).addOutcome(PART_NUMBER,
STEP_NUMBER,
ABORT,
"User cancelled testing at Part 3 Step 2");
assertEquals(299000, dateTimeModule.getTimeAsLong());
}
@Test
public void testMultipleDTCFailure() {
dataRepository.putObdModule(new OBDModuleInformation(0));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dtc2 = DiagnosticTroubleCode.create(456, 3, 0, 1);
var dm6 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF, dtc1, dtc2);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6));
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER,
STEP_NUMBER,
WARN,
"6.3.2.3.a - Engine #1 (0) reported > 1 pending DTC");
}
@Test
public void testDTCsMultipleModulesFailure() {
dataRepository.putObdModule(new OBDModuleInformation(0));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6_0 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF, dtc1);
var dm6_1 = DM6PendingEmissionDTCPacket.create(1, OFF, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6_0, dm6_1));
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6_0));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER,
STEP_NUMBER,
WARN,
"6.3.2.3.b - More than one ECU reported a pending DTC");
}
@Test
public void testMultipleModulesWithOneDTC() {
dataRepository.putObdModule(new OBDModuleInformation(0));
dataRepository.putObdModule(new OBDModuleInformation(1));
var dm6_0 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF);
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6_0));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6_1 = DM6PendingEmissionDTCPacket.create(1, OFF, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any(), eq(1))).thenReturn(new RequestResult<>(false, dm6_1));
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6_0, dm6_1));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(1));
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
}
@Test
public void testMILNotOffFailure() {
dataRepository.putObdModule(new OBDModuleInformation(0));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6 = DM6PendingEmissionDTCPacket.create(0, ON, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6));
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER,
STEP_NUMBER,
FAIL,
"6.3.2.5.b - Engine #1 (0) did not report MIL 'off'");
}
@Test
public void testGlobalDSDifferenceFailure() {
dataRepository.putObdModule(new OBDModuleInformation(0));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6_1 = DM6PendingEmissionDTCPacket.create(0, ON, OFF, OFF, OFF, dtc1);
var dm6_2 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6_1));
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6_2));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(0));
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER,
STEP_NUMBER,
FAIL,
"6.3.2.5.a - Difference compared to data received during global request from Engine #1 (0)");
}
@Test
public void testNoNACKFailure() {
dataRepository.putObdModule(new OBDModuleInformation(0));
dataRepository.putObdModule(new OBDModuleInformation(1));
var dtc1 = DiagnosticTroubleCode.create(123, 12, 0, 1);
var dm6 = DM6PendingEmissionDTCPacket.create(0, OFF, OFF, OFF, OFF, dtc1);
when(communicationsModule.requestDM6(any())).thenReturn(new RequestResult<>(false, dm6));
when(communicationsModule.requestDM6(any(), eq(0))).thenReturn(new RequestResult<>(false, dm6));
when(communicationsModule.requestDM6(any(), eq(1))).thenReturn(new RequestResult<>(false));
runTest();
String expectedMessages = "Step 6.3.2.1.a - Requesting DM6 Attempt 1";
assertEquals(expectedMessages, listener.getMessages());
String expectedResults = "" + NL;
expectedResults += "Attempt 1" + NL;
assertEquals(expectedResults, listener.getResults());
verify(communicationsModule).requestDM6(any());
verify(communicationsModule).requestDM6(any(), eq(0));
verify(communicationsModule).requestDM6(any(), eq(1));
assertEquals(0, dateTimeModule.getTimeAsLong());
verify(mockListener).addOutcome(PART_NUMBER,
STEP_NUMBER,
FAIL,
"6.3.2.5.c - OBD ECU Engine #2 (1) did not provide a response to Global query and did not provide a NACK for the DS query");
}
}
|
TouchFriend/RJForm | RJFormDemo/RJForm/Validators/RJFormRegexValidator.h | <gh_stars>0
//
// RJFormRegexValidator.h
// RJFormDemo
//
// Created by TouchWorld on 2019/7/29.
// Copyright © 2019 RJSoft. All rights reserved.
//
#import "RJFormValidator.h"
NS_ASSUME_NONNULL_BEGIN
@interface RJFormRegexValidator : RJFormValidator
/********* 错误信息 *********/
@property (nonatomic, copy) NSString *errorMsg;
/********* 正则表达式 *********/
@property (nonatomic, copy) NSString *regex;
+ (instancetype)validatorWithErrorMsg:(NSString *)errorMsg regex:(NSString *)regex;
- (instancetype)initWithErrorMsg:(NSString *)errorMsg regex:(NSString *)regex;
@end
NS_ASSUME_NONNULL_END
|
cbm64chris/vsts-authentication-library-for-java | core/src/test/java/com/microsoft/alm/auth/oauth/AzureAuthorityTest.java | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.auth.oauth;
import com.microsoft.alm.auth.PromptBehavior;
import com.microsoft.alm.helpers.Action;
import com.microsoft.alm.helpers.StringContent;
import com.microsoft.alm.oauth2.useragent.AuthorizationException;
import com.microsoft.alm.secret.TokenPair;
import org.junit.Assert;
import org.junit.Test;
import java.net.URI;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A class to test {@link AzureAuthority}.
*/
public class AzureAuthorityTest {
static final String TEST_RESOURCE = "TEST_RESOURCE";
static final String TEST_CLIENT_ID = "d30feefe-9ee4-4b00-ac77-08dbd1199811";
static final String TEST_DEVICE_CODE = "03d5f4b1-c8ab-4ce2-85c0-158d2075ff5f";
static final String TEST_USER_CODE = "DEADBEEF";
static final int TEST_EXPIRATION = 600;
static final int TEST_INTERVAL = 5;
static final String TEST_ACCESS_TOKEN = "<PASSWORD>";
static final String TEST_REFRESH_TOKEN = "<PASSWORD>";
static final URI TEST_REDIRECT_URI = URI.create("https://redirect.test");
@Test
public void deviceFlow_success() throws Exception {
final String authorityHostUrl = "https://authorization.example.com/common/";
final URI verificationUri = URI.create("https://authorization.example.com/oauth/device");
final AtomicInteger requestAuthorizationCalls = new AtomicInteger(0);
final AtomicInteger requestTokenCalls = new AtomicInteger(0);
final AtomicInteger callbackCalls = new AtomicInteger(0);
final AzureDeviceFlowResponse azureDeviceFlowResponse = new AzureDeviceFlowResponse(TEST_DEVICE_CODE, TEST_USER_CODE, verificationUri, TEST_EXPIRATION, TEST_INTERVAL, "message");
final AzureDeviceFlow testDeviceFlow = new AzureDeviceFlow() {
@Override
public DeviceFlowResponse requestAuthorization(final URI deviceEndpoint, final String clientId, final String scope) {
requestAuthorizationCalls.addAndGet(1);
Assert.assertEquals(TEST_CLIENT_ID, clientId);
return azureDeviceFlowResponse;
}
@Override
public TokenPair requestToken(final URI tokenEndpoint, final String clientId, final DeviceFlowResponse deviceFlowResponse) throws AuthorizationException {
requestTokenCalls.addAndGet(1);
Assert.assertEquals(TEST_CLIENT_ID, clientId);
Assert.assertEquals(azureDeviceFlowResponse, deviceFlowResponse);
deviceFlowResponse.setTokenAcquired();
return new TokenPair(TEST_ACCESS_TOKEN, TEST_REFRESH_TOKEN);
}
};
final Action<DeviceFlowResponse> callback = new Action<DeviceFlowResponse>() {
@Override
public void call(final DeviceFlowResponse deviceFlowResponse) {
callbackCalls.addAndGet(1);
Assert.assertEquals(azureDeviceFlowResponse, deviceFlowResponse);
}
};
final AzureAuthority cut = new AzureAuthority(authorityHostUrl, null, testDeviceFlow);
final TokenPair actualTokenPair = cut.acquireToken(TEST_CLIENT_ID, TEST_RESOURCE, TEST_REDIRECT_URI, callback);
Assert.assertEquals(TEST_ACCESS_TOKEN, actualTokenPair.AccessToken.Value);
Assert.assertEquals(TEST_REFRESH_TOKEN, actualTokenPair.RefreshToken.Value);
Assert.assertEquals(TEST_RESOURCE, testDeviceFlow.getResource());
Assert.assertEquals(1, requestAuthorizationCalls.get());
Assert.assertEquals(1, requestTokenCalls.get());
Assert.assertEquals(1, callbackCalls.get());
Assert.assertTrue(azureDeviceFlowResponse.isTokenAcquired());
}
@Test
public void deviceFlow_failure() throws Exception {
final String authorityHostUrl = "https://authorization.example.com/common/";
final URI verificationUri = URI.create("https://authorization.example.com/oauth/device");
final AtomicInteger requestAuthorizationCalls = new AtomicInteger(0);
final AtomicInteger requestTokenCalls = new AtomicInteger(0);
final AtomicInteger callbackCalls = new AtomicInteger(0);
final AzureDeviceFlowResponse azureDeviceFlowResponse = new AzureDeviceFlowResponse(TEST_DEVICE_CODE, TEST_USER_CODE, verificationUri, TEST_EXPIRATION, TEST_INTERVAL, "message");
final AzureDeviceFlow testDeviceFlow = new AzureDeviceFlow() {
@Override
public DeviceFlowResponse requestAuthorization(final URI deviceEndpoint, final String clientId, final String scope) {
requestAuthorizationCalls.addAndGet(1);
Assert.assertEquals(TEST_CLIENT_ID, clientId);
return azureDeviceFlowResponse;
}
@Override
public TokenPair requestToken(final URI tokenEndpoint, final String clientId, final DeviceFlowResponse deviceFlowResponse) throws AuthorizationException {
requestTokenCalls.addAndGet(1);
throw new AuthorizationException("access_denied");
}
};
final Action<DeviceFlowResponse> callback = new Action<DeviceFlowResponse>() {
@Override
public void call(final DeviceFlowResponse deviceFlowResponse) {
callbackCalls.addAndGet(1);
Assert.assertEquals(azureDeviceFlowResponse, deviceFlowResponse);
}
};
final AzureAuthority cut = new AzureAuthority(authorityHostUrl, null, testDeviceFlow);
try {
cut.acquireToken(TEST_CLIENT_ID, TEST_RESOURCE, TEST_REDIRECT_URI, callback);
Assert.fail("An exception should have been thrown before this line.");
} catch (final AuthorizationException e) {
Assert.assertEquals("access_denied", e.getCode());
}
Assert.assertEquals(TEST_RESOURCE, testDeviceFlow.getResource());
Assert.assertEquals(1, requestAuthorizationCalls.get());
Assert.assertEquals(1, requestTokenCalls.get());
Assert.assertEquals(1, callbackCalls.get());
}
@Test
public void deviceFlow_cancelled() throws Exception {
final String authorityHostUrl = "https://authorization.example.com/common/";
final URI verificationUri = URI.create("https://authorization.example.com/oauth/device");
final AtomicInteger requestAuthorizationCalls = new AtomicInteger(0);
final AtomicInteger requestTokenCalls = new AtomicInteger(0);
final AtomicInteger callbackCalls = new AtomicInteger(0);
final AzureDeviceFlowResponse azureDeviceFlowResponse = new AzureDeviceFlowResponse(TEST_DEVICE_CODE, TEST_USER_CODE, verificationUri, TEST_EXPIRATION, TEST_INTERVAL, "message");
final AzureDeviceFlow testDeviceFlow = new AzureDeviceFlow() {
@Override
public DeviceFlowResponse requestAuthorization(final URI deviceEndpoint, final String clientId, final String scope) {
requestAuthorizationCalls.addAndGet(1);
Assert.assertEquals(TEST_CLIENT_ID, clientId);
return azureDeviceFlowResponse;
}
};
final Action<DeviceFlowResponse> callback = new Action<DeviceFlowResponse>() {
@Override
public void call(final DeviceFlowResponse deviceFlowResponse) {
callbackCalls.addAndGet(1);
Assert.assertEquals(azureDeviceFlowResponse, deviceFlowResponse);
deviceFlowResponse.requestCancel();
}
};
final AzureAuthority cut = new AzureAuthority(authorityHostUrl, null, testDeviceFlow);
try {
cut.acquireToken(TEST_CLIENT_ID, TEST_RESOURCE, TEST_REDIRECT_URI, callback);
Assert.fail("An exception should have been thrown before this line.");
} catch (final AuthorizationException e) {
Assert.assertEquals("request_cancelled", e.getCode());
}
Assert.assertEquals(TEST_RESOURCE, testDeviceFlow.getResource());
Assert.assertEquals(1, requestAuthorizationCalls.get());
Assert.assertEquals(0, requestTokenCalls.get());
Assert.assertEquals(1, callbackCalls.get());
}
@Test
public void createAuthorizationEndpointUri_minimal() throws Exception {
final URI redirectUri = URI.create("https://example.com");
final URI actual = AzureAuthority.createAuthorizationEndpointUri(
"https://login.microsoftonline.com/common",
"a8860e8f-ca7d-4efe-b80d-4affab13d4ba", "f7e11bcd-b50b-4869-ad88-8bdd6cbc8473",
redirectUri,
UserIdentifier.ANY_USER,
null,
PromptBehavior.AUTO,
null);
Assert.assertEquals("https://login.microsoftonline.com/common/oauth2/authorize?resource=a8860e8f-ca7d-4efe-b80d-4affab13d4ba&client_id=f7e11bcd-b50b-4869-ad88-8bdd6cbc8473&response_type=code&redirect_uri=https%3A%2F%2Fexample.com", actual.toString());
}
@Test
public void createAuthorizationEndpointUri_typical() throws Exception {
final URI redirectUri = URI.create("https://example.com");
final String state = "519a4fa6-c18f-4230-8290-6c57407656c9";
final URI actual = AzureAuthority.createAuthorizationEndpointUri(
"https://login.microsoftonline.com/common",
"a8860e8f-ca7d-4efe-b80d-4affab13d4ba", "f7e11bcd-b50b-4869-ad88-8bdd6cbc8473",
redirectUri,
UserIdentifier.ANY_USER,
state,
PromptBehavior.ALWAYS,
null);
Assert.assertEquals("https://login.microsoftonline.com/common/oauth2/authorize?resource=a8860e8f-ca7d-4efe-b80d-4affab13d4ba&client_id=f7e11bcd-b50b-4869-ad88-8bdd6cbc8473&response_type=code&redirect_uri=https%3A%2F%2Fexample.com&state=519a4fa6-c18f-4230-8290-6c57407656c9&prompt=login", actual.toString());
}
@Test
public void createAuthorizationEndpointUri_extraState() throws Exception {
final URI redirectUri = URI.create("https://example.com");
final String state = "519a4fa6-c18f-4230-8290-6c57407656c9";
final URI actual = AzureAuthority.createAuthorizationEndpointUri(
"https://login.microsoftonline.com/common",
"a8860e8f-ca7d-4efe-b80d-4affab13d4ba", "f7e11bcd-b50b-4869-ad88-8bdd6cbc8473",
redirectUri,
UserIdentifier.ANY_USER,
state,
PromptBehavior.ALWAYS,
"state=bliss");
Assert.assertEquals("https://login.microsoftonline.com/common/oauth2/authorize?resource=a8860e8f-ca7d-4efe-b80d-4affab13d4ba&client_id=f7e11bcd-b50b-4869-ad88-8bdd6cbc8473&response_type=code&redirect_uri=https%3A%2F%2Fexample.com&state=519a4fa6-c18f-4230-8290-6c57407656c9&prompt=login&state=bliss", actual.toString());
}
@Test
public void createTokenEndpointUri_typical() throws Exception {
final URI actual = AzureAuthority.createTokenEndpointUri("https://login.example.com/common");
Assert.assertEquals("https://login.example.com/common/oauth2/token", actual.toString());
}
@Test
public void createTokenRequest_typical() throws Exception {
final String resource = "a8860e8f-ca7d-4efe-b80d-4affab13d4ba";
final String clientId = "f7e11bcd-b50b-4869-ad88-8bdd6cbc8473";
// authorization codes can be pretty long
final String authorizationCode =
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
final URI redirectUri = URI.create("https://example.com");
final StringContent actual = AzureAuthority.createTokenRequest(resource, clientId, authorizationCode, redirectUri, null);
Assert.assertEquals(
"resource=a8860e8f-ca7d-4efe-b80d-4affab13d4ba" +
"&client_id=f7e11bcd-b50b-4869-ad88-8bdd6cbc8473" +
"&grant_type=authorization_code" +
"&code=" + authorizationCode +
"&redirect_uri=https%3A%2F%2Fexample.com", actual.getContent());
}
@Test
public void createTokenRequest_withCorrelationId() throws Exception {
final String resource = "a8860e8f-ca7d-4efe-b80d-4affab13d4ba";
final String clientId = "<KEY>";
final UUID correlationId = UUID.fromString("519a4fa6-c18f-4230-8290-6c57407656c9");
// authorization codes can be pretty long
final String authorizationCode =
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
final URI redirectUri = URI.create("https://example.com");
final StringContent actual = AzureAuthority.createTokenRequest(resource, clientId, authorizationCode, redirectUri, correlationId);
Assert.assertEquals(
"resource=a8860e8f-ca7d-4efe-b80d-4affab13d4ba" +
"&client_id=f7e11bcd-b50b-4869-ad88-8bdd6cbc8473" +
"&grant_type=authorization_code" +
"&code=" + authorizationCode +
"&redirect_uri=https%3A%2F%2Fexample.com" +
"&client-request-id=519a4fa6-c18f-4230-8290-6c57407656c9" +
"&return-client-request-id=true", actual.getContent());
}
}
|
yihongmingfeng/OrderingS | OrderingS/CSZyDishListCellView.h | <filename>OrderingS/CSZyDishListCellView.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "UIView.h"
#import "CSNumStepperDelegate.h"
@class BaseBizVc, DishData, NSObject<CSZyDishListCellViewDelegate>, NSString;
@interface CSZyDishListCellView : UIView <CSNumStepperDelegate>
{
BaseBizVc *_nrVc;
NSObject<CSZyDishListCellViewDelegate> *_delegate;
DishData *_dishData;
}
+ (int)tagForPriceLabel;
@property(retain, nonatomic) DishData *dishData; // @synthesize dishData=_dishData;
@property NSObject<CSZyDishListCellViewDelegate> *delegate; // @synthesize delegate=_delegate;
@property BaseBizVc *nrVc; // @synthesize nrVc=_nrVc;
- (void)btnClick_showLargePic:(id)arg1;
- (void)onNumStepperChange:(id)arg1 num:(long long)arg2;
- (void)onNumStepperUp:(id)arg1 num:(long long)arg2;
- (void)onNumStepperDown:(id)arg1 num:(long long)arg2;
- (void)refresh:(id)arg1 orderNumInCart:(long long)arg2;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1 withVc:(id)arg2;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
meniga/mobile-sdk-android | sdk/src/main/java/com/meniga/sdk/models/categories/enums/CategoryType.java | package com.meniga.sdk.models.categories.enums;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Copyright 2017 Meniga Iceland Inc.
* Enum that represents if a category is a income or an expense.
*/
public enum CategoryType implements Serializable {
@SerializedName("Expenses")
EXPENSES,
@SerializedName("Income")
INCOME,
@SerializedName("Savings")
SAVINGS,
@SerializedName("Excluded")
EXCLUDED;
@Override
public String toString() {
switch (this) {
case EXCLUDED:
return "Excluded";
case INCOME:
return "Income";
case SAVINGS:
return "Savings";
default:
return "Expenses";
}
}
}
|
madfrog2047/flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/ReleaseOnConsumptionResultPartition.java | <reponame>madfrog2047/flink<filename>flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/ReleaseOnConsumptionResultPartition.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.io.network.partition;
import org.apache.flink.runtime.io.network.buffer.BufferPool;
import org.apache.flink.runtime.io.network.buffer.BufferPoolOwner;
import org.apache.flink.util.function.FunctionWithException;
import java.io.IOException;
import static org.apache.flink.util.Preconditions.checkState;
/**
* ResultPartition that releases itself once all subpartitions have been consumed.
*/
public class ReleaseOnConsumptionResultPartition extends ResultPartition {
private static final Object lock = new Object();
/**
* A flag for each subpartition indicating whether it was already consumed or not.
*/
private final boolean[] consumedSubpartitions;
/**
* The total number of references to subpartitions of this result. The result partition can be
* safely released, iff the reference count is zero.
*/
private int numUnconsumedSubpartitions;
ReleaseOnConsumptionResultPartition(
String owningTaskName,
ResultPartitionID partitionId,
ResultPartitionType partitionType,
ResultSubpartition[] subpartitions,
int numTargetKeyGroups,
ResultPartitionManager partitionManager,
FunctionWithException<BufferPoolOwner, BufferPool, IOException> bufferPoolFactory) {
super(owningTaskName, partitionId, partitionType, subpartitions, numTargetKeyGroups, partitionManager, bufferPoolFactory);
this.consumedSubpartitions = new boolean[subpartitions.length];
this.numUnconsumedSubpartitions = subpartitions.length;
}
@Override
public ResultSubpartitionView createSubpartitionView(int index, BufferAvailabilityListener availabilityListener) throws IOException {
checkState(numUnconsumedSubpartitions > 0, "Partition not pinned.");
return super.createSubpartitionView(index, availabilityListener);
}
@Override
void onConsumedSubpartition(int subpartitionIndex) {
if (isReleased()) {
return;
}
final int remainingUnconsumed;
// we synchronize only the bookkeeping section, to avoid holding the lock during any
// calls into other components
synchronized (lock) {
if (consumedSubpartitions[subpartitionIndex]) {
// repeated call - ignore
return;
}
consumedSubpartitions[subpartitionIndex] = true;
remainingUnconsumed = (--numUnconsumedSubpartitions);
}
LOG.debug("{}: Received consumed notification for subpartition {}.", this, subpartitionIndex);
if (remainingUnconsumed == 0) {
partitionManager.onConsumedPartition(this);
} else if (remainingUnconsumed < 0) {
throw new IllegalStateException("Received consume notification even though all subpartitions are already consumed.");
}
}
@Override
public String toString() {
return "ReleaseOnConsumptionResultPartition " + partitionId.toString() + " [" + partitionType + ", "
+ subpartitions.length + " subpartitions, "
+ numUnconsumedSubpartitions + " pending consumptions]";
}
}
|
ideacrew/polypress | app/operations/individuals/generate_notice.rb | <reponame>ideacrew/polypress<filename>app/operations/individuals/generate_notice.rb
# frozen_string_literal: true
module Individuals
# This operation determines eligibilities and publishes documents accordingly
class GenerateNotice
send(:include, Dry::Monads[:result, :do])
send(:include, Dry::Monads[:try])
# @param [Templates::TemplateModel] :template_model
# @param [Hash] :payload
# @return [Dry::Monads::Result]
def call(params)
values = yield validate(params)
entity = yield init_entity(values)
publish_documents(entity, params[:template_model])
end
def validate(params)
return Failure("Missing template model") unless params[:template_model].present?
return Failure("Missing payload") unless params[:payload]
result =
if params[:payload][:applicants].present?
::AcaEntities::MagiMedicaid::Contracts::ApplicationContract.new.call(params[:payload])
else
AcaEntities::Contracts::Families::FamilyContract.new.call(params[:payload])
end
result.success? ? Success(result.to_h) : Failure(result.errors.to_h)
end
def init_entity(params)
entity =
if params[:applicants].present?
::AcaEntities::MagiMedicaid::Application.new(params)
else
::AcaEntities::Families::Family.new(params)
end
Success(entity)
rescue StandardError => e
Failure(e)
end
def publish_documents(entity, template_model)
result = MagiMedicaid::PublishDocument.new.call(entity: entity, template_model: template_model)
if result.success?
Success(result.success)
else
Failure("Failed to generate notice for family id: #{entity.hbx_id} due to #{result.failure}")
end
end
end
end
|
HDL951236874/Leetcode | src/main/java/Top100/Problem62.java | <filename>src/main/java/Top100/Problem62.java
package Top100;
public class Problem62 {
public int uniquePaths(int m, int n) {
int[][] map = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(i == 0||j == 0){
map[i][j] = 1;
}else {
map[i][j] = map[i-1][j]+map[i][j-1];
}
}
}
return map[m-1][n-1];
}
}
|
epall/selenium | third_party/gecko-1.9.0.11/mac/include/nsIUploadChannel.h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/tinderbox/Xr-Mozilla1.9-Release/Darwin_8.8.4_Depend/mozilla/netwerk/base/public/nsIUploadChannel.idl
*/
#ifndef __gen_nsIUploadChannel_h__
#define __gen_nsIUploadChannel_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIInputStream; /* forward declaration */
/* starting interface: nsIUploadChannel */
#define NS_IUPLOADCHANNEL_IID_STR "ddf633d8-e9a4-439d-ad88-de636fd9bb75"
#define NS_IUPLOADCHANNEL_IID \
{0xddf633d8, 0xe9a4, 0x439d, \
{ 0xad, 0x88, 0xde, 0x63, 0x6f, 0xd9, 0xbb, 0x75 }}
/**
* nsIUploadChannel
*
* A channel may optionally implement this interface if it supports the
* notion of uploading a data stream. The upload stream may only be set
* prior to the invocation of asyncOpen on the channel.
*
* @status FROZEN
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIUploadChannel : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IUPLOADCHANNEL_IID)
/**
* Sets a stream to be uploaded by this channel.
*
* Most implementations of this interface require that the stream:
* (1) implement threadsafe addRef and release
* (2) implement nsIInputStream::readSegments
* (3) implement nsISeekableStream::seek
*
* History here is that we need to support both streams that already have
* headers (e.g., Content-Type and Content-Length) information prepended to
* the stream (by plugins) as well as clients (composer, uploading
* application) that want to upload data streams without any knowledge of
* protocol specifications. For this reason, we have a special meaning
* for the aContentType parameter (see below).
*
* @param aStream
* The stream to be uploaded by this channel.
* @param aContentType
* If aContentType is empty, the protocol will assume that no
* content headers are to be added to the uploaded stream and that
* any required headers are already encoded in the stream. In the
* case of HTTP, if this parameter is non-empty, then its value will
* replace any existing Content-Type header on the HTTP request.
* In the case of FTP and FILE, this parameter is ignored.
* @param aContentLength
* A value of -1 indicates that the length of the stream should be
* determined by calling the stream's |available| method.
*/
/* void setUploadStream (in nsIInputStream aStream, in ACString aContentType, in long aContentLength); */
NS_SCRIPTABLE NS_IMETHOD SetUploadStream(nsIInputStream *aStream, const nsACString & aContentType, PRInt32 aContentLength) = 0;
/**
* Get the stream (to be) uploaded by this channel.
*/
/* readonly attribute nsIInputStream uploadStream; */
NS_SCRIPTABLE NS_IMETHOD GetUploadStream(nsIInputStream * *aUploadStream) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIUploadChannel, NS_IUPLOADCHANNEL_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIUPLOADCHANNEL \
NS_SCRIPTABLE NS_IMETHOD SetUploadStream(nsIInputStream *aStream, const nsACString & aContentType, PRInt32 aContentLength); \
NS_SCRIPTABLE NS_IMETHOD GetUploadStream(nsIInputStream * *aUploadStream);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIUPLOADCHANNEL(_to) \
NS_SCRIPTABLE NS_IMETHOD SetUploadStream(nsIInputStream *aStream, const nsACString & aContentType, PRInt32 aContentLength) { return _to SetUploadStream(aStream, aContentType, aContentLength); } \
NS_SCRIPTABLE NS_IMETHOD GetUploadStream(nsIInputStream * *aUploadStream) { return _to GetUploadStream(aUploadStream); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIUPLOADCHANNEL(_to) \
NS_SCRIPTABLE NS_IMETHOD SetUploadStream(nsIInputStream *aStream, const nsACString & aContentType, PRInt32 aContentLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetUploadStream(aStream, aContentType, aContentLength); } \
NS_SCRIPTABLE NS_IMETHOD GetUploadStream(nsIInputStream * *aUploadStream) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUploadStream(aUploadStream); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsUploadChannel : public nsIUploadChannel
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIUPLOADCHANNEL
nsUploadChannel();
private:
~nsUploadChannel();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsUploadChannel, nsIUploadChannel)
nsUploadChannel::nsUploadChannel()
{
/* member initializers and constructor code */
}
nsUploadChannel::~nsUploadChannel()
{
/* destructor code */
}
/* void setUploadStream (in nsIInputStream aStream, in ACString aContentType, in long aContentLength); */
NS_IMETHODIMP nsUploadChannel::SetUploadStream(nsIInputStream *aStream, const nsACString & aContentType, PRInt32 aContentLength)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIInputStream uploadStream; */
NS_IMETHODIMP nsUploadChannel::GetUploadStream(nsIInputStream * *aUploadStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIUploadChannel_h__ */
|
EdiJunior88/NewTab_Academy_Projetos | Modulo_03/JAVASCRIPT/Capitulo_23/cep.js | function buscaCep() {
let inputCep = document.getElementById('cep');
let cep = inputCep.value.replace('-', '');
let url = 'https://viacep.com.br/ws' + cep + '/json';
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
} |
morynicz/ippon_back | auth_server/views.py | import os
from django.http import JsonResponse
# Create your views here.
from rest_framework_simplejwt.views import TokenObtainPairView
from auth_server.serializers import UserTokenSerializer
def view_pubkey(request):
return JsonResponse({'key': os.environ['SECRET_KEY_PUBLIC']}, safe=False)
class UserTokenObtainPairView(TokenObtainPairView):
serializer_class = UserTokenSerializer
|
JoanAzpeitia/lp_sg | install/app_store/tk-hiero-export/v0.4.3/python/tk_hiero_export/shot_updater.py | <gh_stars>0
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
import hiero.core
from hiero.exporters import FnShotExporter
from .base import ShotgunHieroObjectBase
from .collating_exporter import CollatingExporter
class ShotgunShotUpdater(ShotgunHieroObjectBase, FnShotExporter.ShotTask, CollatingExporter):
"""
Ensures that Shots and Sequences exist in Shotgun
"""
def __init__(self, initDict):
FnShotExporter.ShotTask.__init__(self, initDict)
CollatingExporter.__init__(self)
self._cut_order = None
def get_cut_item_data(self):
"""
Return some computed values for use when creating cut items.
The values correspond to the exported version created on disk.
"""
(head_in, tail_out) = self.collatedOutputRange(clampToSource=False)
handles = self._cutHandles if self._cutHandles is not None else 0
in_handle = handles
out_handle = handles
# get the frame offset specified in the export options
startFrame = self._startFrame or 0
# these are the source in/out frames. we'll use them to determine if we
# have enough frames to account for the handles. versions of
# hiero/nukestudio handle missing handles differently
source_in = int(self._item.sourceIn())
source_out = int(self._item.sourceOut())
if self._has_nuke_backend() and source_in < in_handle:
# newer versions of the hiero/nukestudio. no black frames will be
# written to disk for the head when not enough source for the in
# handle. the in/out should be correct. but the start handle is
# limited by the in value. the source in point is within the
# specified handles.
in_handle = source_in
# NOTE: even new versions of hiero/nukestudio will write black
# frames for insuffient tail handles. so we don't need to account
# for that case here.
# "cut_length" is a boolean set on the updater by the shot processor.
# it signifies whether the transcode task will write the cut length
# to disk (True) or if it will write the full source to disk (False)
if self.is_cut_length_export():
cut_in = head_in + in_handle
cut_out = tail_out - out_handle
else:
cut_in = source_in
cut_out = source_out
# account for any custom start frame
cut_in += startFrame
cut_out += startFrame
# get the edit in/out points from the timeline
edit_in = self._item.timelineIn()
edit_out = self._item.timelineOut()
# account for custom start code in the hiero timeline
seq = self._item.sequence()
edit_in += seq.timecodeStart()
edit_out += seq.timecodeStart()
cut_duration = cut_out - cut_in + 1
edit_duration = edit_out - edit_in + 1
if cut_duration != edit_duration:
self.app.log_warning(
"It looks like the shot %s has a retime applied. SG cuts do "
"not support retimes." % (self.clipName(),)
)
working_duration = tail_out - head_in + 1
if not self._has_nuke_backend() and self.isCollated():
# undo the offset that is automatically added when collating.
# this is only required in older versions of hiero
head_in -= self.HEAD_ROOM_OFFSET
tail_out -= self.HEAD_ROOM_OFFSET
# return the computed cut information
return {
"cut_item_in": cut_in,
"cut_item_out": cut_out,
"cut_item_duration": cut_duration,
"edit_in": edit_in,
"edit_out": edit_out,
"edit_duration": edit_duration,
"head_in": head_in,
"tail_out": tail_out,
"working_duration": working_duration,
}
def taskStep(self):
"""
Execution payload.
"""
# Only process actual shots... so uncollated items and hero collated items
if self.isCollated() and not self.isHero():
return False
# execute base class
FnShotExporter.ShotTask.taskStep(self)
# call the preprocess hook to get extra values
if self.app.shot_count == 0:
self.app.preprocess_data = {}
sg_shot = self.app.execute_hook("hook_get_shot", task=self, item=self._item, data=self.app.preprocess_data)
# clean up the dict
shot_id = sg_shot['id']
del sg_shot['id']
shot_type = sg_shot['type']
del sg_shot['type']
# The cut order may have been set by the processor. Otherwise keep old behavior.
cut_order = self.app.shot_count + 1
if self._cut_order:
cut_order = self._cut_order
# update the frame range
sg_shot["sg_cut_order"] = cut_order
# get cut info
cut_info = self.get_cut_item_data()
head_in = cut_info["head_in"]
tail_out = cut_info["tail_out"]
cut_in = cut_info["cut_item_in"]
cut_out = cut_info["cut_item_out"]
cut_duration = cut_info["cut_item_duration"]
working_duration = cut_info["working_duration"]
self.app.log_debug("Head/Tail from Hiero: %s, %s" % (head_in, tail_out))
if self.isCollated():
if self.is_cut_length_export():
# nothing to do here. the default calculation above is enough.
self.app.log_debug("Exporting... collated, cut length.")
# Log cut length collate metric
try:
self.app.log_metric("Collate/Cut Length", log_version=True)
except:
# ingore any errors. ex: metrics logging not supported
pass
else:
self.app.log_debug("Exporting... collated, clip length.")
# NOTE: Hiero crashes when trying to collate with a
# custom start frame. so this will only work for source start
# frame.
# the head/in out values should be the first and last frames of
# the source, but they're not. they're actually the values we
# expect for the cut in/out.
cut_in = head_in
cut_out = tail_out
# ensure head/tail match the entire clip (clip length export)
head_in = 0
tail_out = self._clip.duration() - 1
# get the frame offset specified in the export options
start_frame = self._startFrame or 0
# account for a custom start frame if/when clip length collate
# works on custom start frame.
head_in += start_frame
tail_out += start_frame
cut_in += start_frame
cut_out += start_frame
# since we've set the head/tail, recalculate the working
# duration to make sure it is correct
working_duration = tail_out - head_in + 1
# since we've set the cut in/out, recalculate the cut duration
# to make sure it is correct
cut_duration = cut_out - cut_in + 1
# Log clip length collate metric
try:
self.app.log_metric("Collate/Clip Length", log_version=True)
except:
# ingore any errors. ex: metrics logging not supported
pass
else:
# regular export. values we have are good. just log it
if self.is_cut_length_export():
self.app.log_debug("Exporting... cut length.")
else:
# the cut in/out should already be correct here. just log
self.app.log_debug("Exporting... clip length.")
# update the frame range
sg_shot["sg_head_in"] = head_in
sg_shot["sg_cut_in"] = cut_in
sg_shot["sg_cut_out"] = cut_out
sg_shot["sg_tail_out"] = tail_out
sg_shot["sg_cut_duration"] = cut_duration
sg_shot["sg_working_duration"] = working_duration
# get status from the hiero tags
status = None
status_map = dict(self._preset.properties()["sg_status_hiero_tags"])
for tag in self._item.tags():
if tag.name() in status_map:
status = status_map[tag.name()]
break
if status:
sg_shot['sg_status_list'] = status
# get task template from the tags
template = None
template_map = dict(self._preset.properties()["task_template_map"])
for tag in self._item.tags():
if tag.name() in template_map:
template = self.app.tank.shotgun.find_one('TaskTemplate',
[['entity_type', 'is', shot_type],
['code', 'is', template_map[tag.name()]]])
break
# if there are no associated, assign default template...
if template is None:
default_template = self.app.get_setting('default_task_template')
if default_template:
template = self.app.tank.shotgun.find_one('TaskTemplate',
[['entity_type', 'is', shot_type], ['code', 'is', default_template]])
if template is not None:
sg_shot['task_template'] = template
# commit the changes and update the thumbnail
self.app.log_debug("Updating info for %s %s: %s" % (shot_type, shot_id, str(sg_shot)))
self.app.tank.shotgun.update(shot_type, shot_id, sg_shot)
# create the directory structure
self.app.log_debug("Creating file system structure for %s %s..." % (shot_type, shot_id))
self.app.tank.create_filesystem_structure(shot_type, [shot_id])
# return without error
self.app.log_info("Updated %s %s" % (shot_type, self.shotName()))
# keep shot count
self.app.shot_count += 1
cut = None
# create the CutItem with the data populated by the shot processor
if hasattr(self, "_cut_item_data"):
cut_item_data = self._cut_item_data
cut_item = self.app.tank.shotgun.create("CutItem", cut_item_data)
self.app.log_info("Created CutItem in Shotgun: %s" % (cut_item,))
# update the object's cut item data to include the new info
self._cut_item_data.update(cut_item)
cut = cut_item["cut"]
# see if this task has been designated to update the Cut thumbnail
if cut and hasattr(self, "_create_cut_thumbnail"):
hiero_sequence = self._item.sequence()
try:
# see if we can find a poster frame for the sequence
thumbnail = hiero_sequence.thumbnail(hiero_sequence.posterFrame())
except Exception:
self.app.log_debug("No thumbnail found for the 'Cut'.")
pass
else:
# found one, uplaod to sg for the cut
self._upload_thumbnail_to_sg(cut, thumbnail)
# return false to indicate success
return False
def is_cut_length_export(self):
"""
Returns ``True`` if this task has the "Cut Length" option checked.
This is set by the shot processor.
"""
return hasattr(self, "_cut_length") and self._cut_length
class ShotgunShotUpdaterPreset(ShotgunHieroObjectBase, hiero.core.TaskPresetBase):
"""
Settings preset
"""
def __init__(self, name, properties):
hiero.core.TaskPresetBase.__init__(self, ShotgunShotUpdater, name)
self.properties().update(properties)
def supportedItems(self):
return hiero.core.TaskPresetBase.kAllItems
|
fishjd/HappyNewMoonWithReport | src/main/java/happynewmoonwithreport/type/U64.java | <filename>src/main/java/happynewmoonwithreport/type/U64.java<gh_stars>10-100
/*
* Copyright 2017 - 2021 Whole Bean Software, LTD.
*
* 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 happynewmoonwithreport.type;
import happynewmoonwithreport.WasmRuntimeException;
import java.util.UUID;
/**
* An Unsigned integer of 64 bits,
* <br>
* Implementation Note: Range is from 0 to 9_223_372_036_854_775_807. The wasm spec is 0 to
* 18_446_744_073_709_551_616
*/
public class U64 extends I64 {
public U64() {
super();
}
@Override
public Integer maxBits() {
return 63; // should be 64 but that is not possible using Java type Long.
}
public U64(Long value) {
if (isBoundByLong(value) == false) {
throw new WasmRuntimeException(UUID.fromString("1c282299-6b1b-4d02-9e81-a29c279840d3"),
"Value too large. Value = " + value + "Only values from 0 to " + Long.MAX_VALUE
+ " are currently supported.");
}
this.value = value;
}
/**
* True if value can be stored in U64.
*
* @param value number to test.
* @return True if value can be stored in U64. 0 to 9_223_372_036_854_775_807 ie 0 to Long
* .MAX_VALUE; <br>
* False if value can not be stored in U64. 9_223_372_036_854_775_808 to
* 18_446_744_073_709_551_616
*/
public static boolean isBoundByLong(Long value) {
return (0x8000_0000_0000_0000L & value.longValue()) == 0;
}
public I32 lessThan(U64 other) {
I32 result;
Integer iResult;
if (value < other.value) {
iResult = 1;
} else {
iResult = 0;
}
result = new I32(iResult);
return result;
}
public I32 lessThanEqual(U64 other) {
I32 result;
Integer iResult;
if (value <= other.value) {
iResult = 1;
} else {
iResult = 0;
}
result = new I32(iResult);
return result;
}
public I32 greaterThan(U64 other) {
I32 result;
Integer iResult;
if (value > other.value) {
iResult = 1;
} else {
iResult = 0;
}
result = new I32(iResult);
return result;
}
public I32 greaterThanEqual(U64 other) {
I32 result;
Integer iResult;
if (value >= other.value) {
iResult = 1;
} else {
iResult = 0;
}
result = new I32(iResult);
return result;
}
@Override
public Long minValue() {
// @TODO change return type to U64.
return 0L;
}
@Override
public Long maxValue() {
return (1L << (maxBits())) - 1;
}
}
|
tangyibin/goblin-core | riscv/riscv-omp/runtime/src/z_Windows_NT-586_util.c | <gh_stars>0
/*
* z_Windows_NT-586_util.c -- platform specific routines.
* $Revision: 42951 $
* $Date: 2014-01-21 14:41:41 -0600 (Tue, 21 Jan 2014) $
*/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
#include "kmp.h"
#if (KMP_ARCH_X86 || KMP_ARCH_X86_64)
/* Only 32-bit "add-exchange" instruction on IA-32 architecture causes us to
* use compare_and_store for these routines
*/
kmp_int32
__kmp_test_then_or32( volatile kmp_int32 *p, kmp_int32 d )
{
kmp_int32 old_value, new_value;
old_value = TCR_4( *p );
new_value = old_value | d;
while ( ! __kmp_compare_and_store32 ( p, old_value, new_value ) )
{
KMP_CPU_PAUSE();
old_value = TCR_4( *p );
new_value = old_value | d;
}
return old_value;
}
kmp_int32
__kmp_test_then_and32( volatile kmp_int32 *p, kmp_int32 d )
{
kmp_int32 old_value, new_value;
old_value = TCR_4( *p );
new_value = old_value & d;
while ( ! __kmp_compare_and_store32 ( p, old_value, new_value ) )
{
KMP_CPU_PAUSE();
old_value = TCR_4( *p );
new_value = old_value & d;
}
return old_value;
}
#if KMP_ARCH_X86
kmp_int64
__kmp_test_then_add64( volatile kmp_int64 *p, kmp_int64 d )
{
kmp_int64 old_value, new_value;
old_value = TCR_8( *p );
new_value = old_value + d;
while ( ! __kmp_compare_and_store64 ( p, old_value, new_value ) )
{
KMP_CPU_PAUSE();
old_value = TCR_8( *p );
new_value = old_value + d;
}
return old_value;
}
#endif /* KMP_ARCH_X86 */
kmp_int64
__kmp_test_then_or64( volatile kmp_int64 *p, kmp_int64 d )
{
kmp_int64 old_value, new_value;
old_value = TCR_8( *p );
new_value = old_value | d;
while ( ! __kmp_compare_and_store64 ( p, old_value, new_value ) )
{
KMP_CPU_PAUSE();
old_value = TCR_8( *p );
new_value = old_value | d;
}
return old_value;
}
kmp_int64
__kmp_test_then_and64( volatile kmp_int64 *p, kmp_int64 d )
{
kmp_int64 old_value, new_value;
old_value = TCR_8( *p );
new_value = old_value & d;
while ( ! __kmp_compare_and_store64 ( p, old_value, new_value ) )
{
KMP_CPU_PAUSE();
old_value = TCR_8( *p );
new_value = old_value & d;
}
return old_value;
}
#endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
|
EnvisionIot/enos-iot-java-sdk | enos-sdk-core/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/internals/constants/FeatureType.java | package com.envisioniot.enos.iot_mqtt_sdk.core.internals.constants;
/**
* This constants defines 4 feature types in TSL model
* @author shenjieyuan
*/
public class FeatureType
{
public static final String ATTRIBUTE = "attribute";
public static final String MEASUREPOINT = "measurepoint";
public static final String EVENT = "event";
public static final String SERVICE = "service";
}
|
BenkeLysander/tursi | src/tursi/view/dialogs/PrefDialog.java | package tursi.view.dialogs;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.prefs.*;
import tursi.view.Misc;
import tursi.view.icons.IconLoader;
// Preferences
public class PrefDialog {
private static final String PREF_AUTO_RESET = "auto_reset";
private static final String PREF_HIST_SIZE = "hist_size";
private static final String PREF_ALIAS_LEFT = "alias_left";
private static final String PREF_ALIAS_NONE = "alias_none";
private static final String PREF_ALIAS_RIGHT = "alias_right";
private static final String PREF_TV_FRAME_LENGTH = "tv_frame_length";
private static final String PREF_TV_STRIPE_SIZE = "tv_stripe_size";
private static final boolean DEF_AUTO_RESET = true;
private static final int DEF_HIST_SIZE = 1000;
private static final String DEF_ALIAS_LEFT = "L";
private static final String DEF_ALIAS_NONE = "N";
private static final String DEF_ALIAS_RIGHT = "R";
private static final int DEF_TV_FRAME_LENGTH = 25;
private static final int DEF_TV_STRIPE_SIZE = 10;
private static final String PREF_LAST_TM_FILE = "last_tm_file";
private static final String PREF_LAST_DIR = "last_dir";
private static final String DEF_LAST_TM_FILE = "no last file";
private static final String DEF_LAST_DIR = System.getProperty("user.home");
// ---------------------------------------------------------------------------
private final Preferences pref;
private final int vGap = 2;
private final int hGap = 10;
private final int btnGap = 2;
private final int secGap = 24;
private final int border = 10;
private final JDialog dialog;
private final JCheckBox autoReset;
private final SpinnerNumberModel histSizeModel;
private final JTextField aliasLeft;
private final JTextField aliasNone;
private final JTextField aliasRight;
private final SpinnerNumberModel tvFrameLengthModel;
private final SpinnerNumberModel tvStripeSizeModel;
private final JButton btnDefs;
private final JButton btnCancel;
private final JButton btnOK;
private final JButton btnApply;
private final PrefConsumer consumer;
public PrefDialog(PrefConsumer consumer) {
this.consumer = consumer;
pref = Preferences.userNodeForPackage(this.getClass());
dialog = new JDialog((JFrame) null);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
hide(false);
}
});
dialog.setIconImages(IconLoader.logoList());
autoReset = new JCheckBox("Reset when starting from end state");
histSizeModel = new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1);
aliasLeft = new JTextField(DEF_ALIAS_LEFT);
aliasNone = new JTextField(DEF_ALIAS_NONE);
aliasRight = new JTextField(DEF_ALIAS_RIGHT);
tvFrameLengthModel = new SpinnerNumberModel(0, 0, 1000, 1);
tvStripeSizeModel = new SpinnerNumberModel(0, -10000, 10000, 1);
loadPrefs();
btnDefs = new JButton("Restore Defaults");
btnCancel = new JButton("Cancel");
btnOK = new JButton("OK");
btnApply = new JButton("Apply");
final PrefDialog thisDialog = this;
btnDefs.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
loadDefs();
}
});
btnCancel.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
hide(false);
}
});
btnOK.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
storePrefs();
thisDialog.consumer.consumePrefChange();
}
});
btnApply.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
storePrefs();
thisDialog.consumer.consumePrefChange();
}
});
assemble();
}
private void assemble() {
JPanel p = new JPanel();
p.setBorder(BorderFactory.createEmptyBorder(border, border, border, border));
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
JLabel titleMachine = new JLabel("Machine");
JLabel titleHist = new JLabel("History");
JLabel titleAlias = new JLabel("Aliases for field 'move'");
JLabel titleTape = new JLabel("Tape visualization");
Font titleFont =
titleHist.getFont().deriveFont(titleHist.getFont().getSize()*1.15f);
titleMachine.setFont(titleFont);
titleHist.setFont(titleFont);
titleHist.setFont(titleFont);
titleAlias.setFont(titleFont);
titleTape.setFont(titleFont);
// ---------- Machine Section ----------------------------------------------
p.add(titleMachine);
p.add(Box.createVerticalStrut(vGap));
p.add(autoReset);
setAlignAndMaxHeight(titleMachine);
setAlignAndMaxHeight(autoReset);
p.add(Box.createVerticalStrut(secGap));
// ---------- History Section ----------------------------------------------
JPanel histPanel = Misc.makeBoxPanel(BoxLayout.X_AXIS);
histPanel.add(new JLabel("Max. size"));
histPanel.add(Box.createHorizontalStrut(hGap));
JSpinner histSize = new JSpinner(histSizeModel);
Misc.setPlainNumEditor(histSize);
histPanel.add(histSize);
p.add(titleHist);
p.add(Box.createVerticalStrut(vGap));
p.add(histPanel);
setAlignAndMaxHeight(titleHist);
setAlignAndMaxHeight(histPanel);
p.add(Box.createVerticalStrut(secGap));
// ---------- Alias Section ------------------------------------------------
JPanel aliasPanel = new JPanel(new GridLayout(2, 3, hGap, vGap));
aliasPanel.add(new JLabel("Left (-1)"));
aliasPanel.add(new JLabel("None (0)"));
aliasPanel.add(new JLabel("Right (1)"));
aliasPanel.add(aliasLeft);
aliasPanel.add(aliasNone);
aliasPanel.add(aliasRight);
p.add(titleAlias);
p.add(Box.createVerticalStrut(vGap));
p.add(aliasPanel);
setAlignAndMaxHeight(titleAlias);
setAlignAndMaxHeight(aliasPanel);
p.add(Box.createVerticalStrut(secGap));
// ---------- Tape Section -------------------------------------------------
JPanel tapePanel = new JPanel(new GridLayout(2, 2, hGap, vGap));
JLabel lblFrameLength = new JLabel("Frame length");
tapePanel.add(lblFrameLength);
tapePanel.add(new JLabel("Stripe size"));
JSpinner tvFrameLength = new JSpinner(tvFrameLengthModel);
JSpinner tvStripeSize = new JSpinner(tvStripeSizeModel);
Misc.setPlainNumEditor(tvFrameLength);
Misc.setPlainNumEditor(tvStripeSize);
tapePanel.add(tvFrameLength);
tapePanel.add(tvStripeSize);
p.add(titleTape);
p.add(Box.createVerticalStrut(vGap));
p.add(tapePanel);
setAlignAndMaxHeight(titleTape);
setAlignAndMaxHeight(tapePanel);
String ttFrameLength = "Time in ms between two repaints (max. 1000 ms)";
tvFrameLength.setToolTipText(ttFrameLength);
lblFrameLength.setToolTipText(ttFrameLength);
p.add(Box.createVerticalStrut(secGap));
p.add(Box.createVerticalGlue());
// ---------- Button Section -----------------------------------------------
Misc.setMaxToPrefSize(btnDefs);
btnDefs.setAlignmentX(0);
p.add(btnDefs);
p.add(Box.createVerticalStrut(vGap));
JPanel buttonPanel = Misc.makeBoxPanel(BoxLayout.X_AXIS);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(btnCancel);
buttonPanel.add(Box.createHorizontalStrut(btnGap));
buttonPanel.add(btnOK);
buttonPanel.add(Box.createHorizontalStrut(btnGap));
buttonPanel.add(btnApply);
p.add(buttonPanel);
setAlignAndMaxHeight(buttonPanel);
dialog.getContentPane().add(p);
dialog.pack();
dialog.setMinimumSize(dialog.getSize());
dialog.setLocationRelativeTo(null);
}
private void setAlignAndMaxHeight(JComponent c) {
c.setAlignmentX(0);
Misc.setMaxToPrefHeight(c);
}
private void loadPrefs() {
autoReset.setSelected(getAutoReset());
histSizeModel.setValue(getHistSize());
aliasLeft.setText(getAliasLeft());
aliasNone.setText(getAliasNone());
aliasRight.setText(getAliasRight());
tvFrameLengthModel.setValue(getTVFrameLength());
tvStripeSizeModel.setValue(getTVStripeSize());
}
private void loadDefs() {
autoReset.setSelected(DEF_AUTO_RESET);
histSizeModel.setValue(DEF_HIST_SIZE);
aliasLeft.setText(DEF_ALIAS_LEFT);
aliasNone.setText(DEF_ALIAS_NONE);
aliasRight.setText(DEF_ALIAS_RIGHT);
tvFrameLengthModel.setValue(DEF_TV_FRAME_LENGTH);
tvStripeSizeModel.setValue(DEF_TV_STRIPE_SIZE);
}
private void storePrefs() {
pref.putBoolean(PREF_AUTO_RESET, autoReset.isSelected());
pref.putInt(PREF_HIST_SIZE, histSizeModel.getNumber().intValue());
pref.put(PREF_ALIAS_LEFT, aliasLeft.getText());
pref.put(PREF_ALIAS_NONE, aliasNone.getText());
pref.put(PREF_ALIAS_RIGHT, aliasRight.getText());
pref.putInt(PREF_TV_FRAME_LENGTH, tvFrameLengthModel.getNumber().intValue());
pref.putInt(PREF_TV_STRIPE_SIZE, tvStripeSizeModel.getNumber().intValue());
}
// ---------------------------------------------------------------------------
public boolean isVisible() {
return dialog.isVisible();
}
public void show() {
dialog.setVisible(true);
dialog.toFront();
}
public void hide(boolean apply) {
dialog.setVisible(false);
if (apply) {
storePrefs();
} else {
loadPrefs();
}
}
public void exit() {
dialog.setVisible(false);
try {
pref.flush();
} catch (BackingStoreException e) {
String msg = "Couldn't save one ore more preferences.\n" + e.getMessage();
JOptionPane.showMessageDialog(dialog.getOwner(),
msg, "Preferences not saved", JOptionPane.ERROR_MESSAGE);
}
dialog.dispose();
}
// ---------------------------------------------------------------------------
public boolean getAutoReset() {
return pref.getBoolean(PREF_AUTO_RESET, DEF_AUTO_RESET);
}
public int getHistSize() {
return pref.getInt(PREF_HIST_SIZE, DEF_HIST_SIZE);
}
public String getAliasLeft() {
return pref.get(PREF_ALIAS_LEFT, DEF_ALIAS_LEFT);
}
public String getAliasNone() {
return pref.get(PREF_ALIAS_NONE, DEF_ALIAS_NONE);
}
public String getAliasRight() {
return pref.get(PREF_ALIAS_RIGHT, DEF_ALIAS_RIGHT);
}
public int getTVFrameLength() {
return pref.getInt(PREF_TV_FRAME_LENGTH, DEF_TV_FRAME_LENGTH);
}
public int getTVStripeSize() {
return pref.getInt(PREF_TV_STRIPE_SIZE, DEF_TV_STRIPE_SIZE);
}
// -----------------
public String getLastTMFile() {
return pref.get(PREF_LAST_TM_FILE, DEF_LAST_TM_FILE);
}
public String getLastDir() {
return pref.get(PREF_LAST_DIR, DEF_LAST_DIR);
}
public void setLastTMFile(String path) {
pref.put(PREF_LAST_TM_FILE, path);
}
public void setLastDir(String path) {
pref.put(PREF_LAST_DIR, path);
}
}
|
arez/arez | integration-tests/src/test/java/arez/integration/context_ref/ContextRefTest.java | <gh_stars>10-100
package arez.integration.context_ref;
import arez.Arez;
import arez.ArezContext;
import arez.annotations.ArezComponent;
import arez.annotations.ContextRef;
import arez.integration.AbstractArezIntegrationTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public final class ContextRefTest
extends AbstractArezIntegrationTest
{
@ArezComponent( allowEmpty = true )
static abstract class TestComponent
{
@ContextRef
abstract ArezContext getContext();
}
@Test
public void contextRef()
{
final ArezContext context = Arez.context();
final TestComponent component = new ContextRefTest_Arez_TestComponent();
assertEquals( component.getContext(), context );
}
}
|
PhantomYdn/ICOFarm | src/main/java/org/orienteer/util/package-info.java | <filename>src/main/java/org/orienteer/util/package-info.java<gh_stars>1-10
/**
* Contains utils for ICOFarm
*/
package org.orienteer.util; |
qsardb/qsardb-common | resolution/chemical/src/main/java/org/qsardb/resolution/chemical/Identifier.java | <reponame>qsardb/qsardb-common
/*
* Copyright (c) 2011 University of Tartu
*/
package org.qsardb.resolution.chemical;
import org.qsardb.model.*;
abstract
public class Identifier {
abstract
public String format(Compound compound);
} |
xj1430688054/jxt | src/main/java/com/gl/jxt/service/IItemService.java | <reponame>xj1430688054/jxt<filename>src/main/java/com/gl/jxt/service/IItemService.java
package com.gl.jxt.service;
import com.gl.jxt.common.dto.ResultModel;
import com.gl.jxt.common.page.Page;
import com.gl.jxt.domain.Item;
public interface IItemService {
ResultModel save(Item item);
Item findById(int iid);
ResultModel update(Item item);
ResultModel delete(int iid);
ResultModel itemList();
/**
*
* @param page
* @return
*/
ResultModel itemListByPage(Page page);
ResultModel itemListByState(int state);
}
|
retropipes/retro-rpgcs | retro-rpgcs-core/src/com/puttysoftware/retrorpgcs/maze/objects/Player.java | /* RetroRPGCS: An RPG */
package com.puttysoftware.retrorpgcs.maze.objects;
import com.puttysoftware.retrorpgcs.maze.Maze;
import com.puttysoftware.retrorpgcs.maze.abc.AbstractCharacter;
import com.puttysoftware.retrorpgcs.resourcemanagers.ObjectImageConstants;
public class Player extends AbstractCharacter {
// Constructors
public Player() {
}
@Override
public int getBaseID() {
return ObjectImageConstants.OBJECT_IMAGE_PLAYER;
}
@Override
public String getDescription() {
return "This is you - the Player.";
}
@Override
public int getMaximumRequiredQuantity(final Maze maze) {
return 1;
}
@Override
public int getMinimumRequiredQuantity(final Maze maze) {
return 1;
}
@Override
public String getName() {
return "Player";
}
@Override
public String getPluralName() {
return "Players";
}
// Random Generation Rules
@Override
public boolean isRequired() {
return true;
}
} |
magx2/jSupla | protocol/src/test/java/pl/grzeslowski/jsupla/protocol/common/randomizers/sc/SuplaChannelGroupRelationPackRandomizer.java | <gh_stars>1-10
package pl.grzeslowski.jsupla.protocol.common.randomizers.sc;
import io.github.benas.randombeans.api.Randomizer;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelGroupRelation;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelGroupRelationPack;
import pl.grzeslowski.jsupla.protocol.common.RandomSupla;
public class SuplaChannelGroupRelationPackRandomizer implements Randomizer<SuplaChannelGroupRelationPack> {
private final RandomSupla randomSupla;
public SuplaChannelGroupRelationPackRandomizer(RandomSupla randomSupla) {
this.randomSupla = randomSupla;
}
@Override
public SuplaChannelGroupRelationPack getRandomValue() {
SuplaChannelGroupRelation[] items = randomSupla
.objects(SuplaChannelGroupRelation.class, randomSupla.nextPositiveInt(5))
.toArray(SuplaChannelGroupRelation[]::new);
return new SuplaChannelGroupRelationPack(
items.length,
randomSupla.nextPositiveInt(),
items
);
}
}
|
Qmeanl/FRKit | FRKit/FRCategories/UIKit/UIViewController/UIViewController+TipView.h | <filename>FRKit/FRCategories/UIKit/UIViewController/UIViewController+TipView.h
//
// UIViewController+TipView.h
// FRKit
//
// Created by wenhua on 2018/11/20.
// Copyright © 2018 黄小华. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (TipView)
@property (nonatomic, strong, readonly) UIView *tt_tipView;
- (void)showTipView:(UIView *)tipView retryAction:(void (^)(id userData))retryAction;
- (void)showTipView:(UIView *)tipView userData:(id)userData retryAction:(void (^)(id userData))retryAction;
- (void)removeTipView;
@end
|
roxiemobile/android-commons | Modules/RoxieMobile.AndroidCommons/android-commons/src/main/java/com/roxiemobile/androidcommons/util/CharacterUtils.java | <filename>Modules/RoxieMobile.AndroidCommons/android-commons/src/main/java/com/roxiemobile/androidcommons/util/CharacterUtils.java
package com.roxiemobile.androidcommons.util;
public final class CharacterUtils
{
// MARK: - Construction
private CharacterUtils() {
// Do nothing
}
// MARK: - Methods
/**
* Indicates whether the specified character is a ASCII letter.
*
* @param c The character to check.
* @return {@code true} if {@code c} is a letter; {@code false} otherwise.
*/
public static boolean isAsciiLetter(char c) {
return isAsciiLetter((int) c);
}
/**
* Indicates whether the specified code point is a ASCII letter.
*
* @param codePoint The code point to check.
* @return {@code true} if {@code codePoint} is a letter; {@code false} otherwise.
*/
public static boolean isAsciiLetter(int codePoint) {
return ('A' <= codePoint && codePoint <= 'Z') || ('a' <= codePoint && codePoint <= 'z');
}
/**
* Indicates whether the specified character is a ASCII letter or a digit.
*
* @param c The character to check.
* @return {@code true} if {@code c} is a letter or a digit; {@code false} otherwise.
*/
public static boolean isAsciiLetterOrDigit(char c) {
return isAsciiLetterOrDigit((int) c);
}
/**
* Indicates whether the specified code point is a ASCII letter or a digit.
*
* @param codePoint The code point to check.
* @return {@code true} if {@code codePoint} is a letter or a digit; {@code false} otherwise.
*/
public static boolean isAsciiLetterOrDigit(int codePoint) {
return ('A' <= codePoint && codePoint <= 'Z') || ('a' <= codePoint && codePoint <= 'z') || ('0' <= codePoint && codePoint <= '9');
}
}
|
joffrey-bion/livedoc | livedoc-core/src/main/java/org/hildan/livedoc/core/readers/annotation/ApiOperationDocReader.java | <filename>livedoc-core/src/main/java/org/hildan/livedoc/core/readers/annotation/ApiOperationDocReader.java
package org.hildan.livedoc.core.readers.annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import org.hildan.livedoc.core.annotations.ApiOperation;
import org.hildan.livedoc.core.annotations.ApiResponseBodyType;
import org.hildan.livedoc.core.model.LivedocDefaultType;
import org.hildan.livedoc.core.model.doc.ApiDoc;
import org.hildan.livedoc.core.model.doc.ApiOperationDoc;
import org.hildan.livedoc.core.model.types.LivedocType;
import org.hildan.livedoc.core.scanners.templates.TemplateProvider;
import org.hildan.livedoc.core.scanners.types.references.TypeReferenceProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.hildan.livedoc.core.readers.annotation.ApiDocReader.nullifyIfEmpty;
public class ApiOperationDocReader {
public static ApiOperationDoc read(Method method, ApiDoc parentApiDoc, TypeReferenceProvider typeReferenceProvider,
TemplateProvider templateProvider) {
ApiOperationDoc apiOperationDoc = new ApiOperationDoc();
apiOperationDoc.setName(method.getName());
apiOperationDoc.setApiErrors(ApiErrorDocReader.build(method));
apiOperationDoc.setSupportedVersions(ApiVersionDocReader.read(method, parentApiDoc.getSupportedVersions()));
apiOperationDoc.setAuth(ApiAuthDocReader.readMethod(method));
apiOperationDoc.setHeaders(ApiHeaderDocReader.read(method));
apiOperationDoc.setPathParameters(ApiPathParamDocReader.read(method, typeReferenceProvider));
apiOperationDoc.setQueryParameters(ApiQueryParamDocReader.read(method, typeReferenceProvider));
apiOperationDoc.setRequestBody(
ApiRequestBodyTypeDocReader.read(method, typeReferenceProvider, templateProvider));
apiOperationDoc.setResponseBodyType(readResponseBodyType(method, typeReferenceProvider));
apiOperationDoc.setStage(ApiStageReader.read(method, parentApiDoc.getStage()));
ApiOperation methodAnnotation = method.getAnnotation(ApiOperation.class);
if (methodAnnotation != null) {
String overriddenId = nullifyIfEmpty(methodAnnotation.id());
if (overriddenId != null) {
apiOperationDoc.setLivedocId(overriddenId);
}
apiOperationDoc.setPaths(Arrays.asList(methodAnnotation.path()));
apiOperationDoc.setVerbs(Arrays.asList(methodAnnotation.verbs()));
apiOperationDoc.setSummary(nullifyIfEmpty(methodAnnotation.summary()));
apiOperationDoc.setDescription(nullifyIfEmpty(methodAnnotation.description()));
apiOperationDoc.setConsumes(Arrays.asList(methodAnnotation.consumes()));
apiOperationDoc.setProduces(Arrays.asList(methodAnnotation.produces()));
apiOperationDoc.setResponseStatusCode(methodAnnotation.responseStatusCode());
}
return apiOperationDoc;
}
@Nullable
private static LivedocType readResponseBodyType(Method method, TypeReferenceProvider typeReferenceProvider) {
ApiResponseBodyType annotation = method.getAnnotation(ApiResponseBodyType.class);
if (annotation == null) {
return null;
}
Type type = extractResponseBodyType(method, annotation);
return typeReferenceProvider.getReference(type);
}
@NotNull
private static Type extractResponseBodyType(@NotNull Method method, @NotNull ApiResponseBodyType annotation) {
Class<?> type = annotation.value();
if (type.equals(LivedocDefaultType.class)) {
return method.getGenericReturnType();
}
return type;
}
}
|
meet-eat/meet-eat-data | src/test/java/meet_eat/data/entity/relation/rating/RatingValueCommonTest.java | package meet_eat.data.entity.relation.rating;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
public class RatingValueCommonTest {
@Test
public void testGetValueByInteger() {
// Test data
int one = 1;
int two = 2;
int three = 3;
int four = 4;
int five = 5;
// Assertions
assertEquals(RatingValue.POINTS_1, RatingValue.getRatingValueByInteger(one));
assertEquals(RatingValue.POINTS_2, RatingValue.getRatingValueByInteger(two));
assertEquals(RatingValue.POINTS_3, RatingValue.getRatingValueByInteger(three));
assertEquals(RatingValue.POINTS_4, RatingValue.getRatingValueByInteger(four));
assertEquals(RatingValue.POINTS_5, RatingValue.getRatingValueByInteger(five));
}
@Test(expected = NoSuchElementException.class)
public void testGetValueByIntegerOutOfBounds() {
// Test data
int value = 10;
// Execution
RatingValue.getRatingValueByInteger(value);
}
}
|
hakandilek/izlek | app/src/main/java/me/dilek/izlek/ui/activity/TvShowActivity.java | <reponame>hakandilek/izlek<filename>app/src/main/java/me/dilek/izlek/ui/activity/TvShowActivity.java
package me.dilek.izlek.ui.activity;
import android.support.v7.app.ActionBarActivity;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import me.dilek.izlek.R;
import me.dilek.izlek.ui.fragment.TvShowFragment;
/**
* Activity to show a single tv show
* <p/>
* Created by <NAME> on 12.04.15.
*/
@EActivity(R.layout.activity_tv_show)
public class TvShowActivity extends ActionBarActivity {
@FragmentById(R.id.f_tv_show)
TvShowFragment tvShowFragment;
@Extra("extra_tv_show_id")
String tvShowId;
@AfterViews
void initializeFragment() {
TvShowFragment tvShowFragment =
(TvShowFragment) getSupportFragmentManager().findFragmentById(R.id.f_tv_show);
tvShowFragment.showTvShow(tvShowId);
}
}
|
susisu/loquat-token | test/token/makeTokenParser/commaSep.js | <filename>test/token/makeTokenParser/commaSep.js
/*
* loquat-token test / token.makeTokenParser().commaSep()
*/
"use strict";
const chai = require("chai");
const expect = chai.expect;
const show = _core.show;
const uncons = _core.uncons;
const SourcePos = _core.SourcePos;
const ErrorMessageType = _core.ErrorMessageType;
const ErrorMessage = _core.ErrorMessage;
const ParseError = _core.ParseError;
const Config = _core.Config;
const State = _core.State;
const Result = _core.Result;
const Parser = _core.Parser;
const assertParser = _core.assertParser;
const LanguageDef = _language.LanguageDef;
const makeTokenParser = _token.makeTokenParser;
const p = new Parser(state => {
const u = uncons(state.input);
if (u.empty) {
return Result.eerr(
new ParseError(
state.pos,
[new ErrorMessage(ErrorMessageType.MESSAGE, "e")]
)
);
}
switch (u.head) {
case "C": {
const newPos = state.pos.addChar(u.head);
return Result.csuc(
new ParseError(
newPos,
[new ErrorMessage(ErrorMessageType.MESSAGE, "C")]
),
u.head,
new State(
state.config,
u.tail,
newPos,
state.userState
)
);
}
case "c": {
const newPos = state.pos.addChar(u.head);
return Result.cerr(
new ParseError(
newPos,
[new ErrorMessage(ErrorMessageType.MESSAGE, "c")]
)
);
}
case "E":
return Result.esuc(
new ParseError(
state.pos,
[new ErrorMessage(ErrorMessageType.MESSAGE, "E")]
),
u.head,
new State(
state.config,
u.tail,
state.pos,
state.userState
)
);
case "e":
default:
return Result.eerr(
new ParseError(
state.pos,
[new ErrorMessage(ErrorMessageType.MESSAGE, "e")]
)
);
}
});
const arrayEqual = (xs, ys) => xs.length === ys.length && xs.every((x, i) => x === ys[i]);
describe(".commaSep(parser)", () => {
it("should return a parser that parses zero or more tokens separated by commas", () => {
const def = new LanguageDef({});
const tp = makeTokenParser(def);
const commaSep = tp.commaSep;
expect(commaSep).to.be.a("function");
const parser = commaSep(p);
assertParser(parser);
// empty
{
const initState = new State(
new Config({ tabWidth: 8 }),
"X",
new SourcePos("foobar", 1, 1),
"none"
);
const res = parser.run(initState);
expect(Result.equal(
res,
Result.esuc(
new ParseError(
new SourcePos("foobar", 1, 1),
[new ErrorMessage(ErrorMessageType.MESSAGE, "e")]
),
[],
initState
),
arrayEqual
)).to.be.true;
}
// many
{
const initState = new State(
new Config({ tabWidth: 8 }),
"C, C, CX",
new SourcePos("foobar", 1, 1),
"none"
);
const res = parser.run(initState);
expect(Result.equal(
res,
Result.csuc(
new ParseError(
new SourcePos("foobar", 1, 8),
[
new ErrorMessage(ErrorMessageType.SYSTEM_UNEXPECT, show("X")),
new ErrorMessage(ErrorMessageType.EXPECT, show(","))
]
),
["C", "C", "C"],
new State(
new Config({ tabWidth: 8 }),
"X",
new SourcePos("foobar", 1, 8),
"none"
)
),
arrayEqual
)).to.be.true;
}
{
const initState = new State(
new Config({ tabWidth: 8 }),
"C, C, C, X",
new SourcePos("foobar", 1, 1),
"none"
);
const res = parser.run(initState);
expect(Result.equal(
res,
Result.cerr(
new ParseError(
new SourcePos("foobar", 1, 10),
[
new ErrorMessage(ErrorMessageType.SYSTEM_UNEXPECT, show("X")),
new ErrorMessage(ErrorMessageType.EXPECT, ""),
new ErrorMessage(ErrorMessageType.MESSAGE, "e")
]
)
),
arrayEqual
)).to.be.true;
}
});
});
|
hmcts/ccd-case-disposer | src/main/java/uk/gov/hmcts/reform/ccd/parameter/ParameterResolver.java | package uk.gov.hmcts.reform.ccd.parameter;
import java.util.List;
public interface ParameterResolver {
List<String> getElasticsearchHosts();
Integer getElasticsearchRequestTimeout();
String getCasesIndexNamePattern();
String getGlobalSearchIndexName();
boolean isGlobalSearchEnabled();
String getCasesIndexType();
List<String> getDeletableCaseTypes();
List<String> getDeletableCaseTypesSimulation();
List<String> getAllDeletableCaseTypes();
String getCaseDefinitionHost();
String getIdamUsername();
String getIdamPassword();
String getDocumentsDeleteUrl();
}
|
bijeshcnair/wavemaker-app-runtime | src/main/webapp/scripts/modules/variables/application/base/variableService.js | <reponame>bijeshcnair/wavemaker-app-runtime
/*global WM, wm*/
/*jslint todo: true */
/**
* @ngdoc service
* @name wm.variables.$VariableService
* @description
* The `VariableService` provides the details about the variable based service apis
*/
wm.variables.services.VariableService = function (BaseService) {
'use strict';
return {
/**
* @ngdoc function
* @name wm.variables.$VariableService#create
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Takes array of variable objects to be created
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
create: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: params.pageName === 'App' ? 'addAppVariables' : 'addPageVariables',
urlParams: params,
data: params.data
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#get
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* get map of variable objects
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
get: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: params.pageName === 'App' ? 'getAppVariables' : 'getPageVariables',
urlParams: params
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#update
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Takes array of variable objects to be updated
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
update: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: params.pageName === 'App' ? 'updateAppVariables' : 'updatePageVariables',
urlParams: params,
data: params.data
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#move
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Takes array of variable objects to be moved
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
move: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: params.pageName === 'App' ? 'moveAppVariables' : 'movePageVariables',
urlParams: params,
data: params.data
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#delete
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Takes array of variable names to be deleted
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
delete: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: params.pageName === 'App' ? 'deleteAppVariables' : 'deletePageVariables',
urlParams: params
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#getServiceOpInfo
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Get service operation info in run
*
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
getServiceOpInfo: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: 'getServiceOpInfo',
urlParams: params
}, successCallback, failureCallback);
},
/**
* @ngdoc function
* @name wm.variables.$VariableService#getPrefabServiceOpInfo
* @methodOf wm.variables.$VariableService
* @function
*
* @description
* Get service operation info in run
* @param {object} params object containing parameters for the request (else throws an error message)
* @param {function} successCallback to be called on success
* @param {function} failureCallback to be called on failure
*/
getPrefabServiceOpInfo: function (params, successCallback, failureCallback) {
BaseService.send({
target: 'VariableService',
action: 'getPrefabServiceOpInfo',
urlParams: params
}, successCallback, failureCallback);
}
};
}; |
ideacrew/ledger_redux | db/migrate/20200701155381_remove_last_request_at_from_users.fat_free_crm.rb | <filename>db/migrate/20200701155381_remove_last_request_at_from_users.fat_free_crm.rb
# frozen_string_literal: true
# This migration comes from fat_free_crm (originally 20200502231473)
# This migration comes from fat_free_crm (originally 20150227123054)
class RemoveLastRequestAtFromUsers < ActiveRecord::Migration[4.2]
def change
remove_column :fat_free_crm_users, :last_request_at
end
end
|
EricLi404/tensorflow | tensorflow/lite/tools/list_flex_ops.cc | <reponame>EricLi404/tensorflow
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/list_flex_ops.h"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "flatbuffers/flexbuffers.h" // from @flatbuffers
#include "json/json.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/device_name_utils.h"
#include "tensorflow/lite/util.h"
namespace tflite {
namespace flex {
std::string OpListToJSONString(const OpKernelSet& flex_ops) {
Json::Value result(Json::arrayValue);
for (const OpKernel& op : flex_ops) {
Json::Value op_kernel(Json::arrayValue);
op_kernel.append(Json::Value(op.op_name));
op_kernel.append(Json::Value(op.kernel_name));
result.append(op_kernel);
}
return Json::FastWriter().write(result);
}
// Find the class name of the op kernel described in the node_def from the pool
// of registered ops. If no kernel class is found, return an empty string.
string FindTensorflowKernelClass(tensorflow::NodeDef* node_def) {
if (!node_def || node_def->op().empty()) {
LOG(FATAL) << "Invalid NodeDef";
}
const tensorflow::OpRegistrationData* op_reg_data;
auto status =
tensorflow::OpRegistry::Global()->LookUp(node_def->op(), &op_reg_data);
if (!status.ok()) {
LOG(FATAL) << "Op " << node_def->op() << " not found: " << status;
}
AddDefaultsToNodeDef(op_reg_data->op_def, node_def);
tensorflow::DeviceNameUtils::ParsedName parsed_name;
if (!tensorflow::DeviceNameUtils::ParseFullName(node_def->device(),
&parsed_name)) {
LOG(FATAL) << "Failed to parse device from node_def: "
<< node_def->ShortDebugString();
}
string class_name;
if (!tensorflow::FindKernelDef(
tensorflow::DeviceType(parsed_name.type.c_str()), *node_def,
nullptr /* kernel_def */, &class_name)
.ok()) {
LOG(FATAL) << "Failed to find kernel class for op: " << node_def->op();
}
return class_name;
}
void AddFlexOpsFromModel(const tflite::Model* model, OpKernelSet* flex_ops) {
// Read flex ops.
auto* subgraphs = model->subgraphs();
if (!subgraphs) return;
for (int subgraph_index = 0; subgraph_index < subgraphs->size();
++subgraph_index) {
const tflite::SubGraph* subgraph = subgraphs->Get(subgraph_index);
auto* operators = subgraph->operators();
auto* opcodes = model->operator_codes();
if (!operators || !opcodes) continue;
for (int i = 0; i < operators->size(); ++i) {
const tflite::Operator* op = operators->Get(i);
const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
if (opcode->builtin_code() != tflite::BuiltinOperator_CUSTOM ||
!tflite::IsFlexOp(opcode->custom_code()->c_str())) {
continue;
}
// Remove the "Flex" prefix from op name.
std::string flex_op_name(opcode->custom_code()->c_str());
std::string tf_op_name =
flex_op_name.substr(strlen(tflite::kFlexCustomCodePrefix));
// Read NodeDef and find the op kernel class.
if (op->custom_options_format() !=
tflite::CustomOptionsFormat_FLEXBUFFERS) {
LOG(FATAL) << "Invalid CustomOptionsFormat";
}
const flatbuffers::Vector<uint8_t>* custom_opt_bytes =
op->custom_options();
if (custom_opt_bytes && custom_opt_bytes->size()) {
// NOLINTNEXTLINE: It is common to use references with flatbuffer.
const flexbuffers::Vector& v =
flexbuffers::GetRoot(custom_opt_bytes->data(),
custom_opt_bytes->size())
.AsVector();
std::string nodedef_str = v[1].AsString().str();
tensorflow::NodeDef nodedef;
if (nodedef_str.empty() || !nodedef.ParseFromString(nodedef_str)) {
LOG(FATAL) << "Failed to parse data into a valid NodeDef";
}
// Flex delegate only supports running flex ops with CPU.
*nodedef.mutable_device() = "/CPU:0";
std::string kernel_class = FindTensorflowKernelClass(&nodedef);
flex_ops->insert({tf_op_name, kernel_class});
}
}
}
}
} // namespace flex
} // namespace tflite
|
ahmadhusseinrezae/not_quite_java | src-generated/notquitejava/ast/NQJUnaryOperator.java | //generated by abstract-syntax-gen
package notquitejava.ast;
import java.util.*;
public interface NQJUnaryOperator extends NQJElement{
NQJElement getParent();
<T> T match(Matcher<T> s);
void match(MatcherVoid s);
public interface Matcher<T> {
T case_Negate(NQJNegate negate);
T case_UnaryMinus(NQJUnaryMinus unaryMinus);
}
public interface MatcherVoid {
void case_Negate(NQJNegate negate);
void case_UnaryMinus(NQJUnaryMinus unaryMinus);
}
NQJUnaryOperator copy();
NQJUnaryOperator copyWithRefs();
/** "information about the source code"*/
public abstract frontend.SourcePosition getSourcePosition();
/** "information about the source code"*/
public abstract void setSourcePosition(frontend.SourcePosition sourcePosition);
}
|
Guoanshisb/smack | test/c/ntdrivers-simplified/kbfiltr_simpl1_true.cil.c | <gh_stars>0
#include "smack.h"
// @expect verified
extern char __VERIFIER_nondet_char(void);
extern int __VERIFIER_nondet_int(void);
extern long __VERIFIER_nondet_long(void);
extern void *__VERIFIER_nondet_pointer(void);
extern int __VERIFIER_nondet_int();
/* Generated by CIL v. 1.3.6 */
/* print_CIL_Input is true */
int KernelMode;
int Executive;
int s;
int UNLOADED;
int NP;
int DC;
int SKIP1;
int SKIP2;
int MPR1;
int MPR3;
int IPC;
int pended;
int compFptr;
int compRegistered;
int lowerDriverReturn;
int setEventCalled;
int customIrp;
int myStatus;
void stub_driver_init(void) {
{
#line 46
s = NP;
#line 47
pended = 0;
#line 48
compFptr = 0;
#line 49
compRegistered = 0;
#line 50
lowerDriverReturn = 0;
#line 51
setEventCalled = 0;
#line 52
customIrp = 0;
#line 53
return;
}
}
#line 56 "kbfiltr_simpl1.cil.c"
void _BLAST_init(void) {
{
#line 60
UNLOADED = 0;
#line 61
NP = 1;
#line 62
DC = 2;
#line 63
SKIP1 = 3;
#line 64
SKIP2 = 4;
#line 65
MPR1 = 5;
#line 66
MPR3 = 6;
#line 67
IPC = 7;
#line 68
s = UNLOADED;
#line 69
pended = 0;
#line 70
compFptr = 0;
#line 71
compRegistered = 0;
#line 72
lowerDriverReturn = 0;
#line 73
setEventCalled = 0;
#line 74
customIrp = 0;
#line 75
return;
}
}
#line 78 "kbfiltr_simpl1.cil.c"
void IofCompleteRequest(int, int);
void errorFn(void);
int KbFilter_PnP(int DeviceObject, int Irp) {
int devExt;
int irpStack;
int status;
int event = __VERIFIER_nondet_int();
int DeviceObject__DeviceExtension = __VERIFIER_nondet_int();
int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int();
int irpStack__MinorFunction = __VERIFIER_nondet_int();
int devExt__TopOfStack = __VERIFIER_nondet_int();
int devExt__Started;
int devExt__Removed;
int devExt__SurpriseRemoved;
int Irp__IoStatus__Status;
int Irp__IoStatus__Information;
int Irp__CurrentLocation = __VERIFIER_nondet_int();
int irpSp;
int nextIrpSp;
int nextIrpSp__Control;
int irpSp___0;
int irpSp__Context;
int irpSp__Control;
long __cil_tmp23;
{
#line 101
status = 0;
#line 102
devExt = DeviceObject__DeviceExtension;
#line 103
irpStack = Irp__Tail__Overlay__CurrentStackLocation;
#line 104
if (irpStack__MinorFunction == 0) {
goto switch_0_0;
} else {
#line 107
if (irpStack__MinorFunction == 23) {
goto switch_0_23;
} else {
#line 110
if (irpStack__MinorFunction == 2) {
goto switch_0_2;
} else {
#line 113
if (irpStack__MinorFunction == 1) {
goto switch_0_1;
} else {
#line 116
if (irpStack__MinorFunction == 5) {
goto switch_0_1;
} else {
#line 119
if (irpStack__MinorFunction == 3) {
goto switch_0_1;
} else {
#line 122
if (irpStack__MinorFunction == 6) {
goto switch_0_1;
} else {
#line 125
if (irpStack__MinorFunction == 13) {
goto switch_0_1;
} else {
#line 128
if (irpStack__MinorFunction == 4) {
goto switch_0_1;
} else {
#line 131
if (irpStack__MinorFunction == 7) {
goto switch_0_1;
} else {
#line 134
if (irpStack__MinorFunction == 8) {
goto switch_0_1;
} else {
#line 137
if (irpStack__MinorFunction == 9) {
goto switch_0_1;
} else {
#line 140
if (irpStack__MinorFunction == 12) {
goto switch_0_1;
} else {
#line 143
if (irpStack__MinorFunction == 10) {
goto switch_0_1;
} else {
#line 146
if (irpStack__MinorFunction == 11) {
goto switch_0_1;
} else {
#line 149
if (irpStack__MinorFunction == 15) {
goto switch_0_1;
} else {
#line 152
if (irpStack__MinorFunction == 16) {
goto switch_0_1;
} else {
#line 155
if (irpStack__MinorFunction == 17) {
goto switch_0_1;
} else {
#line 158
if (irpStack__MinorFunction == 18) {
goto switch_0_1;
} else {
#line 161
if (irpStack__MinorFunction == 19) {
goto switch_0_1;
} else {
#line 164
if (irpStack__MinorFunction == 20) {
goto switch_0_1;
} else {
goto switch_0_1;
#line 169
if (0) {
switch_0_0:
#line 171
irpSp =
Irp__Tail__Overlay__CurrentStackLocation;
#line 172
nextIrpSp =
Irp__Tail__Overlay__CurrentStackLocation -
1;
#line 173
nextIrpSp__Control = 0;
#line 174
if (s != NP) {
{
#line 176
errorFn();
}
} else {
#line 179
if (compRegistered != 0) {
{
#line 181
errorFn();
}
} else {
#line 184
compRegistered = 1;
}
}
{
#line 188
irpSp___0 =
Irp__Tail__Overlay__CurrentStackLocation -
1;
#line 189
irpSp__Control = 224;
#line 192
status = IofCallDriver(
devExt__TopOfStack, Irp);
}
{
#line 197
__cil_tmp23 = (long)status;
#line 197
if (__cil_tmp23 == 259) {
{
#line 199
KeWaitForSingleObject(
event, Executive,
KernelMode, 0, 0);
}
}
}
#line 206
if (status >= 0) {
#line 207
if (myStatus >= 0) {
#line 208
devExt__Started = 1;
#line 209
devExt__Removed = 0;
#line 210
devExt__SurpriseRemoved = 0;
}
}
{
#line 218
Irp__IoStatus__Status =
status;
#line 219
myStatus = status;
#line 220
Irp__IoStatus__Information =
0;
#line 221
IofCompleteRequest(Irp, 0);
}
goto switch_0_break;
switch_0_23:
#line 225
devExt__SurpriseRemoved = 1;
#line 226
if (s == NP) {
#line 227
s = SKIP1;
} else {
{
#line 230
errorFn();
}
}
{
#line 234
Irp__CurrentLocation++;
#line 235
Irp__Tail__Overlay__CurrentStackLocation++;
#line 236
status = IofCallDriver(
devExt__TopOfStack, Irp);
}
goto switch_0_break;
switch_0_2:
#line 241
devExt__Removed = 1;
#line 242
if (s == NP) {
#line 243
s = SKIP1;
} else {
{
#line 246
errorFn();
}
}
{
#line 250
Irp__CurrentLocation++;
#line 251
Irp__Tail__Overlay__CurrentStackLocation++;
#line 252
IofCallDriver(
devExt__TopOfStack, Irp);
#line 253
status = 0;
}
goto switch_0_break;
switch_0_1:;
#line 275
if (s == NP) {
#line 276
s = SKIP1;
} else {
{
#line 279
errorFn();
}
}
{
#line 283
Irp__CurrentLocation++;
#line 284
Irp__Tail__Overlay__CurrentStackLocation++;
#line 285
status = IofCallDriver(
devExt__TopOfStack, Irp);
}
goto switch_0_break;
} else {
switch_0_break:;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
#line 314
return (status);
}
}
#line 317 "kbfiltr_simpl1.cil.c"
int main(void) {
int status;
int irp = __VERIFIER_nondet_int();
int pirp;
int pirp__IoStatus__Status;
int irp_choice = __VERIFIER_nondet_int();
int devobj = __VERIFIER_nondet_int();
int __cil_tmp8;
{
{
;
KernelMode = 0;
Executive = 0;
s = 0;
UNLOADED = 0;
NP = 0;
DC = 0;
SKIP1 = 0;
SKIP2 = 0;
MPR1 = 0;
MPR3 = 0;
IPC = 0;
pended = 0;
compFptr = 0;
compRegistered = 0;
lowerDriverReturn = 0;
setEventCalled = 0;
customIrp = 0;
myStatus = 0;
#line 328
status = 0;
#line 329
pirp = irp;
#line 330
_BLAST_init();
}
#line 332
if (status >= 0) {
#line 333
s = NP;
#line 334
customIrp = 0;
#line 335
setEventCalled = customIrp;
#line 336
lowerDriverReturn = setEventCalled;
#line 337
compRegistered = lowerDriverReturn;
#line 338
pended = compRegistered;
#line 339
pirp__IoStatus__Status = 0;
#line 340
myStatus = 0;
#line 341
if (irp_choice == 0) {
#line 342
pirp__IoStatus__Status = -1073741637;
#line 343
myStatus = -1073741637;
}
{
#line 348
stub_driver_init();
}
{
#line 350
if (status >= 0) {
__cil_tmp8 = 1;
} else {
__cil_tmp8 = 0;
}
#line 350
if (!__cil_tmp8) {
#line 351
return (-1);
}
}
#line 355
int tmp_ndt_1;
tmp_ndt_1 = __VERIFIER_nondet_int();
if (tmp_ndt_1 == 3) {
goto switch_1_3;
} else {
goto switch_1_default;
#line 360
if (0) {
switch_1_3 : {
#line 363
status = KbFilter_PnP(devobj, pirp);
}
goto switch_1_break;
switch_1_default:;
#line 367
return (-1);
} else {
switch_1_break:;
}
}
}
#line 376
if (pended == 1) {
#line 377
if (s == NP) {
#line 378
s = NP;
} else {
goto _L___2;
}
} else {
_L___2:
#line 384
if (pended == 1) {
#line 385
if (s == MPR3) {
#line 386
s = MPR3;
} else {
goto _L___1;
}
} else {
_L___1:
#line 392
if (s != UNLOADED) {
#line 395
if (status != -1) {
#line 398
if (s != SKIP2) {
#line 399
if (s != IPC) {
#line 400
if (s == DC) {
goto _L___0;
}
} else {
goto _L___0;
}
} else {
_L___0:
#line 410
if (pended == 1) {
#line 411
if (status != 259) {
{
#line 413
errorFn();
}
}
} else {
#line 419
if (s == DC) {
#line 420
if (status == 259) {
}
} else {
#line 426
if (status != lowerDriverReturn) {
}
}
}
}
}
}
}
}
return (status);
}
}
#line 441 "kbfiltr_simpl1.cil.c"
void stubMoreProcessingRequired(void) {
{
#line 445
if (s == NP) {
#line 446
s = MPR1;
} else {
{
#line 449
errorFn();
}
}
#line 452
return;
}
}
#line 455 "kbfiltr_simpl1.cil.c"
int IofCallDriver(int DeviceObject, int Irp) {
int returnVal2;
int compRetStatus;
int lcontext = __VERIFIER_nondet_int();
long long __cil_tmp7;
;
{
#line 462
if (compRegistered) {
compRetStatus = KbFilter_Complete(DeviceObject, Irp, lcontext);
stubMoreProcessingRequired();
}
#line 476
int tmp_ndt_2;
tmp_ndt_2 = __VERIFIER_nondet_int();
if (tmp_ndt_2 == 0) {
goto switch_2_0;
} else {
#line 479
int tmp_ndt_3;
tmp_ndt_3 = __VERIFIER_nondet_int();
if (tmp_ndt_3 == 1) {
goto switch_2_1;
} else {
goto switch_2_default;
#line 484
if (0) {
switch_2_0:
#line 486
returnVal2 = 0;
goto switch_2_break;
switch_2_1:
#line 489
returnVal2 = -1073741823;
goto switch_2_break;
switch_2_default:
#line 492
returnVal2 = 259;
goto switch_2_break;
} else {
switch_2_break:;
}
}
}
#line 500
if (s == NP) {
#line 501
s = IPC;
#line 502
lowerDriverReturn = returnVal2;
} else {
#line 504
if (s == MPR1) {
#line 505
if (returnVal2 == 259) {
#line 506
s = MPR3;
#line 507
lowerDriverReturn = returnVal2;
} else {
#line 509
s = NP;
#line 510
lowerDriverReturn = returnVal2;
}
} else {
#line 513
if (s == SKIP1) {
#line 514
s = SKIP2;
#line 515
lowerDriverReturn = returnVal2;
} else {
{
#line 518
errorFn();
}
}
}
}
#line 523
return (returnVal2);
}
}
#line 526 "kbfiltr_simpl1.cil.c"
void IofCompleteRequest(int Irp, int PriorityBoost) {
{
#line 530
if (s == NP) {
#line 531
s = DC;
} else {
{
#line 534
errorFn();
}
}
#line 537
return;
}
}
#line 540 "kbfiltr_simpl1.cil.c"
int KeSetEvent(int Event, int Increment, int Wait) {
int l = __VERIFIER_nondet_int();
{
#line 544
setEventCalled = 1;
#line 545
return (l);
}
}
#line 548 "kbfiltr_simpl1.cil.c"
int KeWaitForSingleObject(int Object, int WaitReason, int WaitMode,
int Alertable, int Timeout) {
;
{
#line 553
if (s == MPR3) {
#line 554
if (setEventCalled == 1) {
#line 555
s = NP;
#line 556
setEventCalled = 0;
} else {
goto _L;
}
} else {
_L:
#line 562
if (customIrp == 1) {
#line 563
s = NP;
#line 564
customIrp = 0;
} else {
#line 566
if (s == MPR3) {
{
#line 568
errorFn();
}
}
}
}
#line 575
int tmp_ndt_4;
tmp_ndt_4 = __VERIFIER_nondet_int();
if (tmp_ndt_4 == 0) {
goto switch_3_0;
} else {
goto switch_3_default;
#line 580
if (0) {
switch_3_0:
#line 582
return (0);
switch_3_default:;
#line 584
return (-1073741823);
} else {
}
}
}
}
#line 592 "kbfiltr_simpl1.cil.c"
int KbFilter_Complete(int DeviceObject, int Irp, int Context) {
int event;
{
{
#line 597
event = Context;
#line 598
KeSetEvent(event, 0, 0);
}
#line 600
return (-1073741802);
}
}
void errorFn(void) {
{
goto ERROR;
ERROR:
assert(0);
#line 23
return;
}
}
|
ShangBaiShuYao/flink-learning-from-zhisheng | flink-learning-from-zhisheng-connectors/flink-learning-connectors-akka/src/main/java/com/shangbaishuyao/connectors/akka/utils/ReceiverActor.java | package com.shangbaishuyao.connectors.akka.utils;
import akka.actor.ActorSelection;
import akka.actor.UntypedActor;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
/**
* Desc:
*
* 源码: https://github.com/apache/bahir-flink/blob/master/flink-connector-akka/src/main/java/org/apache/flink/streaming/connectors/akka/utils/ReceiverActor.java#L57
*
* create by shangbaishuyao 2021-01-19
* @Author: 上白书妖
* @Date: 13:43 2021/1/19
*/
//继承scala类,重写方法
public class ReceiverActor extends UntypedActor {
// --- Fields set by the constructor(由构造函数设置的字段)
private final SourceFunction.SourceContext<Object> ctx;
private final String urlOfPublisher;
private final boolean autoAck;
// --- Runtime fields(运行时字段)
private ActorSelection remotePublisher;
//构造方法
public ReceiverActor(SourceFunction.SourceContext<Object> ctx,
String urlOfPublisher,
boolean autoAck) {
this.ctx = ctx;
this.urlOfPublisher = urlOfPublisher;
this.autoAck = autoAck;
}
@Override
public void preStart() throws Exception {
super.preStart();
remotePublisher = getContext().actorSelection(urlOfPublisher);
remotePublisher.tell(new SubscribeReceiver(getSelf()), getSelf());
}
@Override
public void onReceive(Object message) throws Exception {
}
}
|
johndonggyu/EverytimeProject | modules/chartMakingOnlyOneChart.py | <filename>modules/chartMakingOnlyOneChart.py
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "home.settings")
import django
import sys
sys.path.append('..')
django.setup()
from Web.models import lecture_evaluation, Eval, smu_professor, lecture_time, professor_keyword
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib
from matplotlib import cm
from matplotlib import font_manager, rc
from matplotlib import style
from matplotlib import rcParams
import pandas as pd
from matplotlib.patches import Circle, Wedge, Rectangle
#추가로 불러온 부분 2019-07-24
import re
from konlpy.tag import Kkma
import time
from operator import eq
import itertools
from collections import Counter
from PIL import Image
#===========================================#
# global variables #
#===========================================#
dir_static = '../Web/static/chart/'
#===========================================#
sns.set(style="whitegrid", context="talk")
rs = np.random.RandomState(8)
font_name = font_manager.FontProperties(fname="./raw_data/fonts/malgun.ttf").get_name()
rc('font', family=font_name)
style.use('ggplot')
def get_tokens(match_, match2_):
#교수님별로
match_lect = lecture_time.objects.filter(professor__professor=match_,professor__major=match2_)
#교수님과 교수님 전공에 해당하는 시간표 객체에 들어있는 데이터 불러오기
match_eval = lecture_evaluation.objects.filter(professor__professor__professor=match_)
#교수님의 이름과 매치하는 강의 평가 데이터 가져오기
lect = []
for a in match_lect:
lect.append(a.lecture)
#lect에다가 교수님 시간표로부터 강의명만 가져오기
c = []
#print("---------------------")
print(match_)
for item in match_eval:
if(item.professor.lecture in lect):
#강의평가 데이터에 있는 강의명이 시간표로부터 가져온 강의명과 일치하다면?
c.append(item)
#이렇게 하면 일치하고 있는 강의명을 가진 강의 평가 데이터가 c라는 튜플에 추가 될것이다
#print(item.professor.lecture)
#실제로 해당 강의 평가 데이터들의 강의명이 들어가있는지 한번 확인해보자.
#print("---------------------")
return c
#########################################################
#######################실제 파일 실행 부분 ###############
#smu_professor 에서 이름, 학과 꺼내오기.
#for yo in smu_professor.objects.all():
each_Professor_classess = list()
objective_list = list()
for yo in smu_professor.objects.filter(major='컴퓨터과학과'):
each_Professor_classess = get_tokens(yo.professor, yo.major)
objective_list.append(each_Professor_classess)
#print(objective_list[0])
#[<lecture_evaluation: 강상욱 - 선형대수학>, <lecture_evaluation: 강상욱 - 보안프로그래밍>, <lecture_evaluation: 강상욱 - 캡스톤디자인I>, <lecture_evaluation: 강상욱 - 디지털신호처리>, <lecture_evaluation: 강상욱 - 정보보호>, <lecture_evaluation: 강상욱 - 선형대수학>, <lecture_evaluation: 강상욱 - 보안프로그래밍>, <lecture_evaluation: 강상욱 - 캡스톤디자인I>, <lecture_evaluation: 강상욱 - 디지털신호처리>, <lecture_evaluation: 강상욱 - 정보보호>]
#print(objective_list[0][0]) # 강상욱 - 선형대수학
#print(objective_list[0][0].professor.professor.professor) # 강상욱
#print(objective_list[0][0].professor.lecture) # 선형대수학
#print(len(objective_list[0])) # 10
# ---------------------
# 조용주 <---- each_Professor_classess.professor.professor.professor
# 프로그래밍언어론 <-------
# 캡스톤디자인I
# 캡스톤디자인II
# 프로그래밍2
# C프로그래밍1
# 파이썬프로그래밍
# 프로그래밍언어론
# 캡스톤디자인I
# 캡스톤디자인II
# 프로그래밍2
# C프로그래밍1
# 파이썬프로그래밍
# ---------------------
#------------------------------------------------------------------------------
def get_tokens_for_charts(each_Professor): #추후 구현 type_ =3, match_ = 한종배 교수님
tokens = list() #토큰을 리스트 형태로 생성
#카운트 올릴 변수들 초기화
assignmentMany = 0
assignmentNorm = 0
assignmentNone = 0
#함수 중요 변수 및 메서드
everytime_data = each_Professor #강의평에 들어있는 1|소프트웨어공학|한종대|3.5|보통|보통|비율 채워줌|직접호명|두 번등을 객체화 시킴
print()
#교수님 평균 별점 계산하는 함수
if len(everytime_data) <= 0:
print('db가 비었습니다 : from get_tokens()')
return 0
#교수님 과제분량 어떤지 확인하는 함수
for datum in everytime_data: #객체화 시킨 데이터들을 한줄씩 불러 읽음
strAssignment = datum.assignment #교수님 과제분량 많음?
if strAssignment == '많음':
assignmentMany+=1
elif strAssignment == '보통':
assignmentNorm+=1
elif strAssignment == '없음':
assignmentNone+=1
print(everytime_data[0].professor.professor.professor+"교수님 과제 분량")
print ("많음 : %d" % (assignmentMany))
print ("보통 : %d" % (assignmentNorm))
print ("없음 : %d" % (assignmentNone))
print()
tokens.append(assignmentMany)
tokens.append(assignmentNorm)
tokens.append(assignmentNone)
return tokens
#1차원 배열로 token안에 변수들값이 저장이 됨
#2. 과제 비율 계산 변수 assignmentMany assignmentNorm assignmentNone , index [0-2] 차트 완료
def draw_barPlot_professor_Assignment(each_Professor):
alist = get_tokens_for_charts(each_Professor)
if type(alist) == type(int):
if alist <= 0:
print('db가 비었습니다 : draw_barPlot_professor_Assignment()')
return 0
list_assignment= [int(i) for i in alist]
ds_assignment=[
{'설문조사':1, '과제':'많음', '학생 응답 수':list_assignment[0]},
{'설문조사':2, '과제':'보통', '학생 응답 수':list_assignment[1]},
{'설문조사':3, '과제':'없음', '학생 응답 수':list_assignment[2]}
]
df_assignment = pd.DataFrame(ds_assignment)
sns.barplot(x="과제", y="학생 응답 수",palette="Set2", data=df_assignment, linewidth=2.5, edgecolor=".2");
plt.title(each_Professor[0].professor.professor.professor+' 과제 분량') #차트에 제목 붙이기
outputfile_name = dir_static+each_Professor[0].professor.professor.professor+" assignment.png"
plt.savefig(outputfile_name)
#차트 이미지로 저장하기
plt.show()
#-----------------------------------------------------------------------------------
#실제 코드 제작 하는 코드 부분.
for i in range(0, len(objective_list)):
draw_barPlot_professor_Assignment(objective_list[i])
|
declanvk/Chess | src/core/Move.java | <filename>src/core/Move.java
package core;
/**
* Represents a move in chess
*
* @author declan
*
*/
public class Move {
/**
* Represents a type of move in chess
*
* @author declan
*
*/
public static enum Flags {
/**
* A move that doesn't capture
*/
QUIET,
/**
* A move that captures another piece
*/
CAPTURE,
/**
* A move that castles
*/
CASTLE,
/**
* A pawn promotion
*/
PROMOTION,
/**
* An en passant move
*/
EN_PASSANT,
/**
* A double pawn move
*/
DOUBLE_PAWN_PUSH;
/**
* Returns the serialized form of the Flag
*
* @return the serialized form of the Flag
*/
public int value() {
return this.ordinal();
}
/**
* Returns true if the given value is a valid serialized Flag
*
* @param flag
* the flag value to check the validity of
* @return true if the given value is a valid serialized Flag
*/
public static boolean isValid(int flag) {
return QUIET.value() <= flag && flag <= DOUBLE_PAWN_PUSH.value();
}
/**
* Return the Flag associated with the value
*
* @param flag
* the flag value to construct a Flags from
* @return the Flag associated with the value
*/
public static Flags from(int flag) {
if (!isValid(flag)) {
throw new IllegalArgumentException("Flag value is not valid");
}
return Flags.values()[flag];
}
/**
* The number of bits required to fully represent a Flag
*/
public static final int BIT_WIDTH = 3;
}
private final int startPosition, endPosition;
private final int flags;
private final int startPiece, endPiece;
private final int promotionPieceType;
/**
* Constructs a Move from the given values
*
* @param startPiece
* the starting piece of the move
* @param endPiece
* the ending piece of the move
* @param startPos
* the starting position of the move
* @param endPos
* the ending position of the move
* @param flag
* the flags for the move
* @param promotion
* the promotion piece type of the move, if relevant
*/
public Move(int startPiece, int endPiece, int startPos, int endPos, int flag, int promotion) {
if (!Position.isValid(startPos)) {
throw new IllegalArgumentException("Start position value is not valid");
} else if (!Position.isValid(endPos)) {
throw new IllegalArgumentException("End position value is not valid");
} else if (!Flags.isValid(flag)) {
throw new IllegalArgumentException("Flag value is not valid");
} else if (!ChessPiece.isValid(startPiece)) {
throw new IllegalArgumentException("Start piece value is not valid");
} else if (!(ChessPiece.isValid(endPiece) || endPiece == ChessPiece.NULL_PIECE)) {
throw new IllegalArgumentException(
"End piece value is not valid or not equal to the null piece value");
} else if (!(PieceType.isValidPromotion(promotion)
|| promotion == PieceType.NULL_PROMOTION)) {
throw new IllegalArgumentException(
"Piece type value is not a valid promotion or not equal to the null promotion value");
}
this.startPiece = startPiece;
this.endPiece = endPiece;
this.startPosition = startPos;
this.endPosition = endPos;
this.flags = flag;
this.promotionPieceType = promotion;
}
/**
* Returns the starting position of the move
*
* @return the starting position of the move
*/
public int getStartPosition() {
return startPosition;
}
/**
* Returns the ending position of the move
*
* @return the ending position of the move
*/
public int getEndPosition() {
return endPosition;
}
/**
* Returns the flags associated with the move
*
* @return the flags associated with the move
*/
public int getFlags() {
return flags;
}
/**
* Returns the serialized ChessPiece that the move originates from
*
* @return the serialized ChessPiece that the move originates from
*/
public int getStartPiece() {
return startPiece;
}
/**
* Returns the serialized ChessPiece that the move ends with
*
* @return the serialized ChessPiece that the move ends with
*/
public int getEndPiece() {
return endPiece;
}
/**
* Returns the serialized PieceType of the promotion, if the move has the
* PROMOTION flag
*
* @return the serialized PieceType of the promotion
*/
public int getPromotionPieceType() {
return promotionPieceType;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format(
"Move[startPos=%s, endPos=%s, startPiece=%s, endPiece=%s, flag=%s, promotion=%s]",
Position.toString(startPosition), Position.toString(endPosition),
ChessPiece.from(startPiece),
(endPiece != ChessPiece.NULL_PIECE) ? ChessPiece.from(endPiece) : "NULL",
Move.Flags.from(flags), (promotionPieceType != PieceType.NULL_PROMOTION)
? PieceType.from(promotionPieceType) : "NULL");
}
private static final int FLAG_SHIFT = 0;
private static final int FLAG_MASK = calculateMask(FLAG_SHIFT, Flags.BIT_WIDTH);
private static final int START_POSITION_SHIFT = FLAG_SHIFT + Flags.BIT_WIDTH;
private static final int START_POSITION_MASK =
calculateMask(START_POSITION_SHIFT, Position.BIT_WIDTH);
private static final int END_POSITION_SHIFT = START_POSITION_SHIFT + (Position.BIT_WIDTH);
private static final int END_POSITION_MASK =
calculateMask(END_POSITION_SHIFT, Position.BIT_WIDTH);
private static final int START_PIECE_SHIFT = END_POSITION_SHIFT + (Position.BIT_WIDTH);
private static final int START_PIECE_MASK =
calculateMask(START_PIECE_SHIFT, ChessPiece.BIT_WIDTH);
private static final int END_PIECE_SHIFT = START_PIECE_SHIFT + (ChessPiece.BIT_WIDTH);
private static final int END_PIECE_MASK = calculateMask(END_PIECE_SHIFT, ChessPiece.BIT_WIDTH);
private static final int PROMOTION_PIECE_SHIFT = END_PIECE_SHIFT + (ChessPiece.BIT_WIDTH);
private static final int PROMOTION_PIECE_MASK =
calculateMask(PROMOTION_PIECE_SHIFT, ChessPiece.BIT_WIDTH);
private static int calculateMask(int firstBit, int width) {
return (Integer.MIN_VALUE >> (width - 1)) >>> (32 - (width + firstBit));
}
/**
* Returns the serialized form of the Move
*
* @return the serialized form of the Move
*/
public int value() {
return (flags << FLAG_SHIFT) | (startPosition << START_POSITION_SHIFT)
| (endPosition << END_POSITION_SHIFT) | (startPiece << START_PIECE_SHIFT)
| (endPiece << END_PIECE_SHIFT) | (promotionPieceType << PROMOTION_PIECE_SHIFT);
}
/**
* Returns the serialized form of the Move, given the necessary values
*
* @param startPiece
* the starting piece value
* @param endPiece
* the ending piece value
* @param startPosition
* the starting position value
* @param endPosition
* the ending position value
* @param flags
* the value of any flags that apply to the move
* @param promotionPieceType
* the type value of the promotion
* @return the serialized form of the Move, given the necessary valuess
*/
public static int value(int startPiece, int endPiece, int startPosition, int endPosition,
int flags, int promotionPieceType) {
return (flags << FLAG_SHIFT) | (startPosition << START_POSITION_SHIFT)
| (endPosition << END_POSITION_SHIFT) | (startPiece << START_PIECE_SHIFT)
| (endPiece << END_PIECE_SHIFT) | (promotionPieceType << PROMOTION_PIECE_SHIFT);
}
/**
* Returns true if the given value is a valid serialized move
*
* @param move
* the move value to check the validity of
* @return true if the given value is a valid serialized move
*/
public static boolean isValid(int move) {
int flag = (move & FLAG_MASK) >>> FLAG_SHIFT;
int startPos = (move & START_POSITION_MASK) >>> START_POSITION_SHIFT;
int endPos = (move & END_POSITION_MASK) >>> END_POSITION_SHIFT;
int startPiece = (move & START_PIECE_MASK) >>> START_PIECE_SHIFT;
int endPiece = (move & END_PIECE_MASK) >>> END_PIECE_SHIFT;
int promotion = (move & PROMOTION_PIECE_MASK) >>> PROMOTION_PIECE_SHIFT;
return Flags.isValid(flag) && Position.isValid(startPos) && Position.isValid(endPos)
&& ChessPiece.isValid(startPiece)
&& (ChessPiece.isValid(endPiece) || endPiece == ChessPiece.NULL_PIECE)
&& PieceType.isValidPromotion(promotion);
}
public static final int NULL_MOVE = -1;
/**
* Returns a Move constructed from the given serialized value
*
* @param move
* the move value to construct a Move from
* @return a Move constructed from the given serialized value
*/
public static Move from(int move) {
int flag = (move & FLAG_MASK) >>> FLAG_SHIFT;
int startPos = (move & START_POSITION_MASK) >>> START_POSITION_SHIFT;
int endPos = (move & END_POSITION_MASK) >>> END_POSITION_SHIFT;
int startPiece = (move & START_PIECE_MASK) >>> START_PIECE_SHIFT;
int endPiece = (move & END_PIECE_MASK) >>> END_PIECE_SHIFT;
int promotion = (move & PROMOTION_PIECE_MASK) >>> PROMOTION_PIECE_SHIFT;
return (move != NULL_MOVE)
? new Move(startPiece, endPiece, startPos, endPos, flag, promotion) : null;
}
/**
* Returns the value of the start position from the given serialized move
*
* @param move
* the move value to get the starting position of
* @return the value of the start position from the given serialized move
*/
public static int getStartPosition(int move) {
return (move & START_POSITION_MASK) >>> START_POSITION_SHIFT;
}
/**
* Returns the value of the end position from the given serialized move
*
* @param move
* the move value to get the ending position of
* @return the value of the end position from the given serialized move
*/
public static int getEndPosition(int move) {
return (move & END_POSITION_MASK) >>> END_POSITION_SHIFT;
}
/**
* Returns the value of the flags from the given serialized move
*
* @param move
* the move value to get the flags of
* @return the value of the flags from the given serialized move
*/
public static int getFlags(int move) {
return (move & FLAG_MASK) >>> FLAG_SHIFT;
}
/**
* Returns the value of the start piece from the given serialized move
*
* @param move
* the move value to get the starting piece of
* @return the value of the start piece from the given serialized move
*/
public static int getStartPiece(int move) {
return (move & START_PIECE_MASK) >>> START_PIECE_SHIFT;
}
/**
* Returns the value of the end piece from the given serialized move
*
* @param move
* the move value to get the ending piece of
* @return the value of the end piece from the given serialized move
*/
public static int getEndPiece(int move) {
return (move & END_PIECE_MASK) >>> END_PIECE_SHIFT;
}
/**
* Returns the value of the promotion piece type from the given serialized
* move
*
* @param move
* the move value to get the promotion piece type of
* @return the value of the promotion piece type from the given serialized
* move
*/
public static int getPromotionPieceType(int move) {
return (move & PROMOTION_PIECE_MASK) >>> PROMOTION_PIECE_SHIFT;
}
/**
* Prints a visualization of the serialized move by deconstructing it into
* its component partss
*
* @param move
* the move value to visualize
*/
public static void visualizeMoveContents(int move) {
printSubset("Total", move, ~0, 0);
printSubset("Flag", move, FLAG_MASK, FLAG_SHIFT);
printSubset("Start Pos", move, START_POSITION_MASK, START_POSITION_SHIFT);
printSubset("End Pos", move, END_POSITION_MASK, END_POSITION_SHIFT);
printSubset("Start piece", move, START_PIECE_MASK, START_PIECE_SHIFT);
printSubset("End Piece", move, END_PIECE_MASK, END_PIECE_SHIFT);
printSubset("Promotion", move, PROMOTION_PIECE_MASK, PROMOTION_PIECE_SHIFT);
}
private static void printSubset(String tag, int val, int mask, int shift) {
System.err.printf("%11s: |%32s|->%+10d\n", tag, Integer.toBinaryString(val & mask),
(val & mask) >> shift);
System.err.printf("%13s|%32s|\n", "", Integer.toBinaryString(mask));
}
}
|
aion-camus/rust_avm | aion_vm/org.aion.avm.core/src/org/aion/avm/core/classloading/AvmClassLoader.java | package org.aion.avm.core.classloading;
import java.util.*;
import java.util.function.Function;
import org.aion.avm.core.arraywrapping.ArrayNameMapper;
import org.aion.avm.core.arraywrapping.ArrayWrappingClassGenerator;
import org.aion.avm.core.util.DebugNameResolver;
import org.aion.avm.internal.PackageConstants;
import org.aion.avm.internal.RuntimeAssertionError;
/**
* NOTE: This implementation assumes that the classes we are trying to load are "safe" in that they don't reference
* anything we don't want this classloader to load.
* While we originally imposed some of our isolation at the classloader level, we now assume that is done in the
* bytecode instrumentation/analysis phase.
*/
public class AvmClassLoader extends ClassLoader {
// The ENUM modifier is defined in Class, but that is private so here is our copy of the constant.
private static final int CLASS_IS_ENUM = 0x00004000;
// Bytecode Map of static class of Dapp
private Map<String, byte[]> bytecodeMap;
// List of dynamic class generation handlers
private ArrayList<Function<String, byte[]>> handlers;
// Class object cache
private final Map<String, Class<?>> cache;
/**
* Constructs a new AVM class loader.
*
* @param parent The explicitly required parent for the contract-namespace code which is shared across all contracts.
* @param bytecodeMap the transformed bytecode
* @param handlers a list of handlers which can generate byte code for the given name.
*/
public AvmClassLoader(AvmSharedClassLoader parent, Map<String, byte[]> bytecodeMap, ArrayList<Function<String, byte[]>> handlers) {
super(parent);
this.bytecodeMap = bytecodeMap;
this.handlers = handlers;
this.cache = new HashMap<>();
registerHandlers();
}
/**
* Constructs a new AVM class loader.
*
* @param parent The explicitly required parent for the contract-namespace code which is shared across all contracts.
* @param bytecodeMap the transformed bytecode
*/
public AvmClassLoader(AvmSharedClassLoader parent, Map<String, byte[]> bytecodeMap) {
this(parent, bytecodeMap, new ArrayList<>());
}
private void registerHandlers(){
// Array wrapper is the only handler of the dynamic class generation request.
Function<String, byte[]> wrapperGenerator = (cName) -> ArrayWrappingClassGenerator.arrayWrappingFactory(cName, this);
this.handlers.add(wrapperGenerator);
}
/**
* Loads the class with the specified name.
* This method will load three type of classes
* a) User defined Dapp class
* b) Per Dapp internal/api class
* c) Dynamically generated user defined class
*
* Other class loading requests will be delegated to {@link AvmSharedClassLoader}
*
* @param name The name of the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException
* If the class was not found
*/
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// NOTE: We override this, instead of findClass, since we want to circumvent the normal delegation process of class loaders.
Class<?> result = null;
boolean shouldResolve = resolve;
// Contract classloader only load user Dapp classes and per Dapp internal/api classes
// Non user classes will be delegated to shared class loader
// We have a priority order to load:
// 1) Cache
// 2) Injected static code
// 3) Dynamically generated
if (this.cache.containsKey(name)) {
result = this.cache.get(name);
// We got this from the cache so don't resolve.
shouldResolve = false;
} else if (this.bytecodeMap.containsKey(name)) {
byte[] injected = this.bytecodeMap.get(name);
result = defineClass(name, injected, 0, injected.length);
// Note that this class loader should only be able to see classes we have transformed. This means no enums.
RuntimeAssertionError.assertTrue(0 == (CLASS_IS_ENUM & result.getModifiers()));
this.cache.put(name, result);
} else if (isUserArrayWrapper(name)) {
// Try dynamic generation
for (Function<String, byte[]> handler : handlers) {
byte[] code = handler.apply(name);
if (code != null) {
result = defineClass(name, code, 0, code.length);
this.cache.put(name, result);
break;
}
}
}else{
// Delegate request to parent
result = getParent().loadClass(name);
// We got this from the parent so don't resolve.
shouldResolve = false;
}
if ((null != result) && shouldResolve) {
resolveClass(result);
}
if (null == result) {
throw new ClassNotFoundException(name);
}
return result;
}
private boolean isUserArrayWrapper(String className) {
if (className.startsWith(PackageConstants.kArrayWrapperDotPrefix + "interface")) {
return this.bytecodeMap.containsKey(ArrayNameMapper.getElementInterfaceName(className));
} else if (className.startsWith(PackageConstants.kArrayWrapperDotPrefix + "$")) {
return this.bytecodeMap.containsKey(ArrayNameMapper.getClassWrapperElementName(className));
}
// since it is not an array wrapper
return false;
}
/**
* A helper for tests which want to load a class by its pre-renamed name and also ensure that the receiver was the loader (didn't delegate).
*
* @param originalClassName The pre-renamed class name (.-style).
* @return The transformed/renamed class instance.
* @throws ClassNotFoundException Underlying load failed.
*/
public Class<?> loadUserClassByOriginalName(String originalClassName, boolean preserveDebuggability) throws ClassNotFoundException {
String renamedClass = DebugNameResolver.getUserPackageDotPrefix(originalClassName, preserveDebuggability);
Class<?> clazz = this.loadClass(renamedClass);
RuntimeAssertionError.assertTrue(this == clazz.getClassLoader());
return clazz;
}
//Internal
public byte[] getUserClassBytecodeByOriginalName(String className, boolean preserveDebuggability) {
return this.bytecodeMap.get(DebugNameResolver.getUserPackageDotPrefix(className, preserveDebuggability));
}
public byte[] getUserClassBytecode(String className){
return this.bytecodeMap.get(className);
}
}
|
Fumaloko92/MSc-Thesis | 17-05-2017/neuralturingmachines-master/src/com/anji/floatingeye/LocationXConnection.java | <reponame>Fumaloko92/MSc-Thesis<gh_stars>1-10
/*
* Copyright (C) 2004 <NAME> and <NAME>
*
* This file is part of ANJI (Another NEAT Java Implementation).
*
* ANJI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* created by <NAME> on Jun 10, 2004
*/
package com.anji.floatingeye;
import com.anji.nn.Connection;
/**
* @author <NAME>
*/
public class LocationXConnection implements Connection {
private FloatingEye eye;
/**
* @param anEye floating eye object from which to get location data
*/
public LocationXConnection( FloatingEye anEye ) {
eye = anEye;
}
/**
* @see com.anji.nn.Connection#read()
*/
public double read() {
return eye.eyeLocation.x;
}
/**
* @see com.anji.nn.Connection#toXml()
*/
public String toXml() {
StringBuffer result = new StringBuffer();
result.append( "<" ).append( Connection.XML_TAG );
result.append( "\" from-location=\"x\" />" );
return result.toString();
}
/**
* @see com.anji.nn.Connection#cost()
*/
public long cost() {
return 41;
}
}
|
ehealth-ua/ehealth.web | packages/admin-legacy/src/containers/pages/MedicationCreatePage/index.js | <filename>packages/admin-legacy/src/containers/pages/MedicationCreatePage/index.js
import React from "react";
import { compose } from "redux";
import { connect } from "react-redux";
import { withRouter } from "react-router";
import Helmet from "react-helmet";
import BackLink from "../../blocks/BackLink";
import Line from "../../../components/Line";
import MedicationsCreateForm from "../../forms/MedicationsCreateForm";
import { getInnmDosages, getDictionary } from "../../../reducers";
import { onSubmit, onSearchInnmsDosages } from "./redux";
class MedicationCreatePage extends React.Component {
render() {
const {
router,
innm_dosages = [],
medication_unit = [],
medication_form = [],
countries = [],
onSubmit = () => {},
onSearchInnmsDosages = () => {}
} = this.props;
return (
<div id="medicaion-create-page">
<Helmet
title="Створення торгівельного найменування"
meta={[
{
property: "og:title",
content: "Створення торгівельного найменування"
}
]}
/>
<BackLink onClick={() => router.goBack()}>
Додати торгівельне найменування
</BackLink>
<Line />
<MedicationsCreateForm
onSubmit={onSubmit}
onSearchInnmsDosages={onSearchInnmsDosages}
data={{ innm_dosages, medication_unit, medication_form, countries }}
/>
</div>
);
}
}
export default compose(
withRouter,
connect(
state => ({
innm_dosages: getInnmDosages(
state,
state.pages.MedicationCreatePage.innm_dosages
),
medication_unit: getDictionary(state, "MEDICATION_UNIT"),
medication_form: getDictionary(state, "MEDICATION_FORM"),
countries: getDictionary(state, "COUNTRY")
}),
{ onSubmit, onSearchInnmsDosages }
)
)(MedicationCreatePage);
|
TeamFleet/WhoCallsTheFleet | source/nw.js-base-framework/source/js-app-main.js | // @koala-prepend "js-app/main.js" |
mthirani/SmallTalk-Compiler | src/smalltalk/vm/exceptions/UndefinedGlobal.java | <gh_stars>1-10
package smalltalk.vm.exceptions;
public class UndefinedGlobal extends VMException {
public UndefinedGlobal(String message, String stackTrace) {
super(message, stackTrace);
}
}
|
jodavis42/ZilchShaders | Libraries/Platform/Empty/ThreadSync.cpp | ////////////////////////////////////////////////////////////////////////////////
/// Authors: <NAME>
/// Copyright 2018, DigiPen Institute of Technology
////////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//----------------------------------------------------------- Thread Lock
struct ThreadLockPrivateData
{
};
ThreadLock::ThreadLock()
{
}
ThreadLock::~ThreadLock()
{
}
void ThreadLock::Lock()
{
}
void ThreadLock::Unlock()
{
}
//----------------------------------------------------------- Os Event
OsEvent::OsEvent()
{
}
OsEvent::~OsEvent()
{
}
void OsEvent::Initialize(bool manualReset, bool startSignaled)
{
}
void OsEvent::Close()
{
}
void OsEvent::Signal()
{
}
void OsEvent::Reset()
{
}
void OsEvent::Wait()
{
}
OsHandle OsEvent::GetHandle()
{
return nullptr;
}
//----------------------------------------------------------- Semaphore
Semaphore::Semaphore()
{
}
Semaphore::~Semaphore()
{
}
void Semaphore::Increment()
{
}
void Semaphore::Decrement()
{
}
void Semaphore::Reset()
{
}
void Semaphore::WaitAndDecrement()
{
}
InterprocessMutex::InterprocessMutex()
{
}
InterprocessMutex::~InterprocessMutex()
{
}
void InterprocessMutex::Initialize(Status& status, const char* mutexName, bool failIfAlreadyExists)
{
}
CountdownEvent::CountdownEvent()
{
}
void CountdownEvent::IncrementCount()
{
}
void CountdownEvent::DecrementCount()
{
}
void CountdownEvent::Wait()
{
}
}//namespace Zero
|
isi-nlp/Zoph_RNN | src/BZ_CUDA_UTIL.h | <gh_stars>100-1000
//CUDA utilility for LSTM RNN
#ifndef BZ_CUDA_UTIL_H
#define BZ_CUDA_UTIL_H
#include <stdlib.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include "cublas_v2.h"
#include <cuda_runtime.h>
#include <thrust/device_vector.h>
#include <thrust/device_ptr.h>
#include <thrust/transform.h>
#include <curand.h>
#include <thrust/iterator/constant_iterator.h>
#include "cuda_profiler_api.h"
//This is used since all cuBLAS storage is column major
#define IDX2C(i,j,ld) (((j)*(ld))+(i))
//std::ofstream HPC_output;
namespace deniz {
bool source_side = false;
bool train_source_input_embedding = true;
bool train_target_input_embedding = true;
bool train_target_output_embedding = true;
bool train_source_RNN = true;
bool train_target_RNN = true;
bool train_attention_target_RNN = true;
bool soft_regularizer = false;
precision train_source_input_embedding_lambda = 0;
precision train_target_input_embedding_lambda = 0;
precision train_target_output_embedding_lambda = 0;
precision train_source_RNN_lambda = 0;
precision train_target_RNN_lambda = 0;
precision train_attention_target_RNN_lambda = 0;
}
//for t-sne stuff for paper
namespace BZ_STATS {
precision *h_dump_ht = NULL;
bool tsne_dump = false;
std::ofstream tsne_dump_stream;//("tsne_dump_COMB.txt");
}
//namespace to hold constants
namespace BZ_CUDA {
//for logging the output
//bool HPC_output = false;
OutputLogger logger;
bool cont_train = false;
bool shuffle_data=true;
//for ensembling pre-normalization
bool pre_norm = false;
//for dumping the best model
bool dump_every_best = false;
int curr_dump_num = 1;
//stuff for unk replacement using attention
bool unk_replacement = false;
std::string unk_rep_file_name;
std::ofstream unk_rep_file_stream;
std::vector<int> viterbi_alignments;
std::vector<int> all_viterbi_alignments;
std::vector<precision> alignment_scores; //for ensembling alignment values
int *h_align_indicies;
precision *h_alignment_values;
bool print_norms = false;
unsigned int curr_seed = 0;
//for not storing extra stuff during testing
bool force_decode = false;
//FOR BAD NCE DUMP
bool nce_legacy_dump = false;
boost::random::mt19937 gen;
double lower = -0.08;
double upper = 0.08;
bool global_clip_flag = false;
precision global_norm = 0; //the global norm for gradient clipping
precision global_norm_threshold;
//clip errors with respect to h_t and c_t
bool clip_cell = false;
precision cell_clip_threshold = 50;
precision error_clip_threshold = 1000;
//for stats on gradient norms
double recent_sum = 0;
//grad clipping
bool individual_grad_clip = false;
precision ind_norm_clip_thres = 0.1;
//for gettings only NCE scores (used for reranking, etc ...)
bool nce_score = false;
//for NCE stats for paper
bool dump_NCE_stats = false;
std::string NCE_file_dump_name = "ASHISH_DUMP.txt";
std::ofstream NCE_file_dump;//(NCE_file_dump_name.c_str());
precision *h_h_t_storage;
double *h_part_vals;
double *d_part_vals;
//partition function calculation for NCE
bool print_partition_function = false;
std::vector<double> full_partition_vals; //all the partition function values
void print_partition_stats() {
double total_sum = 0;
double mean = 0;
double variance = 0;
for(int i=0; i<full_partition_vals.size(); i++) {
total_sum+=full_partition_vals[i];
}
mean = total_sum/full_partition_vals.size();
for(int i=0; i<full_partition_vals.size(); i++) {
variance+= (full_partition_vals[i] - mean)*(full_partition_vals[i] - mean);
}
variance = variance/full_partition_vals.size();
BZ_CUDA::logger << "\n-------------------NCE PARTITION STATS------------------\n";
BZ_CUDA::logger << "Partition mean: " << mean << "\n";
BZ_CUDA::logger << "Partition function standard deviation: " << std::sqrt(variance) << "\n\n\n";
full_partition_vals.clear();
}
} //BZ_CUDA namespace
#define FatalError(s) { \
std::stringstream _where, _message; \
_where << __FILE__ << ':' << __LINE__; \
_message << std::string(s) + "\n" << __FILE__ << ':' << __LINE__;\
std::cerr << _message.str() << "\nAborting...\n"; \
cudaDeviceReset(); \
exit(EXIT_FAILURE); \
}
#define checkCUDNN(status) { \
std::stringstream _error; \
if (status != CUDNN_STATUS_SUCCESS) { \
_error << "CUDNN failure\nError: " << cudnnGetErrorString(status); \
FatalError(_error.str()); \
} \
}
#define UNCONST(t,c,uc) Eigen::MatrixBase<t> &uc = const_cast<Eigen::MatrixBase<t>&>(c);
// void CUDA_ERROR_WRAPPER(cudaError_t cudaStat,std::string error_message) {
// if (cudaStat != cudaSuccess) {
// std::cout << error_message << std::endl;
// exit (EXIT_FAILURE);
// }
// }
void CUDA_ERROR_WRAPPER(cudaError_t cudaStat,std::string error_message) {
if ( cudaSuccess != cudaStat ) {
BZ_CUDA::logger << "Error\n";
fprintf(stderr,"GPUassert: %s\n", cudaGetErrorString(cudaStat));
BZ_CUDA::logger << error_message << "\n";
exit (EXIT_FAILURE);
}
}
std::string cublasErrorString(cublasStatus_t error) {
switch (error)
{
case CUBLAS_STATUS_SUCCESS:
return "CUBLAS_STATUS_SUCCESS";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "CUBLAS_STATUS_NOT_INITIALIZED";
case CUBLAS_STATUS_ALLOC_FAILED:
return "CUBLAS_STATUS_ALLOC_FAILED";
case CUBLAS_STATUS_INVALID_VALUE:
return "CUBLAS_STATUS_INVALID_VALUE";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "CUBLAS_STATUS_ARCH_MISMATCH";
case CUBLAS_STATUS_MAPPING_ERROR:
return "CUBLAS_STATUS_MAPPING_ERROR";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "CUBLAS_STATUS_EXECUTION_FAILED";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "CUBLAS_STATUS_INTERNAL_ERROR";
}
return "<unknown>";
}
void CUBLAS_ERROR_WRAPPER(cublasStatus_t cudaStat,std::string error_message) {
//if (cudaStat != cudaSuccess) {
if (cudaStat != CUBLAS_STATUS_SUCCESS) {
std::string msg = cublasErrorString(cudaStat);
std::cout << error_message << std::endl;
BZ_CUDA::logger << msg << "\n";
exit (EXIT_FAILURE);
}
}
void CUDA_GET_LAST_ERROR() {
cudaError_t code = cudaGetLastError();
if ( cudaSuccess != code ) {
BZ_CUDA::logger << "Error in kernel\n";
BZ_CUDA::logger << "NO MESSAGE\n";
fprintf(stderr,"GPUassert: %s\n", cudaGetErrorString(code));
exit (EXIT_FAILURE);
}
}
void CUDA_GET_LAST_ERROR(std::string msg) {
cudaError_t code = cudaGetLastError();
if ( cudaSuccess != code ) {
BZ_CUDA::logger << "Error in kernel\n";
fprintf(stderr,"GPUassert: %s\n", cudaGetErrorString(code));
BZ_CUDA::logger << msg << "\n";
exit (EXIT_FAILURE);
}
}
// void CUDA_GET_LAST_ERROR(std::string message) {
// if ( cudaSuccess != cudaGetLastError() ) {
// std::cout << "Error in kernel: " << message << "\n" ;
// }
// }
//Can be used for either double or float, use floats for performance, but doubles for gradient checking
template<typename dType>
void initialize_Matrix(dType *h_matrix,int rows,int cols) {
boost::uniform_real<> distribution(BZ_CUDA::lower,BZ_CUDA::upper);
for(int j=0; j<cols; j++) {
for(int i=0; i<rows; i++) {
h_matrix[IDX2C(i,j,rows)] = (dType)distribution(BZ_CUDA::gen);
}
}
}
template<typename dType>
void initialize_Matrix_GPU(dType *d_matrix,int rows,int cols) {
boost::uniform_real<> distribution(BZ_CUDA::lower,BZ_CUDA::upper);
thrust::device_ptr<dType> mat_ptr = thrust::device_pointer_cast(d_matrix);
for(int j=0; j<cols; j++) {
for(int i=0; i<rows; i++) {
mat_ptr[IDX2C(i,j,rows)] = (dType)distribution(BZ_CUDA::gen);
}
}
}
template<typename dType>
void initialize_Matrix_ones(dType *h_matrix,int rows,int cols) {
for(int j=0; j<cols; j++) {
for(int i=0; i<rows; i++) {
h_matrix[IDX2C(i,j,rows)] = 1;
}
}
}
template<typename dType>
void initialize_Matrix_zeros(dType *h_matrix,int rows,int cols) {
for(int j=0; j<cols; j++) {
for(int i=0; i<rows; i++) {
h_matrix[IDX2C(i,j,rows)] = 0;
}
}
}
template<typename dType>
void allocate_Matrix_CPU(dType **h_matrix,int rows,int cols) {
*h_matrix = (dType *)malloc(rows*cols*sizeof(dType));
}
template<typename dType>
void allocate_Matrix_GPU(dType **d_matrix,int rows,int cols) {
CUDA_ERROR_WRAPPER(cudaMalloc((void**)d_matrix, rows*cols*sizeof(dType)),"GPU memory allocation failed\n");
}
template<typename dType>
void set_matrix_cuBLAS(dType *h_matrix,dType *d_matrix,int rows,int cols) {
CUBLAS_ERROR_WRAPPER(cublasSetMatrix(rows, cols, sizeof(dType), h_matrix, rows, d_matrix, rows),"cuBLAS set matrix failed\n");
}
template<typename dType>
void set_vector_cuBLAS(dType *h_vector,dType *d_vector,int rows) {
CUBLAS_ERROR_WRAPPER(cublasSetVector(rows, sizeof(dType), h_vector, 1, d_vector, 1),"cuBLAS set vector failed\n");
}
template<typename dType>
void get_matrix_cuBLAS(dType *h_matrix,dType *d_matrix,int rows,int cols) {
CUBLAS_ERROR_WRAPPER(cublasGetMatrix(rows, cols, sizeof(dType), d_matrix, rows, h_matrix, rows),"cuBLAS get matrix failed\n");
}
template<typename dType>
void get_vector_cuBLAS(dType *h_vector,dType *d_vector,int rows) {
CUBLAS_ERROR_WRAPPER(cublasGetVector(rows, sizeof(dType), d_vector, 1, h_vector, 1),"cuBLAS get vector failed\n");
}
// both gpu and cpu
template<typename dType>
void allocate_matrix_dh(dType **h_matrix,dType **d_matrix,int rows,int cols) {
*h_matrix = (dType * ) malloc(rows * cols * sizeof(dType));
CUDA_ERROR_WRAPPER(cudaMalloc((void**)d_matrix, rows * cols * sizeof(dType)),"d_matrix failed\n");
}
template<typename dType>
void full_matrix_setup(dType **h_matrix,dType **d_matrix,int rows,int cols) {
allocate_Matrix_CPU(h_matrix,rows,cols);
initialize_Matrix(*h_matrix,rows,cols);
allocate_Matrix_GPU(d_matrix,rows,cols);
set_matrix_cuBLAS(*h_matrix,*d_matrix,rows,cols);
free(*h_matrix);
}
template<typename dType>
void full_matrix_setup_0(dType **h_matrix,dType **d_matrix,int rows,int cols) {
allocate_Matrix_CPU(h_matrix,rows,cols);
initialize_Matrix_zeros(*h_matrix,rows,cols);
allocate_Matrix_GPU(d_matrix,rows,cols);
set_matrix_cuBLAS(*h_matrix,*d_matrix,rows,cols);
free(*h_matrix);
}
template<typename dType>
void full_vector_setup(dType **h_vector,dType **d_vector,int rows) {
allocate_Matrix_CPU(h_vector,rows,1);
initialize_Matrix(*h_vector,rows,1);
allocate_Matrix_GPU(d_vector,rows,1);
set_vector_cuBLAS(*h_vector,*d_vector,rows);
free(*h_vector);
}
template<typename dType>
void full_vector_setup_ones(dType **h_vector,dType **d_vector,int rows) {
allocate_Matrix_CPU(h_vector,rows,1);
initialize_Matrix_ones(*h_vector,rows,1);
allocate_Matrix_GPU(d_vector,rows,1);
set_vector_cuBLAS(*h_vector,*d_vector,rows);
free(*h_vector);
}
void initialize_vector_vocab(int *h_vector,int rows,int vocab_size) {
boost::uniform_real<> distribution(0,1);
for(int i=0; i<rows; i++) {
h_vector[i] = (int)(vocab_size*distribution(BZ_CUDA::gen));
}
}
void initialize_vector_vocab_01(int *h_vector,int rows) {
srand (time(NULL));
for(int i=0; i<rows; i++) {
h_vector[i] = (int)(rand()%2);
}
}
void full_vector_setup_vocab(int **h_vector,int **d_vector,int rows,int vocab_size) {
allocate_Matrix_CPU(h_vector,rows,1);
initialize_vector_vocab(*h_vector,rows,vocab_size);
allocate_Matrix_GPU(d_vector,rows,1);
set_vector_cuBLAS(*h_vector,*d_vector,rows);
free(*h_vector);
}
void full_vector_setup_vocab_01(int **h_vector,int **d_vector,int rows) {
allocate_Matrix_CPU(h_vector,rows,1);
initialize_vector_vocab_01(*h_vector,rows);
allocate_Matrix_GPU(d_vector,rows,1);
set_vector_cuBLAS(*h_vector,*d_vector,rows);
free(*h_vector);
}
template<typename dType>
void print_matrix(dType *h_matrix,int rows,int cols) {
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
BZ_CUDA::logger << h_matrix[IDX2C(i,j,rows)] << " ";
}
BZ_CUDA::logger << "\n";
}
BZ_CUDA::logger << "\n";
}
template<typename dType>
void print_matrix_gpu(dType *d_matrix,int rows,int cols) {
dType * h_matrix = (dType *)malloc(rows*cols*sizeof(dType));
CUDA_ERROR_WRAPPER(cudaMemcpy(h_matrix, d_matrix, rows*cols*sizeof(dType), cudaMemcpyDeviceToHost),"print_matrix_gpu");
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
BZ_CUDA::logger << h_matrix[IDX2C(i,j,rows)] << " ";
}
BZ_CUDA::logger << "\n";
}
BZ_CUDA::logger << "\n";
free(h_matrix);
}
template<typename Derived>
void print_eigen_matrix(const Eigen::MatrixBase<Derived> &h_mat) {
for(int i=0; i<h_mat.rows(); i++) {
for(int j=0; j<h_mat.cols(); j++) {
BZ_CUDA::logger << h_mat(i,j) << " ";
}
BZ_CUDA::logger << "\n";
}
BZ_CUDA::logger << "\n";
}
template<typename dType>
void print_thrust_matrix(thrust::host_vector<dType> &h_mat,int rows,int cols) {
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
BZ_CUDA::logger << h_mat[IDX2C(i,j,rows)] << " ";
}
BZ_CUDA::logger << "\n";
}
BZ_CUDA::logger << "\n";
}
//returns true if eigen matrix is the same, false otherwise
template<typename Derived,typename dType>
bool eigen_check(const Eigen::MatrixBase<Derived> &h_eigen_mat,dType *h_cuda_matrix) {
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
if(h_eigen_mat(i,j) != h_cuda_matrix[IDX2C(i,j,h_eigen_mat.rows())]) {
return false;
}
}
}
return true;
}
//returns true if eigen matrix is the same, false otherwise
template<typename Derived,typename dType>
bool eigen_check_thres(const Eigen::MatrixBase<Derived> &h_eigen_mat,dType *h_cuda_matrix,dType threshold) {
int num_bad = 0;
dType max_fail = 0;
dType average_fail = 0;
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
if( std::abs(h_eigen_mat(i,j) -h_cuda_matrix[IDX2C(i,j,h_eigen_mat.rows())]) > threshold ) {
//std::cout << "Eigen check failing at: " << i << " " << j << "\n";
//std::cout << "Difference: " << std::abs(h_eigen_mat(i,j) - h_cuda_matrix[IDX2C(i,j,h_eigen_mat.rows())]) << "\n";
dType diff = std::abs(h_eigen_mat(i,j)-h_cuda_matrix[IDX2C(i,j,h_eigen_mat.rows())] );
average_fail+=diff;
if(diff > max_fail) {
max_fail = diff;
}
num_bad++;
}
}
}
if(num_bad > 0) {
BZ_CUDA::logger << "Total that could fail: " << h_eigen_mat.rows()*h_eigen_mat.cols() << "\n";
BZ_CUDA::logger << "Number in eigen check that failed: " << num_bad << "\n";
BZ_CUDA::logger << "Max fail: " << max_fail << "\n";
BZ_CUDA::logger << "average fail: " << average_fail/num_bad << "\n";
return false;
}
return true;
}
#include <set>
template<typename Derived,typename dType>
void eigen_check_thrust_ptr(const Eigen::MatrixBase<Derived> &h_eigen_mat,dType *d_ptr,std::string msg,dType threshold) {
//thrust::device_ptr<dType> debug_ptr = thrust::device_pointer_cast(d_ptr);
int tot_size = h_eigen_mat.rows()*h_eigen_mat.cols()*sizeof(dType);
dType * h_temp = (dType *)malloc(tot_size);
cudaMemcpy(h_temp, d_ptr, tot_size, cudaMemcpyDeviceToHost);
int num_bad =0;
dType max_fail = 0;
dType average_fail = 0;
std::set<int> myset;
std::set<int> myset2;
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
if( std::abs(h_eigen_mat(i,j) -h_temp[IDX2C(i,j,h_eigen_mat.rows())]) > threshold ) {
dType diff = std::abs(h_eigen_mat(i,j)-h_temp[IDX2C(i,j,h_eigen_mat.rows())] );
average_fail+=diff;
if(diff > max_fail) {
max_fail = diff;
}
myset.insert(j);
num_bad++;
myset2.insert(i);
}
}
}
if(num_bad > 0) {
BZ_CUDA::logger << "Operation: " << msg << " failed\n";
BZ_CUDA::logger << "Total that could fail: " << h_eigen_mat.rows()*h_eigen_mat.cols() << "\n";
BZ_CUDA::logger << "Number in eigen check that failed: " << num_bad << "\n";
BZ_CUDA::logger << "Max fail: " << max_fail << "\n";
BZ_CUDA::logger << "average fail: " << average_fail/num_bad << "\n";
for (auto it=myset.begin(); it!=myset.end(); ++it)
BZ_CUDA::logger << ' ' << *it;
BZ_CUDA::logger << "\n\n";
for (auto it=myset2.begin(); it!=myset2.end(); ++it)
BZ_CUDA::logger << ' ' << *it;
BZ_CUDA::logger << "\n\n";
//std::cout << h_eigen_mat << "\n\n\n\n";
// for(int i=0; i<h_eigen_mat.rows(); i++) {
// for(int j=0; j<h_eigen_mat.cols(); j++) {
// std::cout << h_temp[IDX2C(i,j,h_eigen_mat.rows())] << " ";
// }
// std::cout << "\n";
// }
BZ_CUDA::logger << "\n";
exit (EXIT_FAILURE);
}
free(h_temp);
}
template<typename dType>
void check_GPU_GPU(dType *mat1,dType *mat2,dType threshold,int rows,int cols,std::string msg) {
thrust::device_ptr<dType> debug_ptr = thrust::device_pointer_cast(mat1);
thrust::device_ptr<dType> debug_ptr2 = thrust::device_pointer_cast(mat2);
int num_bad =0;
dType max_fail = 0;
dType average_fail = 0;
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
int idx = IDX2C(i,j,rows);
if( std::abs(debug_ptr2[idx] - debug_ptr[idx]) > threshold ) {
dType diff = std::abs( debug_ptr2[idx] - debug_ptr[idx] );
average_fail+=diff;
if(diff > max_fail) {
max_fail = diff;
}
num_bad++;
}
}
}
if(num_bad > 0) {
BZ_CUDA::logger << "Operation: " << msg << " failed\n";
BZ_CUDA::logger << "Total that could fail: " << rows*cols << "\n";
BZ_CUDA::logger << "Number in eigen check that failed: " << num_bad << "\n";
BZ_CUDA::logger << "Max fail: " << max_fail << "\n";
BZ_CUDA::logger << "average fail: " << average_fail/num_bad << "\n";
exit (EXIT_FAILURE);
}
}
//returns true if eigen matrix is the same, false otherwise
template<typename Derived,typename dType>
bool eigen_check_thres_thrust(const Eigen::MatrixBase<Derived> &h_eigen_mat,thrust::host_vector<dType> &h_mat,dType threshold) {
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
if( std::abs(h_eigen_mat(i,j) -h_mat[IDX2C(i,j,h_eigen_mat.rows())]) > threshold ) {
return false;
}
}
}
return true;
}
//Copy a matrix in column major format to eigen
template<typename Derived,typename dType>
void copy_to_eigen(const Eigen::MatrixBase<Derived> &h_eigen_mat_const,dType *h_cuda_matrix) {
UNCONST(Derived,h_eigen_mat_const,h_eigen_mat);
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
h_eigen_mat(i,j) = h_cuda_matrix[IDX2C(i,j,h_eigen_mat.rows())];
}
}
}
//Copy a matrix in column major format to eigen
template<typename Derived,typename dType>
void copy_to_eigen_thrust(const Eigen::MatrixBase<Derived> &h_eigen_mat_const,
thrust::host_vector<dType> &h_mat_thrust)
{
UNCONST(Derived,h_eigen_mat_const,h_eigen_mat);
for(int i=0; i<h_eigen_mat.rows(); i++) {
for(int j=0; j<h_eigen_mat.cols(); j++) {
h_eigen_mat(i,j) = h_mat_thrust[IDX2C(i,j,h_eigen_mat.rows())];
}
}
}
//note there are no thrust matrices only vectors
template<typename dType>
void initialize_thrust_vector(thrust::host_vector<dType> &h_vec,int size) {
boost::uniform_real<> distribution(BZ_CUDA::lower,BZ_CUDA::upper);
for(int i=0; i<size; i++) {
h_vec[i] = (dType)distribution(BZ_CUDA::gen);
}
}
template<typename dType>
void print_GPU_Matrix(dType *d_ptr,int rows,int cols) {
thrust::device_ptr<dType> debug_ptr = thrust::device_pointer_cast(d_ptr);
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
BZ_CUDA::logger << debug_ptr[IDX2C(i,j,rows)] << " ";
}
BZ_CUDA::logger << "\n";
}
BZ_CUDA::logger << "\n";
}
template<typename dType>
void check_mem_loc(dType *d_ptr,int rows,int cols) {
thrust::device_ptr<dType> debug_ptr = thrust::device_pointer_cast(d_ptr);
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
dType temp = debug_ptr[IDX2C(i,j,rows)];
}
}
CUDA_GET_LAST_ERROR("check_mem_loc");
}
//------------------------------------CUBLAS ERROR WRAPPERS--------------------------------------
///////////////////////////////////////////DOUBLE DEFINE BEGIN///////////////////////////////////////
inline cublasStatus_t cublas_gemm_wrapper(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb,
int m, int n, int k, const float *alpha, const float *A, int lda,
const float *B, int ldb, const float *beta, float *C, int ldc)
{
return cublasSgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
}
inline cublasStatus_t cublas_gemm_wrapper(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb,
int m, int n, int k, const double *alpha, const double *A, int lda,
const double *B, int ldb, const double *beta, double *C, int ldc)
{
return cublasDgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
}
///////////////////////////////////////////DOUBLE DEFINE END///////////////////////////////////////
///////////////////////////////////////////DOUBLE DEFINE BEGIN///////////////////////////////////////
inline cublasStatus_t cublas_geam_wrapper(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb,
int m, int n, const float *alpha, const float *A, int lda, const float *beta,
const float *B, int ldb, float *C, int ldc)
{
return cublasSgeam(handle, transa, transb, m, n, alpha, A, lda, beta, B, ldb, C, ldc);
}
inline cublasStatus_t cublas_geam_wrapper(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb,
int m, int n, const double *alpha, const double *A, int lda, const double *beta,
const double *B, int ldb, double *C, int ldc)
{
return cublasDgeam(handle, transa, transb, m, n, alpha, A, lda, beta, B, ldb, C, ldc);
}
///////////////////////////////////////////DOUBLE DEFINE END///////////////////////////////////////
///////////////////////////////////////////DOUBLE DEFINE BEGIN///////////////////////////////////////
inline cublasStatus_t cublas_gemv_wrapper(cublasHandle_t handle, cublasOperation_t trans, int m,
int n, const float *alpha, const float *A, int lda, const float *x, int incx,
const float *beta, float *y, int incy)
{
return cublasSgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy);
}
inline cublasStatus_t cublas_gemv_wrapper(cublasHandle_t handle, cublasOperation_t trans, int m,
int n, const double *alpha, const double *A, int lda, const double *x, int incx,
const double *beta, double *y, int incy)
{
return cublasDgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy);
}
///////////////////////////////////////////DOUBLE DEFINE END///////////////////////////////////////
///////////////////////////////////////////DOUBLE DEFINE BEGIN///////////////////////////////////////
inline cublasStatus_t cublas_dgmm_wrapper(cublasHandle_t handle, cublasSideMode_t mode, int m, int n,
const float *A, int lda, const float *x, int incx, float *C, int ldc)
{
return cublasSdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc);
}
inline cublasStatus_t cublas_dgmm_wrapper(cublasHandle_t handle, cublasSideMode_t mode, int m, int n,
const double *A, int lda, const double *x, int incx, double *C, int ldc)
{
return cublasDdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc);
}
///////////////////////////////////////////DOUBLE DEFINE END///////////////////////////////////////
//atomic add for doubles,since undefined in cuda
__device__ double atomicAddDouble(double* address, double val)
{
unsigned long long int* address_as_ull =
(unsigned long long int*)address;
unsigned long long int old = *address_as_ull, assumed;
do {
assumed = old;
old = atomicCAS(address_as_ull, assumed,
__double_as_longlong(val +
__longlong_as_double(assumed)));
} while (assumed != old);
return __longlong_as_double(old);
}
//atomic add for doubles,since undefined in cuda
/*
__device__ double atomicAdd(double* address, double val)
{
unsigned long long int* address_as_ull =
(unsigned long long int*)address;
unsigned long long int old = *address_as_ull, assumed;
do {
assumed = old;
old = atomicCAS(address_as_ull, assumed,
__double_as_longlong(val +
__longlong_as_double(assumed)));
} while (assumed != old);
return __longlong_as_double(old);
}
*/
void curandGenerateUniform_wrapper(float *d_mask,int size,curandGenerator_t &generator) {
curandGenerateUniform(generator,d_mask,size);
}
void curandGenerateUniform_wrapper(double *d_mask,int size,curandGenerator_t &generator) {
curandGenerateUniformDouble(generator,d_mask,size);
}
__device__
inline float cuda_exp_wrapper(float x) {
return expf(x);
}
__device__
inline double cuda_exp_wrapper(double x) {
return exp(x);
}
__device__
inline float cuda_log_wrapper(float x) {
return logf(x);
}
__device__
inline double cuda_log_wrapper(double x) {
return log(x);
}
__device__
inline float pow_wrapper(float x,float y) {
return powf(x,y);
}
__device__
inline double pow_wrapper(double x,double y) {
return pow(x,y);
}
__device__
inline double tanh_wrapper(double x) {
return tanh(x);
}
__device__
inline float tanh_wrapper(float x) {
return tanhf(x);
}
__device__
inline bool nan_wrapper(float x) {
return isnan((double)x);
}
__device__
inline bool nan_wrapper(double x) {
return isnan(x);
}
__device__
inline bool nan_wrapper(int x) {
return isnan((double)x);
}
__device__
inline bool isinf_wrapper(double x) {
return isinf((float)x);
}
__device__
inline bool isinf_wrapper(float x) {
return isinf(x);
}
__device__
inline double cuda_log1p_wrapper(double x) {
return log1p(x);
}
__device__
inline float cuda_log1p_wrapper(float x) {
return log1pf(x);
}
__device__
inline double cuda_max_wrapper(double x,double y) {
return max(x,y);
}
__device__
inline float cuda_max_wrapper(float x,float y) {
return fmaxf(x,y);
}
__device__
inline double cuda_min_wrapper(double x,double y) {
return min(x,y);
}
__device__
inline float cuda_min_wrapper(float x,float y) {
return fminf(x,y);
}
template<typename dType>
void get_cell_states(dType *d_ptr,int LSTM_size,int minibatch_size) {
thrust::device_ptr<dType> debug_ptr = thrust::device_pointer_cast(d_ptr);
int num_above_10 = 0;
int num_below_10 = 0;
int num_above_50 = 0;
int num_below_50 = 0;
int num_above_100 = 0;
int num_below_100 = 0;
int num_above_500 = 0;
int num_below_500 = 0;
for(int i=0; i<minibatch_size; i++) {
for(int j=0; j< LSTM_size; j++) {
dType val = debug_ptr[IDX2C(j,i,LSTM_size)];
if(val>10) {
num_above_10++;
}
if(val>50) {
num_above_50++;
}
if(val>100) {
num_above_100++;
}
if(val>500) {
num_above_500++;
}
if(val<-10) {
num_below_10++;
}
if(val<-50) {
num_below_50++;
}
if(val<-100) {
num_below_100++;
}
if(val<-500) {
num_below_500++;
}
}
}
BZ_CUDA::logger << "CELL STATS\n";
BZ_CUDA::logger << "Total cell states: " << LSTM_size*minibatch_size << "\n";
BZ_CUDA::logger << "Num above 10: " << num_above_10 << "\n";
BZ_CUDA::logger << "Num above 50: " << num_above_50 << "\n";
BZ_CUDA::logger << "Num above 100: " << num_above_100 << "\n";
BZ_CUDA::logger << "Num above 500: " << num_above_500 << "\n";
BZ_CUDA::logger << "Num below -10: " << num_below_10 << "\n";
BZ_CUDA::logger << "Num below -50: " << num_below_50 << "\n";
BZ_CUDA::logger << "Num below -100: " << num_below_100 << "\n";
BZ_CUDA::logger << "Num below -500: " << num_below_500 << "\n";
}
namespace gpu_info {
std::vector<int> device_numbers;
}
//void devSynchAll() {
// int origin_device;
// cudaGetDevice(&origin_device);
// std::cout << gpu_info::device_numbers.size() << "\n";
// for(int i=0; i<gpu_info::device_numbers.size(); i++) {
// cudaSetDevice(gpu_info::device_numbers[i]);
// cudaDeviceSynchronize();
// }
// cudaSetDevice(origin_device);
//}
void devSynchAll() {
int num_devices;
int origin_device;
cudaGetDevice(&origin_device);
cudaGetDeviceCount(&num_devices);
for(int i=0; i<num_devices; i++) {
cudaSetDevice(i);
cudaDeviceSynchronize();
}
cudaSetDevice(origin_device);
}
template<typename dType>
__global__
void nan_check_kernel(dType *d_ptr,int rows,int cols,bool *d_check) {
for(int i=threadIdx.x + blockIdx.x*blockDim.x; i<rows*cols; i+=gridDim.x*blockDim.x) {
if(nan_wrapper(d_ptr[i])) {
d_check[0] = true;
}
}
}
bool *d_temp_bool=NULL;
template<typename dType>
bool check_nan(dType *d_ptr,int rows,int cols) {
CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_temp_bool, 1*sizeof(bool)),"GPU memory allocation failed\n");
thrust::device_ptr<bool> debug_ptr = thrust::device_pointer_cast(d_temp_bool);
cudaMemset(d_temp_bool,0,1*sizeof(bool));
nan_check_kernel<<<256,256>>>(d_ptr,rows,cols,d_temp_bool);
devSynchAll();
if(debug_ptr[0]) {
BZ_CUDA::logger << "NAN check failed\n";
return true;
}
cudaFree(d_temp_bool);
return false;
}
template<typename dType>
__global__
void zero_check(dType *d_mat, int size) {
for(int i=threadIdx.x + blockIdx.x*blockDim.x; i<size; i+=gridDim.x*blockDim.x) {
assert(d_mat[i]==0);
}
}
template<typename dType>
__global__
void check_nonseg(dType *d_ptr,int rows,int cols) {
}
void printIntroMessage(global_params ¶ms) {
if(params.train) {
BZ_CUDA::logger << "\n\n------------------------Train Info------------------------\n";
BZ_CUDA::logger << "Minibatch Size: " << params.minibatch_size << "\n";
BZ_CUDA::logger << "Number of Epochs: " << params.num_epochs << "\n";
BZ_CUDA::logger << "Learning Rate: " << params.learning_rate << "\n";
if(params.clip_gradient) {
BZ_CUDA::logger << "Gradient Clipping Threshold per matrix (Norm Ball): " << params.norm_clip << "\n";
}
if(params.individual_grad_clip) {
BZ_CUDA::logger << "Gradient Clipping Threshold per element: " << params.ind_norm_clip_thres << "\n";
}
if(params.truncated_softmax) {
BZ_CUDA::logger << "-------------------Truncated softmax info----------------------\n";
BZ_CUDA::logger << "Shortlist Size: " << params.shortlist_size << "\n";
BZ_CUDA::logger << "Sampled Size: " << params.sampled_size << "\n";
BZ_CUDA::logger << "---------------------------------------------------------------\n\n";
}
}
BZ_CUDA::logger << "------------------------Model Info------------------------\n";
if(params.LM) {
BZ_CUDA::logger << "Sequence model\n";
}
else {
BZ_CUDA::logger << "Sequence to sequence model\n";
}
BZ_CUDA::logger << "Source Vocab Size: " << params.source_vocab_size << "\n";
BZ_CUDA::logger << "Target Vocab Size: " << params.target_vocab_size << "\n";
BZ_CUDA::logger << "Number of Hidden Units: " << params.LSTM_size << "\n";
BZ_CUDA::logger << "Number of Layers: " << params.num_layers << "\n";
if(params.attent_params.attention_model) {
BZ_CUDA::logger << "Attention model set as true\n";
BZ_CUDA::logger << "D = " << params.attent_params.D << "\n";
if(params.attent_params.feed_input) {
BZ_CUDA::logger << "Feed Input set as true\n";
}
}
if(params.unk_replace) {
BZ_CUDA::logger << "UNK replace is set to true\n";
}
if(params.NCE) {
BZ_CUDA::logger << "Using NCE objective\n";
BZ_CUDA::logger << "Number of noise samples for NCE: " << params.num_negative_samples << "\n";
}
else {
BZ_CUDA::logger << "Using MLE objective\n";
}
BZ_CUDA::logger << "---------------------------------------------------------------\n\n";
if(params.decode) {
BZ_CUDA::logger << "------------------------Decode Info------------------------\n";
BZ_CUDA::logger << "Beam size for kbest: " << params.beam_size << "\n";
BZ_CUDA::logger << "Number of paths for kbest: " << params.num_hypotheses << "\n";
BZ_CUDA::logger << "------------------------------------------------------------\n\n";
}
// if(stochastic_generation) {
// BZ_CUDA::logger << "------------------------Stoch Generation Info------------------------\n";
// BZ_CUDA::logger << "Number of tokens for stoch generation: " << sg_length << "\n";
// BZ_CUDA::logger << "Stoch generation temperature: " << temperature << "\n";
// BZ_CUDA::logger << "------------------------------------------------------------\n\n";
// }
//BZ_CUDA::logger << "Number of Lines in Training File: " << train_num_lines_in_file << "\n";
BZ_CUDA::logger << "\n\n";
}
#endif
|
TitanComing/small-spring | small-spring-all/src/main/java/peng/springframework/context/ApplicationContext.java | <gh_stars>0
package peng.springframework.context;
import peng.springframework.beans.factory.HierarchicalBeanFactory;
import peng.springframework.beans.factory.ListableBeanFactory;
import peng.springframework.core.io.ResourceLoader;
/**
* Create by peng on 2021/09/18.
* spring中的应用上下文
* 通过这个应用上下文,封装了bean对象的定义的读取,注册,实例化,同时预留了注册、实例化前后的修改
* 继承了bean工厂的方法
* 这个接口的子类提供给用户使用
*/
public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, ResourceLoader, ApplicationEventPublisher {
}
|
TeamNuev/Nuev | src/ga/nullcraft/global/mod/loader/ILocalModLoader.java | package ga.nullcraft.global.mod.loader;
public interface ILocalModLoader extends IModLoader {
}
|
davelaursen/idealogue | angular1-node-hapi-mongodb/src/client/app/app.bootstrap.js | (function() {
'use strict';
// This file manually bootstraps the Angular application
var injector, dataService, util, config, sessionStorageService;
// inject whatever services are needed
injector = angular.injector(['ng', 'blocks.data', 'blocks.util', 'blocks.storage', 'app.config']);
dataService = injector.get('dataService');
util = injector.get('util');
config = injector.get('config');
sessionStorageService = injector.get('sessionStorageService');
// load the currently logged in user from the server, then start the Angular application
dataService.get(util.pathJoin([config.apiBaseUrl, 'currentuser']))
.then(function(res) {
sessionStorageService.setItem('CurrentUser', res.data);
})
.catch(function() {
sessionStorageService.removeItem('CurrentUser');
})
.finally(function() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
});
})();
|
stub-idp/verify-stub-idp | sp/matching-service-adapter/src/test/java/uk/gov/ida/matchingserviceadapter/configuration/DefaultTrustStoreConfigurationTest.java | <gh_stars>0
package uk.gov.ida.matchingserviceadapter.configuration;
import org.junit.jupiter.api.Test;
import java.security.KeyStoreException;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultTrustStoreConfigurationTest {
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForIntegrationHub() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.INTEGRATION.getTrustStoreName(TrustStoreType.HUB)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("test-root-ca");
assertThat(aliases).contains("test-hub-ca");
}
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForIntegrationIdp() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.INTEGRATION.getTrustStoreName(TrustStoreType.IDP)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("test-root-ca");
assertThat(aliases).contains("test-idp-ca");
}
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForIntegrationMetadata() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.INTEGRATION.getTrustStoreName(TrustStoreType.METADATA)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("test-root-ca");
assertThat(aliases).contains("metadata-ca");
}
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForProductionHub() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.PRODUCTION.getTrustStoreName(TrustStoreType.HUB)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("root-ca");
assertThat(aliases).contains("hub-ca");
}
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForProductionIdp() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.PRODUCTION.getTrustStoreName(TrustStoreType.IDP)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("root-ca");
assertThat(aliases).contains("idp-ca");
}
@Test
public void getTrustStoreShouldReturnCorrectTrustStoreForProductionMetadata() throws KeyStoreException {
DefaultTrustStoreConfiguration defaultIntegrationHubTrustStore = new DefaultTrustStoreConfiguration(
MatchingServiceAdapterEnvironment.PRODUCTION.getTrustStoreName(TrustStoreType.METADATA)
);
List<String> aliases = Collections.list(defaultIntegrationHubTrustStore.getTrustStore().aliases());
assertThat(aliases).contains("root-ca");
assertThat(aliases).contains("metadata-ca");
}
}
|
dice-group/metall | include/metall/metall.hpp | // Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
#ifndef METALL_METALL_HPP
#define METALL_METALL_HPP
#include <metall/basic_manager.hpp>
#include <metall/logger.hpp>
#include <metall/version.hpp>
/// \namespace metall
/// \brief The top level of namespace of Metall
namespace metall {
/// \brief Default Metall manager class which is an alias of basic_manager with the default template parameters.
using manager = basic_manager<>;
} // namespace metall
/// \example complex_map.cpp
/// This is an example of how to use a complex STL map container with Metall.
/// \example multilevel_containers.cpp
/// This is an example of how to use a multi-level STL container with Metall.
/// \example simple.cpp
/// This is a simple example of how to use Metall.
/// \example snapshot.cpp
/// This is an example of how to use the snapshot capabilities in Metall.
/// \example string.cpp
/// This is an example of how to use the STL string with Metall.
/// \example string_map.cpp
/// This is an example of how to use a STL map container of which key is STL string.
/// \example vector_of_vectors.cpp
/// This is an example of how to use a multi-level STL container, a vector of vectors, with Metall.
/// \example adjacency_list_graph.cpp
/// This is an example of how to use a adjacency-list graph data structure with Metall.
/// \example csr_graph.cpp
/// This is an example of how to use a CSR graph data structure with Metall.
/// \example datastore_description.cpp
/// This is an example of how to set and get datastore description.
/// \example object_attribute.cpp
/// This is an example of how to access object attributes.
/// \example object_attribute_api_list.cpp
/// This is an example of how to use all API related to object attributes.
/// \example metall_containers.cpp
/// This is an example of how to use Metall containers.
#endif //METALL_METALL_HPP
|
calmsacibis995/minix | minix/servers/vm/regionavl_defs.h | #include <minix/u64.h>
#define AVL_UNIQUE(id) region_ ## id
#define AVL_HANDLE region_t *
#define AVL_KEY vir_bytes
#define AVL_MAX_DEPTH 30 /* good for 2 million nodes */
#define AVL_NULL NULL
#define AVL_GET_LESS(h, a) (h)->lower
#define AVL_GET_GREATER(h, a) (h)->higher
#define AVL_SET_LESS(h1, h2) USE((h1), (h1)->lower = h2;);
#define AVL_SET_GREATER(h1, h2) USE((h1), (h1)->higher = h2;);
#define AVL_GET_BALANCE_FACTOR(h) (h)->factor
#define AVL_SET_BALANCE_FACTOR(h, f) USE((h), (h)->factor = f;);
#define AVL_SET_ROOT(h, v) (h)->root = v;
#define AVL_COMPARE_KEY_KEY(k1, k2) ((k1) > (k2) ? 1 : ((k1) < (k2) ? -1 : 0))
#define AVL_COMPARE_KEY_NODE(k, h) AVL_COMPARE_KEY_KEY((k), (h)->vaddr)
#define AVL_COMPARE_NODE_NODE(h1, h2) AVL_COMPARE_KEY_KEY((h1)->vaddr, (h2)->vaddr)
|
JeroenvdSande/dash-sample-apps | apps/dash-medical-provider-charges/Data-prep.py | import pandas as pd
import numpy as np
import pathlib
from uszipcode import SearchEngine
DATA_PATH = pathlib.Path(__file__, "/data").resolve()
all_data = DATA_PATH.joinpath(
"CMS_inpatient_2016_data/Inpatient_summary_2016_all/Medicare_Provider_Charge_Inpatient_DRGALL_FY2016.csv.gz"
)
# Read all
df = pd.read_csv(str(all_data)[1:], index_col=0, low_memory=False)
state = [
"AL",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DC",
"FL",
"GA",
"IL",
"IN",
"IA",
"KY",
"MD",
"MA",
"MI",
"MN",
"MO",
"NE",
"NJ",
"NY",
"NC",
"OH",
"OK",
"OR",
"PA",
"SC",
"TN",
"TX",
"UT",
"VA",
"WA",
"WI",
"AK",
"DE",
"HI",
"ID",
"KS",
"LA",
"ME",
"MS",
"MT",
"NV",
"NH",
"NM",
"ND",
"RI",
"SD",
"WV",
"VT",
"WY",
]
# Generate lat, lon from zip code
search = SearchEngine(
simple_zipcode=False
) # set simple_zipcode=False to use rich info database
def generate_lat_lon(df):
df["lat"] = df["lon"] = np.nan
zip_code = df["Provider Zip Code"]
for ind, item in enumerate(zip_code):
zipcode = search.by_zipcode(str(item))
zip = zipcode.to_dict()
df.loc[ind, "lat"] = zip["lat"]
df.loc[ind, "lon"] = zip["lng"]
return df
# Replace charges dtype as numeric
metric_list = [
"Average Covered Charges",
"Average Total Payments",
"Average Medicare Payments",
]
for state_name in state:
state_data = df[df["Provider State"] == state_name].reset_index()
state_lat_lon = generate_lat_lon(state_data).dropna()
for metric in metric_list:
state_lat_lon[metric] = state_lat_lon[metric].apply(
lambda x: x.replace("$", "")
)
state_lat_lon[metric] = state_lat_lon[metric].apply(
lambda x: float(x.split()[0].replace(",", ""))
)
state_lat_lon.to_csv("df_{}_lat_lon.csv".format(state_name), index=False)
|
BeryJu/passbook | authentik/core/expression.py | """Property Mapping Evaluator"""
from traceback import format_tb
from typing import Optional
from django.http import HttpRequest
from guardian.utils import get_anonymous_user
from authentik.core.models import PropertyMapping, User
from authentik.events.models import Event, EventAction
from authentik.lib.expression.evaluator import BaseEvaluator
from authentik.policies.types import PolicyRequest
class PropertyMappingEvaluator(BaseEvaluator):
"""Custom Evalautor that adds some different context variables."""
def set_context(
self,
user: Optional[User],
request: Optional[HttpRequest],
mapping: PropertyMapping,
**kwargs,
):
"""Update context with context from PropertyMapping's evaluate"""
req = PolicyRequest(user=get_anonymous_user())
req.obj = mapping
if user:
req.user = user
self._context["user"] = user
if request:
req.http_request = request
self._context["request"] = req
self._context.update(**kwargs)
def handle_error(self, exc: Exception, expression_source: str):
"""Exception Handler"""
error_string = "\n".join(format_tb(exc.__traceback__) + [str(exc)])
event = Event.new(
EventAction.PROPERTY_MAPPING_EXCEPTION,
expression=expression_source,
message=error_string,
)
if "request" in self._context:
req: PolicyRequest = self._context["request"]
event.from_http(req.http_request, req.user)
return
event.save()
|
Srikrishna31/OpenJDKSwingBugs | src/SliderDemo.java | <gh_stars>0
/*
JDK-7124293
*/
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SliderDemo extends JFrame{
public SliderDemo() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) throws Exception {
SliderDemo frame=new SliderDemo();
SwingUtilities.invokeAndWait(() -> {
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
|
jeikabu/lumberyard | dev/Code/Tools/Woodpecker/Woodpecker/ProfilerApplication.cpp | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "stdafx.h"
#include "ProfilerApplication.h"
#include <Woodpecker/Driller/DrillerContext.h>
#include <AzFramework/TargetManagement/TargetManagementComponent.h>
namespace Driller
{
void Application::RegisterCoreComponents()
{
Woodpecker::BaseApplication::RegisterCoreComponents();
Driller::Context::CreateDescriptor();
RegisterComponentDescriptor(AzFramework::TargetManagementComponent::CreateDescriptor());
}
void Application::CreateApplicationComponents()
{
Woodpecker::BaseApplication::CreateApplicationComponents();
EnsureComponentCreated(Driller::Context::RTTI_Type());
EnsureComponentCreated(AzFramework::TargetManagementComponent::RTTI_Type());
}
} |
cedadev/cows | cows/service/imps/geoplot_wms_backend/slabs/slab_contour.py | <filename>cows/service/imps/geoplot_wms_backend/slabs/slab_contour.py
# BSD Licence
# Copyright (c) 2010, Science & Technology Facilities Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution of this software for
# the full license text.
import logging
import time
import numpy
import geoplot.colour_bar
from geoplot.layer_drawer_contour import LayerDrawerContour
from cows.service.imps.geoplot_wms_backend.slabs.slab_base import SlabBase
from cows.service.imps.geoplot_wms_backend.slab_options_parser import SlabOptionsParser
from cows.service.imps.geoplot_wms_backend.rendering_option import RenderingOption
log = logging.getLogger(__name__)
class SlabContour(SlabBase):
style = 'contour'
title = 'Contour Lines'
renderingOptions = SlabBase.renderingOptions + [
RenderingOption('num_contour_lines', "Number of Contour Lines" ,int,10),
RenderingOption('contour_font_size', "Contour Label Size" ,str,'medium',["small","medium", "large",]),
RenderingOption('contour_label_interval', "Interval Between Labels" ,int,1),
RenderingOption('intervals', "Contour Lines" ,str, None),
]
def _setupLayerDrawer(self):
ld = LayerDrawerContour(self.variable,
cmap=self.parser.getOption('cmap'),
colourBarMin=self.parser.getOption('cmap_min'),
colourBarMax=self.parser.getOption('cmap_max'),
bgcolor = self.bgcolor,
colourBarScale = self.parser.getOption('cmap_scale'),
labelInterval= self.parser.getOption('contour_label_interval'),
numLines = self.parser.getOption('num_contour_lines'),
fontSize = self.parser.getOption('contour_font_size'),
intervals = self.parser.getOption('intervals'),
transparent=self.transparent)
return ld
@classmethod
def makeColourBar(cls, width , height, orientation, units, renderOpts, variable):
parser = SlabOptionsParser(SlabContour.renderingOptions, renderOpts)
minval = parser.getOption('cmap_min')
log.debug('setting minval as %s'%minval)
if minval == None:
minval = variable.min()
log.debug('setting minval as variable min%s'%minval)
maxval = parser.getOption('cmap_max')
log.debug('setting maxval as %s'%maxval)
if maxval == None:
maxval = variable.max()
log.debug('setting maxval as variable max%s'%maxval)
# can't have a colourbar with an infinite maximum, take the highest
# non-inf value.
if maxval == numpy.inf:
log.debug(' maxval equals numpy infinite')
maxval = numpy.ma.masked_equal(variable, numpy.inf).max()
log.debug('intervals %s'%repr(parser.getOption('intervals')))
# Check for non-default, but valid, colour map.
cls._setUpColourMap(renderOpts.get('cmap', None))
im = geoplot.colour_bar.getColourBarImage(width, height,
label='Units of measure: %s' % str(units),
cmap=parser.getOption('cmap'),
colourBarMin=minval,
colourBarMax=maxval,
colourBarScale=parser.getOption('cmap_scale'),
numIntervals=parser.getOption('num_contour_lines') - 1,
orientation=orientation,
intervals=parser.getOption('intervals'),
colourBarStyle='line',
)
return im
|
robcxyz/tackle-box | tackle/providers/git/hooks/meta.py | # -*- coding: utf-8 -*-
"""Meta hooks."""
from __future__ import unicode_literals
from __future__ import print_function
import pathlib
import os
import re
from rich import print
import logging
import subprocess
from collections import MutableMapping
from PyInquirer import prompt
from pydantic import BaseModel, ValidationError
from tackle.utils.context_manager import work_in
from tackle.models import BaseHook
from typing import Dict, Optional
logger = logging.getLogger(__name__)
class Repo(BaseModel):
"""Repo class for parsing dict inputs for repo."""
src: str
branch: Optional[str] = None
tag: Optional[str] = None
# https://stackoverflow.com/a/6027615/12642712
def flatten_repo_tree(d, parent_key=''):
"""Flatten a dict to so that keys become nodes in a path."""
items = []
for k, v in d.items():
new_key = os.path.join(parent_key, k)
try:
repo = Repo(**v)
except (ValidationError, TypeError):
repo = None
if repo:
items.append((new_key, v))
elif isinstance(v, MutableMapping):
items.extend(flatten_repo_tree(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
class MetaGitHook(BaseHook):
"""Hook to create meta repo.
:param command: Des...
"""
__slots__ = ('first_run',)
# Per https://github.com/samuelcolvin/pydantic/issues/655 for private vars
type: str = 'meta_repo'
command: str = None
repos: Dict = None
repo_tree: Dict = None
select: bool = True
base_url: str = "github.com"
protocol: str = "https"
git_org: str = None
base_dir: str = os.path.abspath(os.path.curdir)
repo_tree_overrides: list = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
object.__setattr__(self, 'first_run', True)
def get_repo_prefix(self, repo):
"""Return a string to prefix url."""
if repo.startswith("https") or repo.startswith("git"):
# Case where it is provided
return ""
if self.protocol == "https":
return f"https://{self.base_url}/"
if self.protocol == "ssh":
return f"git@{self.base_url}:"
def get_git_command(self, branch, repo, folder_name):
"""Build string to run git command."""
if not branch:
return (
f"git {self.command} {self.get_repo_prefix(repo)}{repo} {folder_name}"
)
else:
return (
f"git {self.command} {self.get_repo_prefix(repo)}{repo} "
f"{folder_name} -b {branch}"
)
def execute_git_command(self, branch, repo, folder_name):
"""Execute the git command."""
cmd = self.get_git_command(branch, repo, folder_name)
p = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
output, err = p.communicate()
if err:
print(f"{err} for repo='{repo}' in folder='{folder_name}'.")
def try_https_then_ssh(self, branch, repo, folder_name):
"""When running first git command, tries with https then falls back to ssh."""
try:
self.execute_git_command(branch, repo, folder_name)
object.__setattr__(self, 'first_run', False)
except Exception:
try:
self.protocol = "ssh"
self.execute_git_command(branch, repo, folder_name)
except Exception as e:
print(f"{e} for repo='{repo}' - Neither https or ssh works. Skipping.")
def run_git_command(self, repo, folder_name, branch=None):
"""Run the git command."""
if self.first_run:
self.try_https_then_ssh(branch, repo, folder_name)
self.execute_git_command(branch, repo, folder_name)
def update_repo_name(self, v):
"""Update the repo name."""
if re.compile(r"(https:\/\/[\w\.]+)|(git@[\w\.]+)").match(v):
return v
git_parts = v.split('/')
if len(git_parts) == 1:
if not self.git_org:
print(
f"No git org declared - only one item declared in {v}, "
f"must be in form org/repo for abbreviated declarations. Skipping."
)
return
else:
return f"{self.git_org}/{git_parts[0]}"
if len(git_parts) == 2:
return f"{git_parts[0]}/{git_parts[1]}"
else:
print(f"Malformed repo name '{v}' in '{self.key}' key. Skipping.")
def prompt_repo_choices(self):
"""Prompt the user to select which items to operate on."""
choices = [
{"name": f"{k} --> {v}", "checked": True} for k, v in self.repo_tree.items()
]
question = {
'type': 'checkbox',
'name': 'tmp',
'message': f"Which repos do you want to {self.command.split(' ')[0]}?",
'choices': choices,
}
repo_choices = prompt([question])['tmp']
self.repo_tree = {
k: v for k, v in self.repo_tree.items() if f"{k} --> {v}" in repo_choices
}
def get_command(self):
"""Get the git command to run."""
if not self.no_input:
git_commands = [
'<custom input>',
'clone',
'pull',
'branch',
]
question = {
'type': 'list',
'name': 'tmp',
'message': "What to do?",
'choices': git_commands,
}
self.command = prompt([question])['tmp']
# Extra input
if self.command == '<custom input>':
message = "Enter git command: "
question = {
'type': 'input',
'name': 'tmp',
'message': message,
}
self.command = prompt([question])['tmp']
if self.command == 'branch':
message = "Enter git branch: "
question = {
'type': 'input',
'name': 'tmp',
'message': message,
}
self.command = "branch " + prompt([question])['tmp']
else:
print(
f"No command given in mete_hook for key = {self.key}. "
f"Defaults to clone."
)
self.command = 'clone'
def execute(self):
"""Run the hook."""
if not self.command:
self.get_command()
# Flatten the repo tree = `{k1: {k2: v}}` -> `[{k1/k2: v}]` where `k1/k2`
# is the path to operate (ie clone, etc) on the repo object `v` that can be
# a string or dict
if self.repo_tree:
self.repo_tree = flatten_repo_tree(self.repo_tree)
# Select is a bool that can override whether to prompt (basically
if self.select and not self.no_input:
self.prompt_repo_choices()
# Parse flattened repo tree from above
for k, v in self.repo_tree.items():
# Create dir to base path if it does not exist
path, folder_name = os.path.split(k)
if not os.path.isdir(path):
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
# Handle string inputs
if isinstance(v, str):
v = self.update_repo_name(v)
if path != "":
with work_in(path):
self.run_git_command(v, folder_name)
else:
self.run_git_command(v, folder_name)
if isinstance(v, dict):
r = Repo(**v)
r.src = self.update_repo_name(r.src)
if path != "":
with work_in(path):
self.run_git_command(r.src, folder_name, r.branch)
else:
self.run_git_command(r.src, folder_name, r.branch)
|
mengshijian/weixin-popular | src/main/java/com/cootf/wechat/bean/datacube/getcardmembercardinfo/MemberCardInfoResult.java | <reponame>mengshijian/weixin-popular
package com.cootf.wechat.bean.datacube.getcardmembercardinfo;
import java.util.List;
import com.cootf.wechat.bean.BaseResult;
/**
* 拉取会员卡数据接口-响应对象
*
* @author Moyq5
*
*/
public class MemberCardInfoResult extends BaseResult {
List<MemberCardInfoResultInfo> list;
public List<MemberCardInfoResultInfo> getList() {
return list;
}
public void setList(List<MemberCardInfoResultInfo> list) {
this.list = list;
}
}
|
lechium/tvOS130Headers | System/Library/PrivateFrameworks/ActionKit.framework/WFEvernoteTagsTagFieldParameter.h | <reponame>lechium/tvOS130Headers
/*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:38:36 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/ActionKit.framework/ActionKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <WorkflowKit/WFDynamicTagFieldParameter.h>
#import <ActionKit/WFDynamicTagFieldDataSource.h>
@class WFEvernoteAccessResource, NSString;
@interface WFEvernoteTagsTagFieldParameter : WFDynamicTagFieldParameter <WFDynamicTagFieldDataSource> {
WFEvernoteAccessResource* _evernoteAccessResource;
}
@property (nonatomic,retain) WFEvernoteAccessResource * evernoteAccessResource; //@synthesize evernoteAccessResource=_evernoteAccessResource - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(id)referencedActionResourceClasses;
-(void)wasAddedToWorkflow;
-(id)suggestedTagsForTagField:(id)arg1 ;
-(void)setActionResources:(id)arg1 ;
-(void)setEvernoteAccessResource:(WFEvernoteAccessResource *)arg1 ;
-(void)updateTags;
-(WFEvernoteAccessResource *)evernoteAccessResource;
@end
|
highfestiva/life | trabantsim/prototypes/snake.py | <reponame>highfestiva/life<gh_stars>1-10
#!/usr/bin/env python3
# Snake prototype.
from trabant import *
cam(distance=60)
pos = vec3()
step = vec3(1,0,0)
block = lambda p: create_box(p, side=0.7, static=True)
blocks,snake_coords = [block(pos)],[pos]
length = 5
while loop(delay=0.2): # Slow down snake.
# Steering.
move = vec3(keydir().x,0,keydir().y)
move += tapdir(pos, digital_direction=True)
if move.x or move.z:
step = move
pos += step
# Check if colliding with self.
if pos in snake_coords: # Collide with block?
explode(pos)
while blocks: # Eat up snake from back to front.
blocks[-1].release()
blocks,snake_coords = blocks[:-1],snake_coords[:-1]
sleep(0.05)
length = 5
# Move one block forward.
blocks = [block(pos)] + blocks
snake_coords = [pos] + snake_coords
if len(snake_coords) >= length: # Remove last block when moving forward.
blocks[-1].release()
blocks,snake_coords = blocks[:-1],snake_coords[:-1]
if timeout(1): # Every second the snake gets longer.
length += 1
|
eltonsrc/biblioteca | biblioteca-webservice/src/main/java/br/org/am/biblioteca/index/elasticsearch/ElasticSearchEngine.java | package br.org.am.biblioteca.index.elasticsearch;
import java.net.InetAddress;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Component;
import br.org.am.biblioteca.index.IndexException;
import br.org.am.biblioteca.index.interfaces.DocumentoSearchResponse;
import br.org.am.biblioteca.index.interfaces.IndexEngine;
import br.org.am.biblioteca.model.Documento;
import br.org.am.biblioteca.rest.json.View;
@Component
class ElasticSearchEngine implements IndexEngine {
private static final Logger logger = LogManager.getLogger(ElasticSearchEngine.class);
private static final String CLUSTER_NAME = "biblioteca";
private static final String INDEX_NAME = "documentos";
private static final String TYPE_NAME = "documento";
private Client client;
public void start() throws IndexException {
try {
Settings settings = Settings.settingsBuilder()
.put("cluster.name", CLUSTER_NAME).build();
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName("localhost"), 9300));
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
}
public void stop() throws IndexException {
try {
if (client != null) {
client.close();
}
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
}
public boolean indexDocumento(Documento documento) throws IndexException {
if (documento == null) {
logger.debug("documento inválido");
return false;
}
if (client == null) {
logger.debug("client não iniciado.");
return false;
}
ObjectMapper mapper = new ObjectMapper();
byte[] docJson = null;
try {
docJson = mapper.writerWithView(View.Public.class)
.writeValueAsBytes(documento);
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
IndexResponse indexResponse = client
.prepareIndex(INDEX_NAME, TYPE_NAME, documento.getId()).setSource(docJson)
.get();
if (indexResponse.isCreated()) {
logger.debug("documento criado.");
} else {
logger.debug("documento atualizado.");
}
return true;
}
public DocumentoSearchResponse searchDocumento(String query, int max, int offset,
String... fieldNames) throws IndexException {
if (client == null) {
logger.debug("client não iniciado.");
return null;
}
try {
SearchRequestBuilder srb = client.prepareSearch(INDEX_NAME)
.setTypes(TYPE_NAME).setFrom(offset).setSize(max);
if (query != null && !query.isEmpty()) {
srb.setQuery(QueryBuilders.multiMatchQuery(query, fieldNames));
}
final SearchResponse response = srb.execute().actionGet();
return new DocumentoSearchResponseElasticsearch(response);
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
}
public long getTotalDocIndexed() throws IndexException {
if (client == null) {
logger.debug("client não iniciado.");
throw new IndexException("client não iniciado.");
}
try {
CountResponse response = client.prepareCount(INDEX_NAME).execute()
.actionGet();
logger.debug(response);
return response.getCount();
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
}
@Override
public boolean removeDocumento(Documento documento) throws IndexException {
try {
DeleteResponse delete = client
.prepareDelete(INDEX_NAME, TYPE_NAME, documento.getId()).get();
return delete.isFound();
} catch (Exception e) {
throw new IndexException(e.getMessage(), e);
}
}
}
|
dominicprice/Graphy | include/Graphy/Graphables/DataSet.hpp | <filename>include/Graphy/Graphables/DataSet.hpp
/////////////////////////////////////////////////////////////////////////////////
//MIT License
//
//Copyright(c) 2017 <NAME>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
/////////////////////////////////////////////////////////////////////////////////
#ifndef GRAPHY_DATASET_H
#define GRAPHY_DATASET_H
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <Graphy/Graphables/Point.hpp>
#include <Graphy/Graphable.hpp>
#include <vector>
#include <Graphy/Graphables/Styles/LineStyle.hpp>
namespace graphy
{
////////////////////////////////////////////////////////////
/// \brief Graphable representing a data set
///
////////////////////////////////////////////////////////////
class DataSet : public Graphable
{
public:
typedef std::vector<Point>::iterator iterator; ///< Convenience typedef for pseudo-iterators pointing to data points
typedef std::vector<Point>::const_iterator const_iterator; ///< Convenience typedef for const psuedo-iterators pointing to data points
////////////////////////////////////////////////////////////
/// \brief Default Constructor
///
/// Constructs an empty data set
///
////////////////////////////////////////////////////////////
DataSet();
////////////////////////////////////////////////////////////
/// \brief Constructor
///
/// Constructs a data set containing the points in \a point_set
///
/// \param point_set Vector containing points in the data set
///
////////////////////////////////////////////////////////////
DataSet(std::vector<Point> point_set);
////////////////////////////////////////////////////////////
/// \brief Returns an iterator pointing to the first data point
///
////////////////////////////////////////////////////////////
iterator begin();
////////////////////////////////////////////////////////////
/// \brief Returns an iterator pointing to the first data point
///
////////////////////////////////////////////////////////////
const_iterator begin() const;
////////////////////////////////////////////////////////////
/// \brief Returns an iterator pointing past the last data point
///
////////////////////////////////////////////////////////////
iterator end();
////////////////////////////////////////////////////////////
/// \brief Returns an iterator pointing past the last data point
///
////////////////////////////////////////////////////////////
const_iterator end() const;
bool join; ///< When set to true data points will be connected by a line
LineStyle style; ///< Styling information for regression line
std::vector<Point> points; ///< Vector containing all the points in the data set
protected:
////////////////////////////////////////////////////////////
/// \brief Defines how the graphable is drawn to the graph
///
////////////////////////////////////////////////////////////
void draw();
};
} // namespace graphy
#endif //GRAPHY_DATASET_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.