code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*******************************
* 名称:详情
* 作者:rubbish.boy@163.com
*******************************
*/
//获取应用实例
var app = getApp()
var config={
//页面的初始数据
data: {
title : '名片介绍',
userInfo : {},
session_id :'',
requestlock :true,
domainName : app.globalData.domainName,
dataid :"",
infodata :{}
},
//生命周期函数--监听页面加载
onLoad: function (options) {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function(userInfo){
//更新数据
that.setData({
userInfo:userInfo
})
})
//异步获取缓存session_id
wx.getStorage({
key: 'session_id',
success: function(res) {
that.setData({
session_id:res.data
})
that.get_info(options.id);
}
})
that.setData({
dataid:options.id
})
},
//生命周期函数--监听页面初次渲染完成
onReady: function() {
// Do something when page ready.
},
//生命周期函数--监听页面显示
onShow: function() {
// Do something when page show.
if(this.data.requestlock==false)
{
this.get_info(this.data.dataid);
}
else
{
this.setData({
requestlock:false
})
}
},
//生命周期函数--监听页面隐藏
onHide: function() {
// Do something when page hide.
},
//生命周期函数--监听页面卸载
onUnload: function() {
// Do something when page close.
},
//页面相关事件处理函数--监听用户下拉动作
onPullDownRefresh: function() {
// Do something when pull down.
this.get_info(this.data.dataid,"onPullDownRefresh");
},
//页面上拉触底事件的处理函数
onReachBottom: function() {
// Do something when page reach bottom.
},
//导航处理函数
bindNavigateTo: function(action)
{
app.bindNavigateTo(action.target.dataset.action,action.target.dataset.params)
},
//页面打开导航处理函数
bindRedirectTo: function(action)
{
app.bindRedirectTo(action.target.dataset.action,action.target.dataset.params)
},
//跳转到 tabBar 页面
bindSwitchTo: function(action)
{
app.bindSwitchTo(action.target.dataset.action)
},
//获取详情数据
get_info: function(id,actionway="")
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,id:id}
app.action_loading();
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_businesscard_info,post_data,function(resback){
if(resback.status==1)
{
app.action_loading_hidden();
that.setData({
infodata:resback.resource
})
if(actionway=="onPullDownRefresh")
{
setTimeout(function(){
wx.stopPullDownRefresh()
},800)
}
}
else
{
app.action_loading_hidden();
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
},
//删除请求
del_action:function(action)
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,actiondata:action.target.dataset}
app.func.showModal("确定要执行删除?",function(resback){
if(resback.confirm)
{
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_del,post_data,function(resback){
if(resback.status==1)
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_success(msgdata);
}
else
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
}
else
{
var msgdata=new Object
msgdata.url=""
msgdata.msg="取消"
app.func.showToast_default(msgdata);
}
})
},
//拨号请求
makePhoneCall:function(action)
{
app.func.makePhoneCall(action.target.dataset.phoneNumber)
},
}
Page(config)
|
q1082121/xcx
|
pages/businessCard/view/view.js
|
JavaScript
|
mit
| 4,635
|
#ifndef CHILON_VARIANT_HPP
#define CHILON_VARIANT_HPP
#include <chilon/meta/at.hpp>
#include <chilon/meta/index_of.hpp>
#include <chilon/meta/max.hpp>
#include <chilon/meta/return.hpp>
#include <chilon/meta/void.hpp>
#include <chilon/meta/call_type.hpp>
#include <chilon/meta/contains.hpp>
#include <chilon/meta/require.hpp>
#include <chilon/singleton.hpp>
#include <chilon/hash.hpp>
#include <boost/ptr_container/ptr_array.hpp>
#include <utility>
#include <memory>
#include <assert.h>
namespace chilon {
/// Thrown when a variant is initalised from another variant which
/// current stores a type that the lhs variant cannot store.
struct invalid_variant_initalisation {};
/**
* @brief A simple variant which can store one of any of the types in
* T on the heap.
* @detailed When it is constructed the variant is empty by default.
* A verison of the variant that stores data on the stack can be
* enabled by defining CHILON_VARIANT_USES_STACK. This version
* can never be empty and constructs the first type when default
* constructed. This version is less convenient to use in places
* where only forward declarations of the variant types are
* available.
* @tparam T pack of valid types the variant may store.
*/
template <class... T>
struct variant {
enum { n_elements = sizeof...(T) };
#ifdef CHILON_VARIANT_USES_STACK
enum { max_size = meta::max<sizeof(T)...>::value };
#else
private:
struct copier {
template <class U> void operator()(U& v) const { v_ = v; }
void operator()() const { v_.set_empty(); }
copier(variant& v) : v_(v) {}
variant& v_;
};
struct comparator {
template <class U> bool operator()(U const& v) const {
return v == v_.at<U>();
}
bool operator()() const { return v_.empty(); }
comparator(variant const& v) : v_(v) {}
variant const& v_;
};
public:
bool operator==(variant const& rhs) const {
return type_index_ == rhs.type_index_ &&
variant_apply(rhs, comparator(*this));
};
bool operator!=(variant const& rhs) const {
return ! (*this == rhs);
};
template <class... U>
variant& operator=(variant<U...> const& rhs) {
variant_apply(rhs, copier(*this));
return *this;
}
variant& operator=(variant&& rhs) {
delete_if_not_empty();
data_ = rhs.data_;
type_index_ = rhs.type_index_;
rhs.data_ = 0;
return *this;
}
template <class V>
variant& operator=(std::auto_ptr<V>& rhs) {
int const new_index = meta::index_of<V, T...>::value;
static_assert(
new_index < n_elements, "type does not exist in variant");
delete_if_not_empty();
type_index_ = new_index;
data_ = rhs.release();
return *this;
}
template <class V>
variant& operator=(V const& rhs) {
int const new_index = meta::index_of<V, T...>::value;
static_assert(
new_index < n_elements, "type does not exist in variant");
#ifdef CHILON_VARIANT_USES_STACK
type_index_ = new_index;
cast<V>() = rhs;
#else
delete_if_not_empty();
type_index_ = new_index;
data_ = new V(rhs);
#endif
return *this;
}
template <class V>
V *release() {
int const index = meta::index_of<V, T...>::value;
static_assert(
index < n_elements, "type does not exist in variant");
assert(type_index_ == index);
V *data = static_cast<V *>(data_);
data_ = 0;
return data;
}
bool empty() const { return ! data_; }
void set_empty() {
if (! empty()) {
variant_apply(*this, deleter());
data_ = 0;
int const void_idx = meta::index_of<void, T...>::value;
if (void_idx < n_elements) type_index_ = void_idx;
}
}
private:
void delete_if_not_empty() {
if (! empty())
variant_apply(*this, deleter());
}
public:
#endif
typedef typename meta::head<T...>::type head_type;
/**
* Change variant to represent a default constructed V
*/
template <class V>
V& construct_default() {
int const new_index = meta::index_of<V, T...>::value;
static_assert(
new_index < n_elements, "type does not exist in variant");
#ifdef CHILON_VARIANT_USES_STACK
type_index_ = new_index;
return *new (data_) V;
#else
set_empty();
type_index_ = new_index;
data_ = new V();
return cast<V>();
#endif
}
template <class V, CHILON_REQUIRE(meta::is_void<V>)>
void construct_default() { set_empty(); }
/**
* Unsafe access to type at index I.
*/
template <int I>
typename meta::at<I, T...>::type& at() {
static_assert(I < n_elements, "index too high");
#ifndef NDEBUG
assert(type_index_ == I);
#endif
return cast<typename meta::at<I, T...>::type>();
}
/**
* Unsafe const access to type at index I.
*/
template <int I>
typename meta::at<I, T...>::type const& at() const {
static_assert(I < n_elements, "type not found in variant");
#ifndef NDEBUG
assert(type_index_ == I);
#endif
return cast<typename meta::at<I, T...>::type>();
}
template <int I,
CHILON_REQUIRE(meta::is_void<typename meta::at<I, T...>::type >) >
void at() const {};
template <class Y>
Y& at() {
return at<meta::index_of<Y, T...>::value>();
}
template <class Y>
Y const& at() const {
return at<meta::index_of<Y, T...>::value>();
}
template <class U>
bool is() const {
int const index = meta::index_of<U, T...>::value;
static_assert(index < n_elements, "type does not exist in variant");
return type_index_ == index;
}
int const type_index() const { return type_index_; }
private:
// unsafe casts
template <class Y>
Y const& cast() const {
return (*reinterpret_cast<Y const *>(data_));
}
template <class Y>
Y& cast() {
return (*reinterpret_cast<Y *>(data_));
}
public:
// default constructor constructs the first element in the tuple
#ifdef CHILON_VARIANT_USES_STACK
variant() : type_index_(0) {
new (data_) head_type;
}
private:
char data_[max_size];
#else
private:
struct initialiser {
template <class U>
void operator()(U const& v) const {
v_.data_ = new U(v);
}
void operator()() const {
v_.set_empty();
}
initialiser(variant& v) : v_(v) {}
protected:
variant& v_;
};
struct careful_initialiser : initialiser {
template <class U>
CHILON_RETURN_REQUIRE(void, meta::contains<U, T...>)
operator()(U const& v) const {
this->v_.type_index_ = meta::index_of<U, T...>::value;
initialiser::operator()(v);
}
template <class U>
CHILON_RETURN_NOT_REQUIRE(void, meta::contains<U, T...>)
operator()(U const& v) const {
throw invalid_variant_initalisation();
}
careful_initialiser(variant& v) : initialiser(v) {}
};
struct deleter {
template <class U> void operator()(U& v) const { delete &v; }
void operator()() const {}
};
public:
variant() : data_(0), type_index_(0) {
construct_default< typename meta::head<T...>::type >();
}
variant(variant const& rhs) : type_index_(rhs.type_index_) {
variant_apply(rhs, initialiser(*this));
}
variant(variant&& rhs)
: data_(rhs.data_), type_index_(rhs.type_index_)
{ rhs.data_ = 0; }
template <class U,
CHILON_REQUIRE_I(meta::index_of<U, T...>::value < n_elements)>
variant(U const& u)
: data_(new U(u)),
type_index_(meta::index_of<U, T...>::value)
{}
template <class U,
CHILON_REQUIRE_I(meta::index_of<U, T...>::value < n_elements)>
variant(U&& u)
: data_(new U(std::move(u))),
type_index_(meta::index_of<U, T...>::value)
{}
// TODO: check variant is not subvariant first, then handle
// it like a regular member type
template <class... U>
variant(variant<U...> const& rhs) {
variant_apply(rhs, careful_initialiser(*this));
}
~variant() { set_empty(); }
template <class U>
variant(std::auto_ptr<U>& rhs)
: type_index_(meta::index_of<U, T...>::value)
{
static_assert(
meta::index_of<U, T...>::value < n_elements,
"type does not exist in variant");
data_ = rhs.release();
}
protected:
void *data_;
#endif
int type_index_;
};
#if 0 && ! defined(CHILON_VARIANT_USES_STACK)
/**
* @brief If a void entry is used as the first entry in a variant, then
* the variant can be empty. The void entry is not considered part
* of the variant in the indexing system.
*/
template <class... T>
struct variant<void, T...> : variant<T...> {
typedef variant<T...> base_t;
template <class U>
variant<void, T...>& operator=(U&& rhs) {
base_t::operator=(std::move<U>(rhs));
}
variant() : base_t() {}
template <class U>
variant(U&& rhs) : base_t(std::forward<U>(rhs)) {}
};
#endif
namespace detail {
template <class T, class F>
struct variant_apply_helper {};
template <class F, class T>
struct variant_call_type;
template <class F, class... T>
struct variant_call_type<F, variant<T...> > :
meta::call_type_ref<F, typename meta::at<0, T...>::type> {};
template <class F, class... T>
struct variant_apply_lookup_table {
typedef variant<T...> type;
struct apply {
virtual typename variant_call_type<F, type>::type
operator()(type const& v, F const& f) =0;
virtual typename variant_call_type<F, type>::type
operator()(type& v, F const& f) =0;
};
boost::ptr_array<apply, type::n_elements> appliers_;
template <int I, class U>
struct apply_idx : apply {
virtual auto operator()(type const& v, F const& f)
CHILON_RETURN(f(v.template at<I>()))
virtual auto operator()(type& v, F const& f)
CHILON_RETURN(f(v.template at<I>()))
};
template <int I>
struct apply_idx<I, void> : apply {
virtual auto operator()(type const& v, F const& f)
CHILON_RETURN(f())
virtual auto operator()(type& v, F const& f)
CHILON_RETURN(f())
};
template <int I, int L>
struct create_applier {
static void exec(decltype(appliers_)& appliers) {
appliers.replace(
I,
new apply_idx<I, typename meta::at<I, T...>::type >()
);
create_applier<I + 1, L>::exec(appliers);
}
};
template <int I>
struct create_applier<I, I> {
static void exec(decltype(appliers_)& appliers) {}
};
variant_apply_lookup_table() {
create_applier<0, type::n_elements>::exec(appliers_);
}
};
template <class... T, class F>
struct variant_apply_helper< variant<T...>, F > {
typedef variant<T...> type;
inline static typename variant_call_type<F, type>::type
exec(type const& v, F const& f) {
return chilon::singleton<
variant_apply_lookup_table<F, T...>
>::instance().appliers_[v.type_index()](v, f);
}
inline static typename variant_call_type<F, type>::type
exec(type& v, F const& f) {
return chilon::singleton<
variant_apply_lookup_table<F, T...>
>::instance().appliers_[v.type_index()](v, f);
}
inline static typename variant_call_type<F, type>::type
exec(int const idx, type const& v, F const& f) {
return chilon::singleton<
variant_apply_lookup_table<F, T...>
>::instance().appliers_[idx](v, f);
}
inline static typename variant_call_type<F, type>::type
exec(int const idx, type& v, F const& f) {
return chilon::singleton<
variant_apply_lookup_table<F, T...>
>::instance().appliers_[idx](v, f);
}
};
}
template <class F, class T>
inline auto variant_apply(T& v, F const& f)
CHILON_RETURN(detail::variant_apply_helper<T, F>::exec(v, f))
template <class F, class T>
inline auto variant_apply(T const& v, F const& f)
CHILON_RETURN(detail::variant_apply_helper<T, F>::exec(v, f))
template <class F, class T>
inline auto variant_construct_apply(int const idx, T const& v, F const& f)
CHILON_RETURN(detail::variant_apply_helper<T, F>::exec(idx, v, f))
template <class F, class T>
inline auto variant_construct_apply(int const idx, T& v, F const& f)
CHILON_RETURN(detail::variant_apply_helper<T, F>::exec(idx, v, f))
template <class T, class... Y>
inline T& variant_as(variant<Y...>& v) {
return v.template at<T>();
}
template <class T, class... Y>
inline T& variant_as(variant<Y...> const& v) {
return v.template at<T>();
}
template <class T>
inline T& variant_as(T& v) { return v; }
template <class T>
inline T const& variant_as(T const& v) { return v; }
/**
* call construct_default on a variant.
*/
template <class T, class... Y>
inline void construct_default(variant<Y...>& v) {
v.template construct_default<T>();
}
/**
* construct_default on non-variant does nothing
*/
template <class T>
inline void construct_default(T const& v) {}
struct hash_variant {
size_t operator()() const { return 0; }
template <class T>
size_t operator()(T const& t) const { return chilon::hash(t); }
};
/**
* register with boost::hash
*/
template <class... T>
std::size_t inline hash_value(variant<T...> const& t) {
return variant_apply(t, hash_variant());
}
}
namespace std {
template <class... T>
struct hash<chilon::variant<T...>> {
std::size_t operator()(chilon::variant<T...> const& arg) const {
return chilon::hash_value(arg);
}
};
}
#endif
|
ohjames/chilon
|
variant.hpp
|
C++
|
mit
| 14,430
|
//
// EditorTools.cpp
// Editor
//
// Created by C218-pc on 15/7/14.
// Copyright (c) 2015年 Bullets in a Burning Box, Inc. All rights reserved.
//
#include "EditorTools.h"
#include <QPoint>
#include <QPointF>
#include <QSize>
#include <QSizeF>
#include <QList>
#include <QMap>
#include <QRect>
#include <QRectF>
#include <QVector2D>
#include <QVector3D>
#include <QVector4D>
#include <QColor>
namespace Editor
{
bool clone_value(rapidjson::Value & output, const rapidjson::Value & input, rapidjson::Value::AllocatorType & allocator)
{
if(&output == &input)
{
return false;
}
if(input.IsNull())
{
output.SetNull();
}
else if(input.IsInt64())
{
output.SetInt(input.GetInt64());
}
else if(input.IsInt())
{
output.SetInt(input.GetInt());
}
else if(input.IsDouble())
{
output.SetDouble(input.GetDouble());
}
else if(input.IsBool())
{
output.SetBool(input.GetBool());
}
else if(input.IsString())
{
output.SetString(input.GetString(), input.GetStringLength(), allocator);
}
else if(input.IsArray())
{
rapidjson::Value temp;
output.SetArray();
output.Reserve(input.Size(), allocator);
for(rapidjson::SizeType i = 0; i < input.Size(); ++i)
{
clone_value(temp, input[i], allocator);
output.PushBack(temp, allocator);
}
}
else if(input.IsObject())
{
output.SetObject();
rapidjson::Value key, val;
for(rapidjson::Value::ConstMemberIterator it = input.MemberBegin();
it != input.MemberEnd(); ++it)
{
clone_value(key, it->name, allocator);
clone_value(val, it->value, allocator);
output.AddMember(key, val, allocator);
}
}
else
{
assert(false && "shuldn't execute to here.");
return false;
}
return true;
}
void json2tvalue(QVariant & output, const rapidjson::Value & input, int itype)
{
if(input.IsNull())
{
output.clear();
}
else if(input.IsInt64())
{
output = QVariant(input.GetInt64());
}
else if(input.IsInt())
{
output = QVariant(input.GetInt());
}
else if(input.IsDouble())
{
output = QVariant(input.GetDouble());
}
else if(input.IsBool())
{
output = QVariant(input.GetBool());
}
else if(input.IsString())
{
output = QVariant(QString(input.GetString()));
}
else if(input.IsArray())
{
switch(itype)
{
case QVariant::Point:
{
assert(input.Size() == 2);
output = QPoint(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::PointF:
{
assert(input.Size() == 2);
output = QPointF(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Size:
{
assert(input.Size() == 2);
output = QSize(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::SizeF:
{
assert(input.Size() == 2);
output = QSizeF(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Rect:
{
assert(input.Size() == 4);
output = QRect(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::RectF:
{
assert(input.Size() == 4);
output = QRectF(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::Vector2D:
{
assert(input.Size() == 2);
output = QVector2D(input[0u].GetDouble(), input[1].GetDouble());
break;
}
case QVariant::Vector3D:
{
assert(input.Size() == 3);
output = QVector3D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble());
break;
}
case QVariant::Vector4D:
{
assert(input.Size() == 4);
output = QVector4D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::Color:
{
assert(input.Size() == 4);
output = QColor(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
break;
}
case QVariant::StringList:
{
QStringList list;
list.reserve(input.Size());
for(rapidjson::Value::ConstValueIterator it = input.Begin(); it != input.End(); ++it)
{
QString tmp(it->GetString());
list.append(tmp);
}
output = list;
break;
}
case QVariant::List:
default:
{
QList<QVariant> list;
list.reserve(input.Size());
for(rapidjson::SizeType i = 0; i < input.Size(); ++i)
{
QVariant tmp;
json2tvalue(tmp, input[i], QVariant::Invalid);
list.append(tmp);
}
output = list;
break;
}
}
}
else if(input.IsObject())
{
QMap<QString, QVariant> map;
for(rapidjson::Value::ConstMemberIterator it= input.MemberBegin();
it != input.MemberEnd(); ++it)
{
QString qstring(QLatin1String(it->name.GetString(), it->name.GetStringLength()));
QVariant qvalue;
json2tvalue(qvalue, it->value, QVariant::Invalid);
map.insert(qstring, qvalue);
}
output = map;
}
else
{
output.clear();
assert(false && "shouldn't execute to here.");
}
}
void tvalue2json(rapidjson::Value & output, const QVariant & input, rapidjson::Value::AllocatorType & allocator)
{
switch(input.type())
{
case QVariant::Invalid:
{
output.SetNull();
break;
}
case QVariant::Bool:
{
output.SetBool(input.toBool());
break;
}
case QVariant::Int:
{
output.SetInt64(input.toInt());
break;
}
case QVariant::LongLong:
{
output.SetInt64(input.toLongLong());
break;
}
case QVariant::Double:
{
output.SetDouble(input.toDouble());
break;
}
case QVariant::String:
{
QByteArray str = input.toString().toUtf8();
output.SetString(str.data(), str.size(), allocator);
break;
}
case QVariant::StringList:
{
QStringList list = input.toStringList();
output.SetArray();
output.Reserve(list.size(), allocator);
rapidjson::Value temp;
for(QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
{
QByteArray str = it->toUtf8();
temp.SetString(str.data(), str.size(), allocator);
output.PushBack(temp, allocator);
}
break;
}
case QVariant::List:
{
QList<QVariant> list = input.toList();
output.SetArray();
output.Reserve(list.size(), allocator);
rapidjson::Value temp;
for(QList<QVariant>::const_iterator it = list.begin(); it != list.end(); ++it)
{
tvalue2json(temp, *it, allocator);
output.PushBack(temp, allocator);
}
break;
}
case QVariant::Map:
{
output.SetObject();
rapidjson::Value tempK, tempV;
QMap<QString, QVariant> qmap = input.toMap();
for(QMap<QString, QVariant>::const_iterator it = qmap.begin(); it != qmap.end(); ++it)
{
tvalue2json(tempK, it.key(), allocator);
tvalue2json(tempV, it.value(), allocator);
output.AddMember(tempK, tempV, allocator);
}
break;
}
case QVariant::Point:
{
QPoint pt = input.toPoint();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
break;
}
case QVariant::PointF:
{
QPointF pt = input.toPointF();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
break;
}
case QVariant::Size:
{
QSize pt = input.toSize();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.width(), allocator);
output.PushBack(pt.height(), allocator);
break;
}
case QVariant::SizeF:
{
QSizeF pt = input.toSizeF();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.width(), allocator);
output.PushBack(pt.height(), allocator);
break;
}
case QVariant::Rect:
{
QRect pt = input.toRect();
output.SetArray();
output.Reserve(4, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
output.PushBack(pt.width(), allocator);
output.PushBack(pt.height(), allocator);
break;
}
case QVariant::RectF:
{
QRectF pt = input.toRectF();
output.SetArray();
output.Reserve(4, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
output.PushBack(pt.width(), allocator);
output.PushBack(pt.height(), allocator);
break;
}
case QVariant::Vector2D:
{
QVector2D pt = input.value<QVector2D>();
output.SetArray();
output.Reserve(2, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
break;
}
case QVariant::Vector3D:
{
QVector3D pt = input.value<QVector3D>();
output.SetArray();
output.Reserve(3, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
output.PushBack(pt.z(), allocator);
break;
}
case QVariant::Vector4D:
{
QVector4D pt = input.value<QVector4D>();
output.SetArray();
output.Reserve(4, allocator);
output.PushBack(pt.x(), allocator);
output.PushBack(pt.y(), allocator);
output.PushBack(pt.z(), allocator);
output.PushBack(pt.w(), allocator);
break;
}
case QVariant::Color:
{
QColor pt = input.value<QColor>();
output.SetArray();
output.Reserve(4, allocator);
output.PushBack(pt.red(), allocator);
output.PushBack(pt.green(), allocator);
output.PushBack(pt.blue(), allocator);
output.PushBack(pt.alpha(), allocator);
break;
}
default:
{
output.SetNull();
assert(false && "shuldn't execute to here.");
}
}
}
} // end namespace Editor
|
youlanhai/cc-qt-framework
|
Classes/editor/EditorTools.cpp
|
C++
|
mit
| 12,756
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.implementation;
import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.Delete;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.Patch;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Put;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.network.fluent.AzureFirewallsClient;
import com.azure.resourcemanager.network.fluent.models.AzureFirewallInner;
import com.azure.resourcemanager.network.models.AzureFirewallListResult;
import com.azure.resourcemanager.network.models.TagsObject;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsGet;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsListing;
import java.nio.ByteBuffer;
import java.util.Map;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in AzureFirewallsClient. */
public final class AzureFirewallsClientImpl
implements InnerSupportsGet<AzureFirewallInner>,
InnerSupportsListing<AzureFirewallInner>,
InnerSupportsDelete<Void>,
AzureFirewallsClient {
private final ClientLogger logger = new ClientLogger(AzureFirewallsClientImpl.class);
/** The proxy service used to perform REST calls. */
private final AzureFirewallsService service;
/** The service client containing this operation class. */
private final NetworkManagementClientImpl client;
/**
* Initializes an instance of AzureFirewallsClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
AzureFirewallsClientImpl(NetworkManagementClientImpl client) {
this.service =
RestProxy.create(AzureFirewallsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for NetworkManagementClientAzureFirewalls to be used by the proxy service
* to perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "NetworkManagementCli")
private interface AzureFirewallsService {
@Headers({"Accept: application/json;q=0.9", "Content-Type: application/json"})
@Delete(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/azureFirewalls/{azureFirewallName}")
@ExpectedResponses({200, 202, 204})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Flux<ByteBuffer>>> delete(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("azureFirewallName") String azureFirewallName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/azureFirewalls/{azureFirewallName}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallInner>> getByResourceGroup(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("azureFirewallName") String azureFirewallName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Put(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/azureFirewalls/{azureFirewallName}")
@ExpectedResponses({200, 201})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Flux<ByteBuffer>>> createOrUpdate(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("azureFirewallName") String azureFirewallName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@BodyParam("application/json") AzureFirewallInner parameters,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Patch(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/azureFirewalls/{azureFirewallName}")
@ExpectedResponses({200, 202})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Flux<ByteBuffer>>> updateTags(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("azureFirewallName") String azureFirewallName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@BodyParam("application/json") TagsObject parameters,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/azureFirewalls")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallListResult>> listByResourceGroup(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewalls")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallListResult>> list(
@HostParam("$host") String endpoint,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallListResult>> listNext(
@PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallListResult>> listAllNext(
@PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(
String resourceGroupName, String azureFirewallName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
return FluxUtil
.withContext(
context ->
service
.delete(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(
String resourceGroupName, String azureFirewallName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
context = this.client.mergeContext(context);
return service
.delete(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
context);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<PollResult<Void>, Void> beginDeleteAsync(String resourceGroupName, String azureFirewallName) {
Mono<Response<Flux<ByteBuffer>>> mono = deleteWithResponseAsync(resourceGroupName, azureFirewallName);
return this
.client
.<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, Context.NONE);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<Void>, Void> beginDeleteAsync(
String resourceGroupName, String azureFirewallName, Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono = deleteWithResponseAsync(resourceGroupName, azureFirewallName, context);
return this
.client
.<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, context);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String azureFirewallName) {
return beginDeleteAsync(resourceGroupName, azureFirewallName).getSyncPoller();
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String azureFirewallName, Context context) {
return beginDeleteAsync(resourceGroupName, azureFirewallName, context).getSyncPoller();
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAsync(String resourceGroupName, String azureFirewallName) {
return beginDeleteAsync(resourceGroupName, azureFirewallName)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Void> deleteAsync(String resourceGroupName, String azureFirewallName, Context context) {
return beginDeleteAsync(resourceGroupName, azureFirewallName, context)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String azureFirewallName) {
deleteAsync(resourceGroupName, azureFirewallName).block();
}
/**
* Deletes the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String azureFirewallName, Context context) {
deleteAsync(resourceGroupName, azureFirewallName, context).block();
}
/**
* Gets the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified Azure Firewall.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AzureFirewallInner>> getByResourceGroupWithResponseAsync(
String resourceGroupName, String azureFirewallName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
return FluxUtil
.withContext(
context ->
service
.getByResourceGroup(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified Azure Firewall.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<AzureFirewallInner>> getByResourceGroupWithResponseAsync(
String resourceGroupName, String azureFirewallName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
context = this.client.mergeContext(context);
return service
.getByResourceGroup(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
context);
}
/**
* Gets the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified Azure Firewall.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AzureFirewallInner> getByResourceGroupAsync(String resourceGroupName, String azureFirewallName) {
return getByResourceGroupWithResponseAsync(resourceGroupName, azureFirewallName)
.flatMap(
(Response<AzureFirewallInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified Azure Firewall.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner getByResourceGroup(String resourceGroupName, String azureFirewallName) {
return getByResourceGroupAsync(resourceGroupName, azureFirewallName).block();
}
/**
* Gets the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified Azure Firewall.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<AzureFirewallInner> getByResourceGroupWithResponse(
String resourceGroupName, String azureFirewallName, Context context) {
return getByResourceGroupWithResponseAsync(resourceGroupName, azureFirewallName, context).block();
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (parameters == null) {
return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
} else {
parameters.validate();
}
final String apiVersion = "2020-05-01";
return FluxUtil
.withContext(
context ->
service
.createOrUpdate(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
parameters,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (parameters == null) {
return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null."));
} else {
parameters.validate();
}
final String apiVersion = "2020-05-01";
context = this.client.mergeContext(context);
return service
.createOrUpdate(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
parameters,
context);
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<PollResult<AzureFirewallInner>, AzureFirewallInner> beginCreateOrUpdateAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) {
Mono<Response<Flux<ByteBuffer>>> mono =
createOrUpdateWithResponseAsync(resourceGroupName, azureFirewallName, parameters);
return this
.client
.<AzureFirewallInner, AzureFirewallInner>getLroResult(
mono, this.client.getHttpPipeline(), AzureFirewallInner.class, AzureFirewallInner.class, Context.NONE);
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<AzureFirewallInner>, AzureFirewallInner> beginCreateOrUpdateAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters, Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono =
createOrUpdateWithResponseAsync(resourceGroupName, azureFirewallName, parameters, context);
return this
.client
.<AzureFirewallInner, AzureFirewallInner>getLroResult(
mono, this.client.getHttpPipeline(), AzureFirewallInner.class, AzureFirewallInner.class, context);
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<AzureFirewallInner>, AzureFirewallInner> beginCreateOrUpdate(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) {
return beginCreateOrUpdateAsync(resourceGroupName, azureFirewallName, parameters).getSyncPoller();
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<AzureFirewallInner>, AzureFirewallInner> beginCreateOrUpdate(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters, Context context) {
return beginCreateOrUpdateAsync(resourceGroupName, azureFirewallName, parameters, context).getSyncPoller();
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AzureFirewallInner> createOrUpdateAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) {
return beginCreateOrUpdateAsync(resourceGroupName, azureFirewallName, parameters)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<AzureFirewallInner> createOrUpdateAsync(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters, Context context) {
return beginCreateOrUpdateAsync(resourceGroupName, azureFirewallName, parameters, context)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner createOrUpdate(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) {
return createOrUpdateAsync(resourceGroupName, azureFirewallName, parameters).block();
}
/**
* Creates or updates the specified Azure Firewall.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param parameters Azure Firewall resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner createOrUpdate(
String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters, Context context) {
return createOrUpdateAsync(resourceGroupName, azureFirewallName, parameters, context).block();
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Flux<ByteBuffer>>> updateTagsWithResponseAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
TagsObject parameters = new TagsObject();
parameters.withTags(tags);
return FluxUtil
.withContext(
context ->
service
.updateTags(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
parameters,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Flux<ByteBuffer>>> updateTagsWithResponseAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (azureFirewallName == null) {
return Mono
.error(new IllegalArgumentException("Parameter azureFirewallName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
TagsObject parameters = new TagsObject();
parameters.withTags(tags);
context = this.client.mergeContext(context);
return service
.updateTags(
this.client.getEndpoint(),
resourceGroupName,
azureFirewallName,
apiVersion,
this.client.getSubscriptionId(),
parameters,
context);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<PollResult<AzureFirewallInner>, AzureFirewallInner> beginUpdateTagsAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags) {
Mono<Response<Flux<ByteBuffer>>> mono = updateTagsWithResponseAsync(resourceGroupName, azureFirewallName, tags);
return this
.client
.<AzureFirewallInner, AzureFirewallInner>getLroResult(
mono, this.client.getHttpPipeline(), AzureFirewallInner.class, AzureFirewallInner.class, Context.NONE);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<AzureFirewallInner>, AzureFirewallInner> beginUpdateTagsAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags, Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono =
updateTagsWithResponseAsync(resourceGroupName, azureFirewallName, tags, context);
return this
.client
.<AzureFirewallInner, AzureFirewallInner>getLroResult(
mono, this.client.getHttpPipeline(), AzureFirewallInner.class, AzureFirewallInner.class, context);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<AzureFirewallInner>, AzureFirewallInner> beginUpdateTags(
String resourceGroupName, String azureFirewallName, Map<String, String> tags) {
return beginUpdateTagsAsync(resourceGroupName, azureFirewallName, tags).getSyncPoller();
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<AzureFirewallInner>, AzureFirewallInner> beginUpdateTags(
String resourceGroupName, String azureFirewallName, Map<String, String> tags, Context context) {
return beginUpdateTagsAsync(resourceGroupName, azureFirewallName, tags, context).getSyncPoller();
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AzureFirewallInner> updateTagsAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags) {
return beginUpdateTagsAsync(resourceGroupName, azureFirewallName, tags)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<AzureFirewallInner> updateTagsAsync(
String resourceGroupName, String azureFirewallName, Map<String, String> tags, Context context) {
return beginUpdateTagsAsync(resourceGroupName, azureFirewallName, tags, context)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AzureFirewallInner> updateTagsAsync(String resourceGroupName, String azureFirewallName) {
final Map<String, String> tags = null;
return beginUpdateTagsAsync(resourceGroupName, azureFirewallName, tags)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner updateTags(String resourceGroupName, String azureFirewallName, Map<String, String> tags) {
return updateTagsAsync(resourceGroupName, azureFirewallName, tags).block();
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner updateTags(
String resourceGroupName, String azureFirewallName, Map<String, String> tags, Context context) {
return updateTagsAsync(resourceGroupName, azureFirewallName, tags, context).block();
}
/**
* Updates tags of an Azure Firewall resource.
*
* @param resourceGroupName The name of the resource group.
* @param azureFirewallName The name of the Azure Firewall.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return azure Firewall resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public AzureFirewallInner updateTags(String resourceGroupName, String azureFirewallName) {
final Map<String, String> tags = null;
return updateTagsAsync(resourceGroupName, azureFirewallName, tags).block();
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listByResourceGroupSinglePageAsync(String resourceGroupName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
return FluxUtil
.withContext(
context ->
service
.listByResourceGroup(
this.client.getEndpoint(),
resourceGroupName,
apiVersion,
this.client.getSubscriptionId(),
context))
.<PagedResponse<AzureFirewallInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listByResourceGroupSinglePageAsync(
String resourceGroupName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
context = this.client.mergeContext(context);
return service
.listByResourceGroup(
this.client.getEndpoint(), resourceGroupName, apiVersion, this.client.getSubscriptionId(), context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AzureFirewallInner> listByResourceGroupAsync(String resourceGroupName) {
return new PagedFlux<>(
() -> listByResourceGroupSinglePageAsync(resourceGroupName), nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<AzureFirewallInner> listByResourceGroupAsync(String resourceGroupName, Context context) {
return new PagedFlux<>(
() -> listByResourceGroupSinglePageAsync(resourceGroupName, context),
nextLink -> listNextSinglePageAsync(nextLink, context));
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallInner> listByResourceGroup(String resourceGroupName) {
return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName));
}
/**
* Lists all Azure Firewalls in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallInner> listByResourceGroup(String resourceGroupName, Context context) {
return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context));
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listSinglePageAsync() {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
return FluxUtil
.withContext(
context ->
service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), context))
.<PagedResponse<AzureFirewallInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listSinglePageAsync(Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-05-01";
context = this.client.mergeContext(context);
return service
.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AzureFirewallInner> listAsync() {
return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listAllNextSinglePageAsync(nextLink));
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<AzureFirewallInner> listAsync(Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(context), nextLink -> listAllNextSinglePageAsync(nextLink, context));
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallInner> list() {
return new PagedIterable<>(listAsync());
}
/**
* Gets all the Azure Firewalls in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewalls in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallInner> list(Context context) {
return new PagedIterable<>(listAsync(context));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return FluxUtil
.withContext(context -> service.listNext(nextLink, context))
.<PagedResponse<AzureFirewallInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
context = this.client.mergeContext(context);
return service
.listNext(nextLink, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listAllNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return FluxUtil
.withContext(context -> service.listAllNext(nextLink, context))
.<PagedResponse<AzureFirewallInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewalls API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallInner>> listAllNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
context = this.client.mergeContext(context);
return service
.listAllNext(nextLink, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureFirewallsClientImpl.java
|
Java
|
mit
| 72,271
|
---
layout: post
title: Oracle SGA
date: 2017-03-18 18:28:58
categories:
- 数据库
tags:
- oracle
---
共享池(Shared Pool),共享池是SGA保留的区,用于存储如SQL、PL/SQL存储过程及包、数据字典、锁、字符集信息、安全属性等。
共享池是Oracle数据库的术语,是数据库实例(Instance)的内存中SGA的一部分,它具体包含如下部分:
库缓存(Library Cache)。该区存放有经过语法分析并且正确的SQL语句,并随时都准备被执行。具体包含:
共享SQL区(Shared Pool Area)
私有SQL区(Private SQL Area)
PL/SQL存储过程及包(PL/SQL Procedure and Package)
控制结构(Control Structure)
字典缓存(Dictionary Cache)
http://blog.csdn.net/haiross/article/details/10069071
```
select sql_text,VERSION_COUNT,INVALIDATIONS,PARSE_CALLS,OPTIMIZER_MODE,
PARSING_USER_ID,PARSING_SCHEMA_ID,ADDRESS,HASH_VALUE
from v$sqlarea where version_count >1000;
select count(*) from v$sqltext;
--命中率
select namespace,pins,pinhits,reloads,invalidations from v$librarycache order by namespace;
通过前面几节的研究我们知道,如果这个sql有7023个子指针,那么意味着这些子指针都将存在于同一个Bucket的链表上。那么这也就意味着,如果同样SQL再次执行,Oracle将不得不搜索这个链表以寻找可以共享的SQL。这将导致大量的library cache latch的竞争。
这时候我开始猜测原因:
1.可能代码存在问题,在每次执行之前程序修改某些session参数,导致sql不能共性
2.可能是8.1.5的v$sqlarea记录存在问题,我们看到的结果是假象:)
3.Bug
V$SQLAREA
本视图持续跟踪所有shared pool中的共享cursor,在shared pool中的每一条SQL语句都对应一列。本视图在分析SQL语句资源使用方面非常重要。
V$SQLAREA中的信息列
HASH_VALUE:SQL语句的Hash值。
ADDRESS:SQL语句在SGA中的地址。
这两列被用于鉴别SQL语句,有时,两条不同的语句可能hash值相同。这时候,必须连同ADDRESS一同使用来确认SQL语句。
PARSING_USER_ID:为语句解析第一条CURSOR的用户
VERSION_COUNT:语句cursor的数量
KEPT_VERSIONS:
SHARABLE_MEMORY:cursor使用的共享内存总数
PERSISTENT_MEMORY:cursor使用的常驻内存总数
RUNTIME_MEMORY:cursor使用的运行时内存总数。
SQL_TEXT:SQL语句的文本(最大只能保存该语句的前1000个字符)。
MODULE,ACTION:使用了DBMS_APPLICATION_INFO时session解析第一条cursor时的信息
V$SQLAREA中的其它常用列
SORTS: 语句的排序数
CPU_TIME: 语句被解析和执行的CPU时间
ELAPSED_TIME: 语句被解析和执行的共用时间
PARSE_CALLS: 语句的解析调用(软、硬)次数
EXECUTIONS: 语句的执行次数
INVALIDATIONS: 语句的cursor失效次数
LOADS: 语句载入(载出)数量
ROWS_PROCESSED: 语句返回的列总数
示例:
1.查看消耗资源最多的SQL:
Sql代码 收藏代码
SELECT hash_value, executions, buffer_gets, disk_reads, parse_calls
FROM V$SQLAREA
WHERE buffer_gets > 10000000 OR disk_reads > 1000000
ORDER BY buffer_gets + 100 * disk_reads DESC;
2.查看某条SQL语句的资源消耗:
Sql代码 收藏代码
SELECT hash_value, buffer_gets, disk_reads, executions, parse_calls
FROM V$SQLAREA
WHERE hash_Value = 228801498 AND address = hextoraw('CBD8E4B0');
查找前10条性能差的sql语句
Sql代码 收藏代码
SELECT * FROM (select PARSING_USER_ID,EXECUTIONS,SORTS,COMMAND_TYPE,DISK_READS,sql_text FROM v$sqlarea
order BY disk_reads DESC )where ROWNUM<10 ;
```
|
netgene/netgene.github.com
|
_posts/2017/2017-03-18-oracle-sga.md
|
Markdown
|
mit
| 3,734
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as Types from 'vs/base/common/types';
import { IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import * as Objects from 'vs/base/common/objects';
import { UriComponents } from 'vs/base/common/uri';
import { ProblemMatcher } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { TaskDefinitionRegistry } from 'vs/workbench/contrib/tasks/common/taskDefinitionRegistry';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
export const TASK_RUNNING_STATE = new RawContextKey<boolean>('taskRunning', false);
export enum ShellQuoting {
/**
* Use character escaping.
*/
Escape = 1,
/**
* Use strong quoting
*/
Strong = 2,
/**
* Use weak quoting.
*/
Weak = 3,
}
export const CUSTOMIZED_TASK_TYPE = '$customized';
export namespace ShellQuoting {
export function from(this: void, value: string): ShellQuoting {
if (!value) {
return ShellQuoting.Strong;
}
switch (value.toLowerCase()) {
case 'escape':
return ShellQuoting.Escape;
case 'strong':
return ShellQuoting.Strong;
case 'weak':
return ShellQuoting.Weak;
default:
return ShellQuoting.Strong;
}
}
}
export interface ShellQuotingOptions {
/**
* The character used to do character escaping.
*/
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
/**
* The character used for string quoting.
*/
strong?: string;
/**
* The character used for weak quoting.
*/
weak?: string;
}
export interface ShellConfiguration {
/**
* The shell executable.
*/
executable?: string;
/**
* The arguments to be passed to the shell executable.
*/
args?: string[];
/**
* Which kind of quotes the shell supports.
*/
quoting?: ShellQuotingOptions;
}
export interface CommandOptions {
/**
* The shell to use if the task is a shell command.
*/
shell?: ShellConfiguration;
/**
* The current working directory of the executed program or shell.
* If omitted VSCode's current workspace root is used.
*/
cwd?: string;
/**
* The environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: { [key: string]: string; };
}
export namespace CommandOptions {
export const defaults: CommandOptions = { cwd: '${workspaceFolder}' };
}
export enum RevealKind {
/**
* Always brings the terminal to front if the task is executed.
*/
Always = 1,
/**
* Only brings the terminal to front if a problem is detected executing the task
* e.g. the task couldn't be started,
* the task ended with an exit code other than zero,
* or the problem matcher found an error.
*/
Silent = 2,
/**
* The terminal never comes to front when the task is executed.
*/
Never = 3
}
export namespace RevealKind {
export function fromString(this: void, value: string): RevealKind {
switch (value.toLowerCase()) {
case 'always':
return RevealKind.Always;
case 'silent':
return RevealKind.Silent;
case 'never':
return RevealKind.Never;
default:
return RevealKind.Always;
}
}
}
export enum RevealProblemKind {
/**
* Never reveals the problems panel when this task is executed.
*/
Never = 1,
/**
* Only reveals the problems panel if a problem is found.
*/
OnProblem = 2,
/**
* Never reveals the problems panel when this task is executed.
*/
Always = 3
}
export namespace RevealProblemKind {
export function fromString(this: void, value: string): RevealProblemKind {
switch (value.toLowerCase()) {
case 'always':
return RevealProblemKind.Always;
case 'never':
return RevealProblemKind.Never;
case 'onproblem':
return RevealProblemKind.OnProblem;
default:
return RevealProblemKind.OnProblem;
}
}
}
export enum PanelKind {
/**
* Shares a panel with other tasks. This is the default.
*/
Shared = 1,
/**
* Uses a dedicated panel for this tasks. The panel is not
* shared with other tasks.
*/
Dedicated = 2,
/**
* Creates a new panel whenever this task is executed.
*/
New = 3
}
export namespace PanelKind {
export function fromString(value: string): PanelKind {
switch (value.toLowerCase()) {
case 'shared':
return PanelKind.Shared;
case 'dedicated':
return PanelKind.Dedicated;
case 'new':
return PanelKind.New;
default:
return PanelKind.Shared;
}
}
}
export interface PresentationOptions {
/**
* Controls whether the task output is reveal in the user interface.
* Defaults to `RevealKind.Always`.
*/
reveal: RevealKind;
/**
* Controls whether the problems pane is revealed when running this task or not.
* Defaults to `RevealProblemKind.Never`.
*/
revealProblems: RevealProblemKind;
/**
* Controls whether the command associated with the task is echoed
* in the user interface.
*/
echo: boolean;
/**
* Controls whether the panel showing the task output is taking focus.
*/
focus: boolean;
/**
* Controls if the task panel is used for this task only (dedicated),
* shared between tasks (shared) or if a new panel is created on
* every task execution (new). Defaults to `TaskInstanceKind.Shared`
*/
panel: PanelKind;
/**
* Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
*/
showReuseMessage: boolean;
/**
* Controls whether to clear the terminal before executing the task.
*/
clear: boolean;
/**
* Controls whether the task is executed in a specific terminal group using split panes.
*/
group?: string;
}
export namespace PresentationOptions {
export const defaults: PresentationOptions = {
echo: true, reveal: RevealKind.Always, revealProblems: RevealProblemKind.Never, focus: false, panel: PanelKind.Shared, showReuseMessage: true, clear: false
};
}
export enum RuntimeType {
Shell = 1,
Process = 2,
CustomExecution = 3,
CustomExecution2 = 4
}
export namespace RuntimeType {
export function fromString(value: string): RuntimeType {
switch (value.toLowerCase()) {
case 'shell':
return RuntimeType.Shell;
case 'process':
return RuntimeType.Process;
case 'customExecution':
return RuntimeType.CustomExecution;
case 'customExecution2':
return RuntimeType.CustomExecution2;
default:
return RuntimeType.Process;
}
}
}
export interface QuotedString {
value: string;
quoting: ShellQuoting;
}
export type CommandString = string | QuotedString;
export namespace CommandString {
export function value(value: CommandString): string {
if (Types.isString(value)) {
return value;
} else {
return value.value;
}
}
}
export interface CommandConfiguration {
/**
* The task type
*/
runtime?: RuntimeType;
/**
* The command to execute
*/
name?: CommandString;
/**
* Additional command options.
*/
options?: CommandOptions;
/**
* Command arguments.
*/
args?: CommandString[];
/**
* The task selector if needed.
*/
taskSelector?: string;
/**
* Whether to suppress the task name when merging global args
*
*/
suppressTaskName?: boolean;
/**
* Describes how the task is presented in the UI.
*/
presentation?: PresentationOptions;
}
export namespace TaskGroup {
export const Clean: 'clean' = 'clean';
export const Build: 'build' = 'build';
export const Rebuild: 'rebuild' = 'rebuild';
export const Test: 'test' = 'test';
export function is(value: string): value is string {
return value === Clean || value === Build || value === Rebuild || value === Test;
}
}
export type TaskGroup = 'clean' | 'build' | 'rebuild' | 'test';
export const enum TaskScope {
Global = 1,
Workspace = 2,
Folder = 3
}
export namespace TaskSourceKind {
export const Workspace: 'workspace' = 'workspace';
export const Extension: 'extension' = 'extension';
export const InMemory: 'inMemory' = 'inMemory';
}
export interface TaskSourceConfigElement {
workspaceFolder: IWorkspaceFolder;
file: string;
index: number;
element: any;
}
interface BaseTaskSource {
readonly kind: string;
readonly label: string;
}
export interface WorkspaceTaskSource extends BaseTaskSource {
readonly kind: 'workspace';
readonly config: TaskSourceConfigElement;
readonly customizes?: KeyedTaskIdentifier;
}
export interface ExtensionTaskSource extends BaseTaskSource {
readonly kind: 'extension';
readonly extension?: string;
readonly scope: TaskScope;
readonly workspaceFolder: IWorkspaceFolder | undefined;
}
export interface ExtensionTaskSourceTransfer {
__workspaceFolder: UriComponents;
__definition: { type: string;[name: string]: any };
}
export interface InMemoryTaskSource extends BaseTaskSource {
readonly kind: 'inMemory';
}
export type TaskSource = WorkspaceTaskSource | ExtensionTaskSource | InMemoryTaskSource;
export interface TaskIdentifier {
type: string;
[name: string]: any;
}
export interface KeyedTaskIdentifier extends TaskIdentifier {
_key: string;
}
export interface TaskDependency {
workspaceFolder: IWorkspaceFolder;
task: string | KeyedTaskIdentifier | undefined;
}
export const enum GroupType {
default = 'default',
user = 'user'
}
export const enum DependsOrder {
parallel = 'parallel',
sequence = 'sequence'
}
export interface ConfigurationProperties {
/**
* The task's name
*/
name?: string;
/**
* The task's name
*/
identifier?: string;
/**
* the task's group;
*/
group?: string;
/**
* The group type
*/
groupType?: GroupType;
/**
* The presentation options
*/
presentation?: PresentationOptions;
/**
* The command options;
*/
options?: CommandOptions;
/**
* Whether the task is a background task or not.
*/
isBackground?: boolean;
/**
* Whether the task should prompt on close for confirmation if running.
*/
promptOnClose?: boolean;
/**
* The other tasks this task depends on.
*/
dependsOn?: TaskDependency[];
/**
* The order the dependsOn tasks should be executed in.
*/
dependsOrder?: DependsOrder;
/**
* The problem watchers to use for this task
*/
problemMatchers?: Array<string | ProblemMatcher>;
}
export enum RunOnOptions {
default = 1,
folderOpen = 2
}
export interface RunOptions {
reevaluateOnRerun?: boolean;
runOn?: RunOnOptions;
}
export namespace RunOptions {
export const defaults: RunOptions = { reevaluateOnRerun: true, runOn: RunOnOptions.default };
}
export abstract class CommonTask {
/**
* The task's internal id
*/
_id: string;
/**
* The cached label.
*/
_label: string;
type?: string;
runOptions: RunOptions;
configurationProperties: ConfigurationProperties;
_source: BaseTaskSource;
private _taskLoadMessages: string[] | undefined;
protected constructor(id: string, label: string | undefined, type: string | undefined, runOptions: RunOptions,
configurationProperties: ConfigurationProperties, source: BaseTaskSource) {
this._id = id;
if (label) {
this._label = label;
}
if (type) {
this.type = type;
}
this.runOptions = runOptions;
this.configurationProperties = configurationProperties;
this._source = source;
}
public getDefinition(useSource?: boolean): KeyedTaskIdentifier | undefined {
return undefined;
}
public getMapKey(): string {
return this._id;
}
public getRecentlyUsedKey(): string | undefined {
return undefined;
}
public clone(): Task {
return this.fromObject(Objects.assign({}, <any>this));
}
protected abstract fromObject(object: any): Task;
public getWorkspaceFolder(): IWorkspaceFolder | undefined {
return undefined;
}
public getTelemetryKind(): string {
return 'unknown';
}
public matches(key: string | KeyedTaskIdentifier | undefined, compareId: boolean = false): boolean {
if (key === undefined) {
return false;
}
if (Types.isString(key)) {
return key === this._label || key === this.configurationProperties.identifier || (compareId && key === this._id);
}
let identifier = this.getDefinition(true);
return identifier !== undefined && identifier._key === key._key;
}
public getQualifiedLabel(): string {
let workspaceFolder = this.getWorkspaceFolder();
if (workspaceFolder) {
return `${this._label} (${workspaceFolder.name})`;
} else {
return this._label;
}
}
public getTaskExecution(): TaskExecution {
let result: TaskExecution = {
id: this._id,
task: <any>this
};
return result;
}
public addTaskLoadMessages(messages: string[] | undefined) {
if (this._taskLoadMessages === undefined) {
this._taskLoadMessages = [];
}
if (messages) {
this._taskLoadMessages = this._taskLoadMessages.concat(messages);
}
}
get taskLoadMessages(): string[] | undefined {
return this._taskLoadMessages;
}
}
export class CustomTask extends CommonTask {
type: '$customized'; // CUSTOMIZED_TASK_TYPE
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
_source: WorkspaceTaskSource;
hasDefinedMatchers: boolean;
/**
* The command configuration
*/
command: CommandConfiguration;
public constructor(id: string, source: WorkspaceTaskSource, label: string, type: string, command: CommandConfiguration | undefined,
hasDefinedMatchers: boolean, runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, undefined, runOptions, configurationProperties, source);
this._source = source;
this.hasDefinedMatchers = hasDefinedMatchers;
if (command) {
this.command = command;
}
}
public customizes(): KeyedTaskIdentifier | undefined {
if (this._source && this._source.customizes) {
return this._source.customizes;
}
return undefined;
}
public getDefinition(useSource: boolean = false): KeyedTaskIdentifier {
if (useSource && this._source.customizes !== undefined) {
return this._source.customizes;
} else {
let type: string;
const commandRuntime = this.command ? this.command.runtime : undefined;
switch (commandRuntime) {
case RuntimeType.Shell:
type = 'shell';
break;
case RuntimeType.Process:
type = 'process';
break;
case RuntimeType.CustomExecution:
type = 'customExecution';
break;
case RuntimeType.CustomExecution2:
type = 'customExecution2';
break;
case undefined:
type = '$composite';
break;
default:
throw new Error('Unexpected task runtime');
}
let result: KeyedTaskIdentifier = {
type,
_key: this._id,
id: this._id
};
return result;
}
}
public static is(value: any): value is CustomTask {
return value instanceof CustomTask;
}
public getMapKey(): string {
let workspaceFolder = this._source.config.workspaceFolder;
return workspaceFolder ? `${workspaceFolder.uri.toString()}|${this._id}` : this._id;
}
public getRecentlyUsedKey(): string | undefined {
interface CustomKey {
type: string;
folder: string;
id: string;
}
let workspaceFolder = this._source.config.workspaceFolder;
if (!workspaceFolder) {
return undefined;
}
let key: CustomKey = { type: CUSTOMIZED_TASK_TYPE, folder: workspaceFolder.uri.toString(), id: this.configurationProperties.identifier! };
return JSON.stringify(key);
}
public getWorkspaceFolder(): IWorkspaceFolder {
return this._source.config.workspaceFolder;
}
public getTelemetryKind(): string {
if (this._source.customizes) {
return 'workspace>extension';
} else {
return 'workspace';
}
}
protected fromObject(object: CustomTask): CustomTask {
return new CustomTask(object._id, object._source, object._label, object.type, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
}
}
export class ConfiguringTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
_source: WorkspaceTaskSource;
configures: KeyedTaskIdentifier;
public constructor(id: string, source: WorkspaceTaskSource, label: string | undefined, type: string | undefined,
configures: KeyedTaskIdentifier, runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this._source = source;
this.configures = configures;
}
public static is(value: any): value is ConfiguringTask {
return value instanceof ConfiguringTask;
}
protected fromObject(object: any): Task {
return object;
}
public getDefinition(): KeyedTaskIdentifier {
return this.configures;
}
}
export class ContributedTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
_source: ExtensionTaskSource;
defines: KeyedTaskIdentifier;
hasDefinedMatchers: boolean;
/**
* The command configuration
*/
command: CommandConfiguration;
public constructor(id: string, source: ExtensionTaskSource, label: string, type: string | undefined, defines: KeyedTaskIdentifier,
command: CommandConfiguration, hasDefinedMatchers: boolean, runOptions: RunOptions,
configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this.defines = defines;
this.hasDefinedMatchers = hasDefinedMatchers;
this.command = command;
}
public getDefinition(): KeyedTaskIdentifier {
return this.defines;
}
public static is(value: any): value is ContributedTask {
return value instanceof ContributedTask;
}
public getMapKey(): string {
let workspaceFolder = this._source.workspaceFolder;
return workspaceFolder
? `${this._source.scope.toString()}|${workspaceFolder.uri.toString()}|${this._id}`
: `${this._source.scope.toString()}|${this._id}`;
}
public getRecentlyUsedKey(): string | undefined {
interface ContributedKey {
type: string;
scope: number;
folder?: string;
id: string;
}
let key: ContributedKey = { type: 'contributed', scope: this._source.scope, id: this._id };
if (this._source.scope === TaskScope.Folder && this._source.workspaceFolder) {
key.folder = this._source.workspaceFolder.uri.toString();
}
return JSON.stringify(key);
}
public getWorkspaceFolder(): IWorkspaceFolder | undefined {
return this._source.workspaceFolder;
}
public getTelemetryKind(): string {
return 'extension';
}
protected fromObject(object: ContributedTask): ContributedTask {
return new ContributedTask(object._id, object._source, object._label, object.type, object.defines, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
}
}
export class InMemoryTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
_source: InMemoryTaskSource;
type: 'inMemory';
public constructor(id: string, source: InMemoryTaskSource, label: string, type: string,
runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this._source = source;
}
public static is(value: any): value is InMemoryTask {
return value instanceof InMemoryTask;
}
public getTelemetryKind(): string {
return 'composite';
}
protected fromObject(object: InMemoryTask): InMemoryTask {
return new InMemoryTask(object._id, object._source, object._label, object.type, object.runOptions, object.configurationProperties);
}
}
export type Task = CustomTask | ContributedTask | InMemoryTask;
export interface TaskExecution {
id: string;
task: Task;
}
export enum ExecutionEngine {
Process = 1,
Terminal = 2
}
export namespace ExecutionEngine {
export const _default: ExecutionEngine = ExecutionEngine.Terminal;
}
export const enum JsonSchemaVersion {
V0_1_0 = 1,
V2_0_0 = 2
}
export interface TaskSet {
tasks: Task[];
extension?: IExtensionDescription;
}
export interface TaskDefinition {
extensionId: string;
taskType: string;
required: string[];
properties: IJSONSchemaMap;
}
export class TaskSorter {
private _order: Map<string, number> = new Map();
constructor(workspaceFolders: IWorkspaceFolder[]) {
for (let i = 0; i < workspaceFolders.length; i++) {
this._order.set(workspaceFolders[i].uri.toString(), i);
}
}
public compare(a: Task, b: Task): number {
let aw = a.getWorkspaceFolder();
let bw = b.getWorkspaceFolder();
if (aw && bw) {
let ai = this._order.get(aw.uri.toString());
ai = ai === undefined ? 0 : ai + 1;
let bi = this._order.get(bw.uri.toString());
bi = bi === undefined ? 0 : bi + 1;
if (ai === bi) {
return a._label.localeCompare(b._label);
} else {
return ai - bi;
}
} else if (!aw && bw) {
return -1;
} else if (aw && !bw) {
return +1;
} else {
return 0;
}
}
}
export const enum TaskEventKind {
DependsOnStarted = 'dependsOnStarted',
Start = 'start',
ProcessStarted = 'processStarted',
Active = 'active',
Inactive = 'inactive',
Changed = 'changed',
Terminated = 'terminated',
ProcessEnded = 'processEnded',
End = 'end'
}
export const enum TaskRunType {
SingleRun = 'singleRun',
Background = 'background'
}
export interface TaskEvent {
kind: TaskEventKind;
taskId?: string;
taskName?: string;
runType?: TaskRunType;
group?: string;
processId?: number;
exitCode?: number;
terminalId?: number;
__task?: Task;
}
export const enum TaskRunSource {
System,
User,
FolderOpen,
ConfigurationChange
}
export namespace TaskEvent {
export function create(kind: TaskEventKind.ProcessStarted | TaskEventKind.ProcessEnded, task: Task, processIdOrExitCode?: number): TaskEvent;
export function create(kind: TaskEventKind.Start, task: Task, terminalId?: number): TaskEvent;
export function create(kind: TaskEventKind.DependsOnStarted | TaskEventKind.Start | TaskEventKind.Active | TaskEventKind.Inactive | TaskEventKind.Terminated | TaskEventKind.End, task: Task): TaskEvent;
export function create(kind: TaskEventKind.Changed): TaskEvent;
export function create(kind: TaskEventKind, task?: Task, processIdOrExitCodeOrTerminalId?: number): TaskEvent {
if (task) {
let result: TaskEvent = {
kind: kind,
taskId: task._id,
taskName: task.configurationProperties.name,
runType: task.configurationProperties.isBackground ? TaskRunType.Background : TaskRunType.SingleRun,
group: task.configurationProperties.group,
processId: undefined as number | undefined,
exitCode: undefined as number | undefined,
terminalId: undefined as number | undefined,
__task: task,
};
if (kind === TaskEventKind.Start) {
result.terminalId = processIdOrExitCodeOrTerminalId;
} else if (kind === TaskEventKind.ProcessStarted) {
result.processId = processIdOrExitCodeOrTerminalId;
} else if (kind === TaskEventKind.ProcessEnded) {
result.exitCode = processIdOrExitCodeOrTerminalId;
}
return Object.freeze(result);
} else {
return Object.freeze({ kind: TaskEventKind.Changed });
}
}
}
export namespace KeyedTaskIdentifier {
function sortedStringify(literal: any): string {
const keys = Object.keys(literal).sort();
let result: string = '';
for (let position in keys) {
let stringified = literal[keys[position]];
if (stringified instanceof Object) {
stringified = sortedStringify(stringified);
} else if (typeof stringified === 'string') {
stringified = stringified.replace(/,/g, ',,');
}
result += keys[position] + ',' + stringified + ',';
}
return result;
}
export function create(value: TaskIdentifier): KeyedTaskIdentifier {
const resultKey = sortedStringify(value);
let result = { _key: resultKey, type: value.taskType };
Objects.assign(result, value);
return result;
}
}
export namespace TaskDefinition {
export function createTaskIdentifier(external: TaskIdentifier, reporter: { error(message: string): void; }): KeyedTaskIdentifier | undefined {
let definition = TaskDefinitionRegistry.get(external.type);
if (definition === undefined) {
// We have no task definition so we can't sanitize the literal. Take it as is
let copy = Objects.deepClone(external);
delete copy._key;
return KeyedTaskIdentifier.create(copy);
}
let literal: { type: string;[name: string]: any } = Object.create(null);
literal.type = definition.taskType;
let required: Set<string> = new Set();
definition.required.forEach(element => required.add(element));
let properties = definition.properties;
for (let property of Object.keys(properties)) {
let value = external[property];
if (value !== undefined && value !== null) {
literal[property] = value;
} else if (required.has(property)) {
let schema = properties[property];
if (schema.default !== undefined) {
literal[property] = Objects.deepClone(schema.default);
} else {
switch (schema.type) {
case 'boolean':
literal[property] = false;
break;
case 'number':
case 'integer':
literal[property] = 0;
break;
case 'string':
literal[property] = '';
break;
default:
reporter.error(nls.localize(
'TaskDefinition.missingRequiredProperty',
'Error: the task identifier \'{0}\' is missing the required property \'{1}\'. The task identifier will be ignored.', JSON.stringify(external, undefined, 0), property
));
return undefined;
}
}
}
}
return KeyedTaskIdentifier.create(literal);
}
}
|
mjbvz/vscode
|
src/vs/workbench/contrib/tasks/common/tasks.ts
|
TypeScript
|
mit
| 25,741
|
package network;
import com.firebase.client.*;
import network.interfaces.*;
import network.model.*;
/**
* Created by brian on 1/24/16.
*/
public class FirebaseConversationManager implements ConversationManager {
public static final int MAX_MESSAGES = 12;
private String myUid;
private Firebase chatRef;
private Firebase messagesRef;
private Firebase partnerLeftRef;
private MessageListener messageListener;
private ChatEndedListener chatEndedListener;
private int messageCount;
public FirebaseConversationManager(Firebase pChatRef) {
chatRef = pChatRef;
messagesRef = chatRef.child("messages");
partnerLeftRef = chatRef.child("someone_left");
myUid = messagesRef.getAuth().getUid();
messageCount = 0;
}
@Override
public void sendMessage(String messageText) {
Message messageObject = new Message(messageText, myUid);
messagesRef.push().setValue(messageObject);
}
@Override
public void listenForMessages(MessageListener listener) {
messageListener = listener;
setFirebaseMessageListener();
}
@Override
public void addOnChatEndedListener(ChatEndedListener listener) {
chatEndedListener = listener;
setPartnerLeftListener();
}
private void forwardPartnerMessageToListener(Message message) {
if (!message.user.equals(myUid)) {
messageListener.onMessageReceived(message.text, this);
}
}
private void setFirebaseMessageListener() {
messagesRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String pastChildKey) {
forwardPartnerMessageToListener(dataSnapshot.getValue(Message.class));
messageCount++;
checkMessageLimit();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
private void checkMessageLimit() {
if (messageCount >= MAX_MESSAGES) {
chatEndedListener.onChatEnded();
}
}
private void setPartnerLeftListener() {
partnerLeftRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null && dataSnapshot.getValue(Boolean.class)) {
chatEndedListener.onChatEnded();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
|
brain-murphy/turingchatai
|
src/main/java/network/FirebaseConversationManager.java
|
Java
|
mit
| 3,006
|
<!DOCTYPE html>
<html>
<head>
<title>DBTag.java</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<link rel='stylesheet' type='text/css' href='../coverage.css'/>
<link rel='shortcut icon' type='image/png' href='../logo.png'/>
<script type='text/javascript' src='../coverage.js'></script>
<script type='text/javascript' src='../prettify.js'></script>
</head>
<body onload='prettyPrint()'>
<table cellpadding='0' cellspacing='1'>
<caption>api/src/db/DBTag.java</caption>
<tr>
<td class='line'>1</td><td> </td>
<td><pre class='prettyprint'>package db;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>3</td><td> </td>
<td><pre class='prettyprint'>public class DBTag {</pre></td>
</tr>
<tr>
<td class='line'>4</td><td> </td>
<td><pre class='prettyprint'> private int id;</pre></td>
</tr>
<tr>
<td class='line'>5</td><td class='count'>25</td>
<td><pre class='prettyprint covered' id='l5s0'> private String name = null;</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>7</td><td class='count'>0</td>
<td><pre class='prettyprint uncovered' id='l7s0'> public DBTag(){}</pre></td>
</tr>
<tr>
<td class='line'>8</td><td class='count'>50</td>
<td><pre class='prettyprint covered' id='l8s0'> public DBTag(int id){ this.id = id; }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>10</td><td> </td>
<td><pre class='prettyprint'> public int getId() {</pre></td>
</tr>
<tr>
<td class='line'>11</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l11s0'> return id;</pre></td>
</tr>
<tr>
<td class='line'>12</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>14</td><td> </td>
<td><pre class='prettyprint'> public String getName() {</pre></td>
</tr>
<tr>
<td class='line'>15</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l15s0'> return name;</pre></td>
</tr>
<tr>
<td class='line'>16</td><td> </td>
<td><pre class='prettyprint'> }</pre></td>
</tr>
<tr><td class='line'></td><td colspan='2'> </td></tr>
<tr>
<td class='line'>18</td><td> </td>
<td><pre class='prettyprint'> public void setName(String name) {</pre></td>
</tr>
<tr>
<td class='line'>19</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l19s0'> this.name = name;</pre></td>
</tr>
<tr>
<td class='line'>20</td><td class='count'>1</td>
<td><pre class='prettyprint covered' id='l20s0'> }</pre></td>
</tr>
<tr>
<td class='line'>21</td><td> </td>
<td><pre class='prettyprint'>}</pre></td>
</tr>
</table>
</body>
</html>
|
andrez89/MusictextService
|
coverage-report/db/DBTag.html
|
HTML
|
mit
| 3,103
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.anggaranothing.pakar.dyslexia.client;
import com.anggaranothing.pakar.dyslexia.dao.IfCfLevelDao;
import com.anggaranothing.pakar.dyslexia.dao.IfDiseaseDao;
import com.anggaranothing.pakar.dyslexia.dao.IfSymptomDao;
import com.anggaranothing.pakar.dyslexia.dao.IfRelationDao;
import com.anggaranothing.pakar.dyslexia.model.Relation;
import com.anggaranothing.pakar.dyslexia.model.Symptom;
import com.anggaranothing.pakar.dyslexia.model.CfLevel;
import com.anggaranothing.pakar.dyslexia.model.Disease;
import java.awt.event.WindowEvent;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
*
* @author AnggaraNothing
*/
public class FrameRelation extends javax.swing.JInternalFrame {
private List<Relation> modelRecord = new ArrayList<Relation>();
private IfRelationDao objectDao = null;
private ListIterator findIter;
private List<Symptom> findRecord = new ArrayList<Symptom>();
private int lastFindIndex;
private boolean isEditRecord = false;
private final int maxTableRows = 10;
private IfDiseaseDao dssDao = null;
private List<Disease> dssRecord = new ArrayList<Disease>();
private IfSymptomDao smpDao = null;
private List<Symptom> smpRecord = new ArrayList<Symptom>();
private IfCfLevelDao cflDao = null;
private List<CfLevel> cflRecord = new ArrayList<CfLevel>();
/**
* Creates new form FrameRelation
*/
public FrameRelation() {
initComponents();
tblRecord.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
lblSelectedRow.setText( String.valueOf( tblRecord.getSelectedRow() + 1 ) );
lblPageNumber.setText( String.valueOf( jSPage.getValue() ) );
}
});
}
// method untuk mengambil referensi remote objek
private void initDao() {
String url = String.format( "rmi://%s:%d/%s" , ClientConfig.getRmiHost() , ClientConfig.getRmiPort() , ClientConfig.RMI_RELATION_NAME );
jBusyLabel.setVisible( true );
try {
// ambil referensi dari remote object yg ada di server
objectDao = ( IfRelationDao ) Naming.lookup(url);
url = String.format( "rmi://%s:%d/%s" , ClientConfig.getRmiHost() , ClientConfig.getRmiPort() , ClientConfig.RMI_DISEASE_NAME );
dssDao = ( IfDiseaseDao ) Naming.lookup(url);
url = String.format( "rmi://%s:%d/%s" , ClientConfig.getRmiHost() , ClientConfig.getRmiPort() , ClientConfig.RMI_SYMPTOM_NAME );
smpDao = ( IfSymptomDao ) Naming.lookup(url);
url = String.format( "rmi://%s:%d/%s" , ClientConfig.getRmiHost() , ClientConfig.getRmiPort() , ClientConfig.RMI_CFLEVEL_NAME );
cflDao = ( IfCfLevelDao ) Naming.lookup(url);
} catch (NotBoundException ex) {
Helper.logThrowable( "FrameRelation initDao() failed!", ex );
} catch (MalformedURLException ex) {
Helper.logThrowable( "FrameRelation initDao() failed!", ex );
} catch (RemoteException ex) {
Helper.ShowDialogAndLogThrowable( this, "FAILED to connect to the server !", ex );
}
jBusyLabel.setVisible( false );
}
// isi semua record DAO ke dalam record model
private void loadRecord() {
jBusyLabel.setVisible( true );
try {
modelRecord = objectDao.read();
dssRecord = dssDao.read();
smpRecord = smpDao.read();
cflRecord = cflDao.read();
updateDiseaseComboBox();
updateMaxPage();
resetFindListInteration();
btnAdd.setEnabled( true );
} catch (RemoteException ex) {
Helper.ShowDialogAndLogThrowable( this, "FAILED to read record from the server !", ex );
} catch(java.lang.NullPointerException ex) {
Helper.logThrowable( "FrameRelation loadRecord() failed!", ex );
}
jBusyLabel.setVisible( false );
}
// isi tabel dengan record model
private void loadTable( int pageNumber, int diseaseNumber ) {
if( modelRecord.size() <= 0 )
return;
jBusyLabel.setVisible( true );
DefaultTableModel temp = (DefaultTableModel) tblRecord.getModel();
temp.setRowCount( 0 );
// ekstrak data customer yg ada di dalam objek list
// kemudian menampilkannya ke objek tabel
if( pageNumber > getMaxPage() ) pageNumber = getMaxPage();
else if( pageNumber < 0 ) pageNumber = 1;
if( diseaseNumber >= modelRecord.size() ) diseaseNumber = modelRecord.size()-1;
else if( diseaseNumber < 0 ) diseaseNumber = 0;
int firstIndex = maxTableRows * --pageNumber,
lastIndex = firstIndex + maxTableRows;
if( lastIndex >= modelRecord.get(diseaseNumber).size() )
lastIndex = modelRecord.get(diseaseNumber).size()-1;
int iterator = 0;
for( Map.Entry<Symptom,Float> entry : modelRecord.get(diseaseNumber).entrySet() ) {
if( iterator < firstIndex )
continue;
else if( iterator > lastIndex )
break;
fillToTable( false, entry.getKey(), entry.getValue(), temp );
iterator++;
}
/*for( User user : modelRecord ) {
fillToTable( false, user , temp );
}*/
tblRecord.setModel( temp );
tblRecord.setEnabled( true );
tblRecord.requestFocus();
tblRecord.changeSelection( 0, 0, false, false );
jBusyLabel.setVisible( false );
}
// method untuk menampilkan data model ke tabel
private void fillToTable( boolean isEditData, Symptom smp, Float cfLvl, DefaultTableModel tableModel ) {
if ( !isEditData ) { // data baru
Object[] objects = new Object[ tableModel.getColumnCount() ];
objects[0] = smp.getId();
objects[1] = smp.getDescription();
objects[2] = cfLvl;
// tambahkan data model ke dalam tabel
tableModel.addRow( objects );
} else { // edit data
// ambil nilai baris yang dipilih
int row = tblRecord.getSelectedRow();
if( row > -1 ) {
// update data customer yg ada di tabel
tableModel.setValueAt( smp.getId(), row, 0);
tableModel.setValueAt( smp.getDescription(), row, 1);
tableModel.setValueAt( cfLvl, row, 2);
}
}
}
private void updateMaxPage() {
int maxPage = getMaxPage();
lblMaxPage.setText( String.valueOf( maxPage ) );
SpinnerNumberModel spModel = (SpinnerNumberModel) jSPage.getModel();
spModel.setMaximum( maxPage );
jSPage.setModel( spModel );
}
public void updateDiseaseComboBox() {
DefaultComboBoxModel<String> mdl = new DefaultComboBoxModel<String>();
for( Relation rtl : modelRecord ) {
mdl.addElement( String.format( "(%s) %s", rtl.getDisease().getId(), rtl.getDisease().getName() ) );
}
cbDisease.setModel( mdl );
cbDisease.setSelectedIndex( 0 );
}
private void resetFindListInteration() {
if( modelRecord.size() <= 0 )
return;
findRecord = new ArrayList<Symptom>();
for( Map.Entry<Symptom,Float> entry : modelRecord.get(cbDisease.getSelectedIndex()).entrySet() ) {
findRecord.add( entry.getKey() );
}
findIter = findRecord.listIterator();
}
private int getPageOnTableIndex( int index ) {
return (int) Math.max( Math.ceil( ( (double) index ) / ( (double) (maxTableRows-1) ) ) , 1 );
}
private int getMaxPage() {
return getPageOnTableIndex( modelRecord.get(cbDisease.getSelectedIndex()).size() - 1 );
}
private int getRecordIndexOnTable() {
return ( ( ( (int) jSPage.getValue() ) - 1 ) * maxTableRows ) + tblRecord.getSelectedRow();
}
private boolean isTableReady() {
return !jBusyLabel.isVisible();
}
private boolean isTableEmpty() {
return tblRecord.getRowCount() <= 0;
}
private boolean isRecordEmpty() {
return modelRecord.size() <= 0;
}
private void setPageSpinner( Object value ) {
if( value == null ) return;
jSPage.setValue( value );
}
private void setFindStatusText( boolean isClear , boolean isOnTop ) {
String arg1 = isOnTop ? "top" : "end";
String status = String.format( "Reached %s of the page.", arg1 );
if( isClear ) status = "";
lblFindStatus.setText( status );
}
private void doFindKeyword( String keyword , boolean isPrevious ) {
if( !isTableReady() || findIter == null ) return;
jBusyLabel.setVisible( true );
new Thread(new Runnable(){ public void run(){
boolean isId = keyword.toLowerCase().startsWith( "c" ) && Character.isDigit( keyword.charAt(1) );
boolean isOkayToChangePage = false;
boolean isFound = false;
int selectedColumn = 1;
int tableSelectedIndex = getRecordIndexOnTable();
// ngatur posisi iterator menuju ke selected table index
if( tableSelectedIndex != lastFindIndex )
{
resetFindListInteration();
int currentIndex = 0;
while( currentIndex != tableSelectedIndex ) {
findIter.next();
currentIndex = findIter.nextIndex()-1;
}
}
boolean whileCondition = !isPrevious ? findIter.hasNext() : findIter.hasPrevious();
while( whileCondition ) {
lastFindIndex = !isPrevious ? findIter.nextIndex()-1 : findIter.previousIndex()+1;
// find next
if( !isPrevious ) {
if( lastFindIndex <= tableSelectedIndex && findIter.hasNext() ) {
findIter.next();
continue;
}
}
// find previous
else {
if( lastFindIndex >= tableSelectedIndex && findIter.hasPrevious() ) {
findIter.previous();
continue;
}
}
setFindStatusText( true, false );
Symptom smp = findRecord.get( lastFindIndex );
// find by Description
if( !isId ) {
if( smp.getDescription().toLowerCase().contains( keyword.toLowerCase() ) ) {
isFound = true;
isOkayToChangePage = true;
}
}
// find by ID
else {
if( smp.getId().toLowerCase().contains( keyword.toLowerCase() ) ) {
isFound = true;
isOkayToChangePage = true;
}
}
// store current index
tableSelectedIndex = lastFindIndex;
// find next
if( !isPrevious ) {
// sudah dalam batas pencarian
if( !findIter.hasNext() ) {
setFindStatusText( false, false );
break;
}
}
// find previous
else {
// sudah dalam batas pencarian
if( !findIter.hasPrevious() ) {
setFindStatusText( false, true );
break;
}
}
// jika sudah ketemu, langsung makan kitkat
if( isFound ) break;
}
if( isOkayToChangePage ) {
setPageSpinner( getPageOnTableIndex( tableSelectedIndex ) );
int selectedIndex = tableSelectedIndex - ( ( getPageOnTableIndex(tableSelectedIndex ) - 1 ) * maxTableRows );
tblRecord.changeSelection( selectedIndex, selectedColumn, false, false );
}
}}).start();
jBusyLabel.setVisible( false );
}
private void doAddEditRecord() {
// tblRecord.setEnabled( false );
Relation rtlObj = new Relation();
rtlObj.setDisease( dssRecord.get( cbDlgDss.getSelectedIndex() ) );
Symptom smpObj = new Symptom();
smpObj.setId( (String) cbDlgSmpId.getSelectedItem() );
rtlObj.put( smpObj, cflRecord.get( cbDlgLvl.getSelectedIndex() ).getValue() );
try {
if( !isEditRecord )
objectDao.create(rtlObj);
else
objectDao.update(rtlObj);
new Thread(new Runnable() { public void run(){
Object dssName = cbDisease.getSelectedItem();
int dssId = cbDisease.getSelectedIndex();
int pageId = getMaxPage();
if( isEditRecord ) {
pageId = (int) jSPage.getValue();
}
loadRecord();
cbDisease.setSelectedItem( dssName );
setPageSpinner( pageId );
loadTable( pageId, dssId );
}}).start();
} catch (RemoteException ex) {
Helper.ShowDialogAndLogThrowable( this, "FAILED to insert/update record to the server !", ex );
}
tblRecord.setEnabled( true );
}
private void doDeleteRecord() {
// tblRecord.setEnabled( false );
Relation rtlObj = new Relation();
rtlObj.setDisease( modelRecord.get( cbDisease.getSelectedIndex() ).getDisease() );
Symptom smpObj = new Symptom();
smpObj.setId( (String) tblRecord.getValueAt( tblRecord.getSelectedRow(), 0 ) );
rtlObj.put( smpObj, (float) 0.0 );
try {
objectDao.delete( rtlObj );
new Thread(new Runnable() { public void run(){
int dssId = cbDisease.getSelectedIndex();
int pageId = (int) jSPage.getValue();
loadRecord();
setPageSpinner( pageId );
loadTable( pageId, dssId );
}}).start();
} catch (RemoteException ex) {
Helper.ShowDialogAndLogThrowable( this, "FAILED to delete record from the server !", ex );
}
tblRecord.setEnabled( true );
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
dialogAddEdit = new javax.swing.JDialog();
jLabel7 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
btnDlgCancel = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
btnDlgConfirm = new javax.swing.JButton();
cbDlgSmpId = new javax.swing.JComboBox<>();
jScrollPane3 = new javax.swing.JScrollPane();
taDlgSmpDesc = new javax.swing.JTextArea();
cbDlgLvl = new javax.swing.JComboBox<>();
jLabel12 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
cbDlgDss = new javax.swing.JComboBox<>();
jScrollPane1 = new javax.swing.JScrollPane();
tblRecord = new javax.swing.JTable();
btnPrev = new javax.swing.JButton();
btnFirst = new javax.swing.JButton();
btnNext = new javax.swing.JButton();
btnLast = new javax.swing.JButton();
jBusyLabel = new org.jdesktop.swingx.JXBusyLabel();
jSPage = new javax.swing.JSpinner();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
lblMaxPage = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jXTaskPaneContainer1 = new org.jdesktop.swingx.JXTaskPaneContainer();
jXTaskPane1 = new org.jdesktop.swingx.JXTaskPane();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
tfFind = new javax.swing.JTextField();
btnFindNext = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
lblFindStatus = new javax.swing.JLabel();
btnFindPrev = new javax.swing.JButton();
jXTaskPane2 = new org.jdesktop.swingx.JXTaskPane();
jPanel2 = new javax.swing.JPanel();
btnAdd = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
lblSelectedRow = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
lblPageNumber = new javax.swing.JLabel();
btnReload = new javax.swing.JButton();
cbDisease = new javax.swing.JComboBox<>();
dialogAddEdit.setTitle("Edit Selected Record");
dialogAddEdit.setMinimumSize(new java.awt.Dimension(360, 300));
dialogAddEdit.setModal(true);
dialogAddEdit.setResizable(false);
dialogAddEdit.setSize(new java.awt.Dimension(360, 300));
dialogAddEdit.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
dialogAddEditComponentShown(evt);
}
});
dialogAddEdit.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
dialogAddEditWindowClosing(evt);
}
});
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel7.setText("ID");
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel11.setText("Description");
btnDlgCancel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnDlgCancel.setText("Cancel");
btnDlgCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDlgCancelActionPerformed(evt);
}
});
btnDlgConfirm.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnDlgConfirm.setText("Confirm");
btnDlgConfirm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDlgConfirmActionPerformed(evt);
}
});
cbDlgSmpId.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cbDlgSmpId.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cbDlgSmpIdItemStateChanged(evt);
}
});
taDlgSmpDesc.setEditable(false);
taDlgSmpDesc.setColumns(20);
taDlgSmpDesc.setLineWrap(true);
taDlgSmpDesc.setRows(5);
jScrollPane3.setViewportView(taDlgSmpDesc);
cbDlgLvl.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel12.setText("CF Level");
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel10.setText("Disease");
cbDlgDss.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout dialogAddEditLayout = new javax.swing.GroupLayout(dialogAddEdit.getContentPane());
dialogAddEdit.getContentPane().setLayout(dialogAddEditLayout);
dialogAddEditLayout.setHorizontalGroup(
dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addContainerGap()
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addComponent(jLabel12)
.addGap(39, 39, 39)
.addComponent(cbDlgLvl, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dialogAddEditLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnDlgConfirm)
.addGap(18, 18, 18)
.addComponent(btnDlgCancel))
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addComponent(jLabel10)
.addGap(46, 46, 46)
.addComponent(cbDlgDss, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(86, 86, 86)
.addComponent(cbDlgSmpId, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
dialogAddEditLayout.setVerticalGroup(
dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addContainerGap()
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(cbDlgDss, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cbDlgSmpId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(dialogAddEditLayout.createSequentialGroup()
.addComponent(jLabel11)
.addGap(0, 73, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbDlgLvl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addGap(18, 18, 18)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(dialogAddEditLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDlgCancel)
.addComponent(btnDlgConfirm))
.addContainerGap())
);
setClosable(true);
setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Disease-Symptom Relation Data");
setMinimumSize(new java.awt.Dimension(739, 538));
setName(""); // NOI18N
addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
formInternalFrameClosing(evt);
}
public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
tblRecord.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"ID", "Description", "CF Level"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Float.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblRecord.setColumnSelectionAllowed(true);
tblRecord.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
tblRecord.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(tblRecord);
tblRecord.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (tblRecord.getColumnModel().getColumnCount() > 0) {
tblRecord.getColumnModel().getColumn(0).setMinWidth(40);
tblRecord.getColumnModel().getColumn(0).setMaxWidth(60);
tblRecord.getColumnModel().getColumn(2).setMinWidth(40);
tblRecord.getColumnModel().getColumn(2).setMaxWidth(60);
}
btnPrev.setText("Prev.");
btnPrev.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrevActionPerformed(evt);
}
});
btnFirst.setText("First");
btnFirst.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirstActionPerformed(evt);
}
});
btnNext.setText("Next");
btnNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNextActionPerformed(evt);
}
});
btnLast.setText("Last");
btnLast.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLastActionPerformed(evt);
}
});
jBusyLabel.setText("Loading...");
jBusyLabel.setBusy(true);
jSPage.setModel(new javax.swing.SpinnerNumberModel(1, 1, 1, 1));
jSPage.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSPageStateChanged(evt);
}
});
jLabel1.setText("Page");
jLabel2.setText("of");
lblMaxPage.setText("%d");
jScrollPane2.setAutoscrolls(true);
org.jdesktop.swingx.VerticalLayout verticalLayout4 = new org.jdesktop.swingx.VerticalLayout();
verticalLayout4.setGap(14);
jXTaskPaneContainer1.setLayout(verticalLayout4);
jLabel3.setText("Find");
tfFind.setHorizontalAlignment(javax.swing.JTextField.CENTER);
tfFind.setToolTipText("E-mail or Name");
tfFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfFindActionPerformed(evt);
}
});
btnFindNext.setText("Find Next");
btnFindNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindNextActionPerformed(evt);
}
});
jLabel4.setText(":");
lblFindStatus.setText(" ");
btnFindPrev.setText("Find Prev.");
btnFindPrev.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindPrevActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblFindStatus)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(tfFind, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnFindPrev)
.addGap(18, 18, 18)
.addComponent(btnFindNext)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(tfFind, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFindNext)
.addComponent(btnFindPrev))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblFindStatus)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jXTaskPane1.getContentPane().add(jPanel1);
jXTaskPaneContainer1.add(jXTaskPane1);
jXTaskPane1.setTitle( "Cari" );
jXTaskPane1.setCollapsed( true );
btnAdd.setText("Add");
btnAdd.setEnabled(false);
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnEdit.setText("Edit");
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
btnDelete.setText("Delete");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText(":");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Selected Row");
lblSelectedRow.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblSelectedRow.setText("%d");
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setText("Page Number");
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText(":");
lblPageNumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblPageNumber.setText("%d");
btnReload.setText("Reload");
btnReload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReloadActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(lblSelectedRow))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9)
.addGap(18, 18, 18)
.addComponent(lblPageNumber)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnReload)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(lblSelectedRow))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel9)
.addComponent(lblPageNumber)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnReload, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jXTaskPane2.getContentPane().add(jPanel2);
jXTaskPaneContainer1.add(jXTaskPane2);
jXTaskPane2.setTitle( "Command" );
jXTaskPane2.setCollapsed( false );
jScrollPane2.setViewportView(jXTaskPaneContainer1);
cbDisease.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
cbDiseaseItemStateChanged(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jBusyLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbDisease, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btnFirst)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnPrev)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSPage, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblMaxPage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnNext)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnLast))
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 703, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLast)
.addComponent(btnNext)
.addComponent(btnPrev)
.addComponent(btnFirst)
.addComponent(jSPage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(lblMaxPage)
.addComponent(cbDisease, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBusyLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane2)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jSPageStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSPageStateChanged
// TODO add your handling code here:
Object spinnerValue = jSPage.getValue();
if( !isTableReady() || spinnerValue == null ) return;
loadTable( (Integer) spinnerValue, cbDisease.getSelectedIndex() );
}//GEN-LAST:event_jSPageStateChanged
private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevActionPerformed
// TODO add your handling code here:
setPageSpinner( jSPage.getPreviousValue() );
}//GEN-LAST:event_btnPrevActionPerformed
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
// TODO add your handling code here:
setPageSpinner( jSPage.getNextValue() );
}//GEN-LAST:event_btnNextActionPerformed
private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirstActionPerformed
// TODO add your handling code here:
setPageSpinner( 1 );
}//GEN-LAST:event_btnFirstActionPerformed
private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLastActionPerformed
// TODO add your handling code here:
setPageSpinner(getMaxPage() );
}//GEN-LAST:event_btnLastActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
// TODO add your handling code here:
btnAdd.setEnabled( false );
new Thread(new Runnable() {
public void run(){
initDao();
loadRecord();
loadTable( 1, 0 );
setPageSpinner( 1 );
}
}).start();
}//GEN-LAST:event_formComponentShown
private void tfFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfFindActionPerformed
// TODO add your handling code here:
btnFindNext.doClick();
}//GEN-LAST:event_tfFindActionPerformed
private void btnFindPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindPrevActionPerformed
// TODO add your handling code here:
doFindKeyword( tfFind.getText() , true );
}//GEN-LAST:event_btnFindPrevActionPerformed
private void btnFindNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindNextActionPerformed
// TODO add your handling code here:
doFindKeyword( tfFind.getText() , false );
}//GEN-LAST:event_btnFindNextActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
if( isTableEmpty() || isRecordEmpty() || tblRecord.getSelectedRow() == -1 ) {
JOptionPane.showMessageDialog( this,
"No record loaded or selected",
null, JOptionPane.WARNING_MESSAGE );
return;
}
if( JOptionPane.showConfirmDialog( this, "Are you sure ?", "Delete Record Confirmation", JOptionPane.YES_NO_OPTION ) == 0 ) {
doDeleteRecord();
}
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
// TODO add your handling code here:
if( isTableEmpty() || isRecordEmpty() || tblRecord.getSelectedRow() == -1 ) {
JOptionPane.showMessageDialog( this,
"No record loaded or selected",
null, JOptionPane.WARNING_MESSAGE );
return;
}
isEditRecord = true;
dialogAddEdit.pack();
dialogAddEdit.setLocationRelativeTo( this );
dialogAddEdit.setModal( true );
dialogAddEdit.setVisible( true );
}//GEN-LAST:event_btnEditActionPerformed
private void dialogAddEditWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_dialogAddEditWindowClosing
// TODO add your handling code here:
}//GEN-LAST:event_dialogAddEditWindowClosing
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
// TODO add your handling code here:
isEditRecord = false;
dialogAddEdit.pack();
dialogAddEdit.setLocationRelativeTo( this );
dialogAddEdit.setModal( true );
dialogAddEdit.setVisible( true );
}//GEN-LAST:event_btnAddActionPerformed
private void dialogAddEditComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_dialogAddEditComponentShown
// TODO add your handling code here:
// Update combobox dss
DefaultComboBoxModel<String> mdl = new DefaultComboBoxModel<String>();
for( Disease dss : dssRecord ) {
mdl.addElement( String.format( "%s", dss.getName() ) );
}
cbDlgDss.setModel( mdl );
cbDlgDss.setSelectedIndex( 0 );
// Update combobox id
mdl = new DefaultComboBoxModel<String>();
for( Symptom smp : smpRecord ) {
mdl.addElement( String.format( "%s", smp.getId() ) );
}
cbDlgSmpId.setModel( mdl );
cbDlgSmpId.setSelectedIndex( 0 );
// Update combobox level
mdl = new DefaultComboBoxModel<String>();
for( CfLevel cfl : cflRecord ) {
mdl.addElement( String.format( "( %.1f ) %s", cfl.getValue(), cfl.getDescription() ) );
}
cbDlgLvl.setModel( mdl );
cbDlgLvl.setSelectedIndex( 0 );
String dlgTitle = "Add New Record";
int dlgValue = 0;
if( isEditRecord && getRecordIndexOnTable() >= 0 ) {
String id = (String) tblRecord.getValueAt( tblRecord.getSelectedRow(), 0 );
dlgTitle = "Edit Selected Record";
cbDlgSmpId.setSelectedItem( id );
cbDlgDss.setSelectedItem( modelRecord.get( cbDisease.getSelectedIndex() ).getDisease().getName() );
for( CfLevel cfl : cflRecord ) {
if( cfl.getValue() == (float) tblRecord.getValueAt( tblRecord.getSelectedRow(), 2 ) )
dlgValue = cflRecord.indexOf( cfl );
}
}
dialogAddEdit.setTitle( dlgTitle );
cbDlgLvl.setSelectedIndex( dlgValue );
taDlgSmpDesc.setText( smpRecord.get( cbDlgSmpId.getSelectedIndex() ).getDescription() );
}//GEN-LAST:event_dialogAddEditComponentShown
private void btnDlgCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDlgCancelActionPerformed
// TODO add your handling code here:
dialogAddEdit.dispatchEvent(new WindowEvent( dialogAddEdit, WindowEvent.WINDOW_CLOSING ) );
}//GEN-LAST:event_btnDlgCancelActionPerformed
private void btnDlgConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDlgConfirmActionPerformed
if( JOptionPane.showConfirmDialog( this, "Are you sure ?", dialogAddEdit.getTitle() + " Confirmation", JOptionPane.YES_NO_OPTION ) == 0 ) {
doAddEditRecord();
dialogAddEdit.dispatchEvent(new WindowEvent( dialogAddEdit, WindowEvent.WINDOW_CLOSING ) );
}
}//GEN-LAST:event_btnDlgConfirmActionPerformed
private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
// TODO add your handling code here:
Main.frameMap.remove( getClass().getName() );
}//GEN-LAST:event_formInternalFrameClosing
private void btnReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReloadActionPerformed
// TODO add your handling code here:
this.setVisible( false );
this.setVisible( true );
}//GEN-LAST:event_btnReloadActionPerformed
private void cbDiseaseItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbDiseaseItemStateChanged
// TODO add your handling code here:
if( !isTableReady() ) return;
loadTable( (Integer) 1, cbDisease.getSelectedIndex() );
resetFindListInteration();
updateMaxPage();
}//GEN-LAST:event_cbDiseaseItemStateChanged
private void cbDlgSmpIdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbDlgSmpIdItemStateChanged
// TODO add your handling code here:
taDlgSmpDesc.setText( smpRecord.get( cbDlgSmpId.getSelectedIndex() ).getDescription() );
}//GEN-LAST:event_cbDlgSmpIdItemStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnDlgCancel;
private javax.swing.JButton btnDlgConfirm;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnFindNext;
private javax.swing.JButton btnFindPrev;
private javax.swing.JButton btnFirst;
private javax.swing.JButton btnLast;
private javax.swing.JButton btnNext;
private javax.swing.JButton btnPrev;
private javax.swing.JButton btnReload;
private javax.swing.JComboBox<String> cbDisease;
private javax.swing.JComboBox<String> cbDlgDss;
private javax.swing.JComboBox<String> cbDlgLvl;
private javax.swing.JComboBox<String> cbDlgSmpId;
private javax.swing.JDialog dialogAddEdit;
private org.jdesktop.swingx.JXBusyLabel jBusyLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JSpinner jSPage;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JSeparator jSeparator1;
private org.jdesktop.swingx.JXTaskPane jXTaskPane1;
private org.jdesktop.swingx.JXTaskPane jXTaskPane2;
private org.jdesktop.swingx.JXTaskPaneContainer jXTaskPaneContainer1;
private javax.swing.JLabel lblFindStatus;
private javax.swing.JLabel lblMaxPage;
private javax.swing.JLabel lblPageNumber;
private javax.swing.JLabel lblSelectedRow;
private javax.swing.JTextArea taDlgSmpDesc;
private javax.swing.JTable tblRecord;
private javax.swing.JTextField tfFind;
// End of variables declaration//GEN-END:variables
}
|
anggaranothing/spselasa
|
SistemPakar_Anggara_Client/src/com/anggaranothing/pakar/dyslexia/client/FrameRelation.java
|
Java
|
mit
| 54,337
|
#ifndef MBLIB_RANGE_COUNT_HPP_
#define MBLIB_RANGE_COUNT_HPP_
#include <mblib/range/traits.hpp>
#include <cstddef>
class counting_range
{
public:
typedef std::size_t value_type;
typedef std::size_t size_type;
typedef range_tag range_tag;
private:
std::size_t i;
public:
counting_range(size_t start)
: i(start)
{}
bool empty() const
{
return false;
}
value_type front() const
{
return i;
}
void pop_front()
{
++i;
}
void pop_front(std::size_t how_many)
{
i += how_many;
}
};
inline counting_range count(std::size_t start)
{
return {start};
}
#endif
|
mbid/asm-lisp
|
include/mblib/range/count.hpp
|
C++
|
mit
| 675
|
v = JSONSchema({
k1: {
type: String
},
k2: {
type: Number
},
k3: {
type: Boolean
},
k4: [{
x: {
type: Number
},
y: {
type: String
}
}],
k5: {
type: Date
},
k6: {
x: {
type: Boolean
},
y: {
type: Date
},
z: {
m: {
type: String
},
n: {
type: Date
}
}
}
});
r = v.validate({
k1: '1',
k2: 10,
k3: true,
k4: [{
x: 10,
y: "sdf"
},
{
x: '20',
y: "sdgfds"
}
],
k5: new Date(),
k6: {
x: false,
y: new Date(),
z: {
n: "sdfgfdg",
m: new Date()
}
}
})
console.log(r);
|
shawonkanji/json-schema-validator
|
bundle.js
|
JavaScript
|
mit
| 877
|
---
layout: post
title: "<深入浅出React和Redux> - 模块化React和Redux应用"
date: 2017-11-07 23:16:07
categories: 读书笔记
---
# 模块化React和Redux应用
实际工作中, 应用汇变得很复杂, 需要划分为多个模块进行管理, 有效的组织代码结构, 精心设计状态树, 并且充分利用开发辅助工具.
## 模块化应用的要点
React适合**视图层**的工作, 而Redux才适合担当**状态管理**的工作.
开始一个新应用的时候, 需要考虑:
- 代码文件的**组织结构**
- 确定**模块边界**
- Store的**状态树设计**
## 代码文件的组织方式
### 按角色组织
在MVC框架下, 经常按照文件的角色划分目录:
```
controllers/
models/
views/
```
在MVC框架的影响下, Redux中也存在按角色组织代码的方式:
```
reducers/
actions/
components/
containers/
```
但是, 按这种方式组织, 代码十分**不利于扩展和迁移**, 每次修改都需要跨目录进行.
### 按功能组织
按功能组织就是将**完成相同功能的代码放在一起**
```
todoList/
actions.js
actionTypes.js
index.js
reducer.js
views/
component.js
container.js
filter/
actions.js
actionTypes.js
index.js
reducer.js
views/
component.js
container.js
```
在这种组织形式下, 每个功能对应一个模块, 每个模块对应一个目录
- actionTypes.js 定义action类型
- actions.js 定义action构造函数, 决定了这个模块可以接受的动作
- reducer.js 定义这个模块如何响应actions.js中定义的动作
- views 目录包含所有的react组件, 包括无状态组件和容器组件
- index.js 把所有角色导入, 然后统一导出, 作为模块的唯一入口
## 模块接口
模块化软件的要求: **"理想情况下, 只需要新增代码就能增加功能, 而不是修改现有代码"**
React+Redux能够帮助我们更为接近这一目标.
- 低耦合 - 模块之间的依赖关系应该简单而且清晰
- 高内聚 - 模块应该封装自己的功能
在React+Redux应用中, 一个模块就是**React组件, 加上actions, reducer**组成的小整体
如果在filter模块中想使用todoList中的功能:
```js
import * from actions from '../todoList/actions'
import container as TodoList from '../todoList/views/container'
```
这种导入方式使得filter模块依赖于todoList的内部结构, 并没有做到低耦合
我们需要一个**接口**, 将内部逻辑封装起来: index.js
```js
import * as actions from './actions'
import reducer from './reducer'
import view from './views/container'
export {actions, reducer, view}
```
filter模块中的使用代码就会变为:
```js
import {actions, reducer, view as TodoList} from '../todoList'
```
模块的内部结构被封装, 客户端只需要关注模块的接口
## 状态树的设计
Redux中所有的状态都保存在一个store上, 状态树的设计直接决定了**要写哪些reducer**, 以及**action怎么写**, 是**程序逻辑的源头**
- 一个模块控制一个状态节点 - reducer在状态树上的修改权是**互斥**的, 不可能让两个reducer修改同一个节点
- 避免冗余数据 - 冗余数据是**一致性**的大敌, 相对于性能问题, 一致性问题更加重要
- 树形结构扁平 - 深层次的数据结构很难进行管理
## Todo应用实例
Todo应用包含三部分功能:
- 待办事项列表
- 增加新待办的输入框和按钮
- 待办事项过滤器, 选择不同状态的待办
前两个部分功能更为紧密, 所以整体划分为两个模块: **todos和filter**
### todo的状态设计
- 使用数组来表示待办事项列表
- 每个待办事项包含id, text, completed来表示
- 过滤器包含三种状态: 'all', 'completed', 'uncompleted'
最终的状态树格式类似于:
```js
{
todos: [
{
id: 0,
text: 'First todo',
completed: false
},
{
id: 1,
text: 'Second todo',
completed: true
}
],
filter: 'all'
}
```
index.js中使用react-redux来导入Provider:
```js
import store from './Store'
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root'));
registerServiceWorker();
```
App.js中引入todos和filter
```js
import { Todos } from './todos';
import { Filter } from './filter';
class App extends Component {
render() {
return (
<div>
<Todos />
<Filter />
</div>
);
}
}
```
todos和filter只包含基本的文本显示:
```
├── App.js
├── Store.js
├── filter
│ ├── index.js
│ └── views
│ └── Filter.js
├── index.js
├── todos
├── index.js
└── views
└── Todos.js
```
### action构造函数
确定状态树结构之后, 就可以给每个模块创建action构造函数了
分为actionTypes和actions两个文件
```js
// todos/actionTypes.js
export const ADD_TODO = 'TODO/ADD'
export const TOGGLE_TODO = 'TODO/TOGGLE'
export const REMOVE_TODO = 'TODO/REMOVE'
// todo/actions.js
import * as ActionTypes from './actionTypes'
let nextTodoId = 0
export const addTodo = (text) => ({
type: ActionTypes.ADD_TODO,
id: nextTodoId++,
text,
completed: false
})
export const toggleTodo = (id) => ({
type: ActionTypes.TOGGLE_TODO,
id
})
export const removeTodo = (id) => ({
type: ActionTypes.REMOVE_TODO,
id
})
// todo/index.js
import Todos from './views/Todos'
import * as actions from './actions'
export {Todos, actions}
```
- 操作类型应该保持**全局唯一**, 使用模块名作为前缀
- 字符串格式的类型能够提供更好的可读性, 而且便于程序调试
- () => ({}) 的写法, 省略了return语句
### 组合reducer
每个模块都会拥有一个reducer, 而Redux的createStore方法只接受一个reducer, 所以要将多个reducer**组合**起来传递给createStore方法
```js
// Store.js
import { createStore, combineReducers } from 'redux'
import { reducer as todoReducer } from './todos'
import { reducer as filterReducer } from './filter'
const reducer = combineReducers({
todos: todoReducer,
filter: filterReducer
})
export default createStore(reducer)
```
- combineReducers参数对象上的字段名对应了**状态树上的属性名**
- combineReducers返回一个新的reducer, 在执行的时候, 会将整体的state**拆分开**, 分别交给不同的reducer执行
- reducer分别执行后, 将结果再**合并**为一个整体的state
```js
// todos/reducer.js
import * as ActionTypes from './actionTypes'
export default (state = [], action) => {
switch (action.type) {
case ActionTypes.ADD_TODO:
return [
{
id: action.id,
text: action.text,
completed: false
},
...state
]
case ActionTypes.TOGGLE_TODO:
return state.map(todo => {
if (todo.id === action.id) {
return { ...todo, completed: !todo.completed }
} else {
return todo
}
})
case ActionTypes.REMOVE_TODO:
return state.filter(todo => todo.id !== action.id)
default:
return state
}
}
```
### Todo视图
首先将Todos视图拆分为两个: AddTodo和TodoList
```js
export default () => {
return (
<div>
<TodoList />
<AddTodo />
</div>
)
}
```
- 使用纯函数进一步简化语法
#### AddTodo
负责获取用户输入, 点击按钮后创建新的待办
```js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions'
class AddTodo extends Component {
constructor(props) {
super(props)
this.refInput = this.refInput.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
refInput(node) {
this.input = node
}
onSubmit(e) {
e.preventDefault()
const input = this.input
if (!input.value.trim()) {
return
}
this.props.onAdd(input.value)
input.value = ''
}
render() {
return (
<div className="row">
<form className="form-inline" onSubmit={this.onSubmit}>
<input className="col-8 form-control" ref={this.refInput} />
<button className="col-3 btn btn-primary" type="submit">Add</button>
</form>
</div>
)
}
}
function mapDispatchToProps(dispatch, ownProps) {
return {
onAdd: (text) => {
dispatch(addTodo(text))
}
}
}
export default connect(null, mapDispatchToProps)(AddTodo);
```
- ref - input元素上的ref会绑定到一个函数, 在函数refInput中, 参数是**实际的DOM节点**, 绑定动作是发生在**组件装载时**
- onSubmit - 表单的默认提交行为会刷新页面, 为了避免刷新, 需要使用e.preventDefault()**屏蔽默认行为**
- onAdd - 在mapDispatchToProps中将onAdd方法绑定到redux的分发动作
- connect - 第一个参数是null, 因为组件并没有从外部接受属性
#### TodoList
首先完成基本的展示功能:
```js
import React from 'react';
import { connect } from 'react-redux';
const TodoList = ({todos}) => {
return (
<ul className="row list-group">
{
todos.map(todo => (
<li key={todo.id} className="list-group-item">{todo.text}</li>
))
}
</ul>
)
}
function mapStateToProps(state = [], ownProps) {
return {
todos: state.todos
}
}
export default connect(mapStateToProps)(TodoList);
```
- 在JSX中不能使用for或while这样的循环语句, 它们是语句, 而不是表达式
- 在map循环生成的结构中, 每个元素都要带有**key**属性, react以此为依据进行性能优化, 避免刷新整个列表
接着, 添加待办的状态切换和移除功能, 可以将li提取到独立的组件todoItem.js
```js
import React from 'react';
import { connect } from 'react-redux';
const TodoItem = ({ text, completed, onToggle, onRemove }) => (
<li className="list-group-item">
<input type="checkbox" checked={completed ? 'checked' : ''} onClick={onToggle}/>
<span>{text}</span>
<button className="btn btn-sm btn-light" onClick={onRemove}>x</button>
</li>
)
export default TodoItem
```
在TodoList中绑定切换状态和删除功能:
```js
function mapDispatchToProps(dispatch, ownProps) {
return {
onToggle: (id) => {
dispatch(toggleTodo(id))
},
onRemove: (id) => {
dispatch(removeTodo(id))
}
}
}
```
利用redux提供的bindActionCreators方法进一步简化代码:
```js
import { bindActionCreators } from 'redux'
const mapDispatchToProps = (dispatch) => bindActionCreators({
onToggle: toggleTodo,
onRemove: removeTodo
}, dispatch)
```
再进一步, 直接使用对象映射:
```js
const mapDispatchToProps = {
onToggle: toggleTodo,
onRemove: removeTodo
}
```
#### filter视图
- filter组件是一个简单的无状态组件
```js
function Filter() {
return (
<p>
<Link filter={ALL}>{ALL}</Link>
<Link filter={COMPLETED}>{COMPLETED}</Link>
<Link filter={UNCOMPLETED}>{UNCOMPLETED}</Link>
</p>
)
}
```
- Link组件略微复杂, 作为容器组件获取状态和派发事件
```js
const Link = ({ active, children, onClick }) => {
if (active) {
return <b>{children}</b>
} else {
return <a href="#" className="badge badge-primary" onClick={(e) => {
e.preventDefault()
onClick()
}}>{children}</a>
}
};
function mapStateToProps(state, ownProps) {
return {
active: state.filter === ownProps.filter
}
}
function mapDispatchToProps(dispatch, ownProps) {
return {
onClick: () => {
dispatch(setFilter(ownProps.filter))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Link);
```
- 当修改状态树中的filter值之后, todoList根据过滤条件过滤列表
```js
function filterByCompleteState(todos, filter) {
switch (filter) {
case FilterTypes.ALL:
return todos;
case FilterTypes.COMPLETED:
return todos.filter(todo => todo.completed)
case FilterTypes.UNCOMPLETED:
return todos.filter(todo => !todo.completed)
default:
return todos;
}
}
function mapStateToProps(state = [], ownProps) {
return {
todos: filterByCompleteState(state.todos, state.filter)
}
}
```
### 不使用ref
我们在提交表单的时候, 通过ref获取input的真实dom节点, ref的用法**非常脆弱**
React的产生就是**避免操作DOM**, 直接访问DOM很容易产生失控的情况
替代方案是使用组件状态来记录DOM元素的值:
```js
onInputChange(e) {
this.setState({
value: e.target.value
})
}
onSubmit(e) {
e.preventDefault()
const value = this.state.value
if (!value.trim()) {
return
}
this.props.onAdd(value)
this.setState({
value: ''
})
}
render() {
return (
<div className="row">
<form className="form-inline" onSubmit={this.onSubmit}>
<input className="col-8 form-control" value={this.state.value} onChange={this.onInputChange} />
<button className="col-3 btn btn-primary" type="submit">Add</button>
</form>
</div>
)
}
```
## 开发辅助工具
### Chrome 扩展包
- React Devtools - 可以检视React组件树
- Redux Devtools - 可以检视Redux数据流, 并且将组件跳到任何一个**历史状态**
- React Perf - 发现React组件的性能问题(**react v16已经不支持**)
### redux-immutable-state-invariant辅助包
每个reducer都必须是**纯函数**, 不能修改state或action, 负责会让程序**陷入混乱**
虽然这是一个规则, 但是总会被无心破坏, 使用redux-immutable-state-invariant提供的Redux中间件
在每次**派发动作**之后做一个检查, 如果发现违反了规则, 就会给出警告
### 工具应用
对于工具的启用, 需要在Store中修改一些代码, 通过**中间件**来启用扩展功能.
```shell
$ yarn add redux-immutable-state-invariant --dev
```
```js
//Store.js
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
const win = window // 引用window是为了避免包过大, UglifyJsPlugin无法处理window这种全局变量
const middlewires = []
if (process.env.NODE_ENV !== 'production') {
middlewires.push(require('redux-immutable-state-invariant').default())
}
const storeEnhancers = compose(
applyMiddleware(...middlewires),
(win && win.devToolsExtension) ? win.devToolsExtension() : (f) => f,
)
export default createStore(reducer, {}, storeEnhancers)
```
- storeEnhancers - 为Store提供增强功能
- compose - 将多个enhancer组合在一起
- redux-immutable-state-invariant 只有在开发环境才加入到增强功能
- 使用require时因为ES6的import不能出现在if语句中, 而且必须处于顶部

|
stoneyangxu/stoneyangxu.github.io
|
_posts/blog/2017-11-07-dissecting-react-and-redux-3.md
|
Markdown
|
mit
| 14,968
|
package org.herrdommel.messaging;
import org.herrdommel.batch.PersonItemProcessor;
import org.herrdommel.model.Book;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
/**
* @author <a href="mailto:dominik.mohr@adesso.de">Dominik Mohr</a>
* @since 29.07.2017
*/
@Component
public class MessagingReceiver {
public static final String BOOK_LOGGER_REQUEST_DESTINATION = "book-view-request-logger";
public static final String BOOK_LOGGER_DISPLAY_DESTINATION = "book-view-display-logger";
private static final Logger LOGGER = LoggerFactory.getLogger(PersonItemProcessor.class);
@JmsListener(destination = BOOK_LOGGER_DISPLAY_DESTINATION)
public void logReceivedBookDisplay(Book book) {
LOGGER.info("Displaying book with isbn " + book.getIsbn() + " and id " + book.getId());
}
@JmsListener(destination = BOOK_LOGGER_REQUEST_DESTINATION)
public void logReceivedBookRequest(String isbn) {
LOGGER.info("Viewed book details for book with isbn " + isbn);
}
}
|
herrdommel/spring-boot-seed
|
src/main/java/org/herrdommel/messaging/MessagingReceiver.java
|
Java
|
mit
| 1,120
|
<?php
/*
* This file is part of the Alice package.
*
* (c) Nelmio <hello@nelm.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer\Calls\MethodFlagHandler;
use Nelmio\Alice\Definition\Flag\ConfiguratorFlag;
use Nelmio\Alice\Definition\FlagInterface;
use Nelmio\Alice\Definition\MethodCall\ConfiguratorMethodCall;
use Nelmio\Alice\Definition\MethodCallInterface;
use Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer\Calls\MethodFlagHandler;
use Nelmio\Alice\IsAServiceTrait;
final class ConfiguratorFlagHandler implements MethodFlagHandler
{
use IsAServiceTrait;
public function handleMethodFlags(MethodCallInterface $methodCall, FlagInterface $flag): MethodCallInterface
{
return $flag instanceof ConfiguratorFlag
? new ConfiguratorMethodCall($methodCall)
: $methodCall
;
}
}
|
nelmio/alice
|
src/FixtureBuilder/Denormalizer/Fixture/SpecificationBagDenormalizer/Calls/MethodFlagHandler/ConfiguratorFlagHandler.php
|
PHP
|
mit
| 1,072
|
## [4.0.2](https://github.com/karma-runner/grunt-karma/compare/v4.0.1...v4.0.2) (2021-05-11)
### Bug Fixes
* **karma:** accept karma 6.x in peerDependencies ([#303](https://github.com/karma-runner/grunt-karma/issues/303)) ([fe01a67](https://github.com/karma-runner/grunt-karma/commit/fe01a67d5d85748f2bbe62a96e2ff52e0d2968d7))
## [4.0.1](https://github.com/karma-runner/grunt-karma/compare/v4.0.0...v4.0.1) (2021-05-11)
### Bug Fixes
* **karma:** use recommended parseConfig pattern for Karma 6 ([#297](https://github.com/karma-runner/grunt-karma/issues/297)) ([a38d9a9](https://github.com/karma-runner/grunt-karma/commit/a38d9a9d896ed8ef6441a17094350a5f3bc2ea2d))
# [4.0.0](https://github.com/karma-runner/grunt-karma/compare/v3.0.2...v4.0.0) (2020-04-14)
### chore
* **ci:** support semanitic-release ([#277](https://github.com/karma-runner/grunt-karma/issues/277)) ([caba218](https://github.com/karma-runner/grunt-karma/commit/caba2181e1541b5461e13ee1c4e09b6064e73465))
### BREAKING CHANGES
* **ci:** drop support for nodejs <8
<a name="3.0.2"></a>
## [3.0.2](https://github.com/karma-runner/grunt-karma/compare/v3.0.1...v3.0.2) (2019-04-09)
<a name="3.0.1"></a>
## [3.0.1](https://github.com/karma-runner/grunt-karma/compare/v3.0.0...v3.0.1) (2018-11-24)
### Features
* **karma:** require karma 3 in peerDependencies ([579f82f](https://github.com/karma-runner/grunt-karma/commit/579f82f)), closes [#261](https://github.com/karma-runner/grunt-karma/issues/261)
<a name="3.0.0"></a>
# [3.0.0](https://github.com/karma-runner/grunt-karma/compare/v2.0.0...v3.0.0) (2018-09-08)
### Bug Fixes
* ensure proper path format ([9314248](https://github.com/karma-runner/grunt-karma/commit/9314248))
* Remove hardcoded useIframe & captureConsole opts ([33386b3](https://github.com/karma-runner/grunt-karma/commit/33386b3)), closes [#165](https://github.com/karma-runner/grunt-karma/issues/165) [#166](https://github.com/karma-runner/grunt-karma/issues/166)
* **deps:** update lodash version to address npm audit warning ([1182766](https://github.com/karma-runner/grunt-karma/commit/1182766)), closes [#259](https://github.com/karma-runner/grunt-karma/issues/259)
* **deps:** Update test to use karma 3.0.0 ([19551fd](https://github.com/karma-runner/grunt-karma/commit/19551fd)), closes [#261](https://github.com/karma-runner/grunt-karma/issues/261) [#251](https://github.com/karma-runner/grunt-karma/issues/251)
### Features
* upgrade dependencies ([a911ca1](https://github.com/karma-runner/grunt-karma/commit/a911ca1)), closes [#178](https://github.com/karma-runner/grunt-karma/issues/178) [#175](https://github.com/karma-runner/grunt-karma/issues/175)
<a name="2.0.0"></a>
# 2.0.0 (2016-05-26)
### Bug Fixes
* handle basePath option for preprocessors paths ([1a45103](https://github.com/karma-runner/grunt-karma/commit/1a45103)), closes [#146](https://github.com/karma-runner/grunt-karma/issues/146)
* Make background option work with grunt tasks written in CoffeeScript ([52174ef](https://github.com/karma-runner/grunt-karma/commit/52174ef)), closes [#174](https://github.com/karma-runner/grunt-karma/issues/174)
<a name="1.0.0"></a>
# 1.0.0 (2016-05-03)
<a name="0.12.2"></a>
## 0.12.2 (2016-03-17)
<a name="0.12.1"></a>
## 0.12.1 (2015-09-09)
### Bug Fixes
* **task:** prevent `spawn ENAMETOOLONG` on Windows ([2b5e643](https://github.com/karma-runner/grunt-karma/commit/2b5e643))
* Upgrade dependencies ([27abcda](https://github.com/karma-runner/grunt-karma/commit/27abcda))
<a name"0.12.0"></a>
## 0.12.0 (2015-07-16)
#### Bug Fixes
* Updating grunt-karma to use the new API interface from Karma ([5d1881c9](https://github.com/karma-runner/grunt-karma/commit/5d1881c9))
* ensure files passed to karma are flat ([6075d692](https://github.com/karma-runner/grunt-karma/commit/6075d692), closes [#142](https://github.com/karma-runner/grunt-karma/issues/142))
<a name"0.11.2"></a>
### 0.11.2 (2015-06-29)
#### Bug Fixes
* ensure files passed to karma are flat ([6075d692](https://github.com/karma-runner/grunt-karma/commit/6075d692), closes [#142](https://github.com/karma-runner/grunt-karma/issues/142))
<a name"0.11.1"></a>
### 0.11.1 (2015-06-19)
#### Bug Fixes
* Allow karma release candidate as peer dependency ([5cdb1844](https://github.com/karma-runner/grunt-karma/commit/5cdb1844))
<a name"0.11.0"></a>
## 0.11.0 (2015-05-28)
#### Bug Fixes
* Allow for karma.conf to be used correctly Now client config is only passed to ka ([15fee6f9](https://github.com/karma-runner/grunt-karma/commit/15fee6f9), closes [#119](https://github.com/karma-runner/grunt-karma/issues/119))
* Update dependencies ([002926f4](https://github.com/karma-runner/grunt-karma/commit/002926f4))
* Flatten files array. ([7fe05940](https://github.com/karma-runner/grunt-karma/commit/7fe05940), closes [#142](https://github.com/karma-runner/grunt-karma/issues/142)
<a name="0.10.1"></a>
### 0.10.1 (2015-01-09)
#### Bug Fixes
* **task:** allow files definition in karma.conf ([6accf230](https://github.com/karma-runner/grunt-karma/commit/6accf230ce3eb945627709cc80fe3eafc82b9944), closes [#134](https://github.com/karma-runner/grunt-karma/issues/134))
<a name="0.10.0"></a>
## 0.10.0 (2015-01-09)
#### Features
* **task:**
* let Grunt do the file matching ([cb53deae](https://github.com/karma-runner/grunt-karma/commit/cb53deaef6da756be55e35c7d9fa57b84afda2ed))
* process templates in the config ([a10aaa75](https://github.com/karma-runner/grunt-karma/commit/a10aaa7548267ab035f8f4689eb54b2ead9245ef))
# 0.9.0 (2014-09-04)
## Features
### conventional-changelog
* add conventional-changelog (72c67e3)
### karma-dependency
* Bump Karma depdency to ~0.9.2 (23a4f25)
###
* make configFile optional (cee07ab)
# 0.8.3
* Flatten `files` input (@cgross)
# 0.8.2
* Emergency fix: Don't pass anything to karma if no browsers are defined.
# 0.8.1
* Kill background child process on main process exit. (@trabianmatt)
* Fix passing `client.args` through the commandline.
* Actually override the browsers array.
* Set client default args.
* Merge `client.args` from all sources.
# 0.8.0
* Update to `karma@0.12.0`
#0.3.0
* changed name from gruntacular to grunt-karma
#0.2.0
* support config sharing via options property
* basic example/test suite
* slight refactor
* use latest testacular
#0.1.1
* initial version
* docs
|
karma-runner/grunt-karma
|
CHANGELOG.md
|
Markdown
|
mit
| 6,380
|
<?php
// what needs to be here
// a list of teams in the region
// a list of comps in the region
// your running QP and RP for reference
// a place to edit your team description, robot abilities, images, and team name?
?>
<!DOCTYPE html>
<html>
<head>
<title> Reliability Index - FTCList </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700,100' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/jqc-1.11.3,dt-1.10.9/datatables.min.css"/>
<link rel='stylesheet' href='../jquery.growl.css' />
<link rel="stylesheet" href="../common.css"/>
</head>
<body>
<div class="container">
<?php include("../topbar.php"); ?>
<h1 class="page-header">Reliability Index</h1>
<p class="lead" style='font-weight:400'>its pretty cool</p>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/r/dt/jqc-1.11.3,dt-1.10.9/datatables.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="../jquery.growl.js"></script>
<script src="../common.js"></script>
<script>
</script>
</body>
</html>
|
Bambusa6226/ftclist
|
rel/index.php
|
PHP
|
mit
| 1,424
|
# Whitehall API
Whitehall is primarily a publishing application but it also provides an API used by some applications. This API is public and is served under [https://www.gov.uk/api/](https://www.gov.uk/api/governments).
Whitehall is not the only application to provide APIs under this path. For example, [/api/content](https://www.gov.uk/api/content/government) is served by [Content API](https://content-api.publishing.service.gov.uk) and [/api/search.json](https://www.gov.uk/api/search.json) is served by [Search API](https://docs.publishing.service.gov.uk/apis/search/search-api.html) (previously known as Rummager). [This Nginx file](https://github.com/alphagov/govuk-puppet/blob/master/modules/govuk/templates/publicapi_nginx_extra_config.erb) configures this behaviour.
The [organisations API](https://www.gov.uk/api/organisations) is now hosted by
[Collections](https://github.com/alphagov/collections).
## Endpoints
[`/api/governments`](https://www.gov.uk/api/governments) (no client available)
Lists governments from newest to oldest. Includes title, start and end dates.
[`/api/governments/:id`](https://www.gov.uk/api/governments/2015-conservative-government) (no client available)
Shows the details for a single government.
[`/api/world-locations`](https://www.gov.uk/api/world-locations) ([client](https://github.com/alphagov/gds-api-adapters/blob/0f24f4bc94ed1f8713c894b854c10ea867e6cf25/lib/gds_api/worldwide.rb#L4-L6))
Lists world locations. Includes title, web URL and country code.
[`/api/world-locations/:slug`](https://www.gov.uk/api/world-locations/afghanistan) ([client](https://github.com/alphagov/gds-api-adapters/blob/0f24f4bc94ed1f8713c894b854c10ea867e6cf25/lib/gds_api/worldwide.rb#L8-L10))
Shows the details for a single world location.
[`/api/world-locations/:slug/organisations`](https://www.gov.uk/api/world-locations/afghanistan/organisations) ([client](https://github.com/alphagov/gds-api-adapters/blob/0f24f4bc94ed1f8713c894b854c10ea867e6cf25/lib/gds_api/worldwide.rb#L12-L14))
Lists worldwide organisations relating to a world location. Includes embassies, departments, sponsor organisations and details for offices such as addresses, telephone numbers and email addresses.
[`/api/worldwide-organisations/:slug`](https://www.gov.uk/api/worldwide-organisations/department-for-international-trade-afghanistan) (no client available)
Shows the details for a single worldwide organisation.
## Consumers
Please [add your application to this list](https://github.com/alphagov/whitehall/edit/master/docs/api.md) if you're using the API.
There was [an incident](https://insidegovuk.blog.gov.uk/2017/09/27/incident-report-broken-smart-answers/) where some code was removed because these dependencies weren't known.
`/api/governments`
- [Smokey](https://github.com/alphagov/smokey/blob/f8678c4fe4805334b0ace8ddf5133be99094fc04/features/publicapi.feature#L22)
`/api/world*`
- [Contacts admin](https://github.com/alphagov/contacts-admin/blob/b1a2596e5dea6eae981bd4c758984398577fced8/app/lib/services.rb#L6)
- [Smart answers](https://github.com/alphagov/smart-answers/blob/b7be47f2d2cc7d25487e4b2c5a92ebba2f8ef317/lib/services.rb#L21)
- [Smokey](https://github.com/alphagov/smokey/blob/c9ddfbe8e00d89a306ca85098509734bb8403c3e/features/whitehall.feature#L112)
|
alphagov/whitehall
|
docs/api.md
|
Markdown
|
mit
| 3,304
|
require 'huanxin/version'
require 'huanxin/configuration'
require 'huanxin/service'
module Huanxin
# Your code goes here..
module_function
def root
File.dirname __dir__
end
# Return the lib path of this gem.
#
# @return [String] Path of the gem's lib.
def lib
File.join root, 'lib'
end
# Return the spec path of this gem.
#
# @return [String] Path of the gem's spec.
def spec
File.join root, 'spec'
end
end
|
yeluojun/haunxin
|
lib/huanxin.rb
|
Ruby
|
mit
| 450
|
package oauth4j.springjdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import oauth4j.core.Client;
import org.springframework.jdbc.core.RowMapper;
public class ClientRowMapper implements RowMapper<Client> {
@Override
public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
String clientID = rs.getString("id");
String hashedSecret = rs.getString("hashed_secret");
String spaceID = rs.getString("space_id");
String name = rs.getString("name");
return Client.valueOf(clientID, hashedSecret, spaceID, name);
}
}
|
sixro/oauth4j
|
spring-jdbc/src/main/java/oauth4j/springjdbc/ClientRowMapper.java
|
Java
|
mit
| 555
|
<?php
if (!(defined('IN_IA'))) {
exit('Access Denied');
}
class Setting_EweiShopV2Page extends PluginWebPage
{
public function main()
{
global $_GPC;
global $_W;
$uniacid = intval($_W['uniacid']);
$data = pdo_fetch('select * from ' . tablename('ewei_shop_live_setting') . ' where uniacid = ' . $uniacid . ' ');
if ($_W['ispost']) {
ca('sysset.notice.edit');
$tdata = ((is_array($_GPC['tdata']) ? $_GPC['tdata'] : array()));
$set_data = ((is_array($_GPC['data']) ? $_GPC['data'] : array()));
if (empty($tdata['willcancel_close_advanced'])) {
$uniacids = m('cache')->get('willcloseuniacid', 'global');
if (!(is_array($uniacids))) {
$uniacids = array();
}
if (!(in_array($_W['uniacid'], $uniacids))) {
$uniacids[] = $_W['uniacid'];
m('cache')->set('willcloseuniacid', $uniacids, 'global');
}
}
else {
$uniacids = m('cache')->get('willcloseuniacid', 'global');
if (is_array($uniacids)) {
if (in_array($_W['uniacid'], $uniacids)) {
$tdatas = array();
foreach ($uniacids as $uniacid ) {
if ($uniacid != $_W['uniacid']) {
$tdatas[] = $uniacid;
}
}
m('cache')->set('willcloseuniacid', $tdatas, 'global');
}
}
}
if (!(empty($data))) {
pdo_update('ewei_shop_live_setting', $set_data, array('uniacid' => $uniacid));
}
else {
$set_data['uniacid'] = $uniacid;
pdo_insert('ewei_shop_live_setting', $set_data);
}
m('common')->updateSysset(array('notice' => $tdata));
show_json(1);
}
$tdata = m('common')->getSysset('notice', false);
$template_list = pdo_fetchall('SELECT id,title,typecode FROM ' . tablename('ewei_shop_member_message_template') . ' WHERE uniacid=:uniacid ', array(':uniacid' => $_W['uniacid']));
$templatetype_list = pdo_fetchall('SELECT * FROM ' . tablename('ewei_shop_member_message_template_type'));
$template_group = array();
foreach ($templatetype_list as $type ) {
$templates = array();
foreach ($template_list as $template ) {
if ($template['typecode'] == $type['typecode']) {
$templates[] = $template;
}
}
$template_group[$type['typecode']] = $templates;
}
include $this->template();
}
}
?>
|
Broomspun/shanque
|
addons/ewei_shopv2/plugin/live/core/web/setting.php
|
PHP
|
mit
| 2,236
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _05Lab_Bomb_Numbers
{
class Program
{
static void Main(string[] args)
{
//Write a program that reads sequence of numbers and special bomb number with a certain power.
//Your task is to detonate every occurrence of the special bomb number and according to its power his neighbors from left and right.
//Detonations are performed from left to right and all detonated numbers disappear.
//Finally print the sum of the remaining elements in the sequence.
List<int> sequence = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
List<int> bombRow = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
int bombNumber = bombRow[0];
int bombPower = bombRow[1];
while (sequence.IndexOf(bombNumber)!=-1)
{
int startIndexBomb = sequence.IndexOf(bombNumber)-bombPower;
int endIndexBomb = sequence.IndexOf(bombNumber) + bombPower;
if (startIndexBomb<0)
{
startIndexBomb = 0;
}
if (endIndexBomb>sequence.Count-1)
{
endIndexBomb = sequence.Count - 1;
}
sequence.RemoveRange(startIndexBomb, endIndexBomb - startIndexBomb+1);
}
int result = sequence.Sum();
Console.WriteLine(result);
}
}
}
|
tanyta78/ProgramingFundamentals
|
04Lists/ListHomework/05Lab Bomb Numbers/Program.cs
|
C#
|
mit
| 1,796
|
<html>
<head>
</head>
<body>
<div id="root"></div>
</body>
<script src="dist.js"></script>
</html>
|
odojs/odojs-autocomplete
|
index.html
|
HTML
|
mit
| 101
|
//------------------------------------------------------------------------------
// <auto-generated>
// 這段程式碼是由工具產生的。
// 執行階段版本:4.0.30319.42000
//
// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼,
// 變更將會遺失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace HttpQlight.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
|
psliurt/HttpQlight
|
HttpQlight/Properties/Settings.Designer.cs
|
C#
|
mit
| 1,102
|
---
layout: post
title: Tweets
date: 2018-09-11
summary: These are the tweets for September 11, 2018.
categories:
---
|
alexlitel/congresstweets
|
_posts/2018-09-11--tweets.md
|
Markdown
|
mit
| 137
|
class News < ActiveRecord::Base
validates_presence_of :title
validates_uniqueness_of :title
validates_presence_of :category_id
belongs_to :category
has_many :images
end
|
aiw-group8-5c11/finalproject_astronomy
|
app/models/news.rb
|
Ruby
|
mit
| 180
|
<div class="home">
<div class="home-wrapper">
<div class="row featured-movie" *ngIf="featuredMovie && featuredVideo">
<div class="left-panel">
<app-movie-card [movie]="featuredMovie"></app-movie-card>
</div>
<div class="right-panel">
<div class="embed-responsive embed-responsive-16by9 video-embed">
<iframe class="embed-responsive-item" [src]="featuredVideo.url"></iframe>
</div>
</div>
</div>
<h3>Now In Theaters</h3>
<div class="row now-playing">
<app-featured-slider [movies]="moviesNowPlaying"></app-featured-slider>
</div>
<h3>Up Coming Movies</h3>
<div class="row up-coming">
<app-featured-slider [movies]="moviesUpComing"></app-featured-slider>
</div>
</div>
</div>
|
DanielYKPan/movies-finder
|
src/app/home/home.component.html
|
HTML
|
mit
| 888
|
"""
.. moduleauthor:: Chris Dusold <DriveLink@chrisdusold.com>
A module containing general purpose, cross instance hashing.
This module intends to make storage and cache checking stable accross instances.
"""
from drivelink.hash._hasher import hash
from drivelink.hash._hasher import frozen_hash
from drivelink.hash._hasher import Deterministic_Hashable
|
cdusold/DriveLink
|
drivelink/hash/__init__.py
|
Python
|
mit
| 357
|
# Builds a Docker image for SciPy with Jupyter Notebook.
#
# It can be found at:
# https://hub.docker.com/r/compdatasci/scipy-notebook
#
# Authors:
# Xiangmin Jiao <xmjiao@gmail.com>
FROM compdatasci/base
LABEL maintainer "Xiangmin Jiao <xmjiao@gmail.com>"
# Install scipy, sympy, and pandas
USER root
WORKDIR /tmp
RUN pip3 install -U \
numpy \
matplotlib \
sympy \
scipy \
pandas \
nose && \
rm -rf /tmp/* /var/tmp/*
WORKDIR $DOCKER_HOME
|
compdatasci/dockerfiles
|
scipy-jupyter/Dockerfile
|
Dockerfile
|
mit
| 475
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NanoScroll</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0pr2/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.8.0pr2/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title=""></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: </em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/NanoScroll.html">NanoScroll</a></li>
</ul>
<ul id="api-modules" class="apis modules">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1>NanoScroll Class</h1>
<div class="box meta">
<div class="foundat">
Defined in: <a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l274"><code>bin/javascripts/jquery.nanoscroller.js:274</code></a>
</div>
</div>
<div class="box intro">
</div>
<div class="constructor">
<h2>Constructor</h2>
<div id="method_NanoScroll" class="method item">
<h3 class="name"><code>NanoScroll</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>element</code>
</li>
<li class="arg">
<code>options</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l274"><code>bin/javascripts/jquery.nanoscroller.js:274</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">element</code>
<span class="type">HTMLElement | Node</span>
<div class="param-description">
<p>the main element</p>
</div>
</li>
<li class="param">
<code class="param-name">options</code>
<span class="type">Object</span>
<div class="param-description">
<p>nanoScroller's options</p>
</div>
</li>
</ul>
</div>
</div>
</div>
<div id="classdocs" class="tabview">
<ul class="api-class-tabs">
<li class="api-class-tab index"><a href="#index">Index</a></li>
<li class="api-class-tab methods"><a href="#methods">Methods</a></li>
<li class="api-class-tab properties"><a href="#properties">Properties</a></li>
</ul>
<div>
<div id="index" class="api-class-tabpanel index">
<h2 class="off-left">Item Index</h2>
<div class="index-section methods">
<h3>Methods</h3>
<ul class="index-list methods">
<li class="index-item method private">
<a href="#method_addEvents">addEvents</a>
</li>
<li class="index-item method private">
<a href="#method_createEvents">createEvents</a>
</li>
<li class="index-item method">
<a href="#method_flash">flash</a>
</li>
<li class="index-item method private">
<a href="#method_generate">generate</a>
</li>
<li class="index-item method private">
<a href="#method_getBrowserScrollbarWidth">getBrowserScrollbarWidth</a>
<span class="flag static">static</span>
</li>
<li class="index-item method private">
<a href="#method_preventScrolling">preventScrolling</a>
</li>
<li class="index-item method private">
<a href="#method_removeEvents">removeEvents</a>
</li>
<li class="index-item method">
<a href="#method_reset">reset</a>
</li>
<li class="index-item method private">
<a href="#method_restore">restore</a>
</li>
<li class="index-item method private">
<a href="#method_scroll">scroll</a>
</li>
<li class="index-item method">
<a href="#method_scrollBottom">scrollBottom</a>
</li>
<li class="index-item method">
<a href="#method_scrollTo">scrollTo</a>
</li>
<li class="index-item method">
<a href="#method_scrollTop">scrollTop</a>
</li>
<li class="index-item method">
<a href="#method_stop">stop</a>
</li>
<li class="index-item method private">
<a href="#method_updateScrollValues">updateScrollValues</a>
</li>
</ul>
</div>
<div class="index-section properties">
<h3>Properties</h3>
<ul class="index-list properties">
<li class="index-item property">
<a href="#property_alwaysVisible">alwaysVisible</a>
</li>
<li class="index-item property private">
<a href="#property_BROWSER_IS_IE7">BROWSER_IS_IE7</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_BROWSER_SCROLLBAR_WIDTH">BROWSER_SCROLLBAR_WIDTH</a>
<span class="flag static">static</span>
</li>
<li class="index-item property">
<a href="#property_contentClass">contentClass</a>
</li>
<li class="index-item property">
<a href="#property_disableResize">disableResize</a>
</li>
<li class="index-item property private">
<a href="#property_DOMSCROLL">DOMSCROLL</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_DOWN">DOWN</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_DRAG">DRAG</a>
<span class="flag static">static</span>
</li>
<li class="index-item property">
<a href="#property_flashDelay">flashDelay</a>
</li>
<li class="index-item property">
<a href="#property_iOSNativeScrolling">iOSNativeScrolling</a>
</li>
<li class="index-item property private">
<a href="#property_KEYDOWN">KEYDOWN</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_KEYUP">KEYUP</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_MOUSEDOWN">MOUSEDOWN</a>
</li>
<li class="index-item property private">
<a href="#property_MOUSEMOVE">MOUSEMOVE</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_MOUSEUP">MOUSEUP</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_MOUSEWHEEL">MOUSEWHEEL</a>
</li>
<li class="index-item property">
<a href="#property_paneClass">paneClass</a>
</li>
<li class="index-item property private">
<a href="#property_PANEDOWN">PANEDOWN</a>
<span class="flag static">static</span>
</li>
<li class="index-item property">
<a href="#property_preventPageScrolling">preventPageScrolling</a>
</li>
<li class="index-item property private">
<a href="#property_RESIZE">RESIZE</a>
</li>
<li class="index-item property private">
<a href="#property_SCROLL">SCROLL</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_SCROLLBAR">SCROLLBAR</a>
<span class="flag static">static</span>
</li>
<li class="index-item property">
<a href="#property_sliderClass">sliderClass</a>
</li>
<li class="index-item property">
<a href="#property_sliderMaxHeight">sliderMaxHeight</a>
</li>
<li class="index-item property">
<a href="#property_sliderMinHeight">sliderMinHeight</a>
</li>
<li class="index-item property private">
<a href="#property_TOUCHMOVE">TOUCHMOVE</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_UP">UP</a>
<span class="flag static">static</span>
</li>
<li class="index-item property private">
<a href="#property_WHEEL">WHEEL</a>
<span class="flag static">static</span>
</li>
</ul>
</div>
</div>
<div id="methods" class="api-class-tabpanel">
<h2 class="off-left">Methods</h2>
<div id="method_addEvents" class="method item private">
<h3 class="name"><code>addEvents</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l443"><code>bin/javascripts/jquery.nanoscroller.js:443</code></a>
</p>
</div>
<div class="description">
<p>Adds event listeners with jQuery.</p>
</div>
</div>
<div id="method_createEvents" class="method item private">
<h3 class="name"><code>createEvents</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l363"><code>bin/javascripts/jquery.nanoscroller.js:363</code></a>
</p>
</div>
<div class="description">
<p>Creates event related methods</p>
</div>
</div>
<div id="method_flash" class="method item">
<h3 class="name"><code>flash</code></h3>
<span class="paren">()</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l689"><code>bin/javascripts/jquery.nanoscroller.js:689</code></a>
</p>
</div>
<div class="description">
<p>To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.</p>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ flash: true });
</code></pre>
</div>
</div>
</div>
<div id="method_generate" class="method item private">
<h3 class="name"><code>generate</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l482"><code>bin/javascripts/jquery.nanoscroller.js:482</code></a>
</p>
</div>
<div class="description">
<p>Generates nanoScroller's scrollbar and elements for it.</p>
</div>
</div>
<div id="method_getBrowserScrollbarWidth" class="method item private">
<h3 class="name"><code>getBrowserScrollbarWidth</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">Number</span>
</span>
<span class="flag private">private</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l252"><code>bin/javascripts/jquery.nanoscroller.js:252</code></a>
</p>
</div>
<div class="description">
<p>Returns browser's native scrollbar width</p>
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Number</span>:
the scrollbar width in pixels
</div>
</div>
</div>
<div id="method_preventScrolling" class="method item private">
<h3 class="name"><code>preventScrolling</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>event</code>
</li>
<li class="arg">
<code>direction</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l303"><code>bin/javascripts/jquery.nanoscroller.js:303</code></a>
</p>
</div>
<div class="description">
<p>Prevents the rest of the page being scrolled
when user scrolls the <code>.content</code> element.</p>
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">event</code>
<span class="type">Event</span>
<div class="param-description">
</div>
</li>
<li class="param">
<code class="param-name">direction</code>
<span class="type">String</span>
<div class="param-description">
<p>Scroll direction (up or down)</p>
</div>
</li>
</ul>
</div>
</div>
<div id="method_removeEvents" class="method item private">
<h3 class="name"><code>removeEvents</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l464"><code>bin/javascripts/jquery.nanoscroller.js:464</code></a>
</p>
</div>
<div class="description">
<p>Removes event listeners with jQuery.</p>
</div>
</div>
<div id="method_reset" class="method item">
<h3 class="name"><code>reset</code></h3>
<span class="paren">()</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l525"><code>bin/javascripts/jquery.nanoscroller.js:525</code></a>
</p>
</div>
<div class="description">
<p>Resets nanoScroller's scrollbar.</p>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller();
</code></pre>
</div>
</div>
</div>
<div id="method_restore" class="method item private">
<h3 class="name"><code>restore</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l513"><code>bin/javascripts/jquery.nanoscroller.js:513</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="method_scroll" class="method item private">
<h3 class="name"><code>scroll</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l592"><code>bin/javascripts/jquery.nanoscroller.js:592</code></a>
</p>
</div>
<div class="description">
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ scroll: 'top' });
</code></pre>
</div>
</div>
</div>
<div id="method_scrollBottom" class="method item">
<h3 class="name"><code>scrollBottom</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>offsetY</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l615"><code>bin/javascripts/jquery.nanoscroller.js:615</code></a>
</p>
</div>
<div class="description">
<p>Scroll at the bottom with an offset value</p>
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">offsetY</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ scrollBottom: value });
</code></pre>
</div>
</div>
</div>
<div id="method_scrollTo" class="method item">
<h3 class="name"><code>scrollTo</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>node</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l653"><code>bin/javascripts/jquery.nanoscroller.js:653</code></a>
</p>
</div>
<div class="description">
<p>Scroll to an element</p>
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">node</code>
<span class="type">Node</span>
<div class="param-description">
<p>A node to scroll to.</p>
</div>
</li>
</ul>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ scrollTo: $('#a_node') });
</code></pre>
</div>
</div>
</div>
<div id="method_scrollTop" class="method item">
<h3 class="name"><code>scrollTop</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>offsetY</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l634"><code>bin/javascripts/jquery.nanoscroller.js:634</code></a>
</p>
</div>
<div class="description">
<p>Scroll at the top with an offset value</p>
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">offsetY</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ scrollTop: value });
</code></pre>
</div>
</div>
</div>
<div id="method_stop" class="method item">
<h3 class="name"><code>stop</code></h3>
<span class="paren">()</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l672"><code>bin/javascripts/jquery.nanoscroller.js:672</code></a>
</p>
</div>
<div class="description">
<p>To stop the operation.
This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.</p>
</div>
<div class="example">
<h4>Example:</h4>
<div class="example-content">
<pre class="code prettyprint"><code>$(".nano").nanoScroller({ stop: true });
</code></pre>
</div>
</div>
</div>
<div id="method_updateScrollValues" class="method item private">
<h3 class="name"><code>updateScrollValues</code></h3>
<span class="paren">()</span>
<span class="flag private">private</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l344"><code>bin/javascripts/jquery.nanoscroller.js:344</code></a>
</p>
</div>
<div class="description">
<p>Updates those nanoScroller properties that
are related to current scrollbar position.</p>
</div>
</div>
</div>
<div id="properties" class="api-class-tabpanel">
<h2 class="off-left">Properties</h2>
<div id="property_alwaysVisible" class="property item">
<h3 class="name"><code>alwaysVisible</code></h3>
<span class="type">Boolean</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l60"><code>bin/javascripts/jquery.nanoscroller.js:60</code></a>
</p>
</div>
<div class="description">
<p>a setting to make the scrollbar always visible.</p>
</div>
<p><strong>Default:</strong> false</p>
</div>
<div id="property_BROWSER_IS_IE7" class="property item private">
<h3 class="name"><code>BROWSER_IS_IE7</code></h3>
<span class="type">Boolean</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l234"><code>bin/javascripts/jquery.nanoscroller.js:234</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_BROWSER_SCROLLBAR_WIDTH" class="property item private">
<h3 class="name"><code>BROWSER_SCROLLBAR_WIDTH</code></h3>
<span class="type">Number</span>
<span class="flag private">private</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l243"><code>bin/javascripts/jquery.nanoscroller.js:243</code></a>
</p>
</div>
<div class="description">
</div>
<p><strong>Default:</strong> null</p>
</div>
<div id="property_contentClass" class="property item">
<h3 class="name"><code>contentClass</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l27"><code>bin/javascripts/jquery.nanoscroller.js:27</code></a>
</p>
</div>
<div class="description">
<p>a classname for the content element.</p>
</div>
<p><strong>Default:</strong> 'content'</p>
</div>
<div id="property_disableResize" class="property item">
<h3 class="name"><code>disableResize</code></h3>
<span class="type">Boolean</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l52"><code>bin/javascripts/jquery.nanoscroller.js:52</code></a>
</p>
</div>
<div class="description">
<p>a setting to disable binding to the resize event.</p>
</div>
<p><strong>Default:</strong> false</p>
</div>
<div id="property_DOMSCROLL" class="property item private">
<h3 class="name"><code>DOMSCROLL</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l180"><code>bin/javascripts/jquery.nanoscroller.js:180</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_DOWN" class="property item private">
<h3 class="name"><code>DOWN</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l189"><code>bin/javascripts/jquery.nanoscroller.js:189</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_DRAG" class="property item private">
<h3 class="name"><code>DRAG</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l153"><code>bin/javascripts/jquery.nanoscroller.js:153</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_flashDelay" class="property item">
<h3 class="name"><code>flashDelay</code></h3>
<span class="type">Number</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l68"><code>bin/javascripts/jquery.nanoscroller.js:68</code></a>
</p>
</div>
<div class="description">
<p>a default timeout for the <code>flash()</code> method.</p>
</div>
<p><strong>Default:</strong> 1500</p>
</div>
<div id="property_iOSNativeScrolling" class="property item">
<h3 class="name"><code>iOSNativeScrolling</code></h3>
<span class="type">Boolean</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l35"><code>bin/javascripts/jquery.nanoscroller.js:35</code></a>
</p>
</div>
<div class="description">
<p>a setting to enable native scrolling in iOS devices.</p>
</div>
<p><strong>Default:</strong> false</p>
</div>
<div id="property_KEYDOWN" class="property item private">
<h3 class="name"><code>KEYDOWN</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l207"><code>bin/javascripts/jquery.nanoscroller.js:207</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_KEYUP" class="property item private">
<h3 class="name"><code>KEYUP</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l216"><code>bin/javascripts/jquery.nanoscroller.js:216</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_MOUSEDOWN" class="property item private">
<h3 class="name"><code>MOUSEDOWN</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l111"><code>bin/javascripts/jquery.nanoscroller.js:111</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_MOUSEMOVE" class="property item private">
<h3 class="name"><code>MOUSEMOVE</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l119"><code>bin/javascripts/jquery.nanoscroller.js:119</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_MOUSEUP" class="property item private">
<h3 class="name"><code>MOUSEUP</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l136"><code>bin/javascripts/jquery.nanoscroller.js:136</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_MOUSEWHEEL" class="property item private">
<h3 class="name"><code>MOUSEWHEEL</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l128"><code>bin/javascripts/jquery.nanoscroller.js:128</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_paneClass" class="property item">
<h3 class="name"><code>paneClass</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l11"><code>bin/javascripts/jquery.nanoscroller.js:11</code></a>
</p>
</div>
<div class="description">
<p>a classname for the pane element.</p>
</div>
<p><strong>Default:</strong> 'pane'</p>
</div>
<div id="property_PANEDOWN" class="property item private">
<h3 class="name"><code>PANEDOWN</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l171"><code>bin/javascripts/jquery.nanoscroller.js:171</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_preventPageScrolling" class="property item">
<h3 class="name"><code>preventPageScrolling</code></h3>
<span class="type">Boolean</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l43"><code>bin/javascripts/jquery.nanoscroller.js:43</code></a>
</p>
</div>
<div class="description">
<p>a setting to prevent the rest of the page being
scrolled when user scrolls the <code>.content</code> element.</p>
</div>
<p><strong>Default:</strong> false</p>
</div>
<div id="property_RESIZE" class="property item private">
<h3 class="name"><code>RESIZE</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l145"><code>bin/javascripts/jquery.nanoscroller.js:145</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_SCROLL" class="property item private">
<h3 class="name"><code>SCROLL</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l102"><code>bin/javascripts/jquery.nanoscroller.js:102</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_SCROLLBAR" class="property item private">
<h3 class="name"><code>SCROLLBAR</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l93"><code>bin/javascripts/jquery.nanoscroller.js:93</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_sliderClass" class="property item">
<h3 class="name"><code>sliderClass</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l19"><code>bin/javascripts/jquery.nanoscroller.js:19</code></a>
</p>
</div>
<div class="description">
<p>a classname for the slider element.</p>
</div>
<p><strong>Default:</strong> 'slider'</p>
</div>
<div id="property_sliderMaxHeight" class="property item">
<h3 class="name"><code>sliderMaxHeight</code></h3>
<span class="type">Number</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l84"><code>bin/javascripts/jquery.nanoscroller.js:84</code></a>
</p>
</div>
<div class="description">
<p>a maximum height for the <code>.slider</code> element.</p>
</div>
<p><strong>Default:</strong> null</p>
</div>
<div id="property_sliderMinHeight" class="property item">
<h3 class="name"><code>sliderMinHeight</code></h3>
<span class="type">Number</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l76"><code>bin/javascripts/jquery.nanoscroller.js:76</code></a>
</p>
</div>
<div class="description">
<p>a minimum height for the <code>.slider</code> element.</p>
</div>
<p><strong>Default:</strong> 20</p>
</div>
<div id="property_TOUCHMOVE" class="property item private">
<h3 class="name"><code>TOUCHMOVE</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l225"><code>bin/javascripts/jquery.nanoscroller.js:225</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_UP" class="property item private">
<h3 class="name"><code>UP</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l162"><code>bin/javascripts/jquery.nanoscroller.js:162</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_WHEEL" class="property item private">
<h3 class="name"><code>WHEEL</code></h3>
<span class="type">String</span>
<span class="flag private">private</span>
<span class="flag final">final</span>
<span class="flag static">static</span>
<div class="meta">
<p>
Defined in
<a href="../files/bin_javascripts_jquery.nanoscroller.js.html#l198"><code>bin/javascripts/jquery.nanoscroller.js:198</code></a>
</p>
</div>
<div class="description">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>
|
bevacqua/nanoScrollerJS
|
docs/classes/NanoScroll.html
|
HTML
|
mit
| 61,334
|
#include "stdio.h"
int main(int argc, char *argv[]) {
char numeroStr[4];
char potenciaStr[4];
int numero, potencia, resultado;
resultado = 1;
printf("Introduzca un numero: ");
fgets(numeroStr, sizeof(numeroStr), stdin):
printf("Introduzca una potencia: ");
fgets(potenciaStr, sizeof(potenciaStr), stdin);
while (potencia > 0) {
resultado = numero * resultado;
potencia = potencia - 1;
}
printf("%i\n", resultado);
return 0;
}
|
clinoge/primer-semestre-udone
|
src/05-ciclos/mientras/mientras.c
|
C
|
mit
| 498
|
<?php
namespace CoinOptimizer;
class CoinCollection
{
/**
* @var Coin[]
*/
private $coins;
/**
* @param Coin[] $coins
*/
public function __construct($coins = [])
{
$this->setCoins($coins);
}
/**
* Get sorted coins, with the largest (highest value) first
*
* @return Coin[]
*/
public function getSortedCoins()
{
$this->sortCoins();
return $this->coins;
}
/**
* @param Coin[] $coins
*/
public function setCoins($coins)
{
$this->coins = $coins;
}
/**
* @param Coin $coin
* @return void
*/
public function addCoin(Coin $coin)
{
$this->coins[] = $coin;
}
/**
* Sorts coins in descending value
*
* @return void
*/
private function sortCoins()
{
usort(
$this->coins,
function (Coin $a, Coin $b) {
if ($a->getValue() == $b->getValue()) {
// sort alphabetically by name if values match
return strcmp($a->getName(), $b->getName());
}
return $a->getValue() > $b->getValue() ? -1 : 1;
}
);
}
}
|
konrness/coin-optimizer
|
src/CoinOptimizer/CoinCollection.php
|
PHP
|
mit
| 1,246
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_72) on Thu Feb 18 20:49:53 EST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.red5.server.adapter (Red5 :: Common server classes 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../org/red5/server/adapter/package-summary.html" target="classFrame">org.red5.server.adapter</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="IApplication.html" title="interface in org.red5.server.adapter" target="classFrame"><span class="interfaceName">IApplication</span></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AbstractScopeAdapter.html" title="class in org.red5.server.adapter" target="classFrame">AbstractScopeAdapter</a></li>
<li><a href="StatefulScopeWrappingAdapter.html" title="class in org.red5.server.adapter" target="classFrame">StatefulScopeWrappingAdapter</a></li>
</ul>
</div>
</body>
</html>
|
Red5/red5.github.io
|
javadoc/red5-server-common/org/red5/server/adapter/package-frame.html
|
HTML
|
mit
| 1,336
|
package com.packt.webstore.domain.repository.impl;
import com.packt.webstore.domain.Comment;
import com.packt.webstore.domain.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.security.RolesAllowed;
import java.sql.ResultSet;
import java.util.List;
/**
* Created by Przemek on 2016-08-11.
*/
@Repository
public class CommentRepositoryImpl implements CommentRepository{
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public List<Comment> getAllComments(int customerId) {
/*language=SQL*/
String SQL_GET_ALL_COMMENTS= "Select customers.NAME, comments.comment_content, comments.comment_date\n" +
"from comments join customers on customers.ID=comments.customer_id\n" +
"where comments.customer_id=?;";
return jdbcTemplate.query(SQL_GET_ALL_COMMENTS, new Object[] {customerId},
(ResultSet result, int i)-> {
Comment comment= new Comment();
comment.setCommentatorName(result.getString(1));
comment.setCommentContent(result.getString(2));
comment.setCommentDate(result.getDate(3).toString());
return comment;
});
}
@Override
@RolesAllowed("USER")
public void deleteComment() {}
@Override
@RolesAllowed("USER")
public void addComment(String commentContent, String commentDate, int customerId) {
/*language=SQL*/
String SQL_ADD_COMMENT="Insert into comments(comment_content, comment_date, customer_id) value (?,?, ?)";
jdbcTemplate.
update(SQL_ADD_COMMENT,
commentContent,
commentDate,
customerId);
}
}
|
Przemek625/Spring-MVC-webshop
|
webstore/src/main/java/com/packt/webstore/domain/repository/impl/CommentRepositoryImpl.java
|
Java
|
mit
| 1,924
|
# ProductTracker
This project is a product tracker. It basically collects data from an excel file and stores in database.
|
deanagan/ProductTracker
|
app/README.md
|
Markdown
|
mit
| 122
|
---
title: Belgium
published: true
featured_image_path:
featured_image_attribution:
geocode: BEL
iso_code: BE
territory: false
state_party: true
signed_but_not_ratified: false
signed_date: 1998-09-10T00:00:00.000Z
ratified_or_acceded_date: 2000-06-28T00:00:00.000Z
entry_into_force_date: 2002-07-01T00:00:00.000Z
ratified_apic_date: 2005-03-27T00:00:00.000Z
genocide: '[Belgian Law on Serious Violations of International Humanitarian Law, Chapter 2, Article 136 bis](https://iccdb.hrlc.net/data/doc/65/keyword/46/)'
crimes_against_humanity: '[Belgian Law on Serious Violations of International Humanitarian Law, Chapter 2, Article 136 ter](https://iccdb.hrlc.net/data/doc/65/keyword/13/)'
aggression:
war_crimes: '[Belgian Law on Serious Violations of International Humanitarian Law, Chapter 2, Article 136 quater](https://iccdb.hrlc.net/data/doc/65/keyword/145/)'
note:
slug: belgium
---
|
ABA-Center-for-Human-Rights/aba-icc
|
_countries/belgium.md
|
Markdown
|
mit
| 891
|
#!/bin/bash
xml_parser() {
if [ $OSTYPE == msys ]; then
echo "xml"
else
echo "xmlstarlet"
fi
}
##
# $1: node selecting XPath expression ("ns" alias is predifined for Maven's POM namespace)
# $2: path to XML file
##
node_text() {
# can not use an empty string as the default output, using this secret constant in place
NOT_FOUND_NODE="not found bastaaa"
cmd=`xml_parser`
value=$($cmd sel -N ns="http://maven.apache.org/POM/4.0.0" -t --if "($1)" -c "$1/text()" -n --else -o "$NOT_FOUND_NODE" "$2")
if [ "$value" = "$NOT_FOUND_NODE" ]; then
echo ""
else
echo "$value"
fi
}
jirac_get_maven_version() {
cmd=`xml_parser`
echo $(node_text "/ns:project/ns:version" "$1")
}
##
# project name is the value of name tag if present and non empty, otherwise the value of the artifactId tag
##
jirac_get_maven_project_name() {
cmd=`xml_parser`
name=$(node_text "/ns:project/ns:name" "$1")
if [ -z "$name" ]; then
echo $(node_text "/ns:project/ns:artifactId" "$1")
else
echo "$name"
fi
}
jirac_get_scm_url() {
cmd=`xml_parser`
echo $(node_text "/ns:project/ns:scm/ns:url" "$1")
}
|
jirac/jirac
|
core_xml_functions.sh
|
Shell
|
mit
| 1,100
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>國會調查兵團 CIC - Congressional Investigation Corps</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="css/admin-style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="outer">
<article id="all-wrap">
<div id="top">
<header id="logo"><h1><a href="admin-list.html">國會調查兵團 CIC Congressional Investigation Corps</a></h1></header>
<nav id="first-nav">
<ul>
<li><a href="admin-list.html">後台首頁</a></li>
<li><a href="video-list.html">影片管理</a></li>
<li><a href="talk-list.html">質詢管理</a></li>
<li><a href="news-list.html">新聞管理</a></li>
<li><a href="count-number-list.html">數據報表</a></li>
<li><a href="congress-list.html">立委管理</a></li>
<li><a href="party-list.html">黨團管理</a></li>
<li><a href="member-list.html">會員管理</a></li>
<li><a href="login.html">登出</a></li>
</ul>
</nav>
</div>
<div id="main-wrap">
<div id="sys-block">
<h2>編輯黨團資料</h2>
<ul class="form-list">
<li>
<p>黨團名稱*</p>
<p class="input-data">
<input type="text" name="textfield2" id="textfield2">
</p>
</li>
<li>
<p>黨旗圖示*</p>
<p class="input-data">
<img src="../images/party-nsu.gif" width="30" height="24"> <br>
<input type="file" name="fileField" id="fileField">
</p>
</li>
<li>
<p>黨團樣式英文名*</p>
<p class="input-data">
<input name="textfield2" type="text" id="textfield2" value="party-kmt">
</p>
</li>
<li><a href="admin-list.html" class="form-btn">新增</a></li>
</ul>
</div>
</div>
<footer id="footer">
這裡是管理後台,這條只是留著好看...</footer></article></div>
</body>
</html>
|
billy3321/cic-website
|
templete/admin/party-edit.html
|
HTML
|
mit
| 2,295
|
---
layout: post
title: Mệt
categories:
- blog
---
Sao mệt hả? Thì nhiều thứ chứ sao? Bắt đầu ho trở lại. Ờ cái người kiểu gì mà đói cái là mất toàn bộ kiềm chế, haizzz. Nếu ai đó thấy mình đang đói thì liệu mà tránh xa đừng có chọc vào, hoặc tốt bụng thì kiếm dùm gì đó nhét vào miệng là mọi chuyện sẽ êm đẹp thôi.
# #mụctiêu
Tự đặt cho mình cái mục tiêu mà tính trên lý thuyết thì không nổi rồi mà cũng cố... dĩ nhiên không phải cố cho bằng được, nhưng là động lực để thay đổi và cố gắng. Nếu là đặt cược thì khoảng đặt cược cũng không phải quá lớn... ờ cũng bằng 1 tháng mồ hôi và nước miếng (ủa lộn, nước mắt) chứ bộ. Nhưng thôi cứ thử, mình tin là thành tâm thì sẽ được hồi đáp. Tăng thu, giảm chi, nhưng sẽ chi những gì mang tính đầu tư và cần thiết :)
# #bựcmình
Có những người nói chuyện không biết khi nào cần dừng lại, nói theo kiểu ***muốn táng vào mặt*** cứ như mình là "mẹ thiên hạ". Mà thôi kệ, chả quan tâm làm gì. Mình sống theo cách của mình, cần gì care mấy người đó.
# #BIT
Cũng hơi buồn vì mới bắt đầu theo dõi được 2-3 số... Coi hết ngay từ đầu trước khi scandal xảy ra khi được bạn giới thiệu. Thà khốn nạn một cách công khai còn hơn giả nai một cách kinh tởm. Cũng nghĩ từ đầu sớm muộn chuyện này cũng xảy ra nhưng nó làm lớn hơn mình tưởng. Cũng hy vọng sẽ có sự thay đổi, dù có bị dẹp thì cũng là một thử nghiệm đáng có... Rồi cũng sẽ thay đổi thôi :)
# #già
Dạo này đi bus không ai còn thèm xé nhầm vé sinh viên hay hỏi mình thẻ nữa, buồn ghê. Chắc bị già thật rồi, ừ cũng sắp 25 rồi còn gì nữa. Vậy mà cũng chưa làm được gì cả... ngoài chuyện đi chơi suốt ngày :(
# #mâuthuẫn
Nhiều lúc thấy mình cũng mâu thuẫn ghê, một mặt thì lên án, một mặt thỏa hiệp và thích nghi. Riếc không biết mình là con người thế nào cả :))... nghe đớn hèn ghê.
# #nhưngvẫnphảisốngtốt
Ừ, thì dù là có mệt, có bị đối xử thế nào thì vẫn phải sống tốt. Vì sao à? Mỗi lần nhìn lại blog trước, chuyện hơn một tháng trước như một lời nhắc nhở. Mày còn sống tiếp thì đã tốt lắm rồi, mày đã hứa là sẽ sống tốt mà phải không? Nói chung là con người ích kỷ đó? Tại sao phải tự làm mình khổ làm gì :)) cứ sống cho tốt, sống sao cho "một số người nào đó" thấy là mày chẳng có rảnh mà bận tâm đến họ làm gì? Haha.
|
nguyenkha/nguyenkha.github.com
|
_posts/2015-11-25-met.md
|
Markdown
|
mit
| 2,925
|
<?php
return array (
'New message from {senderName}' => 'Новое сообщение от {senderName}',
'and {counter} other users' => 'и {counter} других пользователей',
);
|
ProfilerTeam/Profiler
|
protected/modules/mail/messages/ru/models_Message.php
|
PHP
|
mit
| 201
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Azureoth.RestfulDb.Database
{
public class TableNotFoundException : Exception
{
public TableNotFoundException(string message) : base(message)
{
}
public TableNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
|
azureoth/restful-db
|
src/Azureoth.RestfulDb/Database/TableNotFoundException.cs
|
C#
|
mit
| 430
|
//
// PLKThermometerBottomLayer.h
// Dress
//
// Created by Sean Pilkenton on 7/22/13.
// Copyright (c) 2013 Patricio Enterprises. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
@interface SPThermometerBottomLayer : CALayer
+ (id)layerWithRadius:(CGFloat)radius color:(UIColor *)color;
@end
|
pilks/SPThermometer
|
SPThermometerBottomLayer.h
|
C
|
mit
| 310
|
import color from 'color';
import { Platform } from 'react-native';
/* This is an example of a theme */
export default {
// Badge
badgeBg: '#ED1727',
badgeColor: '#fff',
// Button
btnFontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto_medium',
btnDisabledBg: '#b5b5b5',
btnDisabledClr: '#f1f1f1',
get btnPrimaryBg() {
return this.brandPrimary;
},
get btnPrimaryColor() {
return this.inverseTextColor;
},
get btnInfoBg() {
return this.brandInfo;
},
get btnInfoColor() {
return this.inverseTextColor;
},
get btnSuccessBg() {
return this.brandSuccess;
},
get btnSuccessColor() {
return this.inverseTextColor;
},
get btnDangerBg() {
return this.brandDanger;
},
get btnDangerColor() {
return this.inverseTextColor;
},
get btnWarningBg() {
return this.brandWarning;
},
get btnWarningColor() {
return this.inverseTextColor;
},
get btnTextSize() {
return (Platform.OS === 'ios') ? this.fontSizeBase * 1.1 :
this.fontSizeBase - 1;
},
get btnTextSizeLarge() {
return this.fontSizeBase * 1.5;
},
get btnTextSizeSmall() {
return this.fontSizeBase * 0.8;
},
get borderRadiusLarge() {
return this.fontSizeBase * 3.8;
},
buttonPadding: 6,
get iconSizeLarge() {
return this.iconFontSize * 1.5;
},
get iconSizeSmall() {
return this.iconFontSize * 0.6;
},
// Card
cardDefaultBg: '#fff',
// Check Box
checkboxBgColor: '#039BE5',
checkboxSize: 23,
checkboxTickColor: '#fff',
// Color
brandPrimary: '#5067FF',
brandInfo: '#5bc0de',
brandSuccess: '#5cb85c',
brandDanger: '#d9534f',
brandWarning: '#f0ad4e',
brandSidebar: '#252932',
// Font
fontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto',
fontSizeBase: 15,
get fontSizeH1() {
return this.fontSizeBase * 1.8;
},
get fontSizeH2() {
return this.fontSizeBase * 1.6;
},
get fontSizeH3() {
return this.fontSizeBase * 1.4;
},
// Footer
footerHeight: 55,
footerDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
// FooterTab
tabBarTextColor: (Platform.OS === 'ios') ? '#6b6b6b' : '#b3c7f9',
tabBarActiveTextColor: (Platform.OS === 'ios') ? '#007aff' : '#fff',
tabActiveBgColor: (Platform.OS === 'ios') ? '#cde1f9' : undefined,
// Header
iosToolbarBtnColor: '#007aff',
toolbarDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
toolbarHeight: (Platform.OS === 'ios') ? 64 : 56,
toolbarIconSize: (Platform.OS === 'ios') ? 20 : 22,
toolbarInputColor: '#CECDD2',
toolbarInverseBg: '#222',
toolbarTextColor: (Platform.OS === 'ios') ? '#000' : '#fff',
get statusBarColor() {
return color(this.toolbarDefaultBg).darken(0.2).hexString();
},
// Icon
iconFamily: 'Ionicons',
iconFontSize: (Platform.OS === 'ios') ? 30 : 28,
iconMargin: 7,
// InputGroup
inputFontSize: 15,
inputBorderColor: '#D9D5DC',
inputSuccessBorderColor: '#2b8339',
inputErrorBorderColor: '#ed2f2f',
get inputColor() {
return this.textColor;
},
get inputColorPlaceholder() {
return '#575757';
},
inputGroupMarginBottom: 10,
inputHeightBase: 40,
inputPaddingLeft: 5,
get inputPaddingLeftIcon() {
return this.inputPaddingLeft * 8;
},
// Line Height
btnLineHeight: 19,
lineHeightH1: 32,
lineHeightH2: 27,
lineHeightH3: 22,
iconLineHeight: (Platform.OS === 'ios') ? 37 : 30,
lineHeight: (Platform.OS === 'ios') ? 20 : 24,
// List
listBorderColor: '#ddd',
listDividerBg: '#ddd',
listItemHeight: 45,
listItemPadding: 9,
listNoteColor: '#808080',
listNoteSize: 13,
// Progress Bar
defaultProgressColor: '#E4202D',
inverseProgressColor: '#1A191B',
// Radio Button
radioBtnSize: (Platform.OS === 'ios') ? 25 : 23,
radioColor: '#7e7e7e',
get radioSelectedColor() {
return color(this.radioColor).darken(0.2).hexString();
},
// Spinner
defaultSpinnerColor: '#45D56E',
inverseSpinnerColor: '#1A191B',
// Tabs
tabBgColor: '#F8F8F8',
tabFontSize: 15,
tabTextColor: '#fff',
// Text
textColor: '#000',
inverseTextColor: '#fff',
// Title
titleFontSize: (Platform.OS === 'ios') ? 17 : 19,
subTitleFontSize: (Platform.OS === 'ios') ? 12 : 14,
subtitleColor: '#8e8e93',
// Other
borderRadiusBase: (Platform.OS === 'ios') ? 5 : 2,
borderWidth: 1,
contentPadding: 10,
get darkenHeader() {
return color(this.tabBgColor).darken(0.03).hexString();
},
dropdownBg: '#000',
dropdownLinkColor: '#414142',
inputLineHeight: 24,
jumbotronBg: '#C9C9CE',
jumbotronPadding: 30,
};
|
NativeForms/framework-src
|
src/App/themes/base.theme.js
|
JavaScript
|
mit
| 4,619
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Dependinator.Common.ApiHandling;
using Dependinator.Utils;
namespace Dependinator.Common.ModelMetadataFolders.Private
{
internal class OpenModelService : IOpenModelService
{
private readonly IApiManagerService apiManagerService;
private readonly IExistingInstanceService existingInstanceService;
private readonly Lazy<ILoadModelService> loadModelService;
private readonly IModelMetadataService modelMetadataService;
private readonly IOpenFileDialogService openFileDialogService;
private readonly IStartInstanceService startInstanceService;
public OpenModelService(
Lazy<ILoadModelService> loadModelService,
IModelMetadataService modelMetadataService,
IOpenFileDialogService openFileDialogService,
IExistingInstanceService existingInstanceService,
IStartInstanceService startInstanceService,
IApiManagerService apiManagerService)
{
this.loadModelService = loadModelService;
this.modelMetadataService = modelMetadataService;
this.openFileDialogService = openFileDialogService;
this.existingInstanceService = existingInstanceService;
this.startInstanceService = startInstanceService;
this.apiManagerService = apiManagerService;
}
public void ShowOpenModelDialog() => startInstanceService.OpenOrStartDefaultInstance();
public async Task OpenOtherModelAsync()
{
if (!openFileDialogService.TryShowOpenFileDialog(out string modelFilePath))
{
return;
}
await TryModelAsync(modelFilePath);
}
public async Task TryModelAsync(string modelFilePath)
{
if (modelMetadataService.ModelFilePath.IsSameIc(modelFilePath))
{
Log.Debug("User tries to open same model that is already open");
return;
}
await OpenOtherModelAsync(modelFilePath);
}
public async Task OpenCurrentModelAsync()
{
if (existingInstanceService.TryActivateExistingInstance(null))
{
// Another instance for this working folder is already running and it received the
// command line from this instance, lets exit this instance, while other instance continuous
Application.Current.Shutdown(0);
return;
}
apiManagerService.Register();
await loadModelService.Value.LoadAsync();
}
public async Task OpenModelAsync(IReadOnlyList<string> modelFilePaths)
{
// Currently only support one dropped file
string modelFilePath = modelFilePaths.First();
await TryModelAsync(modelFilePath);
}
private async Task OpenOtherModelAsync(string modelFilePath)
{
if (!existingInstanceService.TryActivateExistingInstance(modelFilePath, null))
{
startInstanceService.StartInstance(modelFilePath);
}
if (modelMetadataService.IsDefault)
{
// The open model dialog can be closed after opening other model
await Task.Delay(500);
Application.Current.Shutdown(0);
}
}
}
}
|
michael-reichenauer/Dependinator
|
Dependinator/Common/ModelMetadataFolders/Private/OpenModelService.cs
|
C#
|
mit
| 3,537
|
/*
* I'm well aware how much of a mess this program is. That's what tends
* to happen with complicated programs. If you're trying to grok it,
* please drop me an e-mail at adam@kurkiewicz.pl, I'll be happy to give
* you a few pointers.
* Adam
*/
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
//import org.junit.Assert;
public class Main{
static{
GraphFactory.setProblemLocales(ProblemLocales.exampleLocales());
}
/*static ConcurrentLinkedQueue<NonBlockingHashMap<Long, Node>> giveSolutions(DataGraph dg){
UltimateRecurssion newRecurssion = new UltimateRecurssion(dg);
Future<?> future = uberPool.submit(newRecurssion);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return dg.getSolutions();
}*/
public static void main(String[] args){
//String filepath = args[0];
//FileReader fr = new FileReader(filepath);
//ArrayList<DataGraph> graphs = GraphFactory.makeTwoRandomSparseGraphs(10, 2);
int graphSize = 10000;
int threads = 1;
int maxThreads = 10;
int repetitions = 4;
DataGraph dg;
TarjanGraph dgt;
//DataGraph dg = GraphFactory.makeSanityCheckGraph();
//SCCGraph<? extends DeNode<?, ?>> tusia;
//tusia = graphs.get(0);
/*for (NonBlockingHashMap<Long, ? extends DeNode<?, ?>> map: giveSolutions(dg)){
//System.out.println(map);
}*/
System.out.println("# Cores | SCC speed | Tarjan ");
for(int i = threads; i < maxThreads; i++){
ProblemLocales locales = new ProblemLocales(graphSize, i, 0.75F);
GraphFactory.setProblemLocales(locales);
DataGraph.setLocales();
for(int ii = 0; ii < repetitions; ii++){
System.out.print(i + " ");
dg = new DataGraph();
dgt = new TarjanGraph();
GraphFactory.changeSeed();
GraphFactory.makeRandomSparseGraph(graphSize, 2, dg, Node.class);
GraphFactory.makeRandomSparseGraph(graphSize, 2, dgt, TarjanNode.class);
long dgtResult = dgt.start();
long dgResult = dg.start();
System.out.print(dgResult + " ");
System.out.println(dgtResult + " ");
}
}
/*for (NonBlockingHashMap<Long, ? extends DeNode<?, ?>> map: dgt.getSolutions()){
//System.out.println(map);
}*/
//System.out.println(dg.compareTo(dgt));
//System.out.println(dg.getNodes().get(1).getChildren());
//System.out.println(dgt.getSolutions());
//dg.compareTo(dgt);
}
}
|
picrin/SCDC
|
src/Main.java
|
Java
|
mit
| 2,558
|
use graph::Graph;
use adjacency_matrix::AdjacencyMatrix;
pub fn traveling_salesman_problem(g: &Graph) -> Vec<usize> {
if g.vertex_count == 0 {
return vec![];
}
let m = AdjacencyMatrix::from_graph(&g);
optimize_tour(&construct_tour(&m), &m)
}
// construct_tour incrementally inserts the furthest vertex to create a tour.
fn construct_tour(m: &AdjacencyMatrix) -> Vec<usize> {
let mut tour = vec![0];
while tour.len() < m.size() {
let (x, index) = furthest_vertex(&tour, m);
tour.insert(index, x);
}
tour
}
// furthest_vertex returns the vertex furthest away from tour, and the position at which it should
// be inserted in tour to add the smallest amount of distance.
fn furthest_vertex(tour: &Vec<usize>, m: &AdjacencyMatrix) -> (usize, usize) {
let (x, (index, _)) = (0..m.size())
.filter(|x| !tour.contains(x))
.map(|x| (x, smallest_insertion(x, tour, m)))
.max_by_key(|&(_, (_, distance))| distance)
.unwrap();
(x, index)
}
// smallest_insertion finds where x should be inserted in tour to add the smallest amount of
// distance, and returns the resulting index and added distance.
fn smallest_insertion(x: usize, tour: &Vec<usize>, m: &AdjacencyMatrix) -> (usize, u32) {
(0..tour.len())
.map(|i| {
let prev_vertex = if i == 0 { tour[tour.len() - 1] } else { tour[i - 1] };
let next_vertex = tour[i];
m[prev_vertex][x] + m[x][next_vertex]
})
.enumerate()
.min_by_key(|&(_, distance)| distance)
.unwrap()
}
// optimize_tour returns a new tour improved with 2-opt optimization.
fn optimize_tour(tour: &Vec<usize>, m: &AdjacencyMatrix) -> Vec<usize> {
let mut optimized_tour = tour.to_vec();
while let Some(swapped_tour) = find_optimized_tour(&optimized_tour, m) {
optimized_tour = swapped_tour
}
optimized_tour
}
// find_optimized_tour tries to return a new tour obtained by swapping two vertices of tour and that
// has a smaller distance than tour.
fn find_optimized_tour(tour: &Vec<usize>, m: &AdjacencyMatrix) -> Option<Vec<usize>> {
for i in 0..tour.len()-1 {
for j in i+1..tour.len() {
let new_tour = swap_tour(&tour, i, j);
if m.distance(&new_tour) < m.distance(&tour) {
return Some(new_tour);
}
}
}
None
}
// swap_tour returns a new tour where the positions of the vertices at indexes i and j have been
// swapped.
fn swap_tour(tour: &Vec<usize>, i: usize, j: usize) -> Vec<usize> {
let a = 0..i;
let b = (i..j+1).rev();
let c = j+1..tour.len();
a.chain(b).chain(c).map(|index| tour[index]).collect()
}
|
peferron/algo
|
traveling_salesman_problem/rust/traveling_salesman_problem.rs
|
Rust
|
mit
| 2,716
|
<?php
declare(strict_types=1);
namespace GraphQL\Doctrine\Annotation;
/**
* Annotation used to override values for an field argument in GraphQL.
*
* The name of the argument is required and must match the actual PHP argument name.
*
* All other values are optional and should only be used to override
* what is declared by the original argument of the method.
*
* @Annotation
* @Target({"ANNOTATION"})
*/
final class Filter
{
/**
* Name of the field on which to apply the operator.
*
* The field may or may not actually exist in the entity. It is merely used
* to organize the filter correctly in the API.
*
* @var string
* @Required
*/
public $field;
/**
* Key referring to the type instance of PHP class implementing the GraphQL type.
*
* @var string
* @Required
*/
public $operator;
/**
* GraphQL leaf type name of the type of the field.
*
* @var string
* @Required
*/
public $type;
}
|
Ecodev/graphql-doctrine
|
src/Annotation/Filter.php
|
PHP
|
mit
| 1,017
|
<?php
namespace Codeception;
use Codeception\Exception\ConfigurationException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class Codecept
{
const VERSION = "2.1.0";
/**
* @var \Codeception\PHPUnit\Runner
*/
protected $runner;
/**
* @var \PHPUnit_Framework_TestResult
*/
protected $result;
/**
* @var \Codeception\CodeCoverage
*/
protected $coverage;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
protected $dispatcher;
/**
* @var array
*/
protected $options = [
'silent' => false,
'debug' => false,
'steps' => false,
'html' => false,
'xml' => false,
'json' => false,
'tap' => false,
'report' => false,
'colors' => false,
'coverage' => false,
'coverage-xml' => false,
'coverage-html' => false,
'coverage-text' => false,
'groups' => null,
'excludeGroups' => null,
'filter' => null,
'env' => null,
'fail-fast' => false,
'verbosity' => 1,
'interactive' => true,
'no-rebuild' => false
];
protected $config = [];
/**
* @var array
*/
protected $extensions = [];
public function __construct($options = [])
{
$this->result = new \PHPUnit_Framework_TestResult;
$this->dispatcher = new EventDispatcher();
$baseOptions = $this->mergeOptions($options);
$this->loadExtensions($baseOptions);
$this->config = Configuration::config();
$this->options = $this->mergeOptions($options);
$this->registerSubscribers();
$this->registerPHPUnitListeners();
$printer = new PHPUnit\ResultPrinter\UI($this->dispatcher, $this->options);
$this->runner = new PHPUnit\Runner();
$this->runner->setPrinter($printer);
}
/**
* Merges given options with default values and current configuration
*
* @param array $options options
* @return array
* @throws ConfigurationException
*/
protected function mergeOptions($options)
{
$config = Configuration::config();
$baseOptions = array_merge($this->options, $config['settings']);
return array_merge($baseOptions, $options);
}
protected function loadExtensions($options)
{
$config = Configuration::config();
foreach ($config['extensions']['enabled'] as $extensionClass) {
if (!class_exists($extensionClass)) {
throw new ConfigurationException(
"Class `$extensionClass` is not defined. Autoload it or include into "
. "'_bootstrap.php' file of 'tests' directory"
);
}
$extensionConfig = isset($config['extensions']['config'][$extensionClass])
? $config['extensions']['config'][$extensionClass]
: [];
$extension = new $extensionClass($extensionConfig, $options);
if (!$extension instanceof EventSubscriberInterface) {
throw new ConfigurationException(
"Class $extensionClass is not an EventListener. Please create it as Extension or Group class."
);
}
$this->extensions[] = $extension;
}
}
protected function registerPHPUnitListeners()
{
$listener = new PHPUnit\Listener($this->dispatcher);
$this->result->addListener($listener);
}
public function registerSubscribers()
{
// required
$this->dispatcher->addSubscriber(new Subscriber\GracefulTermination());
$this->dispatcher->addSubscriber(new Subscriber\ErrorHandler());
$this->dispatcher->addSubscriber(new Subscriber\Bootstrap());
$this->dispatcher->addSubscriber(new Subscriber\Module());
$this->dispatcher->addSubscriber(new Subscriber\BeforeAfterTest());
// optional
if (!$this->options['no-rebuild']) {
$this->dispatcher->addSubscriber(new Subscriber\AutoRebuild());
}
if (!$this->options['silent']) {
$this->dispatcher->addSubscriber(new Subscriber\Console($this->options));
}
if ($this->options['fail-fast']) {
$this->dispatcher->addSubscriber(new Subscriber\FailFast());
}
if ($this->options['coverage']) {
$this->dispatcher->addSubscriber(new Coverage\Subscriber\Local($this->options));
$this->dispatcher->addSubscriber(new Coverage\Subscriber\LocalServer($this->options));
$this->dispatcher->addSubscriber(new Coverage\Subscriber\RemoteServer($this->options));
$this->dispatcher->addSubscriber(new Coverage\Subscriber\Printer($this->options));
}
// extensions
foreach ($this->extensions as $subscriber) {
$this->dispatcher->addSubscriber($subscriber);
}
}
public function run($suite, $test = null)
{
ini_set('memory_limit', isset($this->config['settings']['memory_limit']) ? $this->config['settings']['memory_limit'] : '1024M');
$settings = Configuration::suiteSettings($suite, Configuration::config());
$selectedEnvironments = $this->options['env'];
$environments = Configuration::suiteEnvironments($suite);
if (!$selectedEnvironments or empty($environments)) {
$this->runSuite($settings, $suite, $test);
return;
}
foreach (array_unique($selectedEnvironments) as $envList) {
$envArray = explode(',', $envList);
$config = [];
foreach ($envArray as $env) {
if (isset($environments[$env])) {
$currentEnvironment = isset($config['current_environment']) ? [$config['current_environment']] : [];
$config = Configuration::mergeConfigs($config, $environments[$env]);
$currentEnvironment[] = $config['current_environment'];
$config['current_environment'] = implode(',', $currentEnvironment);
}
}
if (empty($config)) {
continue;
}
$suiteToRun = "{$suite}-{$envList}";
$this->runSuite($config, $suiteToRun, $test);
}
}
public function runSuite($settings, $suite, $test = null)
{
$suiteManager = new SuiteManager($this->dispatcher, $suite, $settings);
$suiteManager->initialize();
$suiteManager->loadTests($test);
$suiteManager->run($this->runner, $this->result, $this->options);
return $this->result;
}
public static function versionString()
{
return 'Codeception PHP Testing Framework v' . self::VERSION;
}
public function printResult()
{
$result = $this->getResult();
$result->flushListeners();
$printer = $this->runner->getPrinter();
$printer->printResult($result);
$this->dispatcher->dispatch(Events::RESULT_PRINT_AFTER, new Event\PrintResultEvent($result, $printer));
}
/**
* @return \PHPUnit_Framework_TestResult
*/
public function getResult()
{
return $this->result;
}
public function getOptions()
{
return $this->options;
}
/**
* @return EventDispatcher
*/
public function getDispatcher()
{
return $this->dispatcher;
}
}
|
abbeshamza/TestCodeception
|
vendor/codeception/codeception/src/Codeception/Codecept.php
|
PHP
|
mit
| 7,682
|
2015.02.04
==========
* Checked tightness on YZ traverse screws
* Made a pointer bracket for finding the turbine's zero angle. Found the
location by putting an I-beam across the front edge of the frame and
measuring 2.177 inches away, 8.625 inches down from the blade tip.
* Degreased Vectrino mounting strut for applying gaffer's tape.
* Cleaned and greased YZ traverse linear bearings.
* Got turbine and Vectrino installed at about 5:30 PM.
|
UNH-CORE/RM2-tow-tank
|
Documents/Lab notebooks/2015.02.04-install.md
|
Markdown
|
mit
| 449
|
export * from './baPageTop';
// export * from './baMsgCenter';
export * from './baSidebar';
export * from './baMenu/components/baMenuItem';
export * from './baMenu';
export * from './baContentTop';
export * from './baCard';
export * from './baAmChart';
export * from './baChartistChart';
export * from './baBackTop';
export * from './baFullCalendar';
export * from './baPictureUploader';
export * from './baCheckbox';
export * from './baMultiCheckbox';
|
sahil0026/pint
|
src/app/theme/components/index.ts
|
TypeScript
|
mit
| 453
|
# Development Process
* Semver is used for versionon
* `master` represents the latest state of the app
* features should be implemented on feature branches `feature/*`
* releases are managed by adding flags to commit messages
* hotfixes to previous version are implemented on `hotfix/X.Y` branches (X.Y is major+minor version)
## Development
* Develop features on `feature/*` branches
* Each feature branch is built by Travis (tests + coverage)
* Create a Pull Request
* Merge the Pull Request adding CI flags (see below)
## Release (npm, gh-pages)
* When merging a Pull Request add following flags to message commit:
* `[patch]` - to increment patch version (e.g. 1.1.1 -> 1.1.2) and publish to NPM
* `[minor]` - to increment minor version (e.g. 1.1.1 -> 1.2.0) and publish to NPM
* `[major]` - to increment major version (e.eg 1.1.1 -> 2.0.0) and publish to NPM
* `[gh-pages]` - to deploy to gh-pages
* To release current master version add an empty commit with tags, e.g.
* `git commit --allow-empty -m "Release [patch] [gh-pages]"`
## Hotfixes
Master represents the latest version of the app. If you need to apply a hotfix for older version, e.g. latest version is 2.0.0 and you need a hotfix for 1.4.0:
* Change .travis.yml config to allow running deployment scripts on all branches (on: all_branches: true)
* Create a hotfix branch, e.g. `hotfix/1.4`
* Create a feature branch for the fix
* Create a Pull Request to merge `feature/*` to `hotfix/1.4`
* Merge the Pull Request adding `[patch]` tag in the commit message
* Alternatively you can commit your changes straight to hotfix/* and add `[patch]` tag
|
ifrost/starterkit
|
docs/dev/process.md
|
Markdown
|
mit
| 1,641
|
'use strict';
var _ = require('lodash');
var request = require('request');
var VERSION = require('../package.json').version;
var REST_BASE_URL = 'https://api.spike.cc/v1/';
/**
* SpikeAPI
*/
function SpikeAPI(options) {
this.options = _.assign({
secretKey: '',
publishableKey: ''
}, options);
this.requestDefaults = {
auth: {
user: this.options.secretKey,
pass: ''
},
headers: {
'Accept': '*/*',
'Connection': 'close',
'User-Agent': 'node-spike-api/' + VERSION
},
json: true
};
}
/**
* Create a new charge by REST API.
* @param {object} chargeData Data of charge.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.postCharge = function(chargeData, callback) {
chargeData = _.assign({
currency: '', // Currency billing amount. ['USD'|'JPY']
amount: 0, // Amount of the billing.
card: '', // Token that has been acquired in SPIKE Checkout.
products: [] // Array of Product instance for billing.
}, chargeData);
// validate argments
var isValid = _validateArgs([
'String', 'Number', 'String', 'Array', 'Function'
], [
chargeData.currency,
chargeData.amount,
chargeData.card,
chargeData.products,
callback
]);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges';
// create form data
var formData = {
amount: chargeData.amount,
currency: chargeData.currency,
card: chargeData.card,
products: JSON.stringify(chargeData.products)
};
var options = _.assign(this.requestDefaults, {
form: formData
});
// post API
this._request('post', url, options, callback);
};
/**
* Get a charge info by REST API.
* @param {string} id Charge ID.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getCharge = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges/' + id;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
/**
* Refund the charge of specified ID by REST API.
* @param {string} id charge id.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.refundCharge = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges/' + id + '/refund';
var options = this.requestDefaults;
// post API
this._request('post', url, options, callback);
};
/**
* Get a charge list by REST API.
* @param {number} limit Acquisition number of list.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getChargeList = function(limit, callback) {
// validate argments
if (_.isFunction(limit)) {
callback = limit;
limit = 10;
}
var isValid = _validateArgs([
'Number', 'Function'
], arguments, 1);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges?limit=' + limit;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
/**
* Create a new token by REST API.
* @param {object} cardData Data of card.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.postToken = function(cardData, callback) {
cardData = _.assign({
'card[number]': 4444333322221111, // Number of credit card
'card[exp_month]': 1, // Expire month of credit card
'card[exp_year]': 2020, // Expire year of credit card
'card[cvc]': 111, // Cvc of credit card
'card[name]': '', // Name of credit card holder
'currency': 'JPY', // Currency code
'email': '' // Email of credit card holder
}, cardData);
// validate argments
var isValid = _validateArgs([
'Number',
'Number',
'Number',
'Number',
'String',
'String',
'String',
'Function'
], [
cardData['card[number]'],
cardData['card[exp_month]'],
cardData['card[exp_year]'],
cardData['card[cvc]'],
cardData['card[name]'],
cardData.currency,
cardData.email,
callback
]);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'tokens';
var options = _.assign(this.requestDefaults, {
form: cardData
});
// post API
this._request('post', url, options, callback);
};
/**
* Return token information of specified token ID by REST API.
* @param {string} id token id
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getToken = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'tokens/' + id;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
// Request API
SpikeAPI.prototype._request = function(method, url, options, callback) {
method = method.toLowerCase();
request[method](url, options, function(err, res, body) {
if (err) {
return callback(err);
}
if (res.statusCode >= 400) {
return callback(new Error(res.headers.status), body);
}
return callback(null, body);
});
};
// validate argments
function _validateArgs(argTypes, args, minArgs) {
var isInvalid = false;
minArgs = _.isNumber(minArgs) ? minArgs : argTypes.length;
if (args.length < minArgs) {
return _returnError(args);
}
for(var i = 0, l = argTypes.length; i < l; i++) {
var argType = argTypes[i];
var arg = args[i];
if (args.length === argTypes.length && !_['is' + argType](arg)) {
isInvalid = true;
break;
}
}
if (isInvalid) {
return _returnError(args);
} else {
return true;
}
}
function _returnError(args) {
var err = new Error('Invalid argments.');
var callback = null;
_.each(args, function(arg) {
if (_.isFunction(arg)) {
callback = arg;
}
});
if (_.isFunction(callback)) {
return {
callback: callback,
err: err
};
} else {
throw err;
}
}
/**
* Product
*/
function Product(attrs) {
this.attrs = _.assign({
id: '',
title: '',
description: '',
language: 'EN',
price: 0,
currency: '',
count: 0,
stock: 0
}, attrs);
}
/**
* getter
* @param {string} attr Name of attribute.
* @returns {stirng|number} Value of attribute.
*/
Product.prototype.get = function(attr) {
return this.attrs[attr];
};
/**
* setter
* @param {string} attr Name of attribute.
* @param {string|number} value Value of attribute.
*/
Product.prototype.set = function(attr, value) {
if (!_.isUndefined(this.attrs[attr])) {
this.attrs[attr] = value;
}
};
/**
* return JSON Object
* @returns {object} JSON Object
*/
Product.prototype.toJSON = function() {
return this.attrs;
};
// exports
module.exports = {
SpikeAPI: SpikeAPI,
Product: Product
};
|
takayukii/node-spike-api
|
lib/spike-api.js
|
JavaScript
|
mit
| 7,195
|
# github user name.
#
# %w[github udzura]
default["github-pubkey"]["github-members"] = %w[]
# system user name.
#
# %w[fluentd-user hrforecast-user]
default["github-pubkey"]["usernames"] = %w[]
|
aiming-cookbooks/github-pubkey
|
attributes/default.rb
|
Ruby
|
mit
| 195
|
<?php
namespace FS\SolrBundle\Doctrine\Annotation;
use Doctrine\Common\Annotations\Annotation;
/**
* @Annotation
*/
class MetaFields extends Field
{
public $fields = array();
}
|
andythorne/SolrBundle
|
Doctrine/Annotation/MetaFields.php
|
PHP
|
mit
| 185
|
%% LaTeX Beamer presentation template (requires beamer package)
%% see http://bitbucket.org/rivanvx/beamer/wiki/Home
%% idea contributed by H. Turgut Uyar
%% template based on a template by Till Tantau
%% this template is still evolving - it might differ in future releases!
% by:
% amir sohrabi
% this file is presented for assignment in scientific writing class
% MEEN 653-600 Scientific Writing fall2014
%
\documentclass{beamer}
\mode<presentation>
{
\usetheme{Warsaw}
\setbeamercovered{transparent}
}
\usepackage[english]{babel}
\usepackage[latin1]{inputenc}
% font definitions, try \usepackage{ae} instead of the following
% three lines if you don't like this look
\usepackage{mathptmx}
\usepackage[scaled=.90]{helvet}
\usepackage{courier}
\usepackage[T1]{fontenc}
\title{Introduction to \LaTeX}
\subtitle{A presentation for scinetific writing course}
% - Use the \inst{?} command only if the authors have different
% affiliation.
%\author{F.~Author\inst{1} \and S.~Another\inst{2}}
\author{Amir Sohrabi\inst{1}}
\institute[Universities of]
{
\inst{1}%
Department of Mechanical Engineering\\
Texas A\&M University
}
\date{29 Sep 2014}
% This is only inserted into the PDF information catalog. Can be left
% out.
\subject{presentation for MEEN 653-600 Scientific Writing}
\AtBeginSubsection[]
{
\begin{frame}<beamer>{Outline}
\tableofcontents[currentsection,currentsubsection]
\end{frame}
}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:
%\beamerdefaultoverlayspecification{<+->}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\begin{frame}
\frametitle{Outline}
\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}
\section{Introduction}
\subsection{About \LaTeX }
\begin{frame}{About \LaTeX \cite{LaTeX_wiki}}
\begin{itemize}
\item \LaTeX was originally written in the early 1980s by Leslie Lamport at SRI
\item It was releases in 1984
\item \LaTeX is usually pronounced as: lay-tek or lah-tek
\item Scientific written communication is done in \LaTeX
\item It is good with displaying formulas
\item Its can handle multiple language documents
\item It is distributed under a free software license
\end{itemize}
\end{frame}
\subsection{Comparing Microsoft Word and \LaTeX}
\begin{frame} {Comparing Microsoft Word and \LaTeX}
\begin{itemize}
\item Word is not Free
\item It seems the there is no need to learn Word, \LaTeX has to be learned
\item In Word every thing is in the file, \LaTeX separates all the components
\item Size of the files can be huge in Word, \LaTeX main file are normally smaller than 100KB
\item It takes up to minutes for Word to load, in \LaTeX file can be written in a note pad program
\item Word updates to new version that has problem with old files, \LaTeX is basically the same since begining with new features
\end{itemize}
\end{frame}
\begin{frame} {Performance Test \cite{The_Beauty_of_LATEX}}
\begin{columns}[t]
\begin{column}[T]{5cm}
Justification and hyphenation
\end{column}
\begin{column}[T]{5cm} % alternative top-align that's better for graphics
\includegraphics[height=5cm,trim = 0mm 0mm 00mm 0mm]{../figs/comparison.pdf}\\
\end{column}
\end{columns}
\end{frame}
\section{Distibutions}
\begin{frame}{Distributions of \LaTeX}
\begin{columns}[t]
\begin{column}[T]{5cm}
MiKTeX
\includegraphics[scale=0.15,trim = 0mm 0mm 00mm 0mm]{../figs/MiKText.png}
\end{column}
\begin{column}[T]{5cm} % alternative top-align that's better for graphics
TeXlive
\includegraphics[scale=0.15,trim = 0mm 0mm 00mm 0mm]{../figs/TeXLive.png}
\end{column}
\end{columns}
\end{frame}
\section{\LaTeX editors}
\begin{frame}{\LaTeX editors}
\centering
\begin{columns}[t]
\begin{column}[T]{3cm}
\centering Texmaker
\begin{figure}
\includegraphics[height=2cm,trim = 0mm 0mm 00mm 0mm]{../figs/texmaker.png}
\end{figure}
\end{column}
\begin{column}[T]{3cm} % alternative top-align that's better for graphics
\centering TeXworks
\begin{figure}
\includegraphics[height=2cm,trim = 0mm 0mm 00mm 0mm]{../figs/TeXworks.png}
\end{figure}
\end{column}
\begin{column}[T]{3cm} % alternative top-align that's better for graphics
\centering TeXlipse
\begin{figure}
\includegraphics[height=2cm,trim = 0mm 20mm 0mm 0mm]{../figs/TexLipse.png}
\end{figure}
\end{column}
\end{columns}
\end{frame}
\section{Structure of a document in \LaTeX}
\begin{frame}{Structure of a document in \LaTeX}
Different parts of the document
\includegraphics[height=6cm,trim = 0mm 20mm 0mm 0mm]{../figs/sample_thesis_document.png}
\end{frame}
\subsubsection{Usefull features of \LaTeX}
\subsubsection{Citation}
\begin{frame}{Citation}
\begin{itemize}
\item Citations are stored in a standard way
\item They are printed and sorted as they are used and requested
\item Numbering is automatic
\item The style is defined already
\item There are programs to manage the citations
\item Citing directly from google scholar is possible
\end{itemize}
\end{frame}
\section{Writing in \LaTeX}
\begin{frame}{Writing in \LaTeX}
\begin{itemize}
\item Freedom in writing sentences
\item Commenting the document is easier
\item Reviewing will be faster
\item Changing type of ducument is trivial
\item Using version control is possible
\end{itemize}
\end{frame}
\begin{frame}[allowframebreaks]
\tiny
\frametitle{References}
\bibliographystyle{plain}
\bibliography{references}
\end{frame}
\begin{frame}
\centering
Questions?
\end{frame}
\end{document}
|
eda-globetrotter/SienaLaTeX
|
latex_introduction_to/tex/introduction_to_latex.tex
|
TeX
|
mit
| 5,810
|
var translattionTable = {
"search": "Buscar",
"emptyTable": "",
"decimal": "",
"info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
"infoEmpty": "",
"infoFiltered": "(filtradas de _MAX_ entradas)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "Mostrar _MENU_",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"zeroRecords": "",
"paginate": {
"first": "Primera",
"last": "Última",
"next": ">",
"previous": "<"
}
};
|
trivialbox/aluc
|
public/js/common/tables.js
|
JavaScript
|
mit
| 526
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Dec 03 20:21:22 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID (PMD PL/SQL 5.2.2 API)</title>
<meta name="date" content="2014-12-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID (PMD PL/SQL 5.2.2 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/plsql/ast/class-use/ASTEqualsOldIDNewID.html" target="_top">Frames</a></li>
<li><a href="ASTEqualsOldIDNewID.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID" class="title">Uses of Class<br>net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#net.sourceforge.pmd.lang.plsql.ast">net.sourceforge.pmd.lang.plsql.ast</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sourceforge.pmd.lang.plsql.rule">net.sourceforge.pmd.lang.plsql.rule</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sourceforge.pmd.lang.plsql.ast">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/package-summary.html">net.sourceforge.pmd.lang.plsql.ast</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/package-summary.html">net.sourceforge.pmd.lang.plsql.ast</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><span class="strong">PLSQLParserVisitor.</span><code><strong><a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/PLSQLParserVisitor.html#visit(net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID,%20java.lang.Object)">visit</a></strong>(<a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a> node,
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> data)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><span class="strong">PLSQLParserVisitorAdapter.</span><code><strong><a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/PLSQLParserVisitorAdapter.html#visit(net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID,%20java.lang.Object)">visit</a></strong>(<a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a> node,
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> data)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sourceforge.pmd.lang.plsql.rule">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/rule/package-summary.html">net.sourceforge.pmd.lang.plsql.rule</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/rule/package-summary.html">net.sourceforge.pmd.lang.plsql.rule</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><span class="strong">AbstractPLSQLRule.</span><code><strong><a href="../../../../../../../net/sourceforge/pmd/lang/plsql/rule/AbstractPLSQLRule.html#visit(net.sourceforge.pmd.lang.plsql.ast.ASTEqualsOldIDNewID,%20java.lang.Object)">visit</a></strong>(<a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">ASTEqualsOldIDNewID</a> node,
<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> data)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../net/sourceforge/pmd/lang/plsql/ast/ASTEqualsOldIDNewID.html" title="class in net.sourceforge.pmd.lang.plsql.ast">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/plsql/ast/class-use/ASTEqualsOldIDNewID.html" target="_top">Frames</a></li>
<li><a href="ASTEqualsOldIDNewID.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2002–2014 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p>
</body>
</html>
|
byronka/xenos
|
utils/pmd-bin-5.2.2/docs/pmd-plsql/apidocs/net/sourceforge/pmd/lang/plsql/ast/class-use/ASTEqualsOldIDNewID.html
|
HTML
|
mit
| 10,192
|
<?php
namespace Fup\UnividaBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* DatosBasicosReunionRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class DatosBasicosReunionRepository extends EntityRepository
{
}
|
albeirobet/fup
|
src/Fup/UnividaBundle/Entity/DatosBasicosReunionRepository.php
|
PHP
|
mit
| 287
|
<?php
class ApartmentController extends AdminController
{
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('index','view','delete','create','update'),
'roles'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'apartment'=>$this->loadApartment($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$apartment=new Apartment;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($apartment);
if(isset($_POST['Apartment']))
{
$apartment->attributes=$_POST['Apartment'];
if($apartment->save())
$this->redirect(array('view','id'=>$apartment->id));
}
$this->render('create',array(
'apartment'=>$apartment,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$apartment=$this->loadApartment($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($apartment);
if(isset($_POST['Apartment']))
{
$apartment->attributes=$_POST['Apartment'];
if($apartment->save())
$this->redirect(array('view','id'=>$apartment->id));
}
$this->render('update',array(
'apartment'=>$apartment,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadApartment($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,Yii::t('app','Invalid request. Please do not repeat this request again.'));
}
/**
* Manages all models.
*/
public function actionIndex()
{
$apartment=new Apartment('search');
$apartment->unsetAttributes(); // clear any default values
if(isset($_GET['Apartment']))
$apartment->attributes=$_GET['Apartment'];
$this->render('index',array(
'apartment'=>$apartment,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadApartment($id)
{
$apartment=Apartment::model()->findByPk((int)$id);
if($apartment===null)
throw new CHttpException(404,Yii::t('app','The requested page does not exist.'));
return $apartment;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($apartment)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='apartment-form')
{
echo CActiveForm::validate($apartment);
Yii::app()->end();
}
}
}
|
ata/latumentent
|
protected/controllers/admin/ApartmentController.php
|
PHP
|
mit
| 3,773
|
// ***********************************************************************
// Copyright (c) 2011-2014 Charlie Poole
//
// 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.
// ***********************************************************************
using System;
using System.Xml;
using NUnit.Engine.Internal;
using NUnit.Engine.Services;
namespace NUnit.Engine.Runners
{
/// <summary>
/// Summary description for ProcessRunner.
/// </summary>
public class ProcessRunner : AbstractTestRunner
{
private static readonly Logger log = InternalTrace.GetLogger(typeof(ProcessRunner));
private ITestAgent _agent;
private ITestEngineRunner _remoteRunner;
private TestAgency _agency;
public ProcessRunner(IServiceLocator services, TestPackage package) : base(services, package)
{
_agency = Services.GetService<TestAgency>();
}
#region Properties
public RuntimeFramework RuntimeFramework { get; private set; }
#endregion
#region AbstractTestRunner Overrides
/// <summary>
/// Explore a TestPackage and return information about
/// the tests found.
/// </summary>
/// <param name="filter">A TestFilter used to select tests</param>
/// <returns>A TestEngineResult.</returns>
protected override TestEngineResult ExploreTests(TestFilter filter)
{
try
{
return _remoteRunner.Explore(filter);
}
catch (Exception e)
{
log.Error("Failed to run remote tests {0}", e.Message);
return CreateFailedResult(e);
}
}
/// <summary>
/// Load a TestPackage for possible execution
/// </summary>
/// <returns>A TestEngineResult.</returns>
protected override TestEngineResult LoadPackage()
{
log.Info("Loading " + TestPackage.Name);
Unload();
try
{
if (_agent == null)
{
_agent = _agency.GetAgent(TestPackage, 30000);
if (_agent == null)
throw new Exception("Unable to acquire remote process agent");
}
if (_remoteRunner == null)
_remoteRunner = _agent.CreateRunner(TestPackage);
return _remoteRunner.Load();
}
catch(Exception)
{
// TODO: Check if this is really needed
// Clean up if the load failed
Unload();
throw;
}
}
/// <summary>
/// Unload any loaded TestPackage and clear
/// the reference to the remote runner.
/// </summary>
public override void UnloadPackage()
{
try
{
if (_remoteRunner != null)
{
log.Info("Unloading remote runner");
_remoteRunner.Unload();
_remoteRunner = null;
}
}
catch (Exception e)
{
log.Warning("Failed to unload the remote runner. {0}", e.Message);
_remoteRunner = null;
}
}
/// <summary>
/// Count the test cases that would be run under
/// the specified filter.
/// </summary>
/// <param name="filter">A TestFilter</param>
/// <returns>The count of test cases</returns>
protected override int CountTests(TestFilter filter)
{
try
{
return _remoteRunner.CountTestCases(filter);
}
catch (Exception e)
{
log.Error("Failed to count remote tests {0}", e.Message);
return 0;
}
}
/// <summary>
/// Run the tests in a loaded TestPackage
/// </summary>
/// <param name="listener">An ITestEventHandler to receive events</param>
/// <param name="filter">A TestFilter used to select tests</param>
/// <returns>A TestResult giving the result of the test execution</returns>
protected override TestEngineResult RunTests(ITestEventListener listener, TestFilter filter)
{
try
{
return _remoteRunner.Run(listener, filter);
}
catch (Exception e)
{
log.Error("Failed to run remote tests {0}", e.Message);
return CreateFailedResult(e);
}
}
/// <summary>
/// Start a run of the tests in the loaded TestPackage, returning immediately.
/// The tests are run asynchronously and the listener interface is notified
/// as it progresses.
/// </summary>
/// <param name="listener">An ITestEventHandler to receive events</param>
/// <param name="filter">A TestFilter used to select tests</param>
/// <returns>An AsyncTestRun that will provide the result of the test execution</returns>
protected override AsyncTestEngineResult RunTestsAsync(ITestEventListener listener, TestFilter filter)
{
try
{
return _remoteRunner.RunAsync(listener, filter);
}
catch (Exception e)
{
log.Error("Failed to run remote tests {0}", e.Message);
var result = new AsyncTestEngineResult();
result.SetResult(CreateFailedResult(e));
return result;
}
}
/// <summary>
/// Cancel the ongoing test run. If no test is running, the call is ignored.
/// </summary>
/// <param name="force">If true, cancel any ongoing test threads, otherwise wait for them to complete.</param>
public override void StopRun(bool force)
{
try
{
_remoteRunner.StopRun(force);
}
catch (Exception e)
{
log.Error("Failed to stop the remote run. {0}", e.Message);
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
try
{
if (disposing && _agent != null)
{
log.Info("Stopping remote agent");
_agent.Stop();
_agent = null;
}
}
catch (Exception e)
{
log.Error("Failed to stop the remote agent. {0}", e.Message);
_agent = null;
}
}
TestEngineResult CreateFailedResult(Exception e)
{
var suite = XmlHelper.CreateTopLevelElement("test-suite");
XmlHelper.AddAttribute(suite, "type", "Assembly");
XmlHelper.AddAttribute(suite, "id", TestPackage.ID);
XmlHelper.AddAttribute(suite, "name", TestPackage.Name);
XmlHelper.AddAttribute(suite, "fullname", TestPackage.FullName);
XmlHelper.AddAttribute(suite, "runstate", "NotRunnable");
XmlHelper.AddAttribute(suite, "testcasecount", "1");
XmlHelper.AddAttribute(suite, "result", "Failed");
XmlHelper.AddAttribute(suite, "label", "Error");
XmlHelper.AddAttribute(suite, "start-time", DateTime.UtcNow.ToString("u"));
XmlHelper.AddAttribute(suite, "end-time", DateTime.UtcNow.ToString("u"));
XmlHelper.AddAttribute(suite, "duration", "0.001");
XmlHelper.AddAttribute(suite, "total", "1");
XmlHelper.AddAttribute(suite, "passed", "0");
XmlHelper.AddAttribute(suite, "failed", "1");
XmlHelper.AddAttribute(suite, "inconclusive", "0");
XmlHelper.AddAttribute(suite, "skipped", "0");
XmlHelper.AddAttribute(suite, "asserts", "0");
var failure = suite.AddElement("failure");
var message = failure.AddElementWithCDataSection("message", e.Message);
var stack = failure.AddElementWithCDataSection("stack-trace", e.StackTrace);
return new TestEngineResult(suite);
}
#endregion
}
}
|
michal-franc/nunit
|
src/NUnitEngine/nunit.engine/Runners/ProcessRunner.cs
|
C#
|
mit
| 9,396
|
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Acme\DevisBundle\AcmeDevisBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
josephassiga/Devis
|
app/AppKernel.php
|
PHP
|
mit
| 1,400
|
package mutation
import (
"math/rand"
"testing"
"github.com/arl/evolve/generator"
"github.com/stretchr/testify/require"
)
func TestStringMutation(t *testing.T) {
rng := rand.New(rand.NewSource(99))
alphabet := "abcd"
sm := &String{
Alphabet: alphabet,
Probability: generator.ConstFloat64(0.5),
}
mut := New(sm)
individual1 := "abcd"
individual2 := "abab"
individual3 := "cccc"
population := []interface{}{individual1, individual2, individual3}
// Perform several iterations.
for i := 0; i < 20; i++ {
population = mut.Apply(population, rng)
require.Lenf(t, population, 3, "Population size changed after mutation: %v", len(population))
// Check that each individual is still valid
for _, individual := range population {
sind := individual.(string)
require.Lenf(t, sind, 4, "Individual size changed after mutation: %d", len(sind))
for _, c := range []byte(sind) {
require.Containsf(t, []byte(alphabet), c, "Mutation introduced invalid character: %v", c)
}
}
}
}
|
aurelien-rainone/evolve
|
operator/mutation/string_mutation_test.go
|
GO
|
mit
| 1,020
|
// T42Frame.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// T42Frame frame
struct TalkEditChars {
CHAR m_cErase;
CHAR m_kill;
CHAR m_wErase;
};
class T42View;
class T42Frame : public CFrameWnd
{
DECLARE_DYNCREATE(T42Frame)
// Attributes
public:
BOOL m_bConnected;
void SystemMessage(UINT nID,LPCTSTR str);
void WSSystemMessage(UINT nID,LONG wsaError);
void SystemMessage(UINT nID,UINT nIDi);
void SystemMessage(LPCTSTR str);
void SystemMessage(UINT nID);
BOOL m_bMinimizeSleep;
void DeTray();
void WakeUp();
enum _wakeAction {
wakePopup = 1,
wakeSound = 2
};
UINT m_onWake;
BOOL m_bSleep;
BOOL m_bSleepMinimize;
BOOL m_bTrayed;
void SetTheIcon(HICON hicon);
BOOL m_bTrayMinimize;
void LoadLayout();
BOOL m_bHaveFocus;
HICON m_hFullCup;
HICON m_hNormal;
void AddToHotList(LPCTSTR str=NULL);
BOOL m_bEstablished;
virtual void OnUpdateFrameTitle(BOOL bAddToTitle);
void SetPeerName(LPCTSTR str=NULL);
void SaveLayout();
CString m_nameFromIP;
BYTE m_ghResolve[MAXGETHOSTSTRUCT];
HANDLE m_resolveHandle;
void CleanUp();
CWnd m_wndFake;
void Established(BOOL bEstablished);
void ShowMessage(LPCTSTR msg,UINT flags);
void ShowMessage(UINT nID,UINT flags);
void StatusLine(UINT nID);
CString m_Status;
void StatusLine(LPCTSTR str);
int m_nDatePaneNo;
CString m_sendBuffer;
BOOL m_bSentEC;
UINT m_receivedEC;
TalkEditChars m_localEC;
TalkEditChars m_remoteEC;
BOOL PutRemote(LPCTSTR str);
void SelectTalkSocket();
LONG m_remoteID;
LONG m_localID;
void AsyncCtlTransactSucceeded(TalkCtlResponse& response);
void AsyncCtlTransactFailed(UINT code,LONG error);
enum {
ctlFailSendto = 1,
ctlFailSelect, ctlFailError
};
UINT m_ctlSuccess;
UINT m_ctlFailure;
sockaddr_in m_ctlTarget;
BOOL AsyncCtlTransact(TalkCtlMessage& msg,sockaddr_in& target, UINT wmSuccess,UINT wmFailure);
TalkCtlMessage m_ctlRequest;
TalkCtlResponse m_ctlResponse;
CString m_TargetTTY;
CString m_LocalUser;
BOOL FillInMessage(TalkCtlMessage& msg);
SOCKET m_Socket;
SOCKADDR_IN m_ctlAddr;
SOCKET m_ctlSocket;
SOCKADDR_IN m_SourceAddr;
SOCKADDR_IN m_TargetAddr;
BYTE m_gethostData[MAXGETHOSTSTRUCT];
HANDLE m_asyncHandle;
CString m_TargetHost;
CString m_TargetUser;
CString m_Target;
// Operations
public:
T42Frame(); // protected constructor used by dynamic creation
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(T42Frame)
public:
virtual void ActivateFrame(int nCmdShow = -1);
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
protected:
CStatusBar m_wndStatusBar;
virtual ~T42Frame();
public:
// Generated message map functions
//{{AFX_MSG(T42Frame)
afx_msg void OnClose();
afx_msg void OnTalkRemoteuser();
afx_msg LRESULT OnInitiateTalk(WPARAM,LPARAM);
afx_msg LRESULT OnTargetResolved(WPARAM,LPARAM);
afx_msg LRESULT OnSourceResolved(WPARAM,LPARAM);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg LRESULT OnCTLTransact(WPARAM,LPARAM);
afx_msg LRESULT OnLookupSuccess(WPARAM,LPARAM);
afx_msg LRESULT OnLookupFailure(WPARAM,LPARAM);
afx_msg LRESULT OnAnnounceSuccess(WPARAM,LPARAM);
afx_msg LRESULT OnAnnounceFailure(WPARAM,LPARAM);
afx_msg LRESULT OnLeaveInviteSuccess(WPARAM,LPARAM);
afx_msg LRESULT OnLeaveInviteFailure(WPARAM,LPARAM);
afx_msg LRESULT OnTalkAccept(WPARAM,LPARAM);
afx_msg LRESULT OnLocalRemoveSuccess(WPARAM,LPARAM);
afx_msg LRESULT OnLocalRemoveFailure(WPARAM,LPARAM);
afx_msg LRESULT OnRemoteRemoveSuccess(WPARAM,LPARAM);
afx_msg LRESULT OnRemoteRemoveFailure(WPARAM,LPARAM);
afx_msg LRESULT OnTalk(WPARAM,LPARAM);
afx_msg LRESULT OnTalkChar(WPARAM,LPARAM);
afx_msg LRESULT OnTalkConnect(WPARAM,LPARAM);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnUpdateDate(CCmdUI* pCmdUI);
afx_msg LRESULT OnExitMenuLoop(WPARAM,LPARAM);
afx_msg void OnDestroy();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg LRESULT OnNameResolved(WPARAM,LPARAM);
afx_msg LRESULT OnIPResolved(WPARAM,LPARAM);
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
afx_msg LRESULT OnTrayIcon(WPARAM,LPARAM);
afx_msg void OnUpdateWindowHideintrayonminimize(CCmdUI* pCmdUI);
afx_msg void OnWindowHideintrayonminimize();
afx_msg void OnTalkAbort();
afx_msg void OnUpdateTalkAbort(CCmdUI* pCmdUI);
afx_msg void OnTalkReconnect();
afx_msg void OnUpdateTalkReconnect(CCmdUI* pCmdUI);
afx_msg void OnUpdateTalkRemoteuser(CCmdUI* pCmdUI);
afx_msg void OnUpdateSleepSleep(CCmdUI* pCmdUI);
afx_msg void OnSleepSleep();
afx_msg void OnUpdateSleepSleeponminimize(CCmdUI* pCmdUI);
afx_msg void OnSleepSleeponminimize();
afx_msg void OnUpdateSleepWakeupactionMakesound(CCmdUI* pCmdUI);
afx_msg void OnSleepWakeupactionMakesound();
afx_msg void OnUpdateSleepWakeupactionPopup(CCmdUI* pCmdUI);
afx_msg void OnSleepWakeupactionPopup();
afx_msg void OnUpdateSleepMinimizeonsleep(CCmdUI* pCmdUI);
afx_msg void OnSleepMinimizeonsleep();
afx_msg void OnTalkClose();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
BOOL InitStatusBar(UINT *pIndicators, int nSize, int nSeconds);
};
/////////////////////////////////////////////////////////////////////////////
|
hacker/T42
|
T42Frame.h
|
C
|
mit
| 5,399
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Domain.Apps.Core.HandleRules
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class EditorAttribute : Attribute
{
public RuleFieldEditor Editor { get; }
public EditorAttribute(RuleFieldEditor editor)
{
Editor = editor;
}
}
}
|
Squidex/squidex
|
backend/src/Squidex.Domain.Apps.Core.Operations/HandleRules/EditorAttribute.cs
|
C#
|
mit
| 686
|
package edu.vse.dtos;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;
import static com.fasterxml.jackson.annotation.JsonTypeInfo.As.WRAPPER_OBJECT;
import static com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME;
@JsonTypeInfo(include = WRAPPER_OBJECT, use = NAME)
@JsonTypeName("packages")
public class Packages {
private final List<Package> items;
public Packages(List<Package> items) {
this.items = items;
}
public List<Package> getItems() {
return items;
}
}
|
jirkae/BeerCheese
|
backend/beer-app/src/main/java/edu/vse/dtos/Packages.java
|
Java
|
mit
| 594
|
'use strict';
const { expect } = require('chai');
const _ = require('lodash');
const sinon = require('sinon');
const run = require('../../../src/lib/run');
describe('Command runner library', () => {
describe('run method', () => {
const data = [
{
name: 'first',
words: ['foo', 'bar'],
},
{
name: 'second',
words: ['baz', 'quux'],
},
];
it('should handle a basic expression', () => {
expect(run.run(data, '["foo"]')).to.eql(['foo']);
});
it('should handle an object', () => {
expect(
run.run(data, '{"foo": "bar"}')
).to.eql({ foo: 'bar' });
});
describe('provided variables to the command', () => {
it('should include parsed data as "d"', () => {
expect(
run.run(data, '{"word": d[1].words[0]}')
).to.eql({ word: 'baz' });
});
it('should include the chain as "c"', () => {
expect(
run.run(data, 'c.get(0).value()')
).to.eql(data[0]);
});
it('should include lodash as "_"', () => {
expect(
run.run(data, 'c.get("0.words").map(_.capitalize).value()')
).to.eql(['Foo', 'Bar']);
});
describe('"p"', () => {
beforeEach(() => {
sinon.spy(console, 'json');
});
afterEach(() => {
console.json.restore();
});
it('should include console.json as "p"', () => {
// console.json does not document its return value,
// so don't test for it
run.run(data, 'p(d)');
sinon.assert.calledOnce(console.json);
sinon.assert.calledWithExactly(console.json, data);
});
it('should return the first item passed to it', () => {
expect(
run.run(data, 'p(d,d)')
).to.eql(data);
});
});
it('should not include other variables leaked into scope', () => {
expect(
_.bind(run.run, run, data, 'command')
).to.throw();
});
});
});
});
|
daxelrod/jowl
|
test/unit/lib/run.js
|
JavaScript
|
mit
| 2,058
|
from unittest import TestCase
import pandas as pd
import pandas.util.testing as tm
import numpy as np
import trtools.core.topper as topper
import imp
imp.reload(topper)
arr = np.random.randn(10000)
s = pd.Series(arr)
df = tm.makeDataFrame()
class TestTopper(TestCase):
def __init__(self, *args, **kwargs):
TestCase.__init__(self, *args, **kwargs)
def runTest(self):
pass
def setUp(self):
pass
def test_topn_largest(self):
# get the n largest
bn_res = topper.bn_topn(arr, 10)
assert bn_res[0] == max(arr) # sanity check
pd_res = s.order(ascending=False)[:10]
np.testing.assert_almost_equal(bn_res, pd_res)
# change result to biggest to smallest
bn_res = topper.bn_topn(arr, 10, ascending=True)
assert bn_res[-1] == max(arr) # sanity check
pd_res = s.order(ascending=True)[-10:] # grab from end since we reversed
np.testing.assert_almost_equal(bn_res, pd_res)
def test_topn_big_N(self):
"""
When calling topn where N is greater than the number of non-nan values.
This can happen if you're tracking a Frame of returns where not all series start at the same time.
It's possible that in the begining or end, or anytime for that matter, you might not have enough
values. This screws up the logic.
"""
# test data
arr = np.random.randn(100)
arr[5:] = np.nan # only first four are non-na
s = pd.Series(arr)
# top
bn_res = topper.bn_topn(arr, 10)
assert bn_res[0] == max(arr) # sanity check
pd_res = s.order(ascending=False)[:10].dropna()
tm.assert_almost_equal(bn_res, pd_res.values)
# bottom
bn_res = topper.bn_topn(arr, -10)
assert bn_res[0] == min(arr) # sanity check
pd_res = s.order()[:10].dropna() # grab from end since we reversed
tm.assert_almost_equal(bn_res, pd_res.values)
def test_top_smallest(self):
# get the nsmallest
bn_res = topper.bn_topn(arr, -10)
assert bn_res[0] == min(arr) # sanity check
pd_res = s.order()[:10]
tm.assert_almost_equal(bn_res, pd_res.values)
# change ordering
bn_res = topper.bn_topn(arr, -10, ascending=False)
assert bn_res[-1] == min(arr) # sanity check
pd_res = s.order(ascending=False)[-10:] # grab from end since we reversed
tm.assert_almost_equal(bn_res, pd_res.values)
def test_top_arg(self):
# get the nlargest
bn_res = topper.bn_topn(arr, 10)
bn_args = topper.bn_topargn(arr, 10)
arg_res = arr[bn_args]
tm.assert_almost_equal(bn_res, arg_res)
# get the nsmallest
bn_res = topper.bn_topn(arr, -10)
bn_args = topper.bn_topargn(arr, -10)
arg_res = arr[bn_args]
tm.assert_almost_equal(bn_res, arg_res)
# get the nsmallest
bn_res = topper.bn_topn(arr, -10, ascending=False)
bn_args = topper.bn_topargn(arr, -10, ascending=False)
arg_res = arr[bn_args]
tm.assert_almost_equal(bn_res, arg_res)
def test_nans(self):
"""
bottleneck.partsort doesn't handle nans. We need to correct for them.
the arg version is trickiers since we need to make sure to
translate back into the nan-filled array
"""
nanarr = np.arange(10).astype(float)
nanarr[nanarr % 2 == 0] = np.nan
test = topper.topn(nanarr, 3)
correct = [9,7,5]
tm.assert_almost_equal(test, correct)
test = topper.topn(nanarr, -3)
correct = [1,3,5]
tm.assert_almost_equal(test, correct)
test = topper.topargn(nanarr, 3)
correct = [9,7,5]
tm.assert_almost_equal(test, correct)
test = topper.topargn(nanarr, -3)
correct = [1,3,5]
tm.assert_almost_equal(test, correct)
test = topper.topargn(nanarr, -3, ascending=False)
correct = [5,3,1]
tm.assert_almost_equal(test, correct)
def test_df_topn(self):
# long way of getting the topn
tops = df.apply(lambda s: s.topn(2, ascending=False), axis=1)
correct = pd.DataFrame(tops, index=df.index)
test = topper.topn_df(df, 2, ascending=False)
tm.assert_frame_equal(test, correct)
# sanity check, make sure first value is right
c = df.iloc[0].order()[-1]
t = test.iloc[0][0]
tm.assert_almost_equal(t, c)
# bottom 2
tops = df.apply(lambda s: s.topn(-2), axis=1)
correct = pd.DataFrame(tops, index=df.index)
test = topper.topn_df(df, -2)
tm.assert_frame_equal(test, correct)
# sanity check, make sure first value is right
c = df.iloc[0].order()[0]
t = test.iloc[0][0]
tm.assert_almost_equal(t, c)
def test_df_topindexn(self):
# long way of getting the topindexn
top_pos = df.apply(lambda s: s.topargn(2, ascending=False), axis=1)
correct = df.columns[top_pos.values]
correct = pd.DataFrame(correct, index=df.index)
test = topper.topindexn_df(df, 2, ascending=False)
tm.assert_frame_equal(test, correct)
# sanity check, make sure first value is right
c = df.iloc[0].order().index[-1]
t = test.iloc[0][0]
tm.assert_almost_equal(t, c)
# bottom 2
top_pos = df.apply(lambda s: s.topargn(-2), axis=1)
correct = df.columns[top_pos.values]
correct = pd.DataFrame(correct, index=df.index)
test = topper.topindexn_df(df, -2)
tm.assert_frame_equal(test, correct)
# sanity check, make sure first value is right
c = df.iloc[0].order().index[0]
t = test.iloc[0][0]
tm.assert_frame_equal(test, correct)
def test_df_topargn(self):
# really this is tested via topindexn indirectly
pass
def test_default_ascending(self):
"""
Changed ascending to change based on N
More intuitive, by default you'd expect the greatest or lowest
value would be first, depending on which side you are looking for
"""
# top should default to asc=False
bn_res = topper.bn_topn(arr, 10)
pd_res = s.order(ascending=False)[:10]
tm.assert_almost_equal(bn_res, pd_res.values)
# make sure ascending is still respected
bn_res = topper.bn_topn(arr, 10, ascending=True)
pd_res = s.order(ascending=True)[-10:]
tm.assert_almost_equal(bn_res, pd_res.values)
# bottom defaults asc=True
bn_res = topper.bn_topn(arr, -10)
pd_res = s.order()[:10]
tm.assert_almost_equal(bn_res, pd_res.values)
# make sure ascending is still respected
bn_res = topper.bn_topn(arr, -10, ascending=False)
pd_res = s.order()[:10][::-1]
tm.assert_almost_equal(bn_res, pd_res.values)
def test_test_ndim(self):
"""
Make sure topn and topargn doesn't accept DataFrame
"""
try:
topper.topn(df, 1)
except:
pass
else:
assert False
try:
topper.topargn(df, 1)
except:
pass
else:
assert False
def test_too_big_n_df(self):
df = pd.DataFrame(np.random.randn(100, 10))
df[df > 0] = np.nan
testdf = topper.topn_df(df, 10)
for x in range(len(df)):
correct = df.iloc[x].order(ascending=False).reset_index(drop=True)
test = testdf.iloc[x]
tm.assert_almost_equal(test, correct)
testdf = topper.topn_df(df, 2)
for x in range(len(df)):
correct = df.iloc[x].order(ascending=False).reset_index(drop=True)[:2]
test = testdf.iloc[x]
tm.assert_almost_equal(test, correct)
# bottom
testdf = topper.topn_df(df, -2)
for x in range(len(df)):
correct = df.iloc[x].order().reset_index(drop=True)[:2]
test = testdf.iloc[x]
tm.assert_almost_equal(test, correct)
# bottom
testdf = topper.topn_df(df, -20)
for x in range(len(df)):
correct = df.iloc[x].order().reset_index(drop=True)[:20]
test = testdf.iloc[x]
tm.assert_almost_equal(test, correct)
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],exit=False)
|
dalejung/trtools
|
trtools/core/tests/test_topper.py
|
Python
|
mit
| 8,499
|
package main;
import controller.ModelController;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class SLogo extends Application {
@Override
public void start(Stage stage) {
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
stage.setWidth(bounds.getWidth());
stage.setHeight(bounds.getHeight());
stage.setResizable(false);
new ModelController(stage);
}
public static void main(String[] args) {
launch(args);
}
}
|
karenli1995/slogo_ide
|
src/main/SLogo.java
|
Java
|
mit
| 580
|
class TaskListPageController < ApplicationController
def test
end
end
|
pierre-x/life-planner
|
app/controllers/task_list_page_controller.rb
|
Ruby
|
mit
| 77
|
using System;
using DbAppSettings.Model.DataAccess.Interfaces;
namespace DbAppSettings.Model.Service.CacheManager.Arguments
{
/// <summary>
/// Base class of the manager arguments
/// </summary>
public abstract class CacheManagerArguments
{
/// <summary>
/// Protected constructor
/// </summary>
protected CacheManagerArguments()
{
}
/// <summary>
/// *Optional Property*
/// Default of 5 seconds
/// Function that returns a timespan how long to wait before checking the data access layer for new values
/// </summary>
public Func<TimeSpan> CacheRefreshTimeout { get; set; } = () => TimeSpan.FromSeconds(5);
/// <summary>
/// Implementation of the data access layer to save new settings that are not currently in the data access
/// </summary>
public ISaveNewSettingDao SaveNewSettingDao { get; set; }
}
}
|
mmohoney/DbAppSettings
|
DbAppSettings/Source/DbAppSettings/Model/Service/CacheManager/Arguments/CacheManagerArguments.cs
|
C#
|
mit
| 977
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
module.exports = function(options) {
var watch = function(srcDir, watchOptions) {
return function() {
if (!watchOptions) {
watchOptions = {};
}
watchOptions.watchSrcLess = watchOptions.watchSrcLess || true;
watchOptions.watchSrcHtml = watchOptions.watchSrcHtml || true;
watchOptions.srcJs = watchOptions.srcJs || '/**/*.js';
gulp.watch([options.app + '/*.html', 'bower.json'], ['inject']);
if (watchOptions.watchSrcLess) {
gulp.watch([
srcDir + '/**/*.less'
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles');
} else {
gulp.start('inject');
}
});
}
gulp.watch([srcDir + watchOptions.srcJs, options.app + '/**/*.js'], function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
var htmlToWatch = [options.app + '/*.html'];
if (watchOptions.watchSrcHtml) {
htmlToWatch.push(srcDir + '/**/*.html');
}
return gulp.watch(htmlToWatch, function(event) {
browserSync.reload(event.path);
});
};
};
gulp.task('watch', ['inject'], watch(options.src));
gulp.task('watch:dist', ['inject:dist'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.js'}));
gulp.task('watch:dist:min', ['inject:dist:min'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.min.js'}));
};
|
jacob-meacham/angular-notification-icons
|
gulp/watch.js
|
JavaScript
|
mit
| 1,738
|
import sys
def main():
with open(sys.argv[1]) as input_file:
for line in input_file.readlines():
input_list = list(reversed(line.strip().split(' ')))
index = int(input_list[0])
del input_list[0]
print(input_list[index - 1])
if __name__ == '__main__':
main()
|
leaen/Codeeval-solutions
|
mth-to-last-element.py
|
Python
|
mit
| 325
|
-- phpMyAdmin SQL Dump
-- version 3.4.11.1deb2+deb7u2
-- http://www.phpmyadmin.net
--
-- Client: 5.196.154.204
-- Généré le: Lun 28 Décembre 2015 à 13:14
-- Version du serveur: 5.5.44
-- Version de PHP: 5.4.45-0+deb7u2
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données: `eba_world`
--
-- --------------------------------------------------------
--
-- Structure de la table `characters`
--
CREATE TABLE IF NOT EXISTS `characters` (
`account_id` int(11) NOT NULL,
`name` varchar(40) NOT NULL,
`skin_id` int(11) NOT NULL,
`posx` int(11) NOT NULL,
`posy` int(11) NOT NULL,
`hp` int(11) NOT NULL,
`world` int(11) NOT NULL DEFAULT '0',
`spells` varchar(20) NOT NULL,
PRIMARY KEY (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `characters`
--
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
AlexMog/MMO-Rulemasters-World
|
server/databse/world.sql
|
SQL
|
mit
| 1,261
|
/*
Navicat MySQL Data Transfer
Source Server : 阿里云ECS
Source Server Version : 50718
Source Host : 47.93.61.54:3306
Source Database : ms_blog
Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001
Date: 2017-05-10 09:49:50
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for comment_table
-- ----------------------------
DROP TABLE IF EXISTS `comment_table`;
CREATE TABLE `comment_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '评论的自增id',
`type` int(2) unsigned NOT NULL DEFAULT '0' COMMENT '评论的类型,默认为0,表示某篇文章的直接评论',
`content` text NOT NULL COMMENT '评论的主体内容',
`user_name` char(30) NOT NULL COMMENT '评论的用户的nickname',
`paper_id` int(10) unsigned NOT NULL COMMENT '评论所属的文章id',
`comment_date` datetime NOT NULL COMMENT '评论日期',
UNIQUE KEY `id` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for papers_table
-- ----------------------------
DROP TABLE IF EXISTS `papers_table`;
CREATE TABLE `papers_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '文章内容表,自增id',
`title` varchar(255) NOT NULL COMMENT '文章的标题',
`tag` varchar(100) NOT NULL COMMENT '文章所属标签名称',
`subtag` varchar(100) DEFAULT NULL COMMENT '文章副标签,可为空',
`publish_date` datetime NOT NULL COMMENT '文章上传/发布时间',
`timeline` char(7) CHARACTER SET latin1 DEFAULT NULL COMMENT '时间线(只包含年-月信息),由触发器填写',
`abstract` text NOT NULL COMMENT '文章简述',
`content` text NOT NULL COMMENT '文章主体内容',
UNIQUE KEY `id` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for subcomment_table
-- ----------------------------
DROP TABLE IF EXISTS `subcomment_table`;
CREATE TABLE `subcomment_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '子评论的自增id',
`type` int(2) unsigned NOT NULL COMMENT '评论类型,1表示一级子评论,2表示二级子评论,以此类推',
`content` text NOT NULL COMMENT '子评论的主体内容',
`paper_id` int(10) unsigned NOT NULL COMMENT '子评论所属的文章id',
`comment_id` int(10) unsigned NOT NULL COMMENT '子评论所属的评论的id',
`comment_date` datetime NOT NULL,
`user_name` char(30) NOT NULL COMMENT '评论用户的nickname',
UNIQUE KEY `id` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for tags_index
-- ----------------------------
DROP TABLE IF EXISTS `tags_index`;
CREATE TABLE `tags_index` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '标签索引表,自增id',
`name` varchar(100) NOT NULL COMMENT '标签名称',
`papers_count` int(10) unsigned zerofill NOT NULL COMMENT '对应标签的文章数',
UNIQUE KEY `id` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for timeline_index
-- ----------------------------
DROP TABLE IF EXISTS `timeline_index`;
CREATE TABLE `timeline_index` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '时间线索引表,自增id',
`timeline` char(7) CHARACTER SET latin1 NOT NULL COMMENT '时间线,只包含年-月',
`papers_count` int(10) unsigned NOT NULL COMMENT '对应时间线的文章书目',
UNIQUE KEY `id` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TRIGGER IF EXISTS `add_trigger_before`;
DELIMITER ;;
CREATE TRIGGER `add_trigger_before` BEFORE INSERT ON `papers_table` FOR EACH ROW BEGIN
SET new.content = REPLACE(REPLACE(new.content, CHAR(10), ''), CHAR(13), '');
SET new.timeline = left(new.publish_date, 7);
END
;;
DELIMITER ;
DROP TRIGGER IF EXISTS `add_trigger_after`;
DELIMITER ;;
CREATE TRIGGER `add_trigger_after` AFTER INSERT ON `papers_table` FOR EACH ROW BEGIN
SET @count1 = (SELECT COUNT(*) FROM timeline_index WHERE timeline = new.timeline);
SET @count2 = (SELECT COUNT(*) FROM tags_index WHERE name = new.tag);
IF @count1 = 0 THEN
INSERT INTO timeline_index(timeline, papers_count) VALUES(new.timeline, 1);
ELSE
UPDATE timeline_index SET papers_count = papers_count + 1 WHERE timeline = new.timeline;
END IF;
IF @count2 = 0 THEN
INSERT INTO tags_index(name, papers_count) VALUES(new.tag, 1);
ELSE
UPDATE tags_index SET papers_count = papers_count + 1 WHERE name = new.tag;
END IF;
END
;;
DELIMITER ;
DROP TRIGGER IF EXISTS `delete_trigger`;
DELIMITER ;;
CREATE TRIGGER `delete_trigger` AFTER DELETE ON `papers_table` FOR EACH ROW BEGIN
UPDATE tags_index SET papers_count = papers_count - 1 WHERE name = old.tag;
UPDATE timeline_index SET papers_count = papers_count - 1 WHERE timeline = old.timeline;
DELETE FROM comment_table WHERE paper_id = old.id;
DELETE FROM subcomment_table WHERE paper_id = old.id;
END
;;
DELIMITER ;
|
MonkingStand/MS-blog-site-v3.0
|
_help/ms_blog(structure).sql
|
SQL
|
mit
| 5,138
|
package com.spacechase0.minecraft.componentequipment.addon.ironchests.modifier;
import com.spacechase0.minecraft.componentequipment.tool.modifier.BackpackModifier;
public class ExpandedBackpackModifier extends BackpackModifier
{
public ExpandedBackpackModifier()
{
super( false );
}
@Override
public int getMaxLevel()
{
return 4;
}
@Override
public int getSlotCount( int level )
{
return level * 3 * 9;
}
@Override
public String getGuiTexture( int level )
{
switch ( level )
{
case 1: return super.getGuiTexture( level );
case 2: return "ironchest:textures/gui/ironcontainer.png";
case 3: return "ironchest:textures/gui/goldcontainer.png";
case 4: return "ironchest:textures/gui/diamondcontainer.png";
}
return "";
}
public String getModelTexture( int level )
{
switch ( level )
{
case 1: return super.getModelTexture( level );
case 2: return "ironchest:textures/model/ironchest.png";
case 3: return "ironchest:textures/model/goldchest.png";
case 4: return "ironchest:textures/model/diamondchest.png";
}
return "";
}
}
|
spacechase0/ComponentEquipment
|
com/spacechase0/minecraft/componentequipment/addon/ironchests/modifier/ExpandedBackpackModifier.java
|
Java
|
mit
| 1,099
|
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var UIEle = Class.$extend({
__classvars__ : {
UI_ELEMENT_TABLE : [],
UI_POPUP_TABLE : [],
UI_OPEN_POPUP : undefined
},
__init__ : function(dom) {
this.dom_jq = $(dom);
UIEle.UI_ELEMENT_TABLE.push(this);
},
UIEleHovered : function(event) {
//$(event.delegateTarget).css("cursor","pointer");
////console.debug(event.data.$this.testvar)
},
UIEleUnhovered : function(event) {
//$(event.delegateTarget).css("cursor","auto");
////console.debug(event.data.$this.testvar)
},
UIEleClicked : function(event) {
/*$this = event.data.$this;
if ( $this instanceof UIMenubarEle ) {
//console.debug("menu bar");
}
else if ( $this instanceof UIPopupEle ) {
//console.debug("popup");
}*/
////console.debug(event.data.$this.testvar)
}
});
var UIMenubar = UIEle.$extend({
__init__ : function(dom, data_target) {
this.$super(dom);
this.menus = [];
mb = this;
this.dom_jq.children(".menu_bar_item").each(function( index ) {
mb.menus.push(new UIMenubarPopup(this, mb));
});
this.data_target = data_target;
}
});
var UIPopup = UIEle.$extend({
__init__ : function(dom) {
this.$super(dom);
this.dom_jq.append( "<div class=\"popup_window\"></div>" );
this.dom_jq.children(".popup_window").append( this.dom_jq.children("ul") );
this.dom_jq.children("ul").remove();
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
$("html").click(this.clickOutside);
$(window).resize(this.resizeWindow);
// initilaize all of the sub menu items
pu = this;
this.dom_jq.find("li").each(function(index){
if (!$(this).hasClass("disabled") && !$(this).hasClass("active") ) {
pu.setSubStatus($(this), "on");
}
});
this.fade_duration = 50;
UIEle.UI_POPUP_TABLE.push(this);
},
setSubStatus : function(sub_item, status) {
switch ( status ) {
case "on":
sub_item.mouseenter({$this:this}, this.UIEleSubHovered);
sub_item.mouseleave({$this:this}, this.UIEleSubUnhovered);
sub_item.click({$this:this}, this.UIEleSubClicked);
if ( sub_item.hasClass("disabled") )
sub_item.removeClass("disabled");
if ( sub_item.hasClass("active") )
sub_item.removeClass("active");
break;
case "disabled":
if ( sub_item.hasClass("active") )
sub_item.removeClass("active");
if ( !sub_item.hasClass("disabled") )
sub_item.addClass("disabled");
sub_item.off("click");
sub_item.off("mouseenter");
sub_item.off("mouseleave");
break;
case "active":
if ( sub_item.hasClass("disabled") )
sub_item.removeClass("disabled");
if ( sub_item.hasClass("active") )
sub_item.addClass("active");
sub_item.off("click");
sub_item.off("mouseenter");
sub_item.off("mouseleave");
break;
}
},
UIEleSubHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleSubUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleSubClicked : function(event) {
event.stopPropagation();
$this = event.data.$this;
$(event.delegateTarget).removeClass("hovered");
setTimeout(function() {
$(event.delegateTarget).addClass("active");
setTimeout(function() {
$(event.delegateTarget).removeClass("active");
$this.hidePopup();
$this.doAction(event);
},100);
},100);
},
clickOutside : function(event) {
if ( UIEle.UI_OPEN_POPUP )
UIEle.UI_OPEN_POPUP.hidePopup();
},
resizeWindow : function(event) {
if ( UIEle.UI_OPEN_POPUP ) {
UIEle.UI_OPEN_POPUP.positionPopup();
}
},
UIEleHovered : function(event) {
$this = event.data.$this;
$(event.delegateTarget).css("cursor","pointer");
if ( UIEle.UI_OPEN_POPUP != $this )
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$this = event.data.$this;
$(event.delegateTarget).css("cursor","auto");
if ( UIEle.UI_OPEN_POPUP != $this )
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
event.stopPropagation();
$this = event.data.$this;
if ( UIEle.UI_OPEN_POPUP ) {
if ( UIEle.UI_OPEN_POPUP == $this ) {
UIEle.UI_OPEN_POPUP.hidePopup();
} else {
UIEle.UI_OPEN_POPUP.hidePopup($this);
}
} else {
$this.showPopup();
}
},
hidePopup : function(calling_obj) {
//$this = this;
UIEle.UI_OPEN_POPUP.dom_jq.removeClass("active");
UIEle.UI_OPEN_POPUP.active_popup_jq.fadeOut( UIEle.UI_OPEN_POPUP.fade_duration, function() {
UIEle.UI_OPEN_POPUP.active_popup_jq.remove();
UIEle.UI_OPEN_POPUP.active_popup_jq = undefined;
UIEle.UI_OPEN_POPUP = undefined;
if ( calling_obj )
calling_obj.showPopup();
});
},
showPopup : function() {
UIEle.UI_OPEN_POPUP = this;
this.dom_jq.removeClass("hovered");
this.dom_jq.addClass("active");
// clone the menu item
this.active_popup_jq = this.dom_jq.children(".popup_window").clone(true, true).appendTo("#uber");
this.active_popup_jq.fadeIn($this.fade_duration);
this.active_popup_jq.css({"position":"absolute"});
this.positionPopup();
},
positionPopup : function() {
if ( this.dom_jq.offset().left + this.active_popup_jq.outerWidth() >= $(window).width() ) {
//the popup will appear off the right edge of the window
//align the right edge of the popup with the right edge of the parent element
left = this.dom_jq.offset().left + this.dom_jq.outerWidth() - this.active_popup_jq.outerWidth();
} else {
//position the popup normally
////align the left edge of the popup with the left edge of the parent element
left = this.dom_jq.offset().left;
}
if ( this.dom_jq.offset().top + this.dom_jq.outerHeight() + this.active_popup_jq.outerHeight() >= $(window).height() ) {
//the popup will appear off the bottom of the screen
//align the bottom of the popup with the bottom of the parent element
top = this.dom_jq.offset().top + this.dom_jq.outerHeight() - this.active_popup_jq.outerHeight();
} else {
//position the popup normally
//align the top of the popup with the bottom of the parent element
top = this.dom_jq.offset().top + this.dom_jq.outerHeight();
}
this.active_popup_jq.offset({ top: top, left: left });
}
});
var UIMenubarPopup = UIPopup.$extend({
__init__ : function(dom, parent_menubar) {
this.$super(dom);
this.parent_menubar = parent_menubar;
this.name = this.dom_jq.children("p").text();
//This is for testing
/*
action = this.dom_jq.find(".menu_bar_action");
if (action.hasClass('dialog'))
new UIModalDialog(action);
*/
},
doAction : function(event) {
action = $(event.delegateTarget).children(".menu_bar_action");
////console.debug(action.hasClass('dialog'));
//link = $(event.delegateTarget).children(".menu_bar_link");
if (action.hasClass('dialog'))
new UIModalDialog(action);
if (action.hasClass('link'))
document.location.href = action.children("a").attr("href");
},
showPopup : function() {
this.$super();
////console.debug(this.name);
if ( this.name == "Action" ) {
if ( Object.size(this.parent_menubar.data_target.server_data.selected) > 0 ) {
this.setSubStatus(this.active_popup_jq.find(".disabled"), "on");
}
}
////console.debug(Object.size(this.parent_menubar.data_target.server_data.selected));
}
});
var UIButton = UIEle.$extend({
__init__ : function(dom, callBack, callBackParams) {
this.$super(dom);
this.callBack = callBack;
////console.debug(data);
this.callBackParams = callBackParams;
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
},
UIEleHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
$this = event.data.$this;
$this.callBack($this.callBackParams);
}
});
var UICheckbox = UIEle.$extend({
__init__ : function(dom, callBack, callBackParams) {
//build the checkbox. this will be sent to the UIEle init
name = $(dom).attr("name");
label_text = $(dom).siblings("label").text();
$(dom).after("<div class=\"checkbox\"><div class=\"checkbox_box\"></div><div class=\"checkbox_label\">{{label text}}</div></div>".replace("{{label text}}",label_text));
new_dom = $(dom).siblings(".checkbox");
$(dom).siblings("label").remove();
$(dom).remove();
//now call the super with the new dom element.
this.$super(new_dom);
this.callBack = callBack;
this.name = name;
this.selected = false;
this.callBackParams = callBackParams;
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
},
UIEleHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
$this = event.data.$this;
if ( $this.selected ) {
$(event.delegateTarget).removeClass("selected");
$this.selected = false;
} else {
$(event.delegateTarget).addClass("selected");
$this.selected = true;
}
//$this.callBack($this.callBackParams);
}
});
var UIModalDialog = UIEle.$extend({
__init__ : function(dom) {
this.$super(dom);
// we always have these two
new UIButton(this.dom_jq.find( "[name='cancel']" ), this.doCancel, {$this:this});
new UIButton(this.dom_jq.find( "[name='go']" ), this.doGo, {$this:this});
//look for checkboxes
this.dom_jq.find( "[type='checkbox']" ).each( function (index) {
new UICheckbox(this);
});
$(window).resize({$this:this}, this.resizeWindow);
this.fade_duration = 100;
this.showDialog();
},
doCancel : function(params) {
$this = params.$this;
$this.hideDialog();
},
doGo : function(params) {
$this = params.$this;
//$this.hideDialog();
},
showDialog : function() {
// create an overlay to capture all events outside the dialog box
this.overlay = $("<div class=\"overlay\"></div>").appendTo("#uber");
this.overlay.css({"position":"absolute", "display":"none"});
this.overlay.offset(
{ top: 0,
left: 0
});
this.overlay.width($(window).width());
this.overlay.height($("html").height());
this.overlay.fadeIn($this.fade_duration);
// clone the menu item
this.active_dialog = this.dom_jq.clone(true, true).appendTo("#uber");
this.active_dialog.fadeIn(this.fade_duration);
this.active_dialog.css({"position":"absolute"});
this.positionDialog();
},
hideDialog : function() {
this.active_dialog.fadeOut(this.fade_duration);
$this = this;
this.overlay.fadeOut(this.fade_duration, function() {
$this.active_dialog.remove();
$this.overlay.remove();
});
},
positionDialog : function() {
this.active_dialog.offset(
{ top: $(window).height()/2.0 - this.active_dialog.outerHeight()/2.0,
left: $(window).width()/2.0 - this.active_dialog.outerWidth()/2.0
});
},
resizeWindow : function(event) {
$this = event.data.$this;
$this.positionDialog();
}
});
var UISingleSelectPopup = UIPopup.$extend({
__init__ : function(dom, callBack, callBackParams) {
this.$super(dom);
this.callBackParams = callBackParams;
this.setSelection(this.dom_jq.find(".selected").text());
this.callBack = callBack;
},
setSelection : function(value) {
selection = this.dom_jq.children("p");
if ( selection.length == 0 ) {
this.dom_jq.append("<p>"+value+"</p>");
} else {
this.dom_jq.children("p").text(value);
}
//this.dom_jq.append("<p>"+value+"</p>");
this.callBackParams.selection = value;
},
doAction : function(event) {
this.setSelection($(event.delegateTarget).text());
this.callBack(this.callBackParams);
}
});
|
mksachs/WebVC
|
design/templates/js/ui.js
|
JavaScript
|
mit
| 15,247
|
/* MusicXMLUtils / Structure and Implementation of the MusicXML 3.0
LICENSE - The MIT License (MIT)
Copyright (c) 2014 Tomona Nanase
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.
*/
using System;
using System.CodeDom.Compiler;
using System.Xml.Serialization;
namespace MusicXMLUtils.Structure
{
[GeneratedCode("xsd", "4.0.30319.18020")]
[Serializable]
[XmlType(TypeName = "opusShow", AnonymousType = true, Namespace = "http://www.w3.org/1999/xlink")]
public enum OpusShow
{
[XmlEnum("new")]
New,
[XmlEnum("replace")]
Replace,
[XmlEnum("embed")]
Embed,
[XmlEnum("other")]
Other,
[XmlEnum("none")]
None,
}
}
|
nanase/MusicXMLUtils
|
MusicXMLUtils/Structure/Opus/OpusShow.cs
|
C#
|
mit
| 1,700
|
app.controller('gregorianToJalaliCrtl', function($scope,dateConvertor) {
/**
* validate date
* @returns {undefined}
*/
$scope.allValidation = function () {
$scope.validateGregorianYear();
$scope.validateGregorianMonth();
$scope.validateGregorianDay();
}
/**
* convert date
* @returns {undefined}
*/
$scope.convert = function () {
$scope.allValidation();
if(!$scope.greToShFrm.$invalid) {
// convert to jalali date
var date=dateConvertor.gregorianToJalali($scope.fromGreToShYear,$scope.fromGreToShMonth,$scope.fromGreToShDay);
// showing converted date
$scope.setConvertedDate(date[2]+' '+dateConvertor.getMonthName(date[1],'jalali')+' '+date[0]);
}
}
/**
* validate gregorian year
* @returns {undefined}
*/
$scope.validateGregorianYear = function() {
var result=true;
var yearValue=$scope.fromGreToShYear;
var itemInvalid=false;
var formInvalid=false;
if(!yearValue) {
$scope.fromGreToShYearMessage='سال را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(yearValue <= 0) {
$scope.fromGreToShYearMessage='سال را صحیح وارد نمائید';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShYear.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
};
/**
* validate gregorian moth
* @returns {undefined}
*/
$scope.validateGregorianMonth = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var monthValue=$scope.fromGreToShMonth;
if(!monthValue) {
$scope.fromGreToShMonthMessage='ماه را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result && (monthValue < 1 || monthValue > 12)) {
$scope.fromGreToShMonthMessage='ماه باید عددی بین 1 تا 12 باشد';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShMonth.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
* validate gregorian day
* @returns {undefined}
*/
$scope.validateGregorianDay = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid && !$scope.greToShFrm.fromGreToShMonth.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var yearValue=$scope.fromGreToShYear;
var monthValue=$scope.fromGreToShMonth;
var dayValue=$scope.fromGreToShDay;
if(!dayValue) {
$scope.fromGreToShDayMessage='روز را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result) {
// var dayResult=true;
if(dayValue < 1 || dayValue > 31) {
$scope.fromGreToShDayMessage='روز باید عددی بین 1 تا 31 باشد';
itemInvalid=true;
formInvalid=true;
// dayResult=false;
}
}
$scope.greToShFrm.fromGreToShDay.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
*
* set value of converted date
* @param {string} value
* @returns {undefined}
*/
$scope.setConvertedDate = function(value) {
$scope.convertedDate=value;
};
/**
* empty converted date
* @returns {undefined}
*/
$scope.emptyConvertedDate = function() {
$scope.convertedDate='';
};
});
|
afshintalebi/dateconverter
|
www/js/controllers/gregorian_to_jalali_controller.js
|
JavaScript
|
mit
| 4,088
|
Then(/^(?:the )?role "(.*?)" should exist$/) do |role|
@last_role = @conjur.role(mangle_name role)
@last_role.should exist
end
Then(/^it should (not )?be a member of "(.*?)"$/) do |neg, role|
role = conjur.role(mangle_name role)
if neg
expect(@last_role.member_of?(role)).to_not be_truthy
else
expect(@last_role.member_of?(role)).to be_truthy
end
end
When %r{^I(?: can)?((?: not)|(?: successfully))? sync(?: with options "(.*)")?$} do |success, options|
# TODO this is gross!
set_environment_variable 'CONJUR_LDAP_SYNC_PREFIX', conjur_prefix
set_environment_variable 'LDAP_SYNC_ENV', 'test'
set_environment_variable 'LDAP_SYNC_TEST_NAME', coverage_command_name
command = mangle_name "./bin/conjur-ldap-sync #{options}"
if success.strip == 'successfully'
run_simple unescape_text(command), false
if ENV['LDAP_SYNC_DEBUG_CUKES']
puts '+' * 80
puts "exited with #{last_command.exit_status} -> "
puts last_command.output
puts '-' * 80
puts
end
unless last_command.exit_status == 0
puts "failed to run #{command} | (#{last_command.exit_status}) output => \n#{last_command.output}"
assert_success true
end
else
run_simple unescape(command), false
if success.strip == 'not'
assert_success false
end
end
end
Then %r{^it should (not )?be owned by "(.*?)"$} do |neg, owner|
owner = "#{Conjur.account}:#{mangle_name(owner)}"
kind = @last_role.kind
ownerid = conjur.send(kind, @last_role.identifier).ownerid
if neg
expect(ownerid).to_not eq(owner)
else
expect(ownerid).to eq(owner)
end
end
Then %r{the variable "(.*?)" should (not )?exist} do |name, neg|
id = mangle_name(name)
var = conjur.variable(id)
if neg
expect(var).to_not exist
else
expect(var).to exist
expect(var.version_count).to be > 0
end
@last_variable_id = id
end
And %r{role "(.*?)" can execute the variable} do |role|
role = conjur.role(mangle_name role)
expect(role.permitted?("#{Conjur.account}:variable:#{@last_variable_id}", 'execute')).to be_truthy
end
Given %r{^a role named "(.*?)"$} do |rolename|
roles_by_name[rolename] = find_or_create_role(rolename)
end
And %r{^I grant the service role to "(.*?)"$} do |role|
role = conjur.role mangle_name(role)
service_role.grant_to role
end
Then %r{^a user named "(.*?)" exists and has the uid for "(.*?)"} do |username, uidfor|
uid = uids[uidfor]
user = conjur.user(mangle_name username)
expect(user).to exist
expect(user.attributes['uidnumber'].to_s).to eq(uid.to_s)
end
Then %r{^a group named "(.*?)" exists and has the gid for "(.*?)"$} do |groupname, gidfor|
gid = gids[gidfor]
group = conjur.group mangle_name(groupname)
expect(group).to exist
expect(group.attributes['gidnumber'].to_s).to eq(gid.to_s)
end
Then %r{^the report should have actions:$} do |table|
actual_reports = only_processes.last.stdout.split(/\n/).map{|l| JSON.parse(l)}
expected_reports = expected_actions_from_table(table)
expect(actual_reports.length).to eq(expected_reports.length)
expected_reports.zip(actual_reports).each do |expected, actual|
match_action expected, actual
end
end
Then %r{^a group named "(.*?)" exists and does not have gid (\d+)} do |name, gid|
group = conjur.group mangle_name(name)
expect(group).to exist
expect(group.attributes['gidnumber'].to_s).to_not eq(gid.to_s)
end
Then %r{^a user named "(.*?)" exists and does not have uid (\d+)$} do |name, uid|
user = conjur.user mangle_name(name)
expect(user).to exist
expect(user.attributes['uidnumber'].to_s).to_not eq(uid.to_s)
end
Then %r{^a user named "(.*?)" exists and does not have the uid for "(.*?)"$} do |name, uid_for|
user = conjur.user mangle_name(name)
expect(user).to exist
uid = uids[uid_for]
expect(user.attributes['uidnumber'].to_s).to_not eq(uid.to_s)
end
Then %r{^a group named "(.*?)" exists and does not have the gid for "(.*?)"$} do |name, gid_for|
group = conjur.group mangle_name(name)
expect(group).to exist
gid = gids[gid_for]
expect(group.attributes['gidnumber'].to_s).to_not eq(gid.to_s)
end
Then %r{^the report should have text$} do |text|
expected_lines = mangle_name(insert_uids(text)).split(/\n/).map(&:strip).reject(&:blank?)
actual_lines = only_processes.last.stdout
.split(/\n/).map(&:strip).reject(&:blank?)
expect(actual_lines).to eq(expected_lines)
end
Then %r{^the resource "(.*?)" should have annotation "(.*?)"\s*=\s*"(.*?)"$} do |resource, key, value|
resource_id = "#{Conjur.account}:#{mangle_name(resource)}"
res = conjur.resource(resource_id)
expect(res).to exist
expect(res.annotations[key]).to eq(mangle_name(value))
end
When %r{^I create a (user|group) "(.*?)"$} do |kind, id|
id = mangle_name(id)
conjur.send :"create_#{kind}", id, ownerid: service_role.roleid
end
When %r{^I add user "(.*?)" to group "(.*?)"$} do |user_id, group_id|
group = conjur.group mangle_name(group_id)
user = conjur.user mangle_name(user_id)
group.add_member user
end
Then %r{^the role "(.*?)" should be a member of "(.*?)"$} do |member, role|
role = conjur.role(mangle_name(role))
member = conjur.role(mangle_name(member))
expect(member.member_of?(role)).to be_truthy
end
|
cransom/ldap-sync
|
features/step_definitions/conjur_steps.rb
|
Ruby
|
mit
| 5,242
|
namespace BarracksWars___A_New_Factory.Models.Units
{
public class Horseman : Unit
{
private const int DefaultHealth = 50;
private const int DefaultDamage = 10;
public Horseman()
: base(DefaultHealth, DefaultDamage)
{
}
}
}
|
BlueDress/School
|
C# OOP Advanced/Reflection Exercises/BarracksWars - A New Factory/Models/Units/Horseman.cs
|
C#
|
mit
| 293
|
/**
******************************************************************************
* @file stm32_assert.h
* @author MCD Application Team
* @version $VERSION$
* @date $DATE$
* @brief STM32 assert template file.
* This file should be copied to the application folder and renamed
* to stm32_assert.h.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32_ASSERT_H
#define __STM32_ASSERT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Includes ------------------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for function's parameters check.
* @param expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* @retval None
*/
#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
#ifdef __cplusplus
}
#endif
#endif /* __STM32_ASSERT_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
HiveX-Minibot/hivex
|
firmware/mbed/mbed/TARGET_NUCLEO_F103RB/TARGET_STM/TARGET_STM32F1/device/stm32_assert_template.h
|
C
|
mit
| 3,528
|
"""
Summary:
Container and main interface for accessing the Tuflow model and a class
for containing the main tuflow model files (Tcf, Tgc, etc).
There are several other classes in here that are used to determine the
order of the files in the model and key words for reading in the files.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
from __future__ import unicode_literals
from itertools import chain
from ship.tuflow.tuflowfilepart import TuflowFile, TuflowKeyValue, TuflowUserVariable, TuflowModelVariable
from ship.tuflow import FILEPART_TYPES as fpt
from ship.utils import utilfunctions as uf
import logging
logger = logging.getLogger(__name__)
"""logging references with a __name__ set to this module."""
class TuflowModel(object):
"""Container for the entire loaded tuflow model.
"""
def __init__(self, root):
"""Initialise constants and dictionaries.
"""
self.control_files = {}
"""Tuflow Control File objects.
All types of Tuflow Control file are stored here under the type header.
Types are: TCF, TGC, TBC, ECF, TEF.
TCF is slightly different to the others as it contains an additional
member variable 'main_file_hash' to identify the main tcf file that
was called to load the model.
"""
self._root = ''
"""The current directory path used to reach the run files in the model"""
self.missing_model_files = []
"""Contains any tcf, tgs, etc files that could not be loaded."""
self.bc_event = {}
"""Contains the currently acitve BC Event variables."""
self.user_variables = None
"""Class containing the scenario/event/variable keys and values."""
@property
def root(self):
return self._root
@root.setter
def root(self, value):
self._root = value
self.updateRoot(value)
def checkPathsExist(self):
"""Test that all of the filepaths in the TuflowModel exist."""
failed = []
for file_type, file in self.control_files.items():
failed.extend(file.checkPathsExist())
return failed
def updateRoot(self, root):
"""Update the root variable in all TuflowFile's in the model.
The root variable (TuflowModel.root) is the directory that the main
.tcf file is in. This is used to define the location of all other files
which are usually referenced relative to each other.
Note:
This method will be called automatically when setting the
TuflowModel.root variable.
Args:
root(str): the new root to set.
"""
for c in self.control_files.values():
c.updateRoot(root)
def customPartSearch(self, control_callback, tuflow_callback=None,
include_unknown=False):
"""Return TuflowPart's based on the return value of the callbacks.
control_callback will be used as an argument in each of
self.control_files' customPartSearch() methods. The tuflow_callback
will be called on the combined generators returned from that method.
See Also:
ControlFile.customPartSearch
Continuing the example in the ControlFile.customPartSearch method. This
time the additinal tuflow_callback function is defined as well.
callback_func must accept a TuflowPart and return a tuple of:
keep-status and the return value. For example::
# This is the callback_func that we test the TuflowPart. It is
# defined in your script
def callback_func(part):
# In this case we check for GIS parts and return a tuple of:
# - bool(keep-status): True if it is a GIS filepart_type
# - tuple: filename and parent.model_type. This can be
# whatever you want though
if part.filepart_type == fpt.GIS:
return True, (part.filename, part.associates.parent.model_type)
# Any TuflowPart's that you don't want included must return
# a tuple of (False, None)
else:
return False, None
# Here we define a function to run after the generators are returned
# from callback_func. In the funcion above the return type is a
# tuple, so we accept that as the arg in this function, but it will
# be whatever you return from callback_func above.
# This function checks to see if there are any duplicate filename's.
# Note that it must return the same tuple as the other callback.
# i.e. keep-status, result
def tuflow_callback(part_tuple):
found = []
if part_tuple[0] in found:
return False, None
else:
return True, part_tuple[0]
# Both callback's given this time
results = tuflow.customPartSearch(callback,
tuflow_callback=tuflowCallback)
# You can now iteratre the results
for r in results:
print (str(r))
Args:
callback_func(func): a function to run for each TuflowPart in
this ControlFile's PartHolder.
include_unknown=False(bool): If False any UnknownPart's will be
ignored. If set to True it is the resonsibility of the
callback_func to check for this and deal with it.
Return:
generator - containing the results of the search.
"""
gens = []
for c in self.control_files.values():
gens.append(
c.customPartSearch(control_callback, include_unknown)
)
all_gens = chain(gens[0:-1])
for a in all_gens:
for val in a:
if tuflow_callback:
take, value = tuflow_callback(val)
if take:
yield[value]
else:
yield [val]
def removeTcfModelFile(self, model_file):
"""Remove an existing ModelFile from 'TCF' and update ControlFile.
Note:
You can call this function directly if you want to, but it is also
hooked into a callback in the TCF ControlFile. This means that when
you use the standard ControlFile add/remove/replaceControlFile()
methods these will be called automatically.
Args:
model_files(ModelFile): the ModelFile being removed.
"""
if not model_file in self.control_files[model_file.model_type].control_files:
raise AttributeError("model_file doesn't exists in %s control_files" % model_file.model_type)
self.control_files[model_file.model_type].removeControlFile(model_file)
self.control_files['TCF'].parts.remove(model_file)
def replaceTcfModelFile(self, model_file, control_file, replace_file):
"""Replace an existing ModelFile in 'TCF' and update ControlFile.
Note:
You can call this function directly if you want to, but it is also
hooked into a callback in the TCF ControlFile. This means that when
you use the standard ControlFile add/remove/replaceControlFile()
methods these will be called automatically.
Args:
model_file(ModelFile): the replacement TuflowPart.
control_file(ControlFile): containing the contents to replace the
existing ControlFile.
replace_file(ModelFile): the TuflowPart to be replaced.
"""
if model_file in self.control_files[model_file.model_type].control_files:
raise AttributeError('model_file already exists in this ControlFile')
self.control_files[replace_file.model_type].replaceControlFile(
model_file, control_file, replace_file)
self.control_files['TCF'].parts.replace(model_file, replace_file)
def addTcfModelFile(self, model_file, control_file, **kwargs):
"""Add a new ModelFile instance to a TCF type ControlFile.
Note:
You can call this function directly if you want to, but it is also
hooked into a callback in the TCF ControlFile. This means that when
you use the standard ControlFile add/remove/replaceControlFile()
methods these will be called automatically.
**kwargs:
after(TuflowPart): the part to add the new ModelFile after.
before(TuflowPart): the part to add the new ModelFile before.
Either after or before kwargs must be given. If both are provided after
will take precedence.
Args:
model_file(ModelFile): the replacement ModelFile TuflowPart.
control_file(ControlFile): containing the contents to replace the
existing ControlFile.
"""
if not 'after' in kwargs.keys() and not 'before' in kwargs.keys():
raise AttributeError("Either 'before' or 'after' TuflowPart kwarg must be given")
if model_file in self.control_files[model_file.model_type].control_files:
raise AttributeError('model_file already exists in this ControlFile')
self.control_files[model_file.model_type].addControlFile(
model_file, control_file, **kwargs)
self.control_files['TCF'].parts.add(model_file, **kwargs)
# class TuflowUtils(object):
# """Utility functions for dealing with TuflowModel outputs."""
#
# def __init__(self):
# pass
#
# @staticmethod
# def resultsByParent(results):
# """
# """
class UserVariables(object):
"""Container for all user defined variables.
Includes variable set in the control files with 'Set somevar ==' and the
scenario and event variables.
Note:
Only the currently active scenario and event variables will be stored
in this class.
"""
def __init__(self):
self.variable = {}
self.scenario = {}
self.event = {}
self._names = []
self.has_cmd_args = False
def add(self, filepart, vtype=None):
"""Add a new variables to the class.
Args:
filepart(TuflowModelVariables or TuflowUserVariable):
Raises:
TypeError - if filepart is not a TuflowModelVariable or TuflowUserVariable.
ValueError - if filepart already exists.
"""
if filepart._variable_name in self._names:
raise ValueError('variable already exists with that name - use replace instead')
if isinstance(filepart, TuflowUserVariable):
self.variable[filepart.variable_name] = filepart
self._names.append(filepart.variable_name)
elif isinstance(filepart, TuflowModelVariable):
if filepart._variable_type == 'scenario':
if filepart._variable_name == 's1' or filepart._variable_name == 's':
if 's' in self._names or 's1' in self._names:
raise ValueError("variable already exists with that " +
"name - use replace instead\n" +
"note 's' and 's1' are treated the same.")
self.scenario[filepart._variable_name] = filepart
self.variable[filepart._variable_name] = filepart
self._names.append(filepart.variable_name)
else:
if filepart._variable_name == 'e1' or filepart._variable_name == 'e':
if 'e' in self._names or 'e1' in self._names:
raise ValueError("variable already exists with that " +
"name - use replace instead\n" +
"note 'e' and 'e1' are treated the same.")
self.event[filepart._variable_name] = filepart
self.variable[filepart._variable_name] = filepart
self._names.append(filepart.variable_name)
else:
raise TypeError('filepart must be of type TuflowUserVariable or TuflowModelVariable')
def replace(self, filepart):
"""Replace an existing variable.
Args:
filepart(TuflowModelVariables or TuflowUserVariable):
Raises:
TypeError - if filepart is not a TuflowModelVariable or TuflowUserVariable.
ValueError - if filepart doesn't already exist.
"""
# Make sure it actually already exists.
# s & s1 and e & e1 are treated as the same name - same as tuflow
temp_name = filepart._variable_name
if temp_name == 's' or temp_name == 's1':
if not 's' in self._names and not 's1' in self._names:
raise ValueError("filepart doesn't seem to exist in UserVariables.")
elif temp_name == 'e' or temp_name == 'e1':
if not 'e' in self._names and not 'e1' in self._names:
raise ValueError("filepart doesn't seem to exist in UserVariables.")
elif not filepart._variable_name in self._names:
raise ValueError("filepart doesn't seem to exist in UserVariables.")
# Delete the old one and call add() with the new one
if temp_name == 's' or temp_name == 's1':
if 's' in self.scenario.keys():
del self.scenario['s']
del self.variable['e']
if 's1' in self.scenario.keys():
del self.scenario['s1']
del self.variable['e1']
self.add(filepart, 'scenario')
if temp_name == 'e' or temp_name == 'e1':
if 'e' in self.scenario.keys():
del self.event['e']
del self.variable['e']
if 'e1' in self.scenario.keys():
del self.event['e1']
del self.variable['e1']
self.add(filepart, 'event')
else:
del self.variable[temp_name]
self.add(filepart)
def variablesToDict(self):
"""Get the values of the variables.
Note that, like tuflow, scenario and event values will be includes in
the variables dict returned.
{'name1': var1, 'name2': var2, 'nameN': name2}
Return:
dict - with variables names as key and values as values.
"""
out = {}
for vkey, vval in self.variable.items():
out[vkey] = vval.variable
return out
def seValsToDict(self):
"""Get the values of the scenario and event variables.
Returns the currently active scenario and event values only - not the
placeholder keys - in a dictionary in the format::
{'scenario': [val1, val2, valN], 'event': [val1, val2, valN]}
Return:
dict - of scenario and event values.
"""
scenario = [s.variable for s in self.scenario.values()]
event = [e.variable for e in self.event.values()]
return {'scenario': scenario, 'event': event}
def remove(self, key):
"""Remove the variable stored at the given key.
Args:
key(str): key for either the scenario, event, or variables dict.
"""
if key in self.scenario.keys():
self._names.remove(self.scenario[key]._variable_name)
del self.scenario[key]
if key in self.event.keys():
self._names.remove(self.scenario[key]._variable_name)
del self.event[key]
if key in self.variable.keys():
self._names.remove(self.scenario[key]._variable_name)
del self.variable[key]
def get(self, key, vtype=None):
"""Return the TuflowPart at the given key.
Args:
key(str): the key associated with the required TuflowPart.
vtype=None(str): the type of part to return. If None it will return
a 'variable' type. Other options are 'scenario' and 'event'.
Return:
TuflowPart - TuflowModelVariable or TuflowUserVariable type.
"""
if vtype == 'scenario':
if not key in self.scenario.keys():
raise KeyError('key %s is not in scenario keys' % key)
return self.scenario[key]
elif vtype == 'event':
if not key in self.event.keys():
raise KeyError('key %s is not in event keys' % key)
return self.event[key]
else:
if not key in self.variable.keys():
raise KeyError('key %s is not in variable keys' % key)
return self.variable[key]
class TuflowFilepartTypes(object):
"""Contains key words from Tuflow files for lookup.
This acts as a lookup table for the TuflowLoader class more than anything
else. It is kept here as that seems to be most sensible.
Contains methods for identifying whether a command given to it is known
to the library and what type it is. i.e. what UNIT_CATEGORY it falls into.
"""
def __init__(self):
"""Initialise the categories and known keywords"""
self.ambiguous = {
'WRITE CHECK FILES': [
['WRITE CHECK FILES INCLUDE', fpt.VARIABLE],
['WRITE CHECK FILES EXCLUDE', fpt.VARIABLE]
],
# 'WRITE CHECK FILES INCLUDE': ['WRITE CHECK FILES', fpt.RESULT],
# 'WRITE CHECK FILES EXCLUDE': ['WRITE CHECK FILES', fpt.RESULT],
'DEFINE EVENT': [['DEFINE OUTPUT ZONE', fpt.SECTION_LOGIC]],
'DEFINE OUTPUT ZONE': [['DEFINE EVENT', fpt.EVENT_LOGIC]],
# 'START 1D DOMAIN': ['START 2D DOMAIN', fpt.SECTION_LOGIC],
# 'START 2D DOMAIN': ['START 1D DOMAIN', fpt.SECTION_LOGIC],
}
self.ambiguous_keys = self.ambiguous.keys()
self.types = {}
self.types[fpt.MODEL] = [
'GEOMETRY CONTROL FILE', 'BC CONTROL FILE',
'READ GEOMETRY CONTROL FILE', 'READ BC CONTROL FILE',
'READ FILE', 'ESTRY CONTROL FILE',
'EVENT FILE'
]
self.types[fpt.RESULT] = [
'OUTPUT FOLDER', 'WRITE CHECK FILES', 'LOG FOLDER'
]
self.types[fpt.GIS] = [
'READ MI', 'READ GIS', 'READ GRID', 'SHP PROJECTION',
'MI PROJECTION'
]
self.types[fpt.DATA] = ['READ MATERIALS FILE', 'BC DATABASE']
self.types[fpt.VARIABLE] = [
'START TIME', 'END TIME', 'TIMESTEP', 'SET IWL',
'MAP OUTPUT INTERVAL', 'MAP OUTPUT DATA TYPES', 'CELL WET/DRY DEPTH',
'CELL SIDE WET/DRY DEPTH', 'SET IWL', 'TIME SERIES OUTPUT INTERVAL',
'SCREEN/LOG DISPLAY INTERVAL', 'CSV TIME', 'START OUTPUT',
'OUTPUT INTERVAL', 'STRUCTURE LOSSES', 'WLL APPROACH',
'WLL ADJUST XS WIDTH', 'WLL ADDITIONAL POINTS',
'DEPTH LIMIT FACTOR', 'CELL SIZE', 'SET CODE', 'GRID SIZE (X,Y)',
'SET ZPTS', 'SET MAT', 'MASS BALANCE OUTPUT', 'GIS FORMAT',
'MAP OUTPUT FORMATS', 'END MAT OUTPUT', 'ASC START MAP OUTPUT',
'ASC END MAP OUTPUT', 'XMDF MAP OUTPUT DATA TYPES',
'WRITE PO ONLINE', 'ASC MAP OUTPUT DATA TYPES',
'WRITE CHECK FILES INCLUDE', 'WRITE CHECK FILES EXCLUDE',
'STORE MAXIMUMS AND MINIMUMS'
]
self.types[fpt.IF_LOGIC] = [
'IF SCENARIO', 'ELSE IF SCENARIO', 'IF EVENT',
'ELSE IF EVENT', 'END IF', 'ELSE'
]
self.types[fpt.EVENT_LOGIC] = ['DEFINE EVENT', 'END DEFINE']
self.types[fpt.SECTION_LOGIC] = ['DEFINE OUTPUT ZONE', 'END DEFINE']
self.types[fpt.DOMAIN_LOGIC] = [
'START 1D DOMAIN', 'END 1D DOMAIN', 'START 2D DOMAIN',
'END 2D DOMAIN'
]
self.types[fpt.USER_VARIABLE] = ['SET VARIABLE']
self.types[fpt.EVENT_VARIABLE] = [
'BC EVENT TEXT', 'BC EVENT NAME',
'BC EVENT SOURCE',
]
self.types[fpt.MODEL_VARIABLE] = ['MODEL SCENARIOS', 'MODEL EVENTS', ]
def find(self, find_val, file_type='*'):
"""Checks if the given value is known or not.
The word to look for doesn't have to be an exact match to the given
value, it only has to start with it. This means that we don't need to
know whether it is a 'command == something' or just 'command something'
(like: 'Estry Control File Auto') at this point.
This helps to avoid unnecessary repitition. i.e. many files are like:
'READ GIS' + another word. All of them are GIS type files so they all
get dealt with in the same way.
In some edge cases there are command that start the same. These are
dealt with by secondary check to see if the next character is '=' or
not.
Args:
find_val (str): the value attempt to find in the lookup table.
file_type (int): Optional - reduce the lookup time by providing
the type (catgory) to look for the value in. These are the
constants (MODEL, GIS, etc).
Returns:
Tuple (Bool, int) True if found. Int is the class constant
indicating what type the value was found under.
"""
find_val = find_val.upper()
if file_type == '*':
for key, part_type in self.types.items():
found = [i for i in part_type if find_val.startswith(i)]
if found:
retval = key
if found[0] in self.ambiguous_keys:
retval = self._checkAmbiguity(found[0], find_val, key)
return True, retval
return (False, None)
else:
found = [i for i in self.types[file_type] if find_val.startswith(i)]
if found:
return True, file_type
return (False, None)
def _checkAmbiguity(self, found, find_val, key):
"""Resolves any ambiguity in the keys."""
f = find_val.replace(' ', '')
f2 = found.replace(' ', '') + '='
if f.startswith(f2):
return key
else:
alternatives = self.ambiguous[found]
for i, a in enumerate(alternatives):
if find_val.startswith(a[0]):
return self.ambiguous[found][i][1]
return key
|
duncan-r/SHIP
|
ship/tuflow/tuflowmodel.py
|
Python
|
mit
| 22,689
|
import ProjectLibraryModel from './project-library.model';
let libraries = {
angular: new ProjectLibraryModel(1, 'Angular', require('../../../../images/logos/angular.svg')),
angularJS: new ProjectLibraryModel(2, 'AngularJS', require('../../../../images/logos/angularjs.png')),
jQuery: new ProjectLibraryModel(3, 'jQuery', require('../../../../images/logos/jquery.png')),
cordova: new ProjectLibraryModel(4, 'Cordova/PhoneGap', require('../../../../images/logos/cordova.png')),
materialDesignNG1: new ProjectLibraryModel(5, 'Material Design (AngularJS 1.x.x)', null),
firebase: new ProjectLibraryModel(6, 'Firebase PaaS', null),
dotNET: new ProjectLibraryModel(7, '.NET', null)
};
export default libraries;
|
phil-lgr/phil-lgr
|
client/website/services/data/projects/project-libraries/project-libraries.data.js
|
JavaScript
|
mit
| 747
|
body {
background-color: #E3DEC1;
}
a:hover{
text-decoration: none;
}
.navbar.navbar-default {
margin-bottom: 0;
}
.jumbotron {
margin-top: 0;
background-color: #47AFAF;
}
.navbar {
background-color: #B94629;
}
.nav-header {
color: #FFFFFF;
background-color: #47AFAF;
}
.jumbotron > .container > h2 > a:hover, .jumbotron > .container> h4 > a:hover{
color: #FFFFFF;
text-decoration: none;
}
.nav.navbar-nav.navbar > li > a{
color: #FFFFFF;
background-color: #B94629;
}
.nav.navbar-nav.navbar-right > li > a{
color: #FFFFFF;
background-color: #B94629;
}
.navbar-nav > li{
margin-right:30px;
}
.image {
position: relative;
width: 100%;
}
.text_image {
position: absolute;
color: #FFFFFF;
background-color: #1D1D26;
opacity: 0.8;
padding: 24px;
bottom: 0;
margin: 0;
left: 0;
width: 100%;
}
.col-sm-4.image_project {
max-width: 100%;
height: 100%;
}
.bg-1 {
background-color: #E3DEC1;
color: #555555;
}
.bg-2 {
background-color: #B5B19A;
color: #555555;
}
.bg-3 {
background-color: #FFFFFF;
color: #555555;
}
.contact_me {
list-style-type: none;
}
.contact_me > li {
margin-left: 300px;
}
.contact_me > li > a > img {
margin-right: 12px;
margin-top: 6px;
margin-bottom: 6px;
}
#project_button {
margin: 18px;
padding: 12px
}
body > .container > .row > .col-md-8 > ul > li > img {
max-width: 80%;
height: auto;
display: block;
}
p {
display: block;
margin-top: 10px;
line-height: 22px;
}
br {
display: block;
margin-top: 10px;
line-height: 22px;
}
|
kalari499/PersonalWebsite
|
static/style.css
|
CSS
|
mit
| 1,528
|
namespace Kevsoft.Ssml
{
public enum BreakStrength
{
NotSet = 0,
None,
ExtraWeak,
Weak,
Medium,
Strong,
ExtraStrong
}
}
|
kevbite/Kevsoft.Ssml
|
src/Kevsoft.Ssml/BreakStrength.cs
|
C#
|
mit
| 190
|
package vye;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class City {
private List<Mob> citizens;
private String name;
private int population;
private char type;
public City(String name,char type, int population) {
this.name = name;
this.type = type;
this.population = population;
this.citizens = new ArrayList<Mob>(population);
}
public List<Mob> getCitizens() {
return citizens;
}
public void setCitizens(List<Mob> citizens) {
this.citizens = citizens;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
public String toString() {
Gson gson = new GsonBuilder().create();
String json = gson.toJson(this);
return json;
}
}
|
alexvye/greyworld
|
src/main/java/vye/City.java
|
Java
|
mit
| 1,049
|
/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: contact@flowkit.com
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file
* Copy 2D multiblocks on a new parallel distribution -- header file.
*/
/*
* All functions that take as an argument a Box2D, or compute intersections, or join,
* or crop, do not adjust periodicity of the newly created blocks by default. The user
* is responsible to take care of this matter explicitly.
*/
#ifndef MULTI_BLOCK_GENERATOR_2D_H
#define MULTI_BLOCK_GENERATOR_2D_H
#include "core/globalDefs.h"
#include "multiBlock/multiDataField2D.h"
#include "multiBlock/multiBlockLattice2D.h"
#include "multiBlock/multiContainerBlock2D.h"
#include "multiBlock/sparseBlockStructure2D.h"
#include <memory>
namespace plb {
/* *************** 1. MultiScalarField ************************************** */
/// Generate a multi-scalar-field from scratch. As opposed to the standard
/// constructor, this factory function takes a full bounding-box, as well
/// as the envelope-width, as arguments.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateMultiScalarField (
Box2D boundingBox, plint envelopeWidth=1 );
/// Generate a multi-scalar-field from scratch. As opposed to the standard
/// constructor, this factory function takes a full bounding-box, as well
/// as the envelope-width, as arguments.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateMultiScalarField (
Box2D boundingBox, T iniVal, plint envelopeWidth=1 );
/// Generate a multi-scalar-field from scratch. As opposed to the standard
/// constructor, this factory function takes the explicit block-management
/// object, which includes stuff like block-distribution, parallelization,
/// envelope-width, etc. An optional initialization value can be provided.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > defaultGenerateMultiScalarField2D (
MultiBlockManagement2D const& management, T iniVal=T() );
/// Create a clone of a MultiScalarField (or of a sub-domain).
/** This cannot be handled through a data processor, because the internal data
* processors of the scalar-field must be cloned as well.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > clone (
MultiScalarField2D<T>& originalField, Box2D const& subDomain, bool crop=true );
/// Generate a new multi-scalar-field with same distribution as original block,
/// but intersected with a given domain.
/** No data is being copied, the new scalar-field is initialized to zero values.
* The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateMultiScalarField (
MultiBlock2D const& originalField, Box2D const& intersection,
bool crop=true );
/// Generate a new multi-scalar-field with a distribution which is the
/// intersection of the two original distributions.
/** No data is being copied, the new scalar-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original ones if the parameter "crop" is true, and equal to
* the bound around the original ones if "crop" is false.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateIntersectMultiScalarField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2, bool crop=true );
/// Generate a new multi-scalar-field with a distribution which is the
/// intersection of the two original distributions and a given domain.
/** No data is being copied, the new scalar-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original fields and the domain if the parameter "crop" is
* true, and equal to the bound around the original fields if "crop"
* is false.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateIntersectMultiScalarField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2,
Box2D const& intersection, bool crop=true );
/// Generate a new multi-scalar-field with a distribution which is the
/// union of the two original distributions.
/** No data is being copied, the new scalar-field is initialized to zero values.
* The block identifiers and parallel distributions are taken from
* originalField1 wherever originalField1 is defined. Elsewhere,
* new identifiers are generated, and the parallel disribution is
* taken from originalField2.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > generateJoinMultiScalarField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2 );
/// Generate a new multi-scalar-field with a distribution which is the
/// union between the original one and an additional block.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > extend (
MultiScalarField2D<T>& originalBlock, Box2D const& addedBlock );
/// Generate a new multi-scalar-field with a distribution which is the
/// union between the original one with exception of the specified block.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > except (
MultiScalarField2D<T>& originalBlock,
Box2D const& exceptedBlock );
/// Create a clone of the original field with a different block-distribution.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > redistribute (
MultiScalarField2D<T> const& originalField,
SparseBlockStructure2D const& newBlockStructure,
bool adjustPeriodicity=true );
/// Create a clone of the original field on the domain of intersection,
/// with a different block-distribution.
/** The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > redistribute (
MultiScalarField2D<T> const& originalField,
SparseBlockStructure2D const& newBlockStructure,
Box2D const& intersection, bool crop=true );
/// Create a clone of the original field, re-distributed in such a way
/// that it is aligned with the partner-block, i.e. it can be used
/// together with partner-block from within a data processor.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > align (
MultiScalarField2D<T> const& originalBlock,
MultiBlock2D const& partnerBlock );
/// Create a clone of the original field, on a new regular distribution.
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > reparallelize (
MultiScalarField2D<T> const& originalBlock );
/// Create a clone of the original field, on a new regular distribution.
/** The parameters blockLx and blockLy indicate the approximate size of the blocks.
**/
template<typename T>
std::auto_ptr<MultiScalarField2D<T> > reparallelize (
MultiScalarField2D<T> const& originalBlock,
plint blockLx, plint blockLy);
/* *************** 2. MultiNTensorField ************************************** */
/// Generate a multi-scalar-field from scratch. As opposed to the standard
/// constructor, this factory function takes the explicit block-management
/// object, which includes stuff like block-distribution, parallelization,
/// envelope-width, etc.
template<typename T>
std::auto_ptr<MultiNTensorField2D<T> > defaultGenerateMultiNTensorField2D (
MultiBlockManagement2D const& management, plint nDim=1 );
template<typename T>
MultiNTensorField2D<T>* generateMultiNTensorField2D (
MultiBlock2D& multiBlock, plint envelopeWidth, plint ndim );
template<typename T>
MultiNTensorField2D<T>* generateMultiNTensorField2D(Box2D const& domain, plint ndim);
template<typename T>
MultiNTensorField2D<T>* generateMultiNTensorField2D(Box2D const& domain, plint ndim, T* iniVal, plint envelopeWidth);
/// Create a clone of a MultiNTensorField (or of a sub-domain).
/** This cannot be handled through a data processor, because the internal data
* processors of the ntensor-field must be cloned as well.
**/
template<typename T>
MultiNTensorField2D<T>* clone (
MultiNTensorField2D<T>& originalField, Box2D const& subDomain, bool crop=true );
/// Generate a new multi-tensor-field with same distribution as original block,
/// but intersected with a given domain.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T>
MultiNTensorField2D<T>* generateMultiNTensorField (
MultiBlock2D const& originalField, Box2D const& intersection,
plint nDim, bool crop=true );
template<typename T1, typename T2>
MultiNTensorField2D<T2>*
generateNTensorFieldFromNTensor2D (
MultiNTensorField2D<T1> const& field,
Box2D const& intersection, plint nDim );
template<typename T1, typename T2, template<typename U> class Descriptor>
MultiNTensorField2D<T1>*
generateNTensorFieldFromBlockLattice2D (
MultiBlockLattice2D<T2,Descriptor> const& lattice,
Box2D const& intersection, plint nDim );
/// Generate a new multi-tensor-field with a distribution which is the
/// intersection of the two original distributions.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original ones if the parameter "crop" is true, and equal to
* the bound around the original ones if "crop" is false.
**/
template<typename T>
MultiNTensorField2D<T>* generateIntersectMultiNTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2,
plint nDim, bool crop=true );
/// Generate a new multi-tensor-field with a distribution which is the
/// intersection of the two original distributions and a given domain.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original fields and the domain if the parameter "crop" is
* true, and equal to the bound around the original fields if "crop"
* is false.
**/
template<typename T>
MultiNTensorField2D<T>* generateIntersectMultiNTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2,
Box2D const& intersection, plint nDim, bool crop=true );
/// Generate a new multi-tensor-field with a distribution which is the
/// union of the two original distributions.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distributions are taken from
* originalField1 wherever originalField1 is defined. Elsewhere,
* new identifiers are generated, and the parallel disribution is
* taken from originalField2.
**/
template<typename T>
MultiNTensorField2D<T>* generateJoinMultiNTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2,
plint nDim );
/// Generate a new multi-ntensor-field with a distribution which is the
/// union between the original one and an additional block.
template<typename T>
MultiNTensorField2D<T>* extend (
MultiNTensorField2D<T>& originalBlock, Box2D const& addedBlock );
/// Generate a new multi-ntensor-field with a distribution which is the
/// union between the original one with exception of the specified block.
template<typename T>
MultiNTensorField2D<T>* except (
MultiNTensorField2D<T>& originalBlock,
Box2D const& exceptedBlock );
/// Create a clone of the original field, re-distributed in such a way
/// that it is aligned with the partner-block, i.e. it can be used
/// together with partner-block from within a data processor.
template<typename T>
MultiNTensorField2D<T>* align (
MultiNTensorField2D<T> const& originalBlock,
MultiBlock2D const& partnerBlock );
/// Create a clone of the original field, on a new regular distribution.
template<typename T>
MultiNTensorField2D<T>* reparallelize (
MultiNTensorField2D<T> const& originalBlock );
/* *************** 3. MultiTensorField ************************************** */
/// Generate a multi-tensor-field from scratch. As opposed to the standard
/// constructor, this factory function takes a full bounding-box, as well
/// as the envelope-width, as arguments.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateMultiTensorField (
Box2D boundingBox, plint envelopeWidth=1 );
/// Generate a multi-tensor-field from scratch. As opposed to the standard
/// constructor, this factory function takes a full bounding-box, as well
/// as the envelope-width, as arguments.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateMultiTensorField (
Box2D boundingBox, Array<T,nDim> const& iniVal, plint envelopeWidth=1 );
/// Generate a multi-tensor-field from scratch. As opposed to the standard
/// constructor, this factory function takes the explicit block-management
/// object, which includes stuff like block-distribution, parallelization,
/// envelope-width, etc. A default dummy argument is used for technical reasons.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > defaultGenerateMultiTensorField2D (
MultiBlockManagement2D const& management, plint unnamedDummyArg=1 );
/// Create a clone of a MultiTensorField (or of a sub-domain).
/** This cannot be handled through a data processor, because the internal data
* processors of the tensor-field must be cloned as well.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > clone (
MultiTensorField2D<T,nDim>& originalField, Box2D const& subDomain, bool crop=true );
/// Generate a new multi-tensor-field with same distribution as original block,
/// but intersected with a given domain.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateMultiTensorField (
MultiBlock2D const& originalField, Box2D const& intersection,
bool crop=true );
/// Generate a new multi-tensor-field with a distribution which is the
/// intersection of the two original distributions.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original ones if the parameter "crop" is true, and equal to
* the bound around the original ones if "crop" is false.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateIntersectMultiTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2, bool crop=true );
/// Generate a new multi-tensor-field with a distribution which is the
/// intersection of the two original distributions and a given domain.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distribution are taken from
* originalField1. The new bounding-box is equal to the intersection
* of the original fields and the domain if the parameter "crop" is
* true, and equal to the bound around the original fields if "crop"
* is false.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateIntersectMultiTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2,
Box2D const& intersection, bool crop=true );
/// Generate a new multi-tensor-field with a distribution which is the
/// union of the two original distributions.
/** No data is being copied, the new tensor-field is initialized to zero values.
* The block identifiers and parallel distributions are taken from
* originalField1 wherever originalField1 is defined. Elsewhere,
* new identifiers are generated, and the parallel disribution is
* taken from originalField2.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > generateJoinMultiTensorField (
MultiBlock2D const& originalField1,
MultiBlock2D const& originalField2 );
/// Generate a new multi-tensor-field with a distribution which is the
/// union between the original one and an additional block.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > extend (
MultiTensorField2D<T,nDim>& originalBlock, Box2D const& addedBlock );
/// Generate a new multi-tensor-field with a distribution which is the
/// union between the original one with exception of the specified block.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > except (
MultiTensorField2D<T,nDim>& originalBlock,
Box2D const& exceptedBlock );
/// Create a clone of the original field with a different block-distribution.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > redistribute (
MultiTensorField2D<T,nDim> const& originalField,
SparseBlockStructure2D const& newBlockStructure,
bool adjustPeriodicity=true );
/// Create a clone of the original field on the domain of intersection,
/// with a different block-distribution.
/** The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > redistribute (
MultiTensorField2D<T,nDim> const& originalField,
SparseBlockStructure2D const& newBlockStructure,
Box2D const& intersection, bool crop=true );
/// Create a clone of the original field, re-distributed in such a way
/// that it is aligned with the partner-block, i.e. it can be used
/// together with partner-block from within a data processor.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > align (
MultiTensorField2D<T,nDim> const& originalBlock,
MultiBlock2D const& partnerBlock );
/// Create a clone of the original field, on a new regular distribution.
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > reparallelize (
MultiTensorField2D<T,nDim> const& originalBlock );
/// Create a clone of the original field, on a new regular distribution.
/** The parameters blockLx and blockLy indicate the approximate size of the blocks.
**/
template<typename T, int nDim>
std::auto_ptr<MultiTensorField2D<T,nDim> > reparallelize (
MultiTensorField2D<T,nDim> const& originalBlock,
plint blockLx, plint blockLy);
/* *************** 4. MultiBlockLattice ************************************** */
/// Generate a multi-block-lattice from scratch. As opposed to the standard
/// constructor, this factory function takes a full bounding-box, as well
/// as the envelope-width, as arguments.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > generateMultiBlockLattice (
Box2D boundingBox, Dynamics<T,Descriptor>* backgroundDynamics, plint envelopeWidth=1 );
/// Generate a multi-block-lattice from scratch. As opposed to the standard
/// constructor, this factory function takes the explicit block-management
/// object, which includes stuff like block-distribution, parallelization,
/// envelope-width, etc. A default dummy argument is used for technical reasons.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > defaultGenerateMultiBlockLattice2D (
MultiBlockManagement2D const& management, plint unnamedDummyArg=1 );
/// Create a clone of a MultiBlockLattice (or of a sub-domain).
/** This cannot be handled through a data processor, because the internal data
* processors of the block-lattice must be cloned as well.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > clone (
MultiBlockLattice2D<T,Descriptor>& originalLattice,
Box2D const& subDomain, bool crop=true );
/// Generate a new multi-block-lattice with same distribution as original block,
/// but intersected with a given domain.
/** No data is being copied, the new block-lattice is initialized to default values.
* The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > generateMultiBlockLattice (
MultiBlock2D const& originalBlock, Box2D const& intersection,
bool crop=true );
/// Generate a new multi-block-lattice with a distribution which is the
/// intersection of the two original distributions.
/** No data is being copied, the new block-lattice is initialized to default values.
* The block identifiers and parallel distribution are taken from
* originalBlock1. The new bounding-box is equal to the intersection
* of the original ones if the parameter "crop" is true, and equal to
* the bound around the original ones if "crop" is false.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > generateIntersectMultiBlockLattice (
MultiBlock2D const& originalBlock1,
MultiBlock2D const& originalBlock2, bool crop=true );
/// Generate a new multi-block-lattice with a distribution which is the
/// intersection of the two original distributions and a given domain.
/** No data is being copied, the new block-lattice is initialized to default values.
* The block identifiers and parallel distribution are taken from
* originalBlock1. The new bounding-box is equal to the intersection
* of the original lattices and the domain if the parameter "crop" is
* true, and equal to the bound around the original lattices if "crop"
* is false.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > generateIntersectMultiBlockLattice (
MultiBlock2D const& originalBlock1,
MultiBlock2D const& originalBlock2,
Box2D const& intersection, bool crop=true );
/// Generate a new multi-block-lattice with a distribution which is the
/// union of the two original distributions.
/** No data is being copied, the new block-lattice is initialized to default values.
* The block identifiers and parallel distributions are taken from
* originalBlock1 wherever originalBlock1 is defined. Elsewhere,
* new identifiers are generated, and the parallel disribution is
* taken from originalBlock2.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > generateJoinMultiBlockLattice (
MultiBlock2D const& originalBlock1,
MultiBlock2D const& originalBlock2 );
/// Generate a new multi-block-lattice with a distribution which is the
/// union between the original one and an additional block.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > extend (
MultiBlockLattice2D<T,Descriptor>& originalBlock, Box2D const& addedBlock );
/// Generate a new multi-block-lattice with a distribution which is the
/// union between the original one with exception of the specified block.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T,Descriptor> > except (
MultiBlockLattice2D<T,Descriptor>& originalBlock,
Box2D const& exceptedBlock );
/// Create a clone of the original lattice with a different block-distribution.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T, Descriptor> > redistribute (
MultiBlockLattice2D<T, Descriptor> const& originalBlock,
SparseBlockStructure2D const& newBlockStructure,
bool adjustPeriodicity=true );
/// Create a clone of the original lattice on the domain of intersection,
/// with a different block-distribution.
/** The new boundingBox is either equal to the original one, or equal to the
* intersection, depending on the parameter crop.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T, Descriptor> > redistribute (
MultiBlockLattice2D<T, Descriptor> const& originalBlock,
SparseBlockStructure2D const& newBlockStructure,
Box2D const& intersection, bool crop=true );
/// Create a clone of the original lattice, re-distributed in such a way
/// that it is aligned with the partner-block, i.e. it can be used
/// together with partner-block from within a data processor.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T, Descriptor> > align (
MultiBlockLattice2D<T, Descriptor> const& originalBlock,
MultiBlock2D const& partnerBlock );
/// Create a clone of the original lattice, on a new regular distribution.
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T, Descriptor> > reparallelize (
MultiBlockLattice2D<T, Descriptor> const& originalBlock );
/// Create a clone of the original lattice, on a new regular distribution.
/** The parameters blockLx and blockLy indicate the approximate size of the blocks.
**/
template<typename T, template<typename U> class Descriptor>
std::auto_ptr<MultiBlockLattice2D<T, Descriptor> > reparallelize (
MultiBlockLattice2D<T, Descriptor> const& originalBlock,
plint blockLx, plint blockLy);
/* *************** 5. MultiContainerBlock ************************************ */
std::auto_ptr<MultiContainerBlock2D> generateMultiContainerBlock (
MultiBlock2D& multiBlock, plint envelopeWidth );
MultiContainerBlock2D* createMultiContainerBlock2D (
MultiBlockManagement2D const& management,
PeriodicitySwitch2D& periodicity,
plint envelopeWidth, plint gridLevel );
/* *************** General Functions **************************************** */
/// Copy all data processors from the old to the new block, and replace
/// the "self" block in the list of the data processor to point to the new block.
void transferDataProcessors(MultiBlock2D const& from, MultiBlock2D& to);
} // namespace plb
#endif // MULTI_BLOCK_GENERATOR_2D_H
|
Dwii/Master-Thesis
|
implementation/Palabos/palabos-master/src/multiBlock/multiBlockGenerator2D.h
|
C
|
mit
| 28,056
|
#pragma once
#ifndef __CLOUD_VIEWER_INCLUDE__
#define __CLOUD_VIEWER_INCLUDE__
#include "GL/glew.h"
#include "utils.hpp"
#include <math.h>
#include <thread> // std::thread
#include <mutex> // std::mutex
#include "ZEDModel.hpp" /* OpenGL Utility Toolkit header */
#include <sl/Camera.hpp>
#include "opencv2/opencv.hpp"
#include "glm/common.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class TrackBallCamera {
public:
TrackBallCamera() {
};
TrackBallCamera(vect3 p, vect3 la);
void applyTransformations();
void show();
void rotation(float angle, vect3 v);
void rotate(float speed, vect3 v);
void translate(vect3 v);
void translateLookAt(vect3 v);
void translateAll(vect3 v);
void zoom(float z);
vect3 getPosition();
vect3 getPositionFromLookAt();
vect3 getLookAt();
vect3 getForward();
vect3 getUp();
vect3 getLeft();
void setPosition(vect3 p);
void setLookAt(vect3 p);
private:
vect3 position;
vect3 lookAt;
vect3 forward;
vect3 up;
vect3 left;
float angleX;
void setAngleX();
public:
glm::mat4 P;
glm::mat4 V;
};
class TrackingViewer {
public:
TrackingViewer();
virtual ~TrackingViewer();
void init();
unsigned char getKey();
void updateText(std::string stringT, std::string stringR, sl::TRACKING_STATE stringState);
void updateZEDPosition(sl::Transform);
bool getViewerState() {
return isInit;
}
bool runs() {
return run;
}
void exit();
std::mutex path_locker;
private:
static TrackingViewer* currentInstance_;
//OGL functions
static void redrawCallback();
static void mouseCallback(int button, int state, int x, int y);
static void keyCallback(unsigned char c, int x, int y);
static void specialKeyCallback(int key, int x, int y);
static void motionCallback(int x, int y);
static void reshapeCallback(int width, int height);
static void closeCallback();
// drawing
void drawGridPlan();
void drawRepere();
// ZED model
Zed3D zed3d;
void idle();
void redraw();
void mouse(int button, int state, int x, int y);
void key(unsigned char c, int x, int y);
void specialkey(int key, int x, int y);
void motion(int x, int y);
void reshape(int width, int height);
int windowWidth, windowHeight;
//text
void printText();
std::string txtT;
std::string txtR;
sl::TRACKING_STATE trackState;
std::vector<sl::Translation> zed_path;
//int trackConf;
//! Mouse Save Position
bool Rotate;
bool Translate;
bool Zoom;
int startx;
int starty;
TrackBallCamera camera;
bool isInit;
bool run;
};
#endif
|
balder2046/WorldViewer
|
TrackingViewer.hpp
|
C++
|
mit
| 2,699
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Timers;
using System.Windows;
using CoreAudioApi;
using Decelerate.Annotations;
using Decelerate.Properties;
namespace Decelerate
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public TimeSpan TimeElapsed
{
get { return _timeElapsed; }
set
{
_timeElapsed = value;
OnPropertyChanged();
}
}
public TimeSpan TimeRemaining
{
get { return _timeRemaining; }
set
{
_timeRemaining = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
var deviceEnumerator = new MMDeviceEnumerator();
_mmDevice = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
_mmDevice.AudioEndpointVolume.OnVolumeNotification += OnVolumeNotification;
InitializeControls();
TimeElapsed = new TimeSpan(0);
TimeRemaining = new TimeSpan(0);
}
private void SaveControlValues()
{
Settings.Default.EndVolume = (int) EndVolumeSlider.Value;
Settings.Default.DelayTime = (int) DelayTimeSlider.Value;
Settings.Default.FadeTime = (int) FadeTimeSlider.Value;
Settings.Default.DoNothingAtEnd = AtEndDoNothingButton.IsChecked ?? false;
Settings.Default.HibernateAtEnd = AtEndHibernateButton.IsChecked ?? false;
Settings.Default.ShutdownAtEnd = AtEndShutdownButton.IsChecked ?? false;
Settings.Default.Save();
}
private void Run()
{
_startVolume = MasterVolume;
_running = true;
UpdateControlEnabledState();
SaveControlValues();
var minutesToDelay = (int) DelayTimeSlider.Value;
var totalTime = minutesToDelay + FadeTimeSlider.Value;
StartStopwatchTimer((int)totalTime);
if (minutesToDelay > 0)
{
_delayTimer = new Timer {Interval = minutesToDelay*60*1000};
_delayTimer.Elapsed += (source, elapsedEventArgs) =>
{
((Timer)source).Stop();
Dispatcher.Invoke(StartFade);
};
_delayTimer.Start();
}
else
{
StartFade();
}
}
private void Stop()
{
_running = false;
if (_delayTimer != null && _delayTimer.Enabled)
{
_delayTimer.Stop();
}
if (_fadeTimer != null && _fadeTimer.Enabled)
{
_fadeTimer.Stop();
}
if (_stopwatchTimer != null && _stopwatchTimer.Enabled)
{
_stopwatchTimer.Stop();
}
TimeElapsed = new TimeSpan(0);
TimeRemaining = new TimeSpan(0);
UpdateControlEnabledState();
}
private void Reset()
{
Stop();
MasterVolume = _startVolume;
}
private void StartStopwatchTimer(double totalTime)
{
TimeElapsed = new TimeSpan(0);
TimeRemaining = TimeSpan.FromMinutes(totalTime);
_stopwatchTimer = new Timer {Interval = 1000};
_stopwatchTimer.Elapsed += StopwatchTimerTick;
_stopwatchTimer.Start();
}
private void StopwatchTimerTick(object source, ElapsedEventArgs elapsedEventArgs)
{
TimeElapsed = TimeElapsed.Add(TimeSpan.FromSeconds(1));
TimeRemaining = TimeRemaining.Subtract(TimeSpan.FromSeconds(1));
if (TimeRemaining.TotalSeconds <= 1)
{
((Timer) source).Stop();
}
}
private void StartFade()
{
var minutesToFade = (int) Math.Round(FadeTimeSlider.Value);
var startVolume = (int) Math.Round(StartVolumeSlider.Value);
var endVolume = (int) Math.Round(EndVolumeSlider.Value);
var fadeStartTime = DateTime.UtcNow;
// Time (minutes) between each time we decrease the volume by 1%
var volChangeInterval = (double) minutesToFade / (startVolume - endVolume);
_fadeTimer = new Timer {Interval = volChangeInterval * 60 * 1000};
_fadeTimer.Elapsed += (source, elapsedEventArgs) =>
{
var timeSinceStart = DateTime.UtcNow.Subtract(fadeStartTime).TotalMilliseconds;
MasterVolume = (int) Math.Round
(startVolume - (timeSinceStart * (startVolume - endVolume) / (minutesToFade * 60 * 1000)));
if (MasterVolume <= endVolume)
{
Dispatcher.Invoke(FinishFade);
}
};
_fadeTimer.Start();
}
private void FinishFade()
{
_fadeTimer.Stop();
if (AtEndShutdownButton.IsChecked == true)
{
Process.Start("shutdown", "/s /t 0");
}
if (AtEndHibernateButton.IsChecked == true)
{
Process.Start("shutdown", "/h /t 0");
}
if (AtEndRestoreVolumeCheckbox.IsChecked == true)
{
MasterVolume = _startVolume;
}
_running = false;
UpdateControlEnabledState();
}
private void InitializeControls()
{
StartVolumeSlider.Value = MasterVolume;
EndVolumeSlider.Value = Settings.Default.EndVolume;
DelayTimeSlider.Value = Settings.Default.DelayTime;
FadeTimeSlider.Value = Settings.Default.FadeTime;
AtEndDoNothingButton.IsChecked = Settings.Default.DoNothingAtEnd;
AtEndShutdownButton.IsChecked = Settings.Default.ShutdownAtEnd;
UpdateControlEnabledState();
}
private void UpdateControlEnabledState()
{
FadeTimeSlider.IsEnabled = !_running;
DelayTimeSlider.IsEnabled = !_running;
StartVolumeSlider.IsEnabled = !_running;
EndVolumeSlider.IsEnabled = !_running;
GoButton.IsEnabled = !_running;
StopButton.IsEnabled = _running;
ResetButton.IsEnabled = _running;
}
private void StartVolumeSlider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
MasterVolume = (int) StartVolumeSlider.Value;
}
private void GoButton_OnClick(object sender, RoutedEventArgs e)
{
if (!_running)
{
//start
if ((int) Math.Round(DelayTimeSlider.Value) == 0 && (int) Math.Round(FadeTimeSlider.Value) == 0)
{
MessageBox.Show("Delay time and fade time can't both be zero.");
}
else
{
Run();
}
}
}
private void StopButton_OnClick(object sender, RoutedEventArgs e)
{
Stop();
}
private void ResetButton_OnClickButton_OnClick(object sender, RoutedEventArgs e)
{
Reset();
}
private void OnVolumeNotification(AudioVolumeNotificationData data)
{
Dispatcher.Invoke(() =>
{
StartVolumeSlider.Value = (int) (data.MasterVolume * 100);
});
}
private int MasterVolume
{
get
{
return (int) (_mmDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
}
set
{
_mmDevice.AudioEndpointVolume.MasterVolumeLevelScalar = (value / 100.0f);
}
}
private readonly MMDevice _mmDevice;
private TimeSpan _timeElapsed;
private TimeSpan _timeRemaining;
private int _startVolume;
private bool _running;
private Timer _stopwatchTimer;
private Timer _delayTimer;
private Timer _fadeTimer;
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
olane/Decelerate
|
Decelerate/MainWindow.xaml.cs
|
C#
|
mit
| 8,895
|
require 'rails_helper'
RSpec.describe PagesController, type: :controller do
render_views
describe 'GET show' do
it 'renders the help template' do
get :show, params: { page: 'help' }
expect(response).to render_template 'help'
end
end
end
|
rails-girls-summer-of-code/rgsoc-teams
|
spec/controllers/pages_controller_spec.rb
|
Ruby
|
mit
| 265
|
# laravel-activity-log
Laravel Activity Log
## Installation
Make sure you have the MongoDB PHP driver installed. You can find installation instructions at
http://php.net/manual/en/mongodb.installation.php
Install through Composer
```
composer require vjlau/laravel-activity-log
```
## Configuration
And add a new mongodb connection `config/database.php`:
```
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'options' => [
'database' => 'admin' // sets the authentication database required by mongo 3
]
],
```
## Setup
### Step 1: Register the Service Provider
Add the ActivityLogServiceProvider to the providers array in the `config/app.php` file;
```
Jenssegers\Mongodb\MongodbServiceProvider::class,
VJLau\ActivityLog\ActivityLogServiceProvider::class,
VJLau\ActivityLog\QueryLogServiceProvider::class,
```
### Step 2: Publish config
```
php artisan vendor:publish --provider="VJLau\ActivityLog\ActivityLogServiceProvider" --tag="config"
```
## Usage
To subscribe model for activity log just use `VJLau\ActivityLog\Loggable`
```
use VJLau\ActivityLog\Loggable;
```
To add usage in your model
```
use Loggable;
```
To add middleware in your kernel
```
protected $routeMiddleware = [
......
'log.request' => \VJLau\ActivityLog\Middleware\LogAfterRequest::class,
];
```
## Credits
https://github.com/leomarquine/activity-log - Activity Log for Laravel Eloquent Models
## License
MIT - http://opensource.org/licenses/MIT
|
vj-lau/laravel-activity-log
|
README.md
|
Markdown
|
mit
| 1,653
|
<?php
namespace PR2\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Adversaire
*
* @ORM\Table()
* @ORM\Entity
*/
class Adversaire
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* @var integer
*
* @ORM\Column(name="recompense", type="integer")
*/
private $recompense;
/**
* @ORM\ManyToOne(targetEntity="PR2\ForumBundle\Entity\Lieu", inversedBy="adversaires")
* @ORM\JoinColumn(nullable=false)
*/
private $lieu;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Adversaire
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set recompense
*
* @param integer $recompense
* @return Adversaire
*/
public function setRecompense($recompense)
{
$this->recompense = $recompense;
return $this;
}
/**
* Get recompense
*
* @return integer
*/
public function getRecompense()
{
return $this->recompense;
}
}
|
D1amond/PR2-ForumInteractif
|
src/PR2/ForumBundle/Entity/Adversaire.php
|
PHP
|
mit
| 1,560
|
// flow-typed signature: e9b84c500ccc61d64c1ca78e43399035
// flow-typed version: <<STUB>>/gatsby-link_v^1.6.35/flow_v0.68.0
/**
* This is an autogenerated libdef stub for:
*
* 'gatsby-link'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'gatsby-link' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'gatsby-link/index' {
declare module.exports: $Exports<'gatsby-link'>;
}
declare module 'gatsby-link/index.js' {
declare module.exports: $Exports<'gatsby-link'>;
}
|
mattmischuk/m1x
|
flow-typed/npm/gatsby-link_vx.x.x.js
|
JavaScript
|
mit
| 855
|
<?php
namespace Tarantool\JobQueue\Handler;
use Tarantool\JobQueue\Handler\RetryStrategy\LimitedRetryStrategy;
use Tarantool\JobQueue\Handler\RetryStrategy\RetryStrategyFactory;
use Tarantool\JobQueue\JobBuilder\JobOptions;
use Tarantool\JobQueue\JobBuilder\RetryStrategies;
use Tarantool\Queue\Options;
use Tarantool\Queue\Queue;
use Tarantool\Queue\Task;
class RetryHandler implements Handler
{
private $handler;
private $retryStrategyFactory;
private static $defaults = [
JobOptions::RETRY_LIMIT => 2,
JobOptions::RETRY_ATTEMPT => 1,
JobOptions::RETRY_STRATEGY => RetryStrategies::LINEAR,
];
public function __construct(Handler $handler, RetryStrategyFactory $retryStrategyFactory)
{
$this->handler = $handler;
$this->retryStrategyFactory = $retryStrategyFactory;
}
public function handle(Task $task, Queue $queue): void
{
$data = $task->getData() + self::$defaults;
$attempt = $data[JobOptions::RETRY_ATTEMPT];
$strategy = $this->retryStrategyFactory->create($data[JobOptions::RETRY_STRATEGY]);
$strategy = new LimitedRetryStrategy($strategy, $data[JobOptions::RETRY_LIMIT]);
if (null === $delay = $strategy->getDelay($attempt)) {
$this->handler->handle($task, $queue);
return;
}
// TODO replace these 2 calls with an atomic one
$queue->put([JobOptions::RETRY_ATTEMPT => $attempt + 1] + $data, [Options::DELAY => $delay]);
$queue->delete($task->getId());
}
}
|
tarantool-php/jobqueue
|
src/Handler/RetryHandler.php
|
PHP
|
mit
| 1,549
|
using System;
namespace DDCloud.Platform.Core.CodeAnalysis
{
/// <summary>
/// Mark an element as permitting <c>null</c> values (so a check for <c>null</c> is necessary before using it).
/// </summary>
/// <example>
/// <code>
/// [CanBeNull]
/// public object Test()
/// {
/// return null;
/// }
///
/// public void UseTest()
/// {
/// object val = Test();
/// string str = val.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute
: Attribute
{
/// <summary>
/// Mark the specified element as permitting <c>null</c> values (so a check for <c>null</c> is necessary before using it).
/// </summary>
public CanBeNullAttribute()
{
}
}
}
|
DDCloud/DDCloud.Platform.Core
|
Platform.Core/CodeAnalysis/CanBeNullAttribute.cs
|
C#
|
mit
| 1,020
|
package io.github.xtman.swift.client.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
public class SwiftResponseHeaderUtils {
public static final String VALUE_SEPARATOR = ",";
// Fri, 12 Aug 2016 14:24:16 GMT
public static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z";
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(date);
}
public static Date parseDate(String str) throws Throwable {
if (str != null) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.parse(str);
}
return null;
}
public static Date parseDate(Map<String, List<String>> headerFields, String key) throws Throwable {
return parseDate(getHeaderFieldValue(headerFields, key));
}
public static String getHeaderFieldValue(Map<String, List<String>> headerFields, String key) throws Throwable {
if (headerFields != null && headerFields.containsKey(key)) {
return joinHeaderFieldValues(headerFields.get(key));
}
return null;
}
public static String joinHeaderFieldValues(List<String> values) {
if (values == null || values.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
sb.append(VALUE_SEPARATOR);
}
sb.append(values.get(i));
}
String v = sb.toString();
if (v.isEmpty()) {
return null;
}
return v;
}
public static Long parseLong(Map<String, List<String>> headerFields, String key) throws Throwable {
String value = getHeaderFieldValue(headerFields, key);
if (value != null) {
return Long.parseLong(value);
}
return null;
}
public static long parseLong(Map<String, List<String>> headerFields, String key, long defaultValue)
throws Throwable {
Long v = parseLong(headerFields, key);
if (v == null) {
return defaultValue;
} else {
return v;
}
}
public static Double parseDouble(Map<String, List<String>> headerFields, String key) throws Throwable {
String value = getHeaderFieldValue(headerFields, key);
if (value != null) {
return Double.parseDouble(value);
}
return null;
}
public static double parseLong(Map<String, List<String>> headerFields, String key, double defaultValue)
throws Throwable {
Double v = parseDouble(headerFields, key);
if (v == null) {
return defaultValue;
} else {
return v;
}
}
public static boolean parseBoolean(Map<String, List<String>> headerFields, String key, boolean defaultValue)
throws Throwable {
String v = getHeaderFieldValue(headerFields, key);
if (v == null) {
return defaultValue;
} else {
return Boolean.parseBoolean(v);
}
}
public static Map<String, String> convertHeaderFields(Map<String, List<String>> headerFields,
String valueDelimiter) {
Map<String, String> map = null;
if (headerFields != null && !headerFields.isEmpty()) {
map = new LinkedHashMap<String, String>(headerFields.size());
for (String key : headerFields.keySet()) {
String value = null;
List<String> values = headerFields.get(key);
if (values != null && !values.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
sb.append(valueDelimiter);
}
sb.append(values.get(i));
}
value = sb.toString();
}
map.put(key, value);
}
}
if (map != null && !map.isEmpty()) {
return map;
}
return null;
}
public static Map<String, String> convertHeaderFields(Map<String, List<String>> headerFields) {
return convertHeaderFields(headerFields, VALUE_SEPARATOR);
}
}
|
xtman/java-swift-client
|
src/main/java/io/github/xtman/swift/client/utils/SwiftResponseHeaderUtils.java
|
Java
|
mit
| 4,629
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { FoldingMarkers } from 'vs/editor/common/modes/languageConfiguration';
import { computeRanges } from 'vs/editor/contrib/folding/indentRangeProvider';
import { createTextModel } from 'vs/editor/test/common/editorTestUtils';
interface ExpectedIndentRange {
startLineNumber: number;
endLineNumber: number;
parentIndex: number;
}
function assertRanges(lines: string[], expected: ExpectedIndentRange[], offside: boolean, markers?: FoldingMarkers): void {
let model = createTextModel(lines.join('\n'));
let actual = computeRanges(model, offside, markers);
let actualRanges: ExpectedIndentRange[] = [];
for (let i = 0; i < actual.length; i++) {
actualRanges[i] = r(actual.getStartLineNumber(i), actual.getEndLineNumber(i), actual.getParentIndex(i));
}
assert.deepStrictEqual(actualRanges, expected);
model.dispose();
}
function r(startLineNumber: number, endLineNumber: number, parentIndex: number, marker = false): ExpectedIndentRange {
return { startLineNumber, endLineNumber, parentIndex };
}
suite('Indentation Folding', () => {
test('Fold one level', () => {
let range = [
'A',
' A',
' A',
' A'
];
assertRanges(range, [r(1, 4, -1)], true);
assertRanges(range, [r(1, 4, -1)], false);
});
test('Fold two levels', () => {
let range = [
'A',
' A',
' A',
' A',
' A'
];
assertRanges(range, [r(1, 5, -1), r(3, 5, 0)], true);
assertRanges(range, [r(1, 5, -1), r(3, 5, 0)], false);
});
test('Fold three levels', () => {
let range = [
'A',
' A',
' A',
' A',
'A'
];
assertRanges(range, [r(1, 4, -1), r(2, 4, 0), r(3, 4, 1)], true);
assertRanges(range, [r(1, 4, -1), r(2, 4, 0), r(3, 4, 1)], false);
});
test('Fold decreasing indent', () => {
let range = [
' A',
' A',
'A'
];
assertRanges(range, [], true);
assertRanges(range, [], false);
});
test('Fold Java', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ ' void foo() {',
/* 3*/ ' console.log();',
/* 4*/ ' console.log();',
/* 5*/ ' }',
/* 6*/ '',
/* 7*/ ' void bar() {',
/* 8*/ ' console.log();',
/* 9*/ ' }',
/*10*/ '}',
/*11*/ 'interface B {',
/*12*/ ' void bar();',
/*13*/ '}',
], [r(1, 9, -1), r(2, 4, 0), r(7, 8, 0), r(11, 12, -1)], false);
});
test('Fold Javadoc', () => {
assertRanges([
/* 1*/ '/**',
/* 2*/ ' * Comment',
/* 3*/ ' */',
/* 4*/ 'class A {',
/* 5*/ ' void foo() {',
/* 6*/ ' }',
/* 7*/ '}',
], [r(1, 3, -1), r(4, 6, -1)], false);
});
test('Fold Whitespace Java', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ '',
/* 3*/ ' void foo() {',
/* 4*/ ' ',
/* 5*/ ' return 0;',
/* 6*/ ' }',
/* 7*/ ' ',
/* 8*/ '}',
], [r(1, 7, -1), r(3, 5, 0)], false);
});
test('Fold Whitespace Python', () => {
assertRanges([
/* 1*/ 'def a:',
/* 2*/ ' pass',
/* 3*/ ' ',
/* 4*/ ' def b:',
/* 5*/ ' pass',
/* 6*/ ' ',
/* 7*/ ' ',
/* 8*/ 'def c: # since there was a deintent here'
], [r(1, 5, -1), r(4, 5, 0)], true);
});
test('Fold Tabs', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ '\t\t',
/* 3*/ '\tvoid foo() {',
/* 4*/ '\t \t//hello',
/* 5*/ '\t return 0;',
/* 6*/ ' \t}',
/* 7*/ ' ',
/* 8*/ '}',
], [r(1, 7, -1), r(3, 5, 0)], false);
});
});
let markers: FoldingMarkers = {
start: /^\s*#region\b/,
end: /^\s*#endregion\b/
};
suite('Folding with regions', () => {
test('Inside region, indented', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ ' #region',
/* 3*/ ' void foo() {',
/* 4*/ ' ',
/* 5*/ ' return 0;',
/* 6*/ ' }',
/* 7*/ ' #endregion',
/* 8*/ '}',
], [r(1, 7, -1), r(2, 7, 0, true), r(3, 5, 1)], false, markers);
});
test('Inside region, not indented', () => {
assertRanges([
/* 1*/ 'var x;',
/* 2*/ '#region',
/* 3*/ 'void foo() {',
/* 4*/ ' ',
/* 5*/ ' return 0;',
/* 6*/ ' }',
/* 7*/ '#endregion',
/* 8*/ '',
], [r(2, 7, -1, true), r(3, 6, 0)], false, markers);
});
test('Empty Regions', () => {
assertRanges([
/* 1*/ 'var x;',
/* 2*/ '#region',
/* 3*/ '#endregion',
/* 4*/ '#region',
/* 5*/ '',
/* 6*/ '#endregion',
/* 7*/ 'var y;',
], [r(2, 3, -1, true), r(4, 6, -1, true)], false, markers);
});
test('Nested Regions', () => {
assertRanges([
/* 1*/ 'var x;',
/* 2*/ '#region',
/* 3*/ '#region',
/* 4*/ '',
/* 5*/ '#endregion',
/* 6*/ '#endregion',
/* 7*/ 'var y;',
], [r(2, 6, -1, true), r(3, 5, 0, true)], false, markers);
});
test('Nested Regions 2', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ ' #region',
/* 3*/ '',
/* 4*/ ' #region',
/* 5*/ '',
/* 6*/ ' #endregion',
/* 7*/ ' // comment',
/* 8*/ ' #endregion',
/* 9*/ '}',
], [r(1, 8, -1), r(2, 8, 0, true), r(4, 6, 1, true)], false, markers);
});
test('Incomplete Regions', () => {
assertRanges([
/* 1*/ 'class A {',
/* 2*/ '#region',
/* 3*/ ' // comment',
/* 4*/ '}',
], [r(2, 3, -1)], false, markers);
});
test('Incomplete Regions 2', () => {
assertRanges([
/* 1*/ '',
/* 2*/ '#region',
/* 3*/ '#region',
/* 4*/ '#region',
/* 5*/ ' // comment',
/* 6*/ '#endregion',
/* 7*/ '#endregion',
/* 8*/ ' // hello',
], [r(3, 7, -1, true), r(4, 6, 0, true)], false, markers);
});
test('Indented region before', () => {
assertRanges([
/* 1*/ 'if (x)',
/* 2*/ ' return;',
/* 3*/ '',
/* 4*/ '#region',
/* 5*/ ' // comment',
/* 6*/ '#endregion',
], [r(1, 3, -1), r(4, 6, -1, true)], false, markers);
});
test('Indented region before 2', () => {
assertRanges([
/* 1*/ 'if (x)',
/* 2*/ ' log();',
/* 3*/ '',
/* 4*/ ' #region',
/* 5*/ ' // comment',
/* 6*/ ' #endregion',
], [r(1, 6, -1), r(2, 6, 0), r(4, 6, 1, true)], false, markers);
});
test('Indented region in-between', () => {
assertRanges([
/* 1*/ '#region',
/* 2*/ ' // comment',
/* 3*/ ' if (x)',
/* 4*/ ' return;',
/* 5*/ '',
/* 6*/ '#endregion',
], [r(1, 6, -1, true), r(3, 5, 0)], false, markers);
});
test('Indented region after', () => {
assertRanges([
/* 1*/ '#region',
/* 2*/ ' // comment',
/* 3*/ '',
/* 4*/ '#endregion',
/* 5*/ ' if (x)',
/* 6*/ ' return;',
], [r(1, 4, -1, true), r(5, 6, -1)], false, markers);
});
test('With off-side', () => {
assertRanges([
/* 1*/ '#region',
/* 2*/ ' ',
/* 3*/ '',
/* 4*/ '#endregion',
/* 5*/ '',
], [r(1, 4, -1, true)], true, markers);
});
test('Nested with off-side', () => {
assertRanges([
/* 1*/ '#region',
/* 2*/ ' ',
/* 3*/ '#region',
/* 4*/ '',
/* 5*/ '#endregion',
/* 6*/ '',
/* 7*/ '#endregion',
/* 8*/ '',
], [r(1, 7, -1, true), r(3, 5, 0, true)], true, markers);
});
test('Issue 35981', () => {
assertRanges([
/* 1*/ 'function thisFoldsToEndOfPage() {',
/* 2*/ ' const variable = []',
/* 3*/ ' // #region',
/* 4*/ ' .reduce((a, b) => a,[]);',
/* 5*/ '}',
/* 6*/ '',
/* 7*/ 'function thisFoldsProperly() {',
/* 8*/ ' const foo = "bar"',
/* 9*/ '}',
], [r(1, 4, -1), r(2, 4, 0), r(7, 8, -1)], false, markers);
});
test('Misspelled Markers', () => {
assertRanges([
/* 1*/ '#Region',
/* 2*/ '#endregion',
/* 3*/ '#regionsandmore',
/* 4*/ '#endregion',
/* 5*/ '#region',
/* 6*/ '#end region',
/* 7*/ '#region',
/* 8*/ '#endregionff',
], [], true, markers);
});
test('Issue 79359', () => {
assertRanges([
/* 1*/ '#region',
/* 2*/ '',
/* 3*/ 'class A',
/* 4*/ ' foo',
/* 5*/ '',
/* 6*/ 'class A',
/* 7*/ ' foo',
/* 8*/ '',
/* 9*/ '#endregion',
], [r(1, 9, -1, true), r(3, 4, 0), r(6, 7, 0)], true, markers);
});
});
|
Microsoft/vscode
|
src/vs/editor/contrib/folding/test/indentRangeProvider.test.ts
|
TypeScript
|
mit
| 8,044
|
/// <reference path="../jquery-1.7.1-vsdoc.js" />
var Audio = {
//-- Functions
Initialize: function () {
Audio.player = $('audio').get(0);
$('#Audio_PlayButton').on('click', Audio.Handlers.Button.Play);
$('audio').on('ended', Audio.Handlers.Events.Ended);
$('audio').on('pause', Audio.Handlers.Events.Pause);
$('audio').on('play', Audio.Handlers.Events.Play);
$('audio').on('timeupdate', Audio.Handlers.Events.TimeUpdate);
},
Notify: function (title, text, sticky, time) {
$.gritter.add({
title: title,
text: text,
sticky: sticky,
time: time
});
},
Refresh: function () {
},
Source: function (dataURI) {
Audio.player.src = dataURI;
Audio.player.load();
return (Audio.player.src = dataURI);
},
Play: function () {
Audio.Handlers.Button.Play();
},
//-- Event Handlers
Handlers: {
Button: {
Play: function () {
if (Audio.player.paused) {
Audio.player.play();
}
else {
Audio.player.pause();
}
}
},
Events: {
Ended: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
Play: function (e) {
$('#Audio_PlayButton > i').removeClass('icon-play').addClass('icon-pause');
},
Pause: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
TimeUpdate: function (e) {
$('#Audio_Progress').css('width', e.target.currentTime / e.target.duration * 100 + '%');
}
}
},
//-- Settings & Persistence
Settings: {
},
//-- Internal Vars
player: null
};
|
tmcnab/cloudlab.io
|
v2/Cloudlab/Scripts/IDE/AudioTab.js
|
JavaScript
|
mit
| 1,957
|
package main
import (
"fmt"
"net/http"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
http.HandleFunc("/", hello)
fmt.Println("listening...")
err := http.ListenAndServe(":8000", nil)
if err != nil {
panic(err)
}
}
func hello(res http.ResponseWriter, req *http.Request) {
fmt.Fprintln(res, "the forms are go!")
}
|
madebymarket/ruby-web-benchmark
|
old/gohi.go
|
GO
|
mit
| 443
|
"use strict";
const {XMLParser, XMLBuilder, XMLValidator} = require("../src/fxp");
const he = require("he");
describe("XMLParser", function() {
it("should parse attributes with valid names", function() {
const xmlData = `<issue _ent-ity.23="Mjg2MzY2OTkyNA==" state="partial" version="1"></issue>`;
const expected = {
"issue": {
"_ent-ity.23": "Mjg2MzY2OTkyNA==",
"state": "partial",
"version": 1
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse attributes with newline char", function() {
const xmlData = `<element id="7" data="foo\nbar" bug="true"/>`;
const expected = {
"element": {
"id": 7,
"data": `foo\nbar`,
"bug": true
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
// console.log(JSON.stringify(result,null,4));
// expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse attributes separated by newline char", function() {
const xmlData = `<element
id="7" data="foo bar" bug="true"/>`;
const expected = {
"element": {
"id": 7,
"data": "foo bar",
"bug": true
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse Boolean Attributes", function() {
const xmlData = `<element id="7" str="" data><selfclosing/><selfclosing /><selfclosingwith attr/></element>`;
const expected = {
"element": {
"id": 7,
"str": "",
"data": true,
"selfclosing": [
"",
""
],
"selfclosingwith": {
"attr": true
}
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true,
allowBooleanAttributes: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should not remove xmlns when namespaces are not set to be ignored", function() {
const xmlData = `<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"></project>`;
const expected = {
"project": {
"xmlns": "http://maven.apache.org/POM/4.0.0",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should remove xmlns when namespaces are set to be ignored", function() {
const xmlData = `<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi-ns="http://www.w3.org/2001/XMLSchema-instance" xsi-ns:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"></project>`;
const expected = {
"project": {
//"xmlns": "http://maven.apache.org/POM/4.0.0",
//"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
removeNSPrefix: true
}
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should not parse attributes with name start with number", function() {
const xmlData = `<issue 35entity="Mjg2MzY2OTkyNA==" ></issue>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute '35entity' is an invalid name.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not parse attributes with invalid char", function() {
const xmlData = `<issue enti+ty="Mjg2MzY2OTkyNA=="></issue>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'enti+ty' is an invalid name.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not parse attributes in closing tag", function() {
const xmlData = `<issue></issue invalid="true">`;
const expected = {
"err": {
"code": "InvalidTag",
"msg": "Closing tag 'issue' can't have attributes or invalid starting.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should err for invalid atributes", function() {
const xmlData = `<rootNode =''></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute '''' has no space in starting.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should validate xml with atributes", function() {
const xmlData = `<rootNode attr="123"><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should validate xml atribute has '>' in value", function() {
const xmlData = `<rootNode attr="123>234"><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should not validate xml with invalid atributes", function() {
const xmlData = `<rootNode attr="123><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attributes for 'rootNode' have open quote.",
"line": 1,
"col": 10
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes when duplicate attributes present", function() {
const xmlData = `<rootNode abc='123' abc="567" />`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'abc' is repeated.",
"line": 1,
"col": 22
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes when no space between 2 attributes", function() {
const xmlData = `<rootNode abc='123'bc='567' />`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'bc' has no space in starting.",
"line": 1,
"col": 21
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate a tag with attribute presents without value ", function() {
const xmlData = `<rootNode ab cd='ef'></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "boolean attribute 'ab' is not allowed.",
"line": 1,
"col": 11
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes presents without value", function() {
const xmlData = `<rootNode 123 abc='123' bc='567' />`;
const expected = {
"err": {
"code": "InvalidAttr",
// "msg": "attribute 123 is an invalid name."
"msg": "boolean attribute '123' is not allowed.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should validate xml with attributeshaving openquote in value", function () {
const xmlData = "<rootNode 123 abc='1\"23' bc=\"56'7\" />";
const expected = {
"err": {
"code": "InvalidAttr",
// "msg": "attribute 123 is an invalid name."
"msg": "boolean attribute '123' is not allowed.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should parse and build with tag name 'attributes' ", function() {
const XMLdata = `
<test attr="test bug">
<a name="a">123</a>
<b name="b"/>
<attributes>
<attribute datatype="string" name="DebugRemoteType">dev</attribute>
<attribute datatype="string" name="DebugWireType">2</attribute>
<attribute datatype="string" name="TypeIsVarchar">1</attribute>
</attributes>
</test>`;
const options = {
ignoreAttributes: false,
format: true,
preserveOrder: true,
suppressEmptyNode: true,
unpairedTags: ["star"]
};
const parser = new XMLParser(options);
let result = parser.parse(XMLdata);
// console.log(JSON.stringify(result, null,4));
const builder = new XMLBuilder(options);
const output = builder.build(result);
// console.log(output);
expect(output.replace(/\s+/g, "")).toEqual(XMLdata.replace(/\s+/g, ""));
});
});
|
NaturalIntelligence/fast-xml-parser
|
spec/attr_spec.js
|
JavaScript
|
mit
| 12,552
|
/*
* branch-benches.cpp
*
* Branching benchmarks.
*/
#include "benchmark.hpp"
#define JF_D(f, a, b) f(jmp_forward_##a##_##b, a, b)
#define IN_D(f, a) f(indirect_forward_##a, a)
#define JD_D(f, a, b) f(jmp_forward_dual_##a##_##b##_0, a, b, 0) f(jmp_forward_dual_##a##_##b##_1, a, b, 1)
#define JL_D(f, a, b, c, d) f(a, b, c, d)
#define FORWARD_X(delegate, f) \
delegate(f, 8, 8) \
delegate(f, 16, 16) \
delegate(f, 32, 32) \
delegate(f, 64, 64) \
delegate(f, 96, 96) \
delegate(f, 128, 128) \
#define FORWARD_X2(delegate, f) \
delegate(f, 8) \
delegate(f, 16) \
delegate(f, 32) \
delegate(f, 64) \
#define DUAL_X(delegate, f) \
delegate(f, 32, 16) \
delegate(f, 32, 6) \
delegate(f, 64, 16) \
delegate(f, 64, 48) \
#define LOOP_X(delegate, f) \
delegate(f, 32, 16, 2, 0) \
delegate(f, 32, 16, 2, 1) \
delegate(f, 32, 16, 2, 2) \
\
delegate(f, 32, 16, 3, 0) \
delegate(f, 32, 16, 3, 1) \
delegate(f, 32, 16, 3, 2) \
delegate(f, 32, 16, 3, 3)
#define JMP_FORWARD_X(f) FORWARD_X(JF_D, f)
#define IND_FORWARD_X(f) FORWARD_X2(IN_D, f)
#define JMP_DUAL_X(f) DUAL_X(JD_D, f)
#define JMP_LOOP_X(f) LOOP_X(JL_D, f)
#define DECLARE_FORWARD(name, ...) bench2_f name;
extern "C" {
JMP_FORWARD_X(DECLARE_FORWARD)
IND_FORWARD_X(DECLARE_FORWARD)
JMP_DUAL_X(DECLARE_FORWARD)
bench2_f jmp_loop_generic_32_16;
bench2_f define_indirect_variable;
bench2_f la_load;
bench2_f la_lea;
}
template <typename TIMER>
void register_branch(GroupList& list) {
#if !UARCH_BENCH_PORTABLE
std::shared_ptr<BenchmarkGroup> group = std::make_shared<BenchmarkGroup>("branch/x86/indirect",
"Indirect branch benchmarks");
list.push_back(group);
auto maker = DeltaMaker<TIMER>(group.get());
#define MAKE_JUMP_FORWARD(name, a, b) maker.template make<name> \
(#name, "20 uncond jumps by " #a " then " #b " bytes", 1);
JMP_FORWARD_X(MAKE_JUMP_FORWARD)
#define MAKE_INDIRECT_FORWARD(name, a) maker.template make<name> \
(#name, "20 indirect jumps by " #a " bytes", 1);
IND_FORWARD_X(MAKE_INDIRECT_FORWARD)
// shows that the first target in a 32-byte block gets special (fast) treatment
// in the BTB
#define MAKE_JUMP_DUAL(name, a, b, sprio) maker.template make<name> \
(#name, "30 dual jmps, blk: " #a ", gap: " #b ", sp: " #sprio, 1);
JMP_DUAL_X(MAKE_JUMP_DUAL)
struct jmp_loop_args {
uint32_t total, first;
};
#define MAKE_JUMP_LOOP(a, b, total, first) maker.template make<jmp_loop_generic_##a##_##b> \
("jmp-loop-" #a "-" #b "-" #total "-" #first, "loop blk: " #a " gap: " #b " first: " #first " tot: " #total, 1, \
arg_object(jmp_loop_args{total, first}));
JMP_LOOP_X(MAKE_JUMP_LOOP)
uint32_t sizes[] = {10, 100};
for (auto total : sizes) {
for (uint32_t first = 0; first <= total; first++) {
auto id = std::string("jmp-loop-32-16-{}-{}") + std::to_string(total) + "-" + std::to_string(first);
auto desc = std::string("loop blk: 32 gap: 16 first: ") + std::to_string(first) + " tot: " + std::to_string(total);
maker.template make<jmp_loop_generic_32_16>
(id, desc, 1, arg_object(jmp_loop_args{total, first}));
}
}
maker.template make<define_indirect_variable> \
("define_indirect_variable", "indirect variable", 1);
maker.template make<la_load>("load-alloc", "Load rename/alloc latency", 1);
maker.template make<la_lea>("lea-alloc", "LEA rename/alloc latency", 1);
#endif // #if !UARCH_BENCH_PORTABLE
}
#define REGISTER(CLOCK) template void register_branch<CLOCK>(GroupList& list);
ALL_TIMERS_X(REGISTER);
|
travisdowns/uarch-bench
|
branch-benches.cpp
|
C++
|
mit
| 3,784
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.