code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package render import ( "github.com/gin-gonic/gin" ) /* ================================================================================ * Render 工具模块 * qq group: 582452342 * email : 2091938785@qq.com * author : 美丽的地球啊 - mliu * ================================================================================ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 输出错误消息 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ func Error(c *gin.Context, msg string) { String(c, msg, 400) }
sanxia/ging
render/error.go
GO
mit
601
/* * _____ _ _ _ _____ _ _ _ _____ _ __ _____ _____ * / ___| | | | | | | |_ _| | | / / | | | ____| | | / / | ____| | _ \ * | | | | | | | | | | | | / / | | | |__ | | __ / / | |__ | |_| | * | | _ | | | | | | | | | | / / | | | __| | | / | / / | __| | _ / * | |_| | | |___ | |_| | | | | |/ / | | | |___ | |/ |/ / | |___ | | \ \ * \_____/ |_____| \_____/ |_| |___/ |_| |_____| |___/|___/ |_____| |_| \_\ * * Version 0.9 * Bruno Levy, August 2006 * INRIA, Project ALICE * */ #include "glut_viewer_gui.h" #include <GLsdk/gl_stuff.h> #include <GL/glut.h> #include <iostream> #include <stdarg.h> #include <math.h> #include <stdio.h> namespace GlutViewerGUI { // ------------------- Primitives for internal use -------------------------------------- static void printf_xy(GLfloat x, GLfloat y, const char *format, ...) { va_list args; char buffer[1024], *p; va_start(args, format); vsprintf(buffer, format, args); va_end(args); glPushMatrix(); glTranslatef(x, y, 0); for (p = buffer; *p; p++) { glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, *p); } glPopMatrix(); } static void circle_arc_vertices( GLfloat x, GLfloat y, GLfloat r1, GLfloat r2, GLfloat theta1, GLfloat theta2 ) { const GLfloat delta_theta = 1.0f ; if(theta2 > theta1) { for(GLfloat theta = theta1; theta <= theta2; theta += delta_theta) { GLfloat theta_rad = theta * 3.14159f / 200.0f ; glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ; } } else { for(GLfloat theta = theta1; theta >= theta2; theta -= delta_theta) { GLfloat theta_rad = theta * 3.14159f / 200.0f ; glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ; } } } static void circle_arc_vertices( GLfloat x, GLfloat y, GLfloat r, GLfloat theta1, GLfloat theta2 ) { circle_arc_vertices(x,y,r,r,theta1,theta2) ; } static void circle(GLfloat x, GLfloat y, GLfloat r) { glBegin(GL_LINE_LOOP) ; circle_arc_vertices(x,y,r,0.0f,400.0f) ; glEnd() ; } static void fill_circle(GLfloat x, GLfloat y, GLfloat r) { glBegin(GL_POLYGON) ; circle_arc_vertices(x,y,r,0.0f,400.0f) ; glEnd() ; } static void round_rectangle_vertices( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r ) { glVertex2f(x1+r,y2) ; glVertex2f(x2-r,y2) ; circle_arc_vertices(x2-r, y2-r, r, 100.0f, 0.0f) ; glVertex2f(x2,y2-r) ; glVertex2f(x2,y1+r) ; circle_arc_vertices(x2-r, y1+r, r, 0.0f, -100.0f) ; glVertex2f(x2-r,y1) ; glVertex2f(x1+r,y1) ; circle_arc_vertices(x1+r, y1+r, r, -100.0f, -200.0f) ; glVertex2f(x1,y1+r) ; glVertex2f(x1,y2-r) ; circle_arc_vertices(x1+r, y2-r, r, -200.0f, -300.0f) ; } static void round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) { glBegin(GL_LINE_LOOP) ; round_rectangle_vertices(x1, y1, x2, y2, r) ; glEnd() ; } static void fill_round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) { glBegin(GL_POLYGON) ; round_rectangle_vertices(x1, y1, x2, y2, r) ; glEnd() ; } static void arrow_vertices(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { GLfloat x12 = 0.5 * (x1 + x2) ; GLfloat y12 = 0.5 * (y1 + y2) ; switch(dir) { case DOWN: glVertex2f(x1,y2) ; glVertex2f(x2,y2) ; glVertex2f(x12,y1) ; break ; case UP: glVertex2f(x1,y1) ; glVertex2f(x2,y1) ; glVertex2f(x12,y2) ; break ; case LEFT: glVertex2f(x2,y2) ; glVertex2f(x2,y1) ; glVertex2f(x1,y12) ; break ; case RIGHT: glVertex2f(x1,y2) ; glVertex2f(x1,y1) ; glVertex2f(x2,y12) ; break ; } } static void arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { glBegin(GL_LINE_LOOP) ; arrow_vertices(dir, x1, y1, x2, y2) ; glEnd() ; } static void fill_arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { glBegin(GL_POLYGON) ; arrow_vertices(dir, x1, y1, x2, y2) ; glEnd() ; } // ------------------- Widget class -------------------------------------- Widget::Widget( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ) : style_(BlueStyle), visible_(true), highlight_(false) { set_geometry(x1, y1, x2, y2) ; r_ = 100.0f ; } Widget::~Widget() { } void Widget::glColor(ColorRole role_in) { ColorRole role = role_in ; if(highlight_) { switch(role_in) { case Background: role = Foreground ; break ; case Middleground: role = Middleground ; break ; case Foreground: role = Foreground ; break ; } } switch(style_) { case RedStyle: { switch(role) { case Background: glColor4f(0.5f, 0.0f, 0.0f, 0.5f) ; break ; case Middleground: glColor4f(1.0f, 0.5f, 0.5f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case GreenStyle: { switch(role) { case Background: glColor4f(0.0f, 0.5f, 0.0f, 0.5f) ; break ; case Middleground: glColor4f(0.5f, 1.0f, 0.5f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case BlueStyle: { switch(role) { case Background: glColor4f(0.0f, 0.0f, 0.5f, 0.5f) ; break ; case Middleground: glColor4f(0.5f, 0.5f, 1.0f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case BWStyle: { switch(role) { case Background: glColor4f(5.0f, 5.0f, 5.0f, 0.5f) ; break ; case Middleground: glColor4f(0.2f, 0.2f, 0.2f, 1.0f) ; break ; case Foreground: glColor4f(0.0f, 0.0f, 0.0f, 1.0f) ; break ; } } break ; } } GLboolean Widget::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { return contains(int(x),int(y)) ; } void Widget::draw() { if(!visible()) { return ; } draw_background() ; draw_border() ; } void Widget::draw_background() { glEnable(GL_BLEND) ; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ; glColor(Background) ; fill_round_rectangle(x1_, y1_, x2_, y2_, r_) ; glDisable(GL_BLEND) ; } void Widget::draw_border() { glColor(Foreground) ; glLineWidth(2.0) ; round_rectangle(x1_, y1_, x2_, y2_, r_) ; } //______________________________________________________________________________________________________ Container* Container::main_widget_ = NULL ; Container::~Container() { if(main_widget_ == this) { main_widget_ = NULL ; } for(size_t i=0; i<children_.size(); i++) { delete children_[i] ; } } void Container::draw() { if(!visible()) { return ; } for(size_t i=0; i<children_.size(); i++) { children_[i]->draw() ; } } GLboolean Container::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } switch(event) { case GLUT_VIEWER_DOWN: { for(size_t i=0; i<children_.size(); i++) { if(children_[i]->contains(x,y) && children_[i]->process_mouse_event(x, y, button, event)) { active_child_ = children_[i] ; return GL_TRUE ; } } } break ; case GLUT_VIEWER_MOVE: { if(active_child_ != NULL) { return active_child_->process_mouse_event(x, y, button, event) ; } } break ; case GLUT_VIEWER_UP: { if(active_child_ != NULL) { Widget* w = active_child_ ; active_child_ = NULL ; return w->process_mouse_event(x, y, button, event) ; } } break ; } return GL_FALSE ; } void Container::draw_handler() { if(main_widget_ != NULL) { main_widget_->draw() ; } } GLboolean Container::mouse_handler(float x, float y, int button, enum GlutViewerEvent event) { if(main_widget_ != NULL) { return main_widget_->process_mouse_event(x, y, button, event) ; } return GL_FALSE ; } void Container::set_as_main_widget() { main_widget_ = this ; glut_viewer_set_overlay_func(draw_handler) ; glut_viewer_set_mouse_func(mouse_handler) ; } //______________________________________________________________________________________________________ void Panel::draw() { Widget::draw() ; Container::draw() ; } GLboolean Panel::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible() || !contains(x,y)) { return GL_FALSE ; } return Container::process_mouse_event(x,y,button,event) ; } //______________________________________________________________________________________________________ void Button::draw() { Widget::draw() ; } GLboolean Button::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(visible() && contains(x,y) && event == GLUT_VIEWER_DOWN) { pressed() ; highlight_ = GL_TRUE ; return GL_TRUE ; } if(visible() && contains(x,y) && event == GLUT_VIEWER_UP) { highlight_ = GL_FALSE ; return GL_TRUE ; } return GL_FALSE ; } void Button::pressed() { if(callback_ != NULL) { callback_(client_data_) ; } } //______________________________________________________________________________________________________ void Checkbox::draw() { if(!visible()) { return ; } Button::draw() ; glColor(Foreground) ; GLfloat x = 0.5f * (x1_ + x2_) ; GLfloat y = 0.5f * (y1_ + y2_) ; if(toggle_) { glColor(Middleground) ; fill_circle(x,y,d_) ; glColor(Foreground) ; glLineWidth(1.0f) ; circle(x,y,d_) ; } } void Checkbox::pressed() { toggle_ = !toggle_ ; } //______________________________________________________________________________________________________ ArrowButton::ArrowButton( Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ) : Button(x1, y1, x2, y2), direction_(dir) { d_ /= 1.5 ; r_ /= 2.0 ; } void ArrowButton::draw() { Button::draw() ; glColor(Middleground) ; fill_arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ; glColor(Foreground); arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ; } //______________________________________________________________________________________________________ void Slider::set_value(GLfloat x, bool update) { if(integer_) { x = GLfloat(GLint(x)) ; } if(x < min_) { x = min_ ; } if(x > max_) { x = max_ ; } value_ = x ; if(update && callback_ != NULL) { callback_(value_) ; } } void Slider::set_range(GLfloat x1, GLfloat x2) { min_ = x1 ; max_ = x2 ; if(value_ < min_) { set_value(min_) ; } if(value_ > max_) { set_value(max_) ; } } void Slider::draw() { if(!visible()) { return ; } Widget::draw() ; glColor(Middleground) ; glLineWidth(2.0f) ; glBegin(GL_LINES) ; glVertex2f(x1_+d_, 0.5f*(y1_+y2_)) ; glVertex2f(x2_-d_, 0.5f*(y1_+y2_)) ; glEnd() ; GLfloat w = (value_ - min_) / (max_ - min_) ; GLfloat x = w*(x2_ - d_) + (1.0f - w)*(x1_ + d_) ; GLfloat y = 0.5f*(y1_+y2_) ; glColor(Middleground) ; fill_circle(x,y,d_) ; glColor(Foreground) ; glLineWidth(1.0f) ; circle(x,y,d_) ; } GLboolean Slider::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } if(event == GLUT_VIEWER_DOWN || event == GLUT_VIEWER_MOVE) { GLfloat w = GLfloat(x - x1_ - d_) / GLfloat(x2_ - x1_ - 2.0f * d_) ; set_value((1.0f - w) * min_ + w * max_, continuous_update_ == GL_TRUE) ; return GL_TRUE ; } else if(event == GLUT_VIEWER_UP) { set_value(value_) ; } return GL_FALSE ; } //______________________________________________________________________________________________________ void CurveEditor::draw() { if(!visible()) { return ; } draw_background() ; // Draw grid glColor(Middleground) ; glLineWidth(1.0) ; glBegin(GL_LINES) ; for(unsigned int i=1; i<10; i++) { float x = x1_ + (x2_ - x1_) * float(i) / 10.0f ; glVertex2f(x, y1_) ; glVertex2f(x, y2_) ; } for(unsigned int i=1; i<4; i++) { float y = y1_ + (y2_ - y1_) * float(i) / 4.0f ; glVertex2f(x1_, y) ; glVertex2f(x2_, y) ; } glEnd() ; // Draw curve glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_STRIP) ; for(unsigned int i=0; i<CurveSize; i++) { glVertex2f( x1_ + (float)i * (x2_ - x1_) / (float)(CurveSize - 1), y1_ + curve_[i] * (y2_ - y1_) ) ; } glEnd() ; draw_border() ; } GLboolean CurveEditor::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } if(event == GLUT_VIEWER_DOWN && !contains(x,y)) { return GL_FALSE ; } int i = int((x - x1_) * (CurveSize - 1) / (x2_ - x1_)) ; GLfloat v = GLfloat(y - y1_) / GLfloat(y2_ - y1_) ; if(v < 0.0) { v = 0.0 ; } if(v > 1.0) { v = 1.0 ; } if(i < 0) { i = 0 ; } if(i >= CurveSize) { i = CurveSize - 1 ; } if(event == GLUT_VIEWER_DOWN) { last_i_ = i ; last_v_ = v ; return GL_TRUE ; } if(event == GLUT_VIEWER_UP) { if(callback_ != NULL) { callback_(curve_, CurveSize) ; } return GL_TRUE ; } if(event == GLUT_VIEWER_MOVE) { if(i > last_i_) { set_curve(last_i_, last_v_, i, v) ; } else { set_curve(i, v, last_i_, last_v_) ; } } last_i_ = i ; last_v_ = v ; return GL_TRUE ; } void CurveEditor::set_curve(int i1, float val1, int i2, float val2) { if(i1 == i2) { curve_[i1] = val1 ; } else { for(int i=i1; i<=i2; i++) { curve_[i] = val1 + (float)(i - i1) * (val2 - val1) / (float)(i2 - i1) ; } } } void CurveEditor::set_curve(GLfloat* curve, bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = curve[i] ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } void CurveEditor::reset(bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = 0.5f ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } void CurveEditor::reset_ramp(bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = float(i) / float(CurveSize - 1) ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } GLfloat CurveEditor::value(GLfloat x) const { if(x < 0.0f) { x = 0.0f ; } if(x > 1.0f) { x = 1.0f ; } return curve_[int(x * (CurveSize - 1))] ; } //______________________________________________________________________________________________________ void ColormapEditor::draw() { if(!visible()) { return ; } draw_background() ; // Draw curve glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_STRIP) ; for(unsigned int i=0; i<ColormapSize; i++) { glVertex2f( x1_ + (float)i * (x2_ - x1_) / (float)(ColormapSize - 1), y1_ + curve()[i] * (y2_ - y1_) ) ; } glEnd() ; draw_border() ; } void ColormapEditor::draw_background() { glEnable(GL_BLEND) ; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ; drawBackgroundCB_(curve(), ColormapSize) ; glDisable(GL_BLEND) ; } void ColormapEditor::draw_border() { glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_LOOP) ; glVertex2f(x1_, y1_) ; glVertex2f(x1_, y2_) ; glVertex2f(x2_, y2_) ; glVertex2f(x2_, y1_) ; glEnd() ; } void ColormapEditor::update(unsigned char* cmap_data, int size, int component) { for(unsigned int i = 0; i < ColormapSize; ++i) { int idx = (double(i) / double(ColormapSize)) * (size-1) ; curve()[i] = double(cmap_data[4*idx + component]) / 255.0 ; } } //______________________________________________________________________________________________________ void TextLabel::draw() { if(!visible()) { return ; } glLineWidth(textwidth_) ; printf_xy(x1_+10, y1_+50, (char*)text_.c_str()) ; } //______________________________________________________________________________________________________ Spinbox::Spinbox( GLfloat x, GLfloat y, GLenum& value, const std::vector<std::string>& labels ) : Container(x, y, x+3000, y+170), value_(value), labels_(labels) { down_ = new ArrowButton(DOWN, x, y, x+170, y+170) ; up_ = new ArrowButton(UP, x+200, y, x+370, y+170) ; up_->set_callback(increment_CB, this) ; down_->set_callback(decrement_CB, this) ; if(value_ < 0) { value_ = 0 ; } if(value_ >= int(labels_.size())) { value_ = (GLenum)(labels_.size() - 1) ; } text_ = new TextLabel(x+450,y,labels_[value_]) ; add_child(up_) ; add_child(down_) ; add_child(text_) ; show() ; } void Spinbox::draw() { Container::draw() ; } void Spinbox::increment() { value_++ ; if(value_ >= labels_.size()) { value_ = 0 ; } text_->set_text(labels_[value_]) ; } void Spinbox::decrement() { if(int(value_) - 1 < 0) { value_ = (GLenum)(labels_.size() - 1) ; } else { value_-- ; } text_->set_text(labels_[value_]) ; } void Spinbox::increment_CB(void* spinbox) { static_cast<Spinbox*>(spinbox)->increment() ; } void Spinbox::decrement_CB(void* spinbox) { static_cast<Spinbox*>(spinbox)->decrement() ; } //______________________________________________________________________________________________________ void MessageBox::draw() { if(!visible()) { return ; } Panel::draw() ; glLineWidth(2) ; for(unsigned int i=0; i<message_.size(); i++) { printf_xy(x1_+100, y2_-200-i*150, (char*)message_[i].c_str()) ; } } //______________________________________________________________________________________________________ PropertyPage::PropertyPage( GLfloat x_in, GLfloat y_in, const std::string& caption ) : Panel(x_in,y_in-10,x_in+Width,y_in) { y_ = y2_ - 200 ; x_caption_ = x1_ + 100 ; x_widget_ = x1_ + 1300 ; caption_ = add_separator(caption) ; y1_ = y_ ; } TextLabel* PropertyPage::add_separator(const std::string& text) { TextLabel* w = new TextLabel(x1_ + 400, y_, text, 2.0f) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } TextLabel* PropertyPage::add_string(const std::string& text) { TextLabel* w = new TextLabel(x1_ + 200, y_, text, 1.0f) ; add_child(w) ; y_ -= 150 ; y1_ = y_ ; return w ; } Slider* PropertyPage::add_slider( const std::string& caption, GLfloat& value, GLfloat vmin, GLfloat vmax ) { add_child(new TextLabel(x_caption_, y_, caption)) ; Slider* w = new Slider(x_widget_, y_, x_widget_+800, y_+200, value) ; w->set_range(vmin, vmax) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } Checkbox* PropertyPage::add_toggle( const std::string& caption, GLboolean& value ) { add_child(new TextLabel(x_caption_, y_, caption)) ; Checkbox* w = new Checkbox(x_widget_, y_, x_widget_+200, y_+200, value) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } Spinbox* PropertyPage::add_enum( const std::string& caption, GLenum& value, const std::vector<std::string>& labels) { add_child(new TextLabel(x_caption_, y_, caption)) ; Spinbox* w = new Spinbox(x_widget_, y_, value, labels) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } //______________________________________________________________________________________________________ ViewerProperties::ViewerProperties(GLfloat x_left, GLfloat y_top) : PropertyPage( x_left, y_top, "Viewer" ) { add_toggle("Rot. light", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_ROTATE_LIGHT)) ; if(glut_viewer_is_enabled(GLUT_VIEWER_HDR)) { add_slider("Exposure", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_EXPOSURE), 0.001, 3.0) ; add_slider("Gamma", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_GAMMA), 0.2, 1.5) ; add_toggle("Vignette", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_VIGNETTE)) ; add_slider("Blur amount", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_AMOUNT)) ; add_slider("Blur width", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_WIDTH), 1.0, 20.0) ; add_toggle("UnMsk.", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING)) ; add_toggle("UnMsk.+", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_POSITIVE_UNSHARP_MASKING)) ; add_slider("UnMsk. Gamm", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING_GAMMA), 0.2, 1.5) ; } } void ViewerProperties::draw() { if(glut_viewer_is_enabled(GLUT_VIEWER_IDLE_REDRAW)) { static char buff[256] ; sprintf(buff, " [%4d FPS]", glut_viewer_fps()) ; caption_->set_text("Viewer" + std::string(buff)) ; } else { caption_->set_text("Viewer") ; } PropertyPage::draw() ; } void ViewerProperties::apply() { } //______________________________________________________________________________________________________ Image::Image( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLint texture, GLint target ) : Widget(x1, y1, x2, y2), texture_(texture), texture_target_(target) { } void Image::draw() { if(texture_ == 0) { return ; } glEnable(texture_target_) ; glBindTexture(texture_target_, texture_) ; glBegin(GL_QUADS) ; glTexCoord2f(0.0, 0.0) ; glVertex2f(x1_, y1_) ; glTexCoord2f(1.0, 0.0) ; glVertex2f(x2_, y1_) ; glTexCoord2f(1.0, 1.0) ; glVertex2f(x2_, y2_) ; glTexCoord2f(0.0, 1.0) ; glVertex2f(x1_, y2_) ; glEnd() ; glDisable(texture_target_) ; } //______________________________________________________________________________________________________ }
stormHan/gpu_rvd
Gpu_Rvd/header/thid_party/glut_viewer/glut_viewer_gui.cpp
C++
mit
25,552
<?php /** * Description of aSites * * @author almaz */ class aSitesUsers extends Action { protected $defaultAct = 'List'; protected function configure() { require_once $this->module->pathModels . 'as_Sites.php'; require_once $this->module->pathModels . 'as_SitesUsers.php'; $authModule = General::$loadedModules['Auth']; require_once $authModule->pathModels . 'au_Users.php'; } /**setTpl * выводит список всех сайтов */ public function act_List() { if ($this->request->isAjax()) { $this->context->setTopTpl('html_list'); } else { $this->_parent(); $this->context->setTpl('content', 'html_list'); } $sql = Stmt::prepare2(as_Stmt::GET_SITES_USERS_USER, array('user_id' => $this->userInfo['user']['id'])); $tbl = new oTable(DBExt::selectToTable($sql)); $tbl->setIsDel(); $tbl->setIsEdit(); $tbl->setNamesColumns(array('host'=>'Сайт')); $tbl->addRulesView('password', '******'); $tbl->sort(Navigation::get('field'), Navigation::get('order')); $this->context->set('tbl', $tbl); $this->context->set('h1', 'Мои сайты'); } /** * выводит список всех сайтов */ public function act_Add() { if ($this->request->isAjax()) { $this->context->setTopTpl('site_add_html'); } else { $this->_parent(); $this->context->setTpl('content', 'site_add_html'); } $sqlSites = Stmt::prepare2(as_Stmt::ALL_SITES, array(), array (Stmt::ORDER => 'sort')); $listSites = new oList(DBExt::selectToList($sqlSites)); $fields['site_id'] = array('title' => 'Сайт', 'value' => '', 'data' => $listSites, 'type'=>'select', 'required' => true, 'validator' => null, 'info'=>'Список поддерживаемых на данный момент сайтов', 'error' => false, 'attr' => '', $checked = array()); $fields['login'] = array('title' => 'Логин', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array()); $fields['password'] = array('title' => 'Пароль', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array()); $form = new oForm($fields); $this->context->set('form', $form); $this->context->set('info_text', 'Добавление настроек для нового сайта...'); if ($this->request->is('POST')) { $form->fill($this->request->get('POST')); if ($form->isComplited()) { $siteUser = new as_SitesUsers(); $siteUser->site_id = $form->getFieldValue('site_id'); $siteUser->login = $form->getFieldValue('login'); $siteUser->password = $form->getFieldValue('password'); $siteUser->user_id = $this->userInfo['user']['id']; $siteUser->save(); $this->context->del('form'); $this->context->set('info_text', 'Настройки добавлены'); } } } function act_Del () { $id = (int)$this->request->get('id', 0); $sqlSites = Stmt::prepare2(as_Stmt::DEL_SITE_USER, array('user_id' => $this->userInfo['user']['id'], 'site_id' => $id)); DB::execute($prepare_stmt); $sql = Stmt::prepare(se_Stmt::IS_KEYWORDS_SET, array('set_id' => $id, Stmt::LIMIT => 1)); $sitesUsers = new as_SitesUsers((int)$this->request->get('id')); $sets->delete(); $iRoute = new InternalRoute(); $iRoute->module = 'SEParsing'; $iRoute->action = 'Sets'; $actR = new ActionResolver(); $act = $actR->getInternalAction($iRoute); $act->runAct(); } /** * Функция-обвертка, модули уровнем выще. для отображения * @param InternalRoute $iRoute */ function _parent(InternalRoute $iRoute = null) { $this->context->set('title', 'Сайты'); if (!$iRoute) { $iRoute = new InternalRoute(); $iRoute->module = 'Pages'; $iRoute->action = 'Pages'; } $actR = new ActionResolver(); $act = $actR->getInternalAction($iRoute); $act->runParentAct(); } }
AlmazKo/Brill
Brill/Modules/AutoSubmitter/Actions/aSitesUsers.php
PHP
mit
4,519
package cz.muni.fi.pa165.mushrooms.service.exceptions; /** * @author bkompis */ public class EntityOperationServiceException extends MushroomHunterServiceDataAccessException { public <T> EntityOperationServiceException(String what, String operation, T entity, Throwable e) { super("Could not " + operation + " " + what + " (" + entity + ").", e); } public EntityOperationServiceException(String msg) { super(msg); } public EntityOperationServiceException(String msg, Throwable cause) { super(msg, cause); } }
PA165-MushroomHunter/MushroomHunter
service/src/main/java/cz/muni/fi/pa165/mushrooms/service/exceptions/EntityOperationServiceException.java
Java
mit
563
#!/usr/bin/env python import subprocess import praw from hashlib import sha1 from flask import Flask from flask import Response from flask import request from cStringIO import StringIO from base64 import b64encode from base64 import b64decode from ConfigParser import ConfigParser import OAuth2Util import os import markdown import bleach # encoding=utf8 import sys from participantCollection import ParticipantCollection reload(sys) sys.setdefaultencoding('utf8') # Edit Me! # Each day after you post a signup post, copy its 6-character ID to this array. signupPageSubmissionIds = [ '7zrrj1', '7zxkpq', '8055hn', '80ddrf', '80nbm1', '80waq3' ] flaskport = 8993 app = Flask(__name__) app.debug = True commentHashesAndComments = {} def loginAndReturnRedditSession(): config = ConfigParser() config.read("../reddit-password-credentials.cfg") user = config.get("Reddit", "user") password = config.get("Reddit", "password") # TODO: password auth is going away, and we will soon need to do oauth. redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') redditSession.login(user, password, disable_warning=True) # submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5) # print [str(x) for x in submissions] return redditSession def loginOAuthAndReturnRedditSession(): redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') # New version of praw does not require explicit use of the OAuth2Util object. Presumably because reddit now REQUIRES oauth. # o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../reddit-oauth-credentials.cfg") # TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh(). # o.refresh(force=True) return redditSession def getSubmissionsForRedditSession(redditSession): # submissions = [redditSession.get_submission(submission_id=submissionId) for submissionId in signupPageSubmissionIds] submissions = [redditSession.submission(id=submissionId) for submissionId in signupPageSubmissionIds] for submission in submissions: submission.comments.replace_more(limit=None) # submission.replace_more_comments(limit=None, threshold=0) return submissions def getCommentsForSubmissions(submissions): comments = [] for submission in submissions: commentForest = submission.comments comments += [comment for comment in commentForest.list() if comment.__class__ == praw.models.Comment] return comments def retireCommentHash(commentHash): with open("retiredcommenthashes.txt", "a") as commentHashFile: commentHashFile.write(commentHash + '\n') def retiredCommentHashes(): with open("retiredcommenthashes.txt", "r") as commentHashFile: # return commentHashFile.readlines() return commentHashFile.read().splitlines() @app.route('/moderatesignups.html') def moderatesignups(): global commentHashesAndComments commentHashesAndComments = {} stringio = StringIO() stringio.write('<html>\n<head>\n</head>\n\n') # redditSession = loginAndReturnRedditSession() redditSession = loginOAuthAndReturnRedditSession() submissions = getSubmissionsForRedditSession(redditSession) flat_comments = getCommentsForSubmissions(submissions) retiredHashes = retiredCommentHashes() i = 1 stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n') stringio.write("<h3>") stringio.write(os.getcwd()) stringio.write("<br>\n") for submission in submissions: stringio.write(submission.title) stringio.write("<br>\n") stringio.write("</h3>\n\n") stringio.write('<form action="copydisplayduringsignuptoclipboard.html" method="post" target="invisibleiframe">') stringio.write('<input type="submit" value="Copy display-during-signup.py stdout to clipboard">') stringio.write('</form>') for comment in flat_comments: # print comment.is_root # print comment.score i += 1 commentHash = sha1() commentHash.update(comment.fullname) commentHash.update(comment.body.encode('utf-8')) commentHash = commentHash.hexdigest() if commentHash not in retiredHashes: commentHashesAndComments[commentHash] = comment authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None. stringio.write("<hr>\n") stringio.write('<font color="blue"><b>') stringio.write(authorName) # can be None if author was deleted. So check for that and skip if it's None. stringio.write('</b></font><br>') if ParticipantCollection().hasParticipantNamed(authorName): stringio.write(' <small><font color="green">(member)</font></small>') # if ParticipantCollection().participantNamed(authorName).isStillIn: # stringio.write(' <small><font color="green">(in)</font></small>') # else: # stringio.write(' <small><font color="red">(out)</font></small>') else: stringio.write(' <small><font color="red">(not a member)</font></small>') stringio.write('<form action="takeaction.html" method="post" target="invisibleiframe">') stringio.write('<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">') # stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">') # stringio.write('<input type="submit" name="actiontotake" value="Relapse">') # stringio.write('<input type="submit" name="actiontotake" value="Reinstate">') stringio.write('<input type="submit" name="actiontotake" value="Skip comment">') stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">') stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">') stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">') # stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">') stringio.write('</form>') stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p'])) stringio.write("\n<br><br>\n\n") stringio.write('</html>') pageString = stringio.getvalue() stringio.close() return Response(pageString, mimetype='text/html') @app.route('/takeaction.html', methods=["POST"]) def takeaction(): username = b64decode(request.form["username"]) commentHash = str(request.form["commenthash"]) # commentPermalink = request.form["commentpermalink"] actionToTake = request.form["actiontotake"] # print commentHashesAndComments comment = commentHashesAndComments[commentHash] # print "comment: " + str(comment) if actionToTake == 'Signup': print "signup - " + username subprocess.call(['./signup.py', username]) comment.upvote() retireCommentHash(commentHash) # if actionToTake == 'Signup and checkin': # print "signup and checkin - " + username # subprocess.call(['./signup-and-checkin.sh', username]) # comment.upvote() # retireCommentHash(commentHash) # elif actionToTake == 'Relapse': # print "relapse - " + username # subprocess.call(['./relapse.py', username]) # comment.upvote() # retireCommentHash(commentHash) # elif actionToTake == 'Reinstate': # print "reinstate - " + username # subprocess.call(['./reinstate.py', username]) # comment.upvote() # retireCommentHash(commentHash) elif actionToTake == 'Skip comment': print "Skip comment - " + username comment.upvote() retireCommentHash(commentHash) elif actionToTake == "Skip comment and don't upvote": print "Skip comment and don't upvote - " + username retireCommentHash(commentHash) return Response("hello", mimetype='text/html') @app.route('/copydisplayduringsignuptoclipboard.html', methods=["POST"]) def copydisplayduringsignuptoclipboard(): print "TODO: Copy display to clipboard" subprocess.call(['./display-during-signup.py']) return Response("hello", mimetype='text/html') if __name__ == '__main__': app.run(host='127.0.0.1', port=flaskport)
foobarbazblarg/stayclean
stayclean-2018-march/serve-signups-with-flask.py
Python
mit
8,581
using System.Collections.Generic; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Objects; namespace JsonApiDotNetCore.Serialization.Building { /// <summary> /// Responsible for converting resources into <see cref="ResourceObject" />s given a collection of attributes and relationships. /// </summary> public interface IResourceObjectBuilder { /// <summary> /// Converts <paramref name="resource" /> into a <see cref="ResourceObject" />. Adds the attributes and relationships that are enlisted in /// <paramref name="attributes" /> and <paramref name="relationships" />. /// </summary> /// <param name="resource"> /// Resource to build a <see cref="ResourceObject" /> for. /// </param> /// <param name="attributes"> /// Attributes to include in the building process. /// </param> /// <param name="relationships"> /// Relationships to include in the building process. /// </param> /// <returns> /// The resource object that was built. /// </returns> ResourceObject Build(IIdentifiable resource, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships); } }
Research-Institute/json-api-dotnet-core
src/JsonApiDotNetCore/Serialization/Building/IResourceObjectBuilder.cs
C#
mit
1,337
'use strict'; var page = 'projects'; module.exports = { renderPage: function(req, res) { if (!req.user) { res.redirect('/login'); } else { res.render(page, { helpers: { activeClass: function(section) { if (section === 'projects') { return 'active'; } else { return ''; } } }, user: req.user ? req.user.toJSON() : null }); } } }
bobholt/genealogists-friend
app/controllers/project.js
JavaScript
mit
472
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; this.init = function() { var _this = this; var observer = function(e) { switch(e.originalEvent.keyCode) { case 38: // Event.KEY_UP case 40: // Event.KEY_DOWN return; } _this.search(_this.$input[0].value); }; this.$input.keyup(observer); this.$input.click(observer); // mac's clear field this.searcher.ready(function(results, isLast) { _this.addResults(results, isLast); }); this.initNavigation(); this.setNavigationActive(false); }; this.search = function(value, selectFirstMatch) { value = jQuery.trim(value).toLowerCase(); if (value) { this.setNavigationActive(true); } else { this.setNavigationActive(false); } if (value == '') { this.lastQuery = value; this.$result.empty(); this.$result.attr('aria-expanded', 'false'); this.setNavigationActive(false); } else if (value != this.lastQuery) { this.lastQuery = value; this.$result.attr('aria-busy', 'true'); this.$result.attr('aria-expanded', 'true'); this.firstRun = true; this.searcher.find(value); } }; this.addResults = function(results, isLast) { var target = this.$result.get(0); if (this.firstRun && (results.length > 0 || isLast)) { this.$current = null; this.$result.empty(); } for (var i=0, l = results.length; i < l; i++) { var item = this.renderItem.call(this, results[i]); item.setAttribute('id', 'search-result-' + target.childElementCount); target.appendChild(item); } if (this.firstRun && results.length > 0) { this.firstRun = false; this.$current = $(target.firstChild); this.$current.addClass('search-selected'); } if (jQuery.browser.msie) this.$element[0].className += ''; if (isLast) this.$result.attr('aria-busy', 'false'); }; this.move = function(isDown) { if (!this.$current) return; var $next = this.$current[isDown ? 'next' : 'prev'](); if ($next.length) { this.$current.removeClass('search-selected'); $next.addClass('search-selected'); this.$input.attr('aria-activedescendant', $next.attr('id')); this.scrollIntoView($next[0], this.$view[0]); this.$current = $next; this.$input.val($next[0].firstChild.firstChild.text); this.$input.select(); } return true; }; this.hlt = function(html) { return this.escapeHTML(html). replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); }; this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
gadzorg/gorg_mail
doc/app/js/search.js
JavaScript
mit
2,999
version https://git-lfs.github.com/spec/v1 oid sha256:505b4ccd47ed9526d0238c6f2d03a343ce476abc1c4aa79a9f22cabcbd0a3c16 size 12575
yogeshsaroya/new-cdnjs
ajax/libs/require.js/0.22.0/require.min.js
JavaScript
mit
130
#include "ConfirmationMenu.h" ConfirmationMenu::ConfirmationMenu(CarrotQt5* mainClass, std::function<void(bool)> callback, const QString& text, const QString& yesLabel, const QString& noLabel) : MenuScreen(mainClass), text(text) { menuOptions.append(buildMenuItem([this, callback]() { root->popState(); callback(true); }, yesLabel)); menuOptions.append(buildMenuItem([this, callback]() { root->popState(); callback(false); }, noLabel)); cancelItem = buildMenuItem([this, callback]() { root->popState(); callback(false); }, noLabel); setMenuItemSelected(0); } ConfirmationMenu::~ConfirmationMenu() { } void ConfirmationMenu::renderTick(bool, bool) { auto canvas = root->getCanvas(); uint viewWidth = canvas->getView().getSize().x; uint viewHeight = canvas->getView().getSize().y; BitmapString::drawString(canvas, root->getFont(), text, viewWidth / 2, viewHeight / 2 - 50, FONT_ALIGN_CENTER); menuOptions[0]->text->drawString(canvas, viewWidth / 2 - 100, viewHeight / 2 + 50); menuOptions[1]->text->drawString(canvas, viewWidth / 2 + 100, viewHeight / 2 + 50); } void ConfirmationMenu::processControlDownEvent(const ControlEvent& e) { MenuScreen::processControlDownEvent(e); switch (e.first.keyboardKey) { case Qt::Key_Left: setMenuItemSelected(-1, true); break; case Qt::Key_Right: setMenuItemSelected(1, true); break; } }
soulweaver91/project-carrot
src/menu/ConfirmationMenu.cpp
C++
mit
1,509
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.nott.mrl.gles.program; import android.opengl.GLES20; import android.util.Log; import com.android.grafika.gles.GlUtil; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; public class GraphProgram { private static final int SIZEOF_FLOAT = 4; private static final int VERTEX_STRIDE = SIZEOF_FLOAT * 2; private static final String TAG = GlUtil.TAG; private static final String VERTEX_SHADER = "uniform mat4 uMVPMatrix;" + "attribute vec4 aPosition;" + "void main() {" + " gl_Position = uMVPMatrix * aPosition;" + "}"; private static final String FRAGMENT_SHADER = "precision mediump float;" + "uniform vec4 uColor;" + "void main() {" + " gl_FragColor = uColor;" + "}"; private final int MAX_SIZE = 200; // Handles to the GL program and various components of it. private int programHandle = -1; private int colorLocation = -1; private int matrixLocation = -1; private int positionLocation = -1; private final float[] colour = {1f, 1f, 1f, 1f}; private final FloatBuffer points; private final float[] values = new float[MAX_SIZE]; private int size = 0; private int offset = 0; private boolean bufferValid = false; private float min = Float.MAX_VALUE; private float max = Float.MIN_VALUE; private static final float left = 1.8f; private static final float right = 0.2f; private static final float top = 0.8f; private static final float bottom = -0.8f; /** * Prepares the program in the current EGL context. */ public GraphProgram() { programHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER); if (programHandle == 0) { throw new RuntimeException("Unable to create program"); } Log.d(TAG, "Created program " + programHandle); // get locations of attributes and uniforms ByteBuffer bb = ByteBuffer.allocateDirect(MAX_SIZE * VERTEX_STRIDE); bb.order(ByteOrder.nativeOrder()); points = bb.asFloatBuffer(); positionLocation = GLES20.glGetAttribLocation(programHandle, "aPosition"); GlUtil.checkLocation(positionLocation, "aPosition"); matrixLocation = GLES20.glGetUniformLocation(programHandle, "uMVPMatrix"); GlUtil.checkLocation(matrixLocation, "uMVPMatrix"); colorLocation = GLES20.glGetUniformLocation(programHandle, "uColor"); GlUtil.checkLocation(colorLocation, "uColor"); } /** * Releases the program. */ public void release() { GLES20.glDeleteProgram(programHandle); programHandle = -1; } public synchronized void add(float value) { values[offset] = value; min = Math.min(value, min); max = Math.max(value, max); size = Math.min(size + 1, MAX_SIZE); offset = (offset + 1) % MAX_SIZE; bufferValid = false; } public void setColour(final float r, final float g, final float b) { colour[0] = r; colour[1] = g; colour[2] = b; } private synchronized FloatBuffer getValidBuffer() { if (!bufferValid) { points.position(0); for(int index = 0; index < size; index++) { float value = values[(offset + index) % size]; float scaledValue = ((value - min) / (max - min) * (top - bottom)) + bottom; //Log.i(TAG, "x=" + ((index * (right - left) / size) + left) + ", y=" + scaledValue); points.put((index * (right - left) / (size - 1)) + left); points.put(scaledValue); } points.position(0); bufferValid = true; } return points; } public void draw(float[] matrix) { GlUtil.checkGlError("draw start"); // Select the program. GLES20.glUseProgram(programHandle); GlUtil.checkGlError("glUseProgram"); // Copy the model / view / projection matrix over. GLES20.glUniformMatrix4fv(matrixLocation, 1, false, matrix, 0); GlUtil.checkGlError("glUniformMatrix4fv"); // Copy the color vector in. GLES20.glUniform4fv(colorLocation, 1, colour, 0); GlUtil.checkGlError("glUniform4fv "); // Enable the "aPosition" vertex attribute. GLES20.glEnableVertexAttribArray(positionLocation); GlUtil.checkGlError("glEnableVertexAttribArray"); // Connect vertexBuffer to "aPosition". GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, VERTEX_STRIDE, getValidBuffer()); GlUtil.checkGlError("glVertexAttribPointer"); // Draw the rect. GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, size); GlUtil.checkGlError("glDrawArrays"); // Done -- disable vertex array and program. GLES20.glDisableVertexAttribArray(positionLocation); GLES20.glUseProgram(0); } }
ktg/openFood
src/main/java/uk/ac/nott/mrl/gles/program/GraphProgram.java
Java
mit
5,077
package org.sfm.tuples; public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> { private final T20 element19; public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) { super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18); this.element19 = element19; } public final T20 getElement19() { return element19; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Tuple20 tuple20 = (Tuple20) o; if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (element19 != null ? element19.hashCode() : 0); return result; } @Override public String toString() { return "Tuple20{" + "element0=" + getElement0() + ", element1=" + getElement1() + ", element2=" + getElement2() + ", element3=" + getElement3() + ", element4=" + getElement4() + ", element5=" + getElement5() + ", element6=" + getElement6() + ", element7=" + getElement7() + ", element8=" + getElement8() + ", element9=" + getElement9() + ", element10=" + getElement10() + ", element11=" + getElement11() + ", element12=" + getElement12() + ", element13=" + getElement13() + ", element14=" + getElement14() + ", element15=" + getElement15() + ", element16=" + getElement16() + ", element17=" + getElement17() + ", element18=" + getElement18() + ", element19=" + getElement19() + '}'; } public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) { return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20); } }
tsdl2013/SimpleFlatMapper
sfm/src/main/java/org/sfm/tuples/Tuple20.java
Java
mit
3,155
<?php $districts = array('Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kaluthara', 'Kandy', 'Kilinochchi', 'Kegalle', 'Mannar', 'Matale', 'Matara', 'Monaragala', 'Mulattivu', 'Nuwaraeliya', 'Polonnaruwa', 'Rathnapura', 'Trincomalee', 'Vavuniya'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Log in</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.5 --> <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="../plugins/select2/select2.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../dist/css/AdminLTE.min.css"> <!-- iCheck --> <link rel="stylesheet" href="../plugins/iCheck/square/blue.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="../plugins/select2/select2.full.min.js"></script> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition login-page"> <div class="login-box"> <div class="login-logo"> <a href="../index2.html"><b>SCHOOL</b> LOGIN</a> </div> <!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">Choose your school and enter password</p> <form action="./index.php" method="post"> <div class="row"> <div class="form-group has-feedback"> <label for="name" class="col-sm-2 control-label">District</label> <div class="col-sm-12"> <select class="form-control select2" style="width: 100%;" onchange="load_district_schools(this.value)" name="district" id="district"> <option></option> <?php foreach ($districts as $district) { ?> <option><?php echo $district; ?></option> <?php } ?> </select> </div> <br><br><br><br> <div class="form-group"> <label for="name" class="col-sm-2 control-label">School</label> <div class="col-sm-12"> <select class="form-control select2" style="width: 100%;" name="schoolsfordistrict" id="schoolsfordistrict" > </select> </div> </div> </div> </div> <br> <label for="name" class=" control-label">Password</label> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Password" name="password"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> <div class="checkbox icheck"> </div> </div> <!-- /.col --> <div class="col-xs-4"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> <input type="hidden" id="login" name="login"> </form> </div> <!-- /.login-box-body --> </div> <!-- /.login-box --> <!-- jQuery 2.1.4 --> <script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="../plugins/select2/select2.full.min.js"></script> <!-- Bootstrap 3.3.5 --> <script src="../bootstrap/js/bootstrap.min.js"></script> <!-- iCheck --> <script src="../plugins/iCheck/icheck.min.js"></script> <script> $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); }); </script> <script type="text/javascript"> $('#Date').datepicker({ autoclose: true, todayHighlight: true, format: 'yyyy-mm-dd' }); function load_district_schools(district) { if (district != "") { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('schoolsfordistrict').innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "get_schools_from_district.php?district=" + district, true); xmlhttp.send(); } } function load_school_students(school_id) { if (school_id != "") { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { string = xmlhttp.responseText; alert(string); document.getElementById('studentsforschool').innerHTML = string; } }; xmlhttp.open("GET", "get_students_from_school.php?school_id=" + school_id, true); xmlhttp.send(); } } </script> <script> $(function () { //Initialize Select2 Elements $(".select2").select2(); //Datemask dd/mm/yyyy $("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"}); //Datemask2 mm/dd/yyyy $("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"}); //Money Euro $("[data-mask]").inputmask(); //Date range picker $('#reservation').daterangepicker(); //Date range picker with time picker $('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'}); //Date range as a button $('#daterange-btn').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, startDate: moment().subtract(29, 'days'), endDate: moment() }, function (start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); //iCheck for checkbox and radio inputs $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass: 'iradio_minimal-blue' }); //Red color scheme for iCheck $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({ checkboxClass: 'icheckbox_minimal-red', radioClass: 'iradio_minimal-red' }); //Flat red color scheme for iCheck $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' }); //Colorpicker $(".my-colorpicker1").colorpicker(); //color picker with addon $(".my-colorpicker2").colorpicker(); //Timepicker $(".timepicker").timepicker({ showInputs: false }); }); </script> </body> </html>
buddhiv/DatabaseProject
school_views/login.php
PHP
mit
9,115
/* * This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion * Copyright (C) 2016-2021 ViaVersion and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.viaversion.viaversion.protocols.protocol1_12_2to1_12_1; import com.viaversion.viaversion.api.protocol.AbstractProtocol; import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper; import com.viaversion.viaversion.api.type.Type; import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1; import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1; public class Protocol1_12_2To1_12_1 extends AbstractProtocol<ClientboundPackets1_12_1, ClientboundPackets1_12_1, ServerboundPackets1_12_1, ServerboundPackets1_12_1> { public Protocol1_12_2To1_12_1() { super(ClientboundPackets1_12_1.class, ClientboundPackets1_12_1.class, ServerboundPackets1_12_1.class, ServerboundPackets1_12_1.class); } @Override protected void registerPackets() { registerClientbound(ClientboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() { @Override public void registerMap() { map(Type.VAR_INT, Type.LONG); } }); registerServerbound(ServerboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() { @Override public void registerMap() { map(Type.LONG, Type.VAR_INT); } }); } }
MylesIsCool/ViaVersion
common/src/main/java/com/viaversion/viaversion/protocols/protocol1_12_2to1_12_1/Protocol1_12_2To1_12_1.java
Java
mit
2,084
<?php /** * @author "Michael Collette" <metrol@metrol.net> * @package Metrol_Libs * @version 2.0 * @copyright (c) 2014, Michael Collette */ namespace Metrol\HTML\Table; /** * Defines an HTML Table Foot Area */ class Foot extends Section { /** */ public function __construct() { parent::__construct('tfoot'); $this->rows = array(); } }
Metrol/Metrol
HTML/Table/Foot.php
PHP
mit
364
import sys sys.path.insert(0,'../') from fast_guided_filter import blur print("hello")
justayak/fast_guided_filters
test/sample.py
Python
mit
88
#include "core/bomberman.hpp" #include "core/menu.hpp" #include "core/screens.hpp" #include "core/view.hpp" #include "core/views/menu.hpp" MenuView::MenuView(Screen *screen, Menu *menu) : View(screen) , menu(menu) , clock(Timer::get(2)) { } MenuView::~MenuView() { delete this->menu; } void MenuView::update(const Events &events) { Vec2u pos(events.touch.x, events.touch.y); if (events.touch.isTouch && this->clock.current() > 10000) { this->clock.reset(); this->menu->onClick(pos); } } void MenuView::render() { swiWaitForVBlank(); dmaCopy(this->menu->bgSrc, bgGetGfxPtr(this->getScreen().bg), this->menu->bgSize); } void MenuView::setMenu(Menu *menu) { if (menu != nullptr) { menu->setView(this); } Menu *old = this->menu; Bomberman::getInstance().nextTick([old]() { delete old; }); this->menu = menu; } Menu &MenuView::getMenu() { return *this->menu; } const Menu &MenuView::getMenu() const { return *this->menu; }
kassisdion/Epitech_year_2
bomberman/src/core/views/menu.cpp
C++
mit
1,035
///<reference src="js/tempus-dominus"/> /*global $ */ tempusDominus.jQueryInterface = function (option, argument) { if (this.length === 1) { return tempusDominus.jQueryHandleThis(this, option, argument); } // "this" is jquery here return this.each(function () { tempusDominus.jQueryHandleThis(this, option, argument); }); }; tempusDominus.jQueryHandleThis = function (me, option, argument) { let data = $(me).data(tempusDominus.Namespace.dataKey); if (typeof option === 'object') { $.extend({}, tempusDominus.DefaultOptions, option); } if (!data) { data = new tempusDominus.TempusDominus($(me)[0], option); $(me).data(tempusDominus.Namespace.dataKey, data); } if (typeof option === 'string') { if (data[option] === undefined) { throw new Error(`No method named "${option}"`); } if (argument === undefined) { return data[option](); } else { if (option === 'date') { data.isDateUpdateThroughDateOptionFromClientCode = true; } const ret = data[option](argument); data.isDateUpdateThroughDateOptionFromClientCode = false; return ret; } } }; tempusDominus.getSelectorFromElement = function ($element) { let selector = $element.data('target'), $selector; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $element; } if (!$selector.data(tempusDominus.Namespace.dataKey)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }; /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $(document) .on( `click${tempusDominus.Namespace.events.key}.data-api`, `[data-toggle="${tempusDominus.Namespace.dataKey}"]`, function () { const $originalTarget = $(this), $target = tempusDominus.getSelectorFromElement($originalTarget), config = $target.data(tempusDominus.Namespace.dataKey); if ($target.length === 0) { return; } if ( config._options.allowInputToggle && $originalTarget.is('input[data-toggle="datetimepicker"]') ) { return; } tempusDominus.jQueryInterface.call($target, 'toggle'); } ) .on( tempusDominus.Namespace.events.change, `.${tempusDominus.Namespace.NAME}-input`, function (event) { const $target = tempusDominus.getSelectorFromElement($(this)); if ($target.length === 0 || event.isInit) { return; } tempusDominus.jQueryInterface.call($target, '_change', event); } ) .on( tempusDominus.Namespace.events.blur, `.${tempusDominus.Namespace.NAME}-input`, function (event) { const $target = tempusDominus.getSelectorFromElement($(this)), config = $target.data(tempusDominus.Namespace.dataKey); if ($target.length === 0) { return; } if (config._options.debug || window.debug) { return; } tempusDominus.jQueryInterface.call($target, 'hide', event); } ) /*.on(tempusDominus.Namespace.Events.keydown, `.${tempusDominus.Namespace.NAME}-input`, function (event) { const $target = tempusDominus.getSelectorFromElement($(this)); if ($target.length === 0) { return; } tempusDominus.jQueryInterface.call($target, '_keydown', event); }) .on(tempusDominus.Namespace.Events.keyup, `.${tempusDominus.Namespace.NAME}-input`, function (event) { const $target = tempusDominus.getSelectorFromElement($(this)); if ($target.length === 0) { return; } tempusDominus.jQueryInterface.call($target, '_keyup', event); })*/ .on( tempusDominus.Namespace.events.focus, `.${tempusDominus.Namespace.NAME}-input`, function (event) { const $target = tempusDominus.getSelectorFromElement($(this)), config = $target.data(tempusDominus.Namespace.dataKey); if ($target.length === 0) { return; } if (!config._options.allowInputToggle) { return; } tempusDominus.jQueryInterface.call($target, 'show', event); } ); const name = 'tempusDominus'; $.fn[name] = tempusDominus.jQueryInterface; $.fn[name].Constructor = tempusDominus.TempusDominus; $.fn[name].noConflict = function () { $.fn[name] = $.fn[name]; return tempusDominus.jQueryInterface; };
cdnjs/cdnjs
ajax/libs/tempus-dominus/6-alpha1/js/jQuery-provider.js
JavaScript
mit
4,501
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'sanitizeHtml', pure: false }) export class SanitizerPipe implements PipeTransform { constructor(private _sanitizer: DomSanitizer) { } transform(v: string): SafeHtml { const html = this._sanitizer.bypassSecurityTrustHtml(v); if (html.hasOwnProperty('changingThisBreaksApplicationSecurity') && /^<p>\d+\./.test(html['changingThisBreaksApplicationSecurity'])) { html['changingThisBreaksApplicationSecurity'] = '<p>' + html['changingThisBreaksApplicationSecurity'] .substr(html['changingThisBreaksApplicationSecurity'].indexOf('.') + 1); } return html; } }
ultimate-comparisons/ultimate-comparison-BASE
src/app/components/pipes/sanitizer-pipe/sanitizer.pipe.ts
TypeScript
mit
809
# from test_plus.test import TestCase # # # class TestUser(TestCase): # # def setUp(self): # self.user = self.make_user() # # def test__str__(self): # self.assertEqual( # self.user.__str__(), # 'testuser' # This is the default username for self.make_user() # ) # # def test_get_absolute_url(self): # self.assertEqual( # self.user.get_absolute_url(), # '/users/testuser/' # )
Alex-Just/gymlog
gymlog/main/tests/test_models.py
Python
mit
476
<?php class WPML_ST_Track_Strings_Notice { const NOTICE_ID = 'wpml-st-tracking-all-strings-as-english-notice'; const NOTICE_GROUP = 'wpml-st-strings-tracking'; /** * @var WPML_Notices */ private $admin_notices; public function __construct( WPML_Notices $admin_notices ) { $this->admin_notices = $admin_notices; } /** * @param int $track_strings */ public function add( $track_strings ) { if ( ! $track_strings ) { return; } $options_nonce = 'wpml-localization-options-nonce'; $message = __( 'For String Tracking to work, the option', 'wpml-string-translation' ); $message .= '<strong> ' . __( 'Assume that all texts in PHP strings are in English', 'wpml-string-translation' ) . ' </strong>'; $message .= __( 'was automatically disabled. To enable it back, go to WPML->Theme and Plugins localization.', 'wpml-string-translation' ); $message .= '<input type="hidden" id="' . $options_nonce . '" name="' . $options_nonce . '" value="' . wp_create_nonce( $options_nonce ) . '">'; $notice = $this->admin_notices->get_new_notice( self::NOTICE_ID, $message, self::NOTICE_GROUP ); $notice->set_css_class_types( 'info' ); $notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Cancel and undo changes', 'wpml-string-translation' ), '#', false, false, 'button-primary' ) ); $notice->add_action( $this->admin_notices->get_new_notice_action( __( 'Skip', 'wpml-string-translation' ), '#', false, true ) ); $this->admin_notices->add_notice( $notice ); } public function remove() { $this->admin_notices->remove_notice( self::NOTICE_GROUP, self::NOTICE_ID ); } }
mandino/hotelmilosantabarbara.com
wp-content/plugins/wpml-string-translation/classes/notices/track-strings/wpml-st-track-strings-notice.php
PHP
mit
1,629
using System; using System.Xml.Serialization; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AlipayEbppPdeductSignValidateResponse. /// </summary> public class AlipayEbppPdeductSignValidateResponse : AopResponse { } }
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Response/AlipayEbppPdeductSignValidateResponse.cs
C#
mit
257
import Telescope from 'meteor/nova:lib'; import Posts from "meteor/nova:posts"; import Comments from "meteor/nova:comments"; import Users from 'meteor/nova:users'; serveAPI = function(terms){ var posts = []; var parameters = Posts.parameters.get(terms); const postsCursor = Posts.find(parameters.selector, parameters.options); postsCursor.forEach(function(post) { var url = Posts.getLink(post); var postOutput = { title: post.title, headline: post.title, // for backwards compatibility author: post.author, date: post.postedAt, url: url, pageUrl: Posts.getPageUrl(post, true), guid: post._id }; if(post.body) postOutput.body = post.body; if(post.url) postOutput.domain = Telescope.utils.getDomain(url); if (post.thumbnailUrl) { postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl); } var twitterName = Users.getTwitterNameById(post.userId); if(twitterName) postOutput.twitterName = twitterName; var comments = []; Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) { var commentProperties = { body: comment.body, author: comment.author, date: comment.postedAt, guid: comment._id, parentCommentId: comment.parentCommentId }; comments.push(commentProperties); }); var commentsToDelete = []; comments.forEach(function(comment, index) { if (comment.parentCommentId) { var parent = comments.filter(function(obj) { return obj.guid === comment.parentCommentId; })[0]; if (parent) { parent.replies = parent.replies || []; parent.replies.push(JSON.parse(JSON.stringify(comment))); commentsToDelete.push(index); } } }); commentsToDelete.reverse().forEach(function(index) { comments.splice(index,1); }); postOutput.comments = comments; posts.push(postOutput); }); return JSON.stringify(posts); };
trujunzhang/newspoliticl
packages/nova-api/lib/server/api.js
JavaScript
mit
2,059
class ImportResult < ActiveRecord::Base belongs_to :import enum status: [ :starting, :running, :finishing, :finished, :stalled, :aborted ] serialize :found_listing_keys serialize :removed_listing_keys serialize :snapshots def found_count_difference previous_run = self.import.import_results.where(['start_time < ?', self.start_time]).order("start_time DESC").limit(1).first previous_run.present? ? self.found_listing_keys.count - previous_run.found_listing_keys.count : nil end end
arcticleo/reso_data_dictionary
app/models/import_result.rb
Ruby
mit
507
package fr.pizzeria.exception; public class StockageException extends Exception { public StockageException() { super(); } public StockageException(String message, Throwable cause) { super(message, cause); } public StockageException(String message) { super(message); } public StockageException(Throwable cause) { super(cause); } }
lionelcollidor/dta-formation
apps/pizzeria-console-objet/pizzeria-dao/src/main/java/fr/pizzeria/exception/StockageException.java
Java
mit
353
from rest_framework import serializers from django.contrib.auth.models import User from dixit.account.models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('name', ) class UserSerializer(serializers.ModelSerializer): """ Serializes User objects """ profile = UserProfileSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'profile', )
jminuscula/dixit-online
server/src/dixit/api/auth/serializers/user.py
Python
mit
494
# == Schema Information # # Table name: tecnicos # # id :integer not null, primary key # phone_number :string # health_post_id :integer # created_at :datetime not null # updated_at :datetime not null # name :string # class Tecnico < ActiveRecord::Base include SendsMessages belongs_to :health_post has_many :messages validates_uniqueness_of :phone_number end
CUPeru/CUPeru
app/models/tecnico.rb
Ruby
mit
432
using System; using System.Collections.Generic; namespace Paladino.Drawing { /// <summary> /// The thumbnails class handles all thumbnails to different types of content /// embedded in the core. /// </summary> public static class Thumbnails { #region Members private static Dictionary<Guid, string> guidToThumb = null; private static Dictionary<string, string> typeToThumb = null; private static Dictionary<string, Guid> typeToGuid = null; private static object mutex = new object(); #endregion /// <summary> /// Gets whether the current thumbnail collection contains a /// thumbnail for the given mime-type. /// </summary> /// <param name="type">The mime-type</param> /// <returns>Whether the key exists</returns> public static bool ContainsKey(string type) { Ensure(); return typeToThumb.ContainsKey(type); } /// <summary> /// Gets whether the current thumbnail collection contains a /// thumbnail for the given thumbnail id. /// </summary> /// <param name="id">The id</param> /// <returns>Whether the key exists</returns> public static bool ContainsKey(Guid id) { Ensure(); return guidToThumb.ContainsKey(id); } /// <summary> /// Gets the resource path for the thumbnail with the given id. /// </summary> /// <param name="id">The id</param> /// <returns>The resource path</returns> public static string GetById(Guid id) { Ensure(); return guidToThumb[id]; } /// <summary> /// Gets the resource path fo the thumbnail with the given mime-type. /// </summary> /// <param name="type">The mime-type</param> /// <returns>The resource path</returns> public static string GetByType(string type) { Ensure(); if (!String.IsNullOrEmpty(type)) return typeToThumb[type]; return typeToThumb["default"]; } /// <summary> /// Gets the internal thumbnail id for the given mime-type. /// </summary> /// <param name="type">The mime-type</param> /// <returns>The thumbnail id</returns> public static Guid GetIdByType(string type) { Ensure(); if (!String.IsNullOrEmpty(type)) { if (ContainsKey(type)) return typeToGuid[type]; } return Guid.Empty; } #region Private methods /// <summary> /// Ensures that the thumbnail collection is created. /// </summary> private static void Ensure() { if (guidToThumb == null) { lock (mutex) { if (guidToThumb == null) { guidToThumb = new Dictionary<Guid, string>(); typeToThumb = new Dictionary<string, string>(); typeToGuid = new Dictionary<string, Guid>(); // Pdf Add(new Guid("6DC9DF6B-3378-4576-90B5-2E801C6484EA"), "application/pdf", "Piranha.Areas.Manager.Content.Img.ico-pdf-64.png"); // Excel Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-dos_ms_excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png"); // Mp3 Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpegaudio", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); // Wma Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-ms-wma", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); // Flac Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/flac", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); // Ogg Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/ogg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); // M4a Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4a-latm", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png"); // Avi Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/xmpg2", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "application/x-troff-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/aiff", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); // Mpeg Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mpeg", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mp4", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); // Mov Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/mov", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-midi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-wav", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); // Ppt Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd.ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpnt", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd-mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-m", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png"); // Zip Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/octet-stream", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compress", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "multipart/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); // Rar Add(new Guid("F63BBF1C-93F5-4B90-9337-232EBBB65908"), "application/x-rar-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png"); // Folder Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder", "Piranha.Areas.Manager.Content.Img.ico-folder-96.png"); Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder-small", "Piranha.Areas.Manager.Content.Img.ico-folder-32.png"); // Reference Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "youtube.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "vimeo.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png"); Add(Guid.Empty, "reference", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png"); // Default Add(Guid.Empty, "default", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png"); } } } } /// <summary> /// Adds a thumbnail resource with the given id and mime-type. /// </summary> /// <param name="id">The thumbnail id</param> /// <param name="type">The mime-type</param> /// <param name="thumbnail">The resource path</param> private static void Add(Guid id, string type, string thumbnail) { if (!guidToThumb.ContainsKey(id)) guidToThumb.Add(id, thumbnail); if (!typeToThumb.ContainsKey(type)) typeToThumb.Add(type, thumbnail); if (!typeToGuid.ContainsKey(type)) typeToGuid.Add(type, id); } #endregion } }
cnascimento/Paladino
Paladino/Drawing/Thumbnails.cs
C#
mit
13,732
using System.Linq; using UnityEditor; using UnityEditor.Animations; using UnityEngine; namespace Framework.Editor { [CustomActionEditor(typeof(ActionAnimParam))] public class ActionGraphEditorAnimParamNode : ActionGraphEditorNode { public ActionAnimParam Node => (ActionAnimParam) ActionNode; public ActionGraphEditorAnimParamNode(ActionGraph graph, ActionGraphNode node, ActionGraphPresenter presenter) : base(graph, node, presenter) { } private void SetNewParam(AnimatorControllerParameter param) { Undo.RecordObject(Node, "Changed anim param"); Node.AnimParam.Name = param.name; switch (param.type) { case AnimatorControllerParameterType.Trigger: Node.AnimParam = new Variant ( new SerializedType(typeof(bool), ActionAnimParam.TriggerMetadata) ); break; case AnimatorControllerParameterType.Bool: Node.AnimParam = new Variant ( typeof(bool) ); Node.AnimParam.SetAs(param.defaultBool); break; case AnimatorControllerParameterType.Float: Node.AnimParam = new Variant ( typeof(float) ); Node.AnimParam.SetAs(param.defaultFloat); break; case AnimatorControllerParameterType.Int: Node.AnimParam = new Variant ( typeof(int) ); Node.AnimParam.SetAs(param.defaultInt); break; } Node.AnimParam.Name = param.name; } protected override void DrawContent() { if (Node.Anim) { GUI.Box(drawRect, GUIContent.none, EditorStyles.helpBox); var controller = AssetDatabase.LoadAssetAtPath<AnimatorController>(AssetDatabase.GetAssetPath(Node.Anim)); if (controller == null) { Debug.LogErrorFormat("AnimatorController must not be null."); return; } int index = -1; var paramList = controller.parameters.ToList(); var param = paramList.FirstOrDefault(p => p.name == Node.AnimParam.Name); if (param != null) { index = paramList.IndexOf(param); } drawRect.x += ContentMargin; drawRect.width = drawRect.width - ContentMargin * 2; drawRect.height = VariantUtils.FieldHeight; int newIndex = EditorGUI.Popup(drawRect, index, paramList.Select(p => p.name).ToArray()); if (newIndex != index) { SetNewParam(paramList[newIndex]); } if (string.IsNullOrWhiteSpace(Node.AnimParam?.HoldType?.Metadata)) { drawRect.y += drawRect.height; VariantUtils.DrawParameter(drawRect, Node.AnimParam, false); } } else { EditorGUI.HelpBox(drawRect, "AnimController is required!", MessageType.Error); } } } }
MrJaqbq/Unity3DFramework
Editor/ActionGraph/ActionGraphEditorAnimParamNode.cs
C#
mit
3,547
/** * @author Vexatos */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault package vexatos.backpacks.backpack; import mcp.MethodsReturnNonnullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
Vexatos/ForecastersBackpacks
src/main/java/vexatos/backpacks/backpack/package-info.java
Java
mit
225
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as Waste } from '../../entities/Waste'; import { Deferred } from '../../util/utils'; import NavLink from '../../components/NavLink'; import Progress from 'react-progress-2'; import { PageHeader, Row, Col, Panel, Label } from 'react-bootstrap'; import radio from 'backbone.radio'; const router = radio.channel('router'); export default class WasteShowRoute extends Route { breadcrumb({ params }) { const dfd = new Deferred; const waste = new Waste({ fid: params.wfid }); waste.forSubjectParam(params.fid); waste.fetch({ success: m => dfd.resolve(m.get('title')) }); return dfd.promise; } fetch({ params }) { this.companyFid = params.fid; this.waste = new Waste({ fid: params.wfid }); this.waste.forSubjectParam(params.fid).expandParam('subtype'); return this.waste.fetch(); } render() { const waste = this.waste.toJSON(); return ( <div> <Helmet title={waste.title} /> <PageHeader>{waste.title}</PageHeader> <Row> <Col md={12}> <ul className="nav menu-nav-pills"> <li> <NavLink to={`/companies/${this.companyFid}/waste/${waste.fid}/edit`} > <i className="fa fa-pencil-square-o" /> Редактировать </NavLink> </li> <li> <a href="javascript:;" onClick={() => { Progress.show(); this.waste.destroy({ success: () => { Progress.hide(); router.request('navigate', `companies/${this.companyFid}`); }, }); }} > <i className="fa fa-ban" aria-hidden="true" /> Удалить </a> </li> </ul> </Col> </Row> <Row> <Col md={12}> <Panel> <h4><Label>Название</Label>{' '} {waste.title} </h4> <h4><Label>Вид отходов</Label>{' '} <NavLink to={`/waste-types/${waste.subtype.fid}`}>{waste.subtype.title}</NavLink> </h4> <h4><Label>Количество</Label>{' '} {waste.amount} т </h4> </Panel> </Col> </Row> </div> ); } }
ryrudnev/dss-wm
app/routes/waste/ShowRoute.js
JavaScript
mit
2,612
var basePaths = { src: 'public/', dest: 'public.dist/', bower: 'bower_components/' }; var paths = { images: { src: basePaths.src + 'images/', dest: basePaths.dest + 'images/min/' }, scripts: { src: basePaths.src + 'scripts/', dest: basePaths.dest + 'scripts/min/' }, styles: { src: basePaths.src + 'styles/', dest: basePaths.dest + 'styles/min/' }, sprite: { src: basePaths.src + 'sprite/*' } }; var appFiles = { styles: paths.styles.src + '**/*.scss', scripts: [paths.scripts.src + 'scripts.js'] }; var vendorFiles = { styles: '', scripts: '' }; var spriteConfig = { imgName: 'sprite.png', cssName: '_sprite.scss', imgPath: paths.images.dest.replace('public', '') + 'sprite.png' }; // let the magic begin var gulp = require('gulp'); var es = require('event-stream'); var gutil = require('gulp-util'); var autoprefixer = require('gulp-autoprefixer'); var plugins = require("gulp-load-plugins")({ pattern: ['gulp-*', 'gulp.*'], replaceString: /\bgulp[\-.]/ }); // allows gulp --dev to be run for a more verbose output var isProduction = true; var sassStyle = 'compressed'; var sourceMap = false; if (gutil.env.dev === true) { sassStyle = 'expanded'; sourceMap = true; isProduction = false; } var changeEvent = function(evt) { gutil.log('File', gutil.colors.cyan(evt.path.replace(new RegExp('/.*(?=/' + basePaths.src + ')/'), '')), 'was', gutil.colors.magenta(evt.type)); }; gulp.task('css', function() { var sassFiles = gulp.src(appFiles.styles) /* .pipe(plugins.rubySass({ style: sassStyle, sourcemap: sourceMap, precision: 2 })) */ .pipe(plugins.sass()) .on('error', function(err) { new gutil.PluginError('CSS', err, {showStack: true}); }); return es.concat(gulp.src(vendorFiles.styles), sassFiles) .pipe(plugins.concat('style.min.css')) .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox >= 4')) /* .pipe(isProduction ? plugins.combineMediaQueries({ log: true }) : gutil.noop()) */ .pipe(isProduction ? plugins.cssmin() : gutil.noop()) .pipe(plugins.size()) .pipe(gulp.dest(paths.styles.dest)) ; }); gulp.task('scripts', function() { gulp.src(vendorFiles.scripts.concat(appFiles.scripts)) .pipe(plugins.concat('app.js')) .pipe(isProduction ? plugins.uglify() : gutil.noop()) .pipe(plugins.size()) .pipe(gulp.dest(paths.scripts.dest)) ; }); // sprite generator gulp.task('sprite', function() { var spriteData = gulp.src(paths.sprite.src).pipe(plugins.spritesmith({ imgName: spriteConfig.imgName, cssName: spriteConfig.cssName, imgPath: spriteConfig.imgPath, cssOpts: { functions: false }, cssVarMap: function (sprite) { sprite.name = 'sprite-' + sprite.name; } })); spriteData.img.pipe(gulp.dest(paths.images.dest)); spriteData.css.pipe(gulp.dest(paths.styles.src)); }); gulp.task('watch', ['sprite', 'css', 'scripts'], function() { gulp.watch(appFiles.styles, ['css']).on('change', function(evt) { changeEvent(evt); }); gulp.watch(paths.scripts.src + '*.js', ['scripts']).on('change', function(evt) { changeEvent(evt); }); gulp.watch(paths.sprite.src, ['sprite']).on('change', function(evt) { changeEvent(evt); }); }); gulp.task('default', ['css', 'scripts']);
marcolino/escrape2
.old/gulpfile-advanced.js
JavaScript
mit
3,371
/* * Vulkan Example - Implements a separable two-pass fullscreen blur (also known as bloom) * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <vector> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vulkan/vulkan.h> #include "vulkanexamplebase.h" #define VERTEX_BUFFER_BIND_ID 0 #define ENABLE_VALIDATION false // Offscreen frame buffer properties #define FB_DIM 256 #define FB_COLOR_FORMAT VK_FORMAT_R8G8B8A8_UNORM // Vertex layout for this example std::vector<vkMeshLoader::VertexLayout> vertexLayout = { vkMeshLoader::VERTEX_LAYOUT_POSITION, vkMeshLoader::VERTEX_LAYOUT_UV, vkMeshLoader::VERTEX_LAYOUT_COLOR, vkMeshLoader::VERTEX_LAYOUT_NORMAL }; class VulkanExample : public VulkanExampleBase { public: bool bloom = true; struct { vkTools::VulkanTexture cubemap; } textures; struct { vkMeshLoader::MeshBuffer ufo; vkMeshLoader::MeshBuffer ufoGlow; vkMeshLoader::MeshBuffer skyBox; vkMeshLoader::MeshBuffer quad; } meshes; struct { VkPipelineVertexInputStateCreateInfo inputState; std::vector<VkVertexInputBindingDescription> bindingDescriptions; std::vector<VkVertexInputAttributeDescription> attributeDescriptions; } vertices; struct { vkTools::UniformData vsScene; vkTools::UniformData vsFullScreen; vkTools::UniformData vsSkyBox; vkTools::UniformData fsVertBlur; vkTools::UniformData fsHorzBlur; } uniformData; struct UBO { glm::mat4 projection; glm::mat4 model; }; struct UBOBlur { float blurScale = 1.0f; float blurStrength = 1.5f; uint32_t horizontal; }; struct { UBO scene, fullscreen, skyBox; UBOBlur vertBlur, horzBlur; } ubos; struct { VkPipeline blurVert; VkPipeline blurHorz; VkPipeline glowPass; VkPipeline phongPass; VkPipeline skyBox; } pipelines; // Pipeline layout is shared amongst all descriptor sets VkPipelineLayout pipelineLayout; struct { VkDescriptorSet scene; VkDescriptorSet verticalBlur; VkDescriptorSet horizontalBlur; VkDescriptorSet skyBox; } descriptorSets; // Descriptor set layout is shared amongst all descriptor sets VkDescriptorSetLayout descriptorSetLayout; // Framebuffer for offscreen rendering struct FrameBufferAttachment { VkImage image; VkDeviceMemory mem; VkImageView view; }; struct FrameBuffer { VkFramebuffer framebuffer; FrameBufferAttachment color, depth; VkDescriptorImageInfo descriptor; }; struct OffscreenPass { int32_t width, height; VkRenderPass renderPass; VkSampler sampler; VkCommandBuffer commandBuffer = VK_NULL_HANDLE; // Semaphore used to synchronize between offscreen and final scene rendering VkSemaphore semaphore = VK_NULL_HANDLE; std::array<FrameBuffer, 2> framebuffers; } offscreenPass; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { zoom = -10.25f; rotation = { 7.5f, -343.0f, 0.0f }; timerSpeed *= 0.5f; enableTextOverlay = true; title = "Vulkan Example - Bloom"; } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroySampler(device, offscreenPass.sampler, nullptr); // Frame buffer for (auto& framebuffer : offscreenPass.framebuffers) { // Attachments vkDestroyImageView(device, framebuffer.color.view, nullptr); vkDestroyImage(device, framebuffer.color.image, nullptr); vkFreeMemory(device, framebuffer.color.mem, nullptr); vkDestroyImageView(device, framebuffer.depth.view, nullptr); vkDestroyImage(device, framebuffer.depth.image, nullptr); vkFreeMemory(device, framebuffer.depth.mem, nullptr); vkDestroyFramebuffer(device, framebuffer.framebuffer, nullptr); } vkDestroyRenderPass(device, offscreenPass.renderPass, nullptr); vkFreeCommandBuffers(device, cmdPool, 1, &offscreenPass.commandBuffer); vkDestroySemaphore(device, offscreenPass.semaphore, nullptr); vkDestroyPipeline(device, pipelines.blurHorz, nullptr); vkDestroyPipeline(device, pipelines.blurVert, nullptr); vkDestroyPipeline(device, pipelines.phongPass, nullptr); vkDestroyPipeline(device, pipelines.glowPass, nullptr); vkDestroyPipeline(device, pipelines.skyBox, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); // Meshes vkMeshLoader::freeMeshBufferResources(device, &meshes.ufo); vkMeshLoader::freeMeshBufferResources(device, &meshes.ufoGlow); vkMeshLoader::freeMeshBufferResources(device, &meshes.skyBox); vkMeshLoader::freeMeshBufferResources(device, &meshes.quad); // Uniform buffers vkTools::destroyUniformData(device, &uniformData.vsScene); vkTools::destroyUniformData(device, &uniformData.vsFullScreen); vkTools::destroyUniformData(device, &uniformData.vsSkyBox); vkTools::destroyUniformData(device, &uniformData.fsVertBlur); vkTools::destroyUniformData(device, &uniformData.fsHorzBlur); textureLoader->destroyTexture(textures.cubemap); } // Setup the offscreen framebuffer for rendering the mirrored scene // The color attachment of this framebuffer will then be sampled from void prepareOffscreenFramebuffer(FrameBuffer *frameBuf, VkFormat colorFormat, VkFormat depthFormat) { // Color attachment VkImageCreateInfo image = vkTools::initializers::imageCreateInfo(); image.imageType = VK_IMAGE_TYPE_2D; image.format = colorFormat; image.extent.width = FB_DIM; image.extent.height = FB_DIM; image.extent.depth = 1; image.mipLevels = 1; image.arrayLayers = 1; image.samples = VK_SAMPLE_COUNT_1_BIT; image.tiling = VK_IMAGE_TILING_OPTIMAL; // We will sample directly from the color attachment image.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; VkImageViewCreateInfo colorImageView = vkTools::initializers::imageViewCreateInfo(); colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; colorImageView.format = colorFormat; colorImageView.flags = 0; colorImageView.subresourceRange = {}; colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorImageView.subresourceRange.baseMipLevel = 0; colorImageView.subresourceRange.levelCount = 1; colorImageView.subresourceRange.baseArrayLayer = 0; colorImageView.subresourceRange.layerCount = 1; VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->color.image)); vkGetImageMemoryRequirements(device, frameBuf->color.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->color.mem)); VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->color.image, frameBuf->color.mem, 0)); colorImageView.image = frameBuf->color.image; VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &frameBuf->color.view)); // Depth stencil attachment image.format = depthFormat; image.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; VkImageViewCreateInfo depthStencilView = vkTools::initializers::imageViewCreateInfo(); depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D; depthStencilView.format = depthFormat; depthStencilView.flags = 0; depthStencilView.subresourceRange = {}; depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; depthStencilView.subresourceRange.baseMipLevel = 0; depthStencilView.subresourceRange.levelCount = 1; depthStencilView.subresourceRange.baseArrayLayer = 0; depthStencilView.subresourceRange.layerCount = 1; VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &frameBuf->depth.image)); vkGetImageMemoryRequirements(device, frameBuf->depth.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &frameBuf->depth.mem)); VK_CHECK_RESULT(vkBindImageMemory(device, frameBuf->depth.image, frameBuf->depth.mem, 0)); depthStencilView.image = frameBuf->depth.image; VK_CHECK_RESULT(vkCreateImageView(device, &depthStencilView, nullptr, &frameBuf->depth.view)); VkImageView attachments[2]; attachments[0] = frameBuf->color.view; attachments[1] = frameBuf->depth.view; VkFramebufferCreateInfo fbufCreateInfo = vkTools::initializers::framebufferCreateInfo(); fbufCreateInfo.renderPass = offscreenPass.renderPass; fbufCreateInfo.attachmentCount = 2; fbufCreateInfo.pAttachments = attachments; fbufCreateInfo.width = FB_DIM; fbufCreateInfo.height = FB_DIM; fbufCreateInfo.layers = 1; VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &frameBuf->framebuffer)); // Fill a descriptor for later use in a descriptor set frameBuf->descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; frameBuf->descriptor.imageView = frameBuf->color.view; frameBuf->descriptor.sampler = offscreenPass.sampler; } // Prepare the offscreen framebuffers used for the vertical- and horizontal blur void prepareOffscreen() { offscreenPass.width = FB_DIM; offscreenPass.height = FB_DIM; // Find a suitable depth format VkFormat fbDepthFormat; VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &fbDepthFormat); assert(validDepthFormat); // Create a separate render pass for the offscreen rendering as it may differ from the one used for scene rendering std::array<VkAttachmentDescription, 2> attchmentDescriptions = {}; // Color attachment attchmentDescriptions[0].format = FB_COLOR_FORMAT; attchmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT; attchmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attchmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attchmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attchmentDescriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attchmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attchmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // Depth attachment attchmentDescriptions[1].format = fbDepthFormat; attchmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT; attchmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attchmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attchmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attchmentDescriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attchmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attchmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkAttachmentReference depthReference = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; subpassDescription.pDepthStencilAttachment = &depthReference; // Use subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Create the actual renderpass VkRenderPassCreateInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = static_cast<uint32_t>(attchmentDescriptions.size()); renderPassInfo.pAttachments = attchmentDescriptions.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpassDescription; renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassInfo, nullptr, &offscreenPass.renderPass)); // Create sampler to sample from the color attachments VkSamplerCreateInfo sampler = vkTools::initializers::samplerCreateInfo(); sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; sampler.addressModeV = sampler.addressModeU; sampler.addressModeW = sampler.addressModeU; sampler.mipLodBias = 0.0f; sampler.maxAnisotropy = 0; sampler.minLod = 0.0f; sampler.maxLod = 1.0f; sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &offscreenPass.sampler)); // Create two frame buffers prepareOffscreenFramebuffer(&offscreenPass.framebuffers[0], FB_COLOR_FORMAT, fbDepthFormat); prepareOffscreenFramebuffer(&offscreenPass.framebuffers[1], FB_COLOR_FORMAT, fbDepthFormat); } // Sets up the command buffer that renders the scene to the offscreen frame buffer // The blur method used in this example is multi pass and renders the vertical // blur first and then the horizontal one. // While it's possible to blur in one pass, this method is widely used as it // requires far less samples to generate the blur void buildOffscreenCommandBuffer() { if (offscreenPass.commandBuffer == VK_NULL_HANDLE) { offscreenPass.commandBuffer = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false); } if (offscreenPass.semaphore == VK_NULL_HANDLE) { VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo(); VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &offscreenPass.semaphore)); } VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); // First pass: Render glow parts of the model (separate mesh) // ------------------------------------------------------------------------------------------------------- VkClearValue clearValues[2]; clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } }; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = offscreenPass.renderPass; renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[0].framebuffer; renderPassBeginInfo.renderArea.extent.width = offscreenPass.width; renderPassBeginInfo.renderArea.extent.height = offscreenPass.height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; VK_CHECK_RESULT(vkBeginCommandBuffer(offscreenPass.commandBuffer, &cmdBufInfo)); VkViewport viewport = vkTools::initializers::viewport((float)offscreenPass.width, (float)offscreenPass.height, 0.0f, 1.0f); vkCmdSetViewport(offscreenPass.commandBuffer, 0, 1, &viewport); VkRect2D scissor = vkTools::initializers::rect2D(offscreenPass.width, offscreenPass.height, 0, 0); vkCmdSetScissor(offscreenPass.commandBuffer, 0, 1, &scissor); vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL); vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.glowPass); VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.ufoGlow.vertices.buf, offsets); vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.ufoGlow.indices.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.ufoGlow.indexCount, 1, 0, 0, 0); vkCmdEndRenderPass(offscreenPass.commandBuffer); // Second pass: Render contents of the first pass into second framebuffer and apply a vertical blur // This is the first blur pass, the horizontal blur is applied when rendering on top of the scene // ------------------------------------------------------------------------------------------------------- renderPassBeginInfo.framebuffer = offscreenPass.framebuffers[1].framebuffer; vkCmdBeginRenderPass(offscreenPass.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // Draw horizontally blurred texture vkCmdBindDescriptorSets(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.verticalBlur, 0, NULL); vkCmdBindPipeline(offscreenPass.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurVert); vkCmdBindVertexBuffers(offscreenPass.commandBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets); vkCmdBindIndexBuffer(offscreenPass.commandBuffer, meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(offscreenPass.commandBuffer, meshes.quad.indexCount, 1, 0, 0, 0); vkCmdEndRenderPass(offscreenPass.commandBuffer); VK_CHECK_RESULT(vkEndCommandBuffer(offscreenPass.commandBuffer)); } void reBuildCommandBuffers() { if (!checkCommandBuffers()) { destroyCommandBuffers(); createCommandBuffers(); } buildCommandBuffers(); } void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vkTools::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor = vkTools::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); VkDeviceSize offsets[1] = { 0 }; // Skybox vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.skyBox, 0, NULL); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skyBox); vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.skyBox.vertices.buf, offsets); vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.skyBox.indices.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(drawCmdBuffers[i], meshes.skyBox.indexCount, 1, 0, 0, 0); // 3D scene vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.scene, 0, NULL); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.phongPass); vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.ufo.vertices.buf, offsets); vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.ufo.indices.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(drawCmdBuffers[i], meshes.ufo.indexCount, 1, 0, 0, 0); // Render vertical blurred scene applying a horizontal blur // Render the (vertically blurred) contents of the second framebuffer and apply a horizontal blur // ------------------------------------------------------------------------------------------------------- if (bloom) { vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets.horizontalBlur, 0, NULL); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.blurHorz); vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.quad.vertices.buf, offsets); vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.quad.indices.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(drawCmdBuffers[i], meshes.quad.indexCount, 1, 0, 0, 0); } vkCmdEndRenderPass(drawCmdBuffers[i]); VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); } if (bloom) { buildOffscreenCommandBuffer(); } } void loadAssets() { loadMesh(getAssetPath() + "models/retroufo.dae", &meshes.ufo, vertexLayout, 0.05f); loadMesh(getAssetPath() + "models/retroufo_glow.dae", &meshes.ufoGlow, vertexLayout, 0.05f); loadMesh(getAssetPath() + "models/cube.obj", &meshes.skyBox, vertexLayout, 1.0f); textureLoader->loadCubemap(getAssetPath() + "textures/cubemap_space.ktx", VK_FORMAT_R8G8B8A8_UNORM, &textures.cubemap); } // Setup vertices for a single uv-mapped quad void generateQuad() { struct Vertex { float pos[3]; float uv[2]; float col[3]; float normal[3]; }; #define QUAD_COLOR_NORMAL { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } std::vector<Vertex> vertexBuffer = { { { 1.0f, 1.0f, 0.0f },{ 1.0f, 1.0f }, QUAD_COLOR_NORMAL }, { { 0.0f, 1.0f, 0.0f },{ 0.0f, 1.0f }, QUAD_COLOR_NORMAL }, { { 0.0f, 0.0f, 0.0f },{ 0.0f, 0.0f }, QUAD_COLOR_NORMAL }, { { 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f }, QUAD_COLOR_NORMAL } }; #undef QUAD_COLOR_NORMAL createBuffer( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexBuffer.size() * sizeof(Vertex), vertexBuffer.data(), &meshes.quad.vertices.buf, &meshes.quad.vertices.mem); // Setup indices std::vector<uint32_t> indexBuffer = { 0,1,2, 2,3,0 }; meshes.quad.indexCount = indexBuffer.size(); createBuffer( VK_BUFFER_USAGE_INDEX_BUFFER_BIT, indexBuffer.size() * sizeof(uint32_t), indexBuffer.data(), &meshes.quad.indices.buf, &meshes.quad.indices.mem); } void setupVertexDescriptions() { // Binding description // Same for all meshes used in this example vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0] = vkTools::initializers::vertexInputBindingDescription( VERTEX_BUFFER_BIND_ID, vkMeshLoader::vertexSize(vertexLayout), VK_VERTEX_INPUT_RATE_VERTEX); // Attribute descriptions vertices.attributeDescriptions.resize(4); // Location 0 : Position vertices.attributeDescriptions[0] = vkTools::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, 0); // Location 1 : Texture coordinates vertices.attributeDescriptions[1] = vkTools::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3); // Location 2 : Color vertices.attributeDescriptions[2] = vkTools::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 5); // Location 3 : Normal vertices.attributeDescriptions[3] = vkTools::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8); vertices.inputState = vkTools::initializers::pipelineVertexInputStateCreateInfo(); vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { std::vector<VkDescriptorPoolSize> poolSizes = { vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 8), vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6) }; VkDescriptorPoolCreateInfo descriptorPoolInfo = vkTools::initializers::descriptorPoolCreateInfo( poolSizes.size(), poolSizes.data(), 5); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); } void setupDescriptorSetLayout() { // Textured quad pipeline layout std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vkTools::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 1 : Fragment shader image sampler vkTools::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // Binding 2 : Framgnet shader image sampler vkTools::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vkTools::initializers::descriptorSetLayoutCreateInfo( setLayoutBindings.data(), setLayoutBindings.size()); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vkTools::initializers::pipelineLayoutCreateInfo( &descriptorSetLayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); } void setupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo = vkTools::initializers::descriptorSetAllocateInfo( descriptorPool, &descriptorSetLayout, 1); std::vector<VkWriteDescriptorSet> writeDescriptorSets; // Full screen blur descriptor sets // Vertical blur VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.verticalBlur)); writeDescriptorSets = { // Binding 0: Vertex shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor), // Binding 1: Fragment shader texture sampler vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[0].descriptor), // Binding 2: Fragment shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.verticalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsVertBlur.descriptor) }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); // Horizontal blur VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.horizontalBlur)); writeDescriptorSets = { // Binding 0: Vertex shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsScene.descriptor), // Binding 1: Fragment shader texture sampler vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &offscreenPass.framebuffers[1].descriptor), // Binding 2: Fragment shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.horizontalBlur, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformData.fsHorzBlur.descriptor) }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); // 3D scene VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.scene)); writeDescriptorSets = { // Binding 0: Vertex shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.scene, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsFullScreen.descriptor) }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); // Skybox VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skyBox)); writeDescriptorSets = { // Binding 0: Vertex shader uniform buffer vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.vsSkyBox.descriptor), // Binding 1: Fragment shader texture sampler vkTools::initializers::writeDescriptorSet(descriptorSets.skyBox, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.cubemap.descriptor), }; vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; // Vertical gauss blur // Load shaders shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/gaussblur.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); // Additive blending blendAttachmentState.colorWriteMask = 0xF; blendAttachmentState.blendEnable = VK_TRUE; blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA; pipelineCreateInfo.renderPass = offscreenPass.renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurVert)); pipelineCreateInfo.renderPass = renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.blurHorz)); // Phong pass (3D model) shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/phongpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/phongpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); blendAttachmentState.blendEnable = VK_FALSE; depthStencilState.depthWriteEnable = VK_TRUE; rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT; pipelineCreateInfo.renderPass = renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.phongPass)); // Color only pass (offscreen blur base) shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/colorpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/colorpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); pipelineCreateInfo.renderPass = offscreenPass.renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.glowPass)); // Skybox (cubemap) shaderStages[0] = loadShader(getAssetPath() + "shaders/bloom/skybox.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/bloom/skybox.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); depthStencilState.depthWriteEnable = VK_FALSE; rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT; pipelineCreateInfo.renderPass = renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skyBox)); } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Phong and color pass vertex shader uniform buffer createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ubos.scene), &ubos.scene, &uniformData.vsScene.buffer, &uniformData.vsScene.memory, &uniformData.vsScene.descriptor); // Fullscreen quad display vertex shader uniform buffer createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ubos.fullscreen), &ubos.fullscreen, &uniformData.vsFullScreen.buffer, &uniformData.vsFullScreen.memory, &uniformData.vsFullScreen.descriptor); // Fullscreen quad fragment shader uniform buffers // Vertical blur createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ubos.vertBlur), &ubos.vertBlur, &uniformData.fsVertBlur.buffer, &uniformData.fsVertBlur.memory, &uniformData.fsVertBlur.descriptor); // Horizontal blur createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ubos.horzBlur), &ubos.horzBlur, &uniformData.fsHorzBlur.buffer, &uniformData.fsHorzBlur.memory, &uniformData.fsHorzBlur.descriptor); // Skybox createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ubos.skyBox), &ubos.skyBox, &uniformData.vsSkyBox.buffer, &uniformData.vsSkyBox.memory, &uniformData.vsSkyBox.descriptor); // Intialize uniform buffers updateUniformBuffersScene(); updateUniformBuffersScreen(); } // Update uniform buffers for rendering the 3D scene void updateUniformBuffersScene() { // UFO ubos.fullscreen.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f); glm::mat4 viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, -1.0f, zoom)); ubos.fullscreen.model = viewMatrix * glm::translate(glm::mat4(), glm::vec3(sin(glm::radians(timer * 360.0f)) * 0.25f, 0.0f, cos(glm::radians(timer * 360.0f)) * 0.25f) + cameraPos); ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, -sinf(glm::radians(timer * 360.0f)) * 0.15f, glm::vec3(1.0f, 0.0f, 0.0f)); ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(timer * 360.0f), glm::vec3(0.0f, 1.0f, 0.0f)); ubos.fullscreen.model = glm::rotate(ubos.fullscreen.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); uint8_t *pData; VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsFullScreen.memory, 0, sizeof(ubos.fullscreen), 0, (void **)&pData)); memcpy(pData, &ubos.fullscreen, sizeof(ubos.fullscreen)); vkUnmapMemory(device, uniformData.vsFullScreen.memory); // Skybox ubos.skyBox.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f); ubos.skyBox.model = glm::mat4(); ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); ubos.skyBox.model = glm::rotate(ubos.skyBox.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsSkyBox.memory, 0, sizeof(ubos.skyBox), 0, (void **)&pData)); memcpy(pData, &ubos.skyBox, sizeof(ubos.skyBox)); vkUnmapMemory(device, uniformData.vsSkyBox.memory); } // Update uniform buffers for the fullscreen quad void updateUniformBuffersScreen() { // Vertex shader ubos.scene.projection = glm::ortho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f); ubos.scene.model = glm::mat4(); uint8_t *pData; VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsScene.memory, 0, sizeof(ubos.scene), 0, (void **)&pData)); memcpy(pData, &ubos.scene, sizeof(ubos.scene)); vkUnmapMemory(device, uniformData.vsScene.memory); // Fragment shader // Vertical ubos.vertBlur.horizontal = 0; VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsVertBlur.memory, 0, sizeof(ubos.vertBlur), 0, (void **)&pData)); memcpy(pData, &ubos.vertBlur, sizeof(ubos.vertBlur)); vkUnmapMemory(device, uniformData.fsVertBlur.memory); // Horizontal ubos.horzBlur.horizontal = 1; VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsHorzBlur.memory, 0, sizeof(ubos.horzBlur), 0, (void **)&pData)); memcpy(pData, &ubos.horzBlur, sizeof(ubos.horzBlur)); vkUnmapMemory(device, uniformData.fsHorzBlur.memory); } void draw() { VulkanExampleBase::prepareFrame(); // The scene render command buffer has to wait for the offscreen rendering to be finished before we can use the framebuffer // color image for sampling during final rendering // To ensure this we use a dedicated offscreen synchronization semaphore that will be signaled when offscreen rendering has been finished // This is necessary as an implementation may start both command buffers at the same time, there is no guarantee // that command buffers will be executed in the order they have been submitted by the application // Offscreen rendering // Wait for swap chain presentation to finish submitInfo.pWaitSemaphores = &semaphores.presentComplete; // Signal ready with offscreen semaphore submitInfo.pSignalSemaphores = &offscreenPass.semaphore; // Submit work submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &offscreenPass.commandBuffer; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); // Scene rendering // Wait for offscreen semaphore submitInfo.pWaitSemaphores = &offscreenPass.semaphore; // Signal ready with render complete semaphpre submitInfo.pSignalSemaphores = &semaphores.renderComplete; // Submit work submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VulkanExampleBase::submitFrame(); } void prepare() { VulkanExampleBase::prepare(); loadAssets(); generateQuad(); setupVertexDescriptions(); prepareUniformBuffers(); prepareOffscreen(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); if (!paused) { updateUniformBuffersScene(); } } virtual void viewChanged() { updateUniformBuffersScene(); updateUniformBuffersScreen(); } virtual void keyPressed(uint32_t keyCode) { switch (keyCode) { case KEY_KPADD: case GAMEPAD_BUTTON_R1: changeBlurScale(0.25f); break; case KEY_KPSUB: case GAMEPAD_BUTTON_L1: changeBlurScale(-0.25f); break; case KEY_B: case GAMEPAD_BUTTON_A: toggleBloom(); break; } } virtual void getOverlayText(VulkanTextOverlay *textOverlay) { #if defined(__ANDROID__) textOverlay->addText("Press \"L1/R1\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft); textOverlay->addText("Press \"Button A\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft); #else textOverlay->addText("Press \"NUMPAD +/-\" to change blur scale", 5.0f, 85.0f, VulkanTextOverlay::alignLeft); textOverlay->addText("Press \"B\" to toggle bloom", 5.0f, 105.0f, VulkanTextOverlay::alignLeft); #endif } void changeBlurScale(float delta) { ubos.vertBlur.blurScale += delta; ubos.horzBlur.blurScale += delta; updateUniformBuffersScreen(); } void toggleBloom() { bloom = !bloom; reBuildCommandBuffers(); } }; VULKAN_EXAMPLE_MAIN()
martty/Vulkan
bloom/bloom.cpp
C++
mit
42,639
package mcjty.deepresonance.jei.smelter; import mezz.jei.api.recipe.IRecipeWrapper; import javax.annotation.Nonnull; public class SmelterRecipeHandler implements mezz.jei.api.recipe.IRecipeHandler<SmelterRecipeWrapper> { private final String id; public SmelterRecipeHandler() { this.id = SmelterRecipeCategory.ID; } @Nonnull @Override public Class<SmelterRecipeWrapper> getRecipeClass() { return SmelterRecipeWrapper.class; } @Nonnull @Override public IRecipeWrapper getRecipeWrapper(@Nonnull SmelterRecipeWrapper recipe) { return recipe; } @Override public String getRecipeCategoryUid(SmelterRecipeWrapper recipe) { return id; } @Override public boolean isRecipeValid(SmelterRecipeWrapper recipe) { return true; } }
McJty/DeepResonance
src/main/java/mcjty/deepresonance/jei/smelter/SmelterRecipeHandler.java
Java
mit
834
var g_batchAssessmentEditor = null; var g_tabAssessments = null; var g_updatingAttendance = false; var g_onRefresh = null; var g_lockedCount = 0; var g_btnSubmit = null; var g_sectionAssessmentEditors = null; var g_sectionAssessmentButtons = null; function createAssessment(content, to) { var assessmentJson = {}; assessmentJson["content"] = content; assessmentJson["to"] = to; return new Assessment(assessmentJson); } function SingleAssessmentEditor(){ this.participantId = 0; this.name = ""; this.content = ""; this.lock = null; } function BatchAssessmentEditor(){ this.switchAttendance = null; this.selectAll = null; this.editors = null; } function generateAssessmentEditor(par, participant, activity, batchEditor){ var singleEditor = new SingleAssessmentEditor(); var row = $('<div>', { "class": "assessment-input-row" }).appendTo(par); var avatar = $("<img>", { src: participant.avatar, "class": "assessment-avatar" }).click(function(evt) { evt.preventDefault(); window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString()); }).appendTo(row); var name = $('<a>', { href: "#", text: participant.name }).appendTo(row); name.click(function(evt) { evt.preventDefault(); window.location.hash = ("profile?" + g_keyVieweeId + "=" + participant.id.toString()); }); singleEditor.participantId = participant.id; singleEditor.name = participant.name; if ( activity.containsRelation() && ((activity.relation & assessed) == 0) ) generateUnassessedView(row, singleEditor, batchEditor); else generateAssessedView(row, participant, activity); if(g_loggedInUser != null && g_loggedInUser.id == participant.id) row.hide(); return singleEditor; } function generateAssessmentEditors(par, activity, batchEditor) { par.empty(); var participants = activity.selectedParticipants; var editors = new Array(); for(var i = 0; i < participants.length; i++){ var editor = generateAssessmentEditor(par, participants[i], activity, batchEditor); editors.push(editor); } return editors; } function generateAssessmentButtons(par, activity, batchEditor){ par.empty(); if(batchEditor.editors == null || batchEditor.editors.length <= 1) return; var row = $('<div>', { "class": "assessment-button" }).appendTo(par); var btnCheckAll = $("<button>", { text: TITLES["check_all"], "class": "gray assessment-button" }).appendTo(row); btnCheckAll.click(batchEditor, function(evt){ evt.preventDefault(); for(var i = 0; i < evt.data.editors.length; i++) { var editor = evt.data.editors[i]; editor.lock.prop("checked", true).change(); } }); var btnUncheckAll = $("<button>", { text: TITLES["uncheck_all"], "class": "gray assessment-button" }).appendTo(row); btnUncheckAll.click(batchEditor, function(evt){ evt.preventDefault(); for(var i = 0; i < evt.data.editors.length; i++) { var editor = evt.data.editors[i]; editor.lock.prop("checked", false).change(); } }); g_btnSubmit = $("<button>", { text: TITLES["submit"], "class": "assessment-button positive-button" }).appendTo(row); g_btnSubmit.click({editor: batchEditor, activity: activity}, function(evt){ evt.preventDefault(); if (g_loggedInUser == null) return; var aBatchEditor = evt.data.editor; var aActivity = evt.data.activity; var assessments = new Array(); for(var i = 0; i < aBatchEditor.editors.length; i++) { var editor = aBatchEditor.editors[i]; var content = editor.content; var to = editor.participantId; if(to == g_loggedInUser.id) continue; var assessment = createAssessment(content, to); assessments.push(assessment); } if (assessments.length == 0) return; var params = {}; var token = $.cookie(g_keyToken); params[g_keyToken] = token; params[g_keyActivityId] = aActivity.id; params[g_keyBundle] = JSON.stringify(assessments); var aButton = $(this); disableField(aButton); $.ajax({ type: "POST", url: "/assessment/submit", data: params, success: function(data, status, xhr){ enableField(aButton); if (isTokenExpired(data)) { logout(null); return; } alert(ALERTS["assessment_submitted"]); aActivity.relation |= assessed; refreshBatchEditor(aActivity); }, error: function(xhr, status, err){ enableField(aButton); alert(ALERTS["assessment_not_submitted"]); } }); }).appendTo(row); disableField(g_btnSubmit); } function generateBatchAssessmentEditor(par, activity, onRefresh){ par.empty(); if(g_onRefresh == null) g_onRefresh = onRefresh; g_lockedCount = 0; // clear lock count on batch editor generated g_batchAssessmentEditor = new BatchAssessmentEditor(); if(activity == null) return g_batchAssessmentEditor; var editors = []; var sectionAll = $('<div>', { "class": "assessment-container" }).appendTo(par); var initVal = false; var disabled = false; // Determine attendance switch initial state based on viewer-activity-relation if (g_loggedInUser != null && activity.host.id == g_loggedInUser.id) { // host cannot choose presence initVal = true; disabled = true; } else if((activity.relation & present) > 0) { // present participants initVal = true; } else if((activity.relation & selected) > 0 || (activity.relation & absent) > 0) { // selected but not present initVal = false; } else { disabled = true; } var attendanceSwitch = createBinarySwitch(sectionAll, disabled, initVal, TITLES["assessment_disabled"], TITLES["present"], TITLES["absent"], "switch-attendance"); g_sectionAssessmentEditors = $('<div>', { style: "margin-top: 5pt" }).appendTo(sectionAll); g_sectionAssessmentButtons = $('<div>', { style: "margin-top: 5pt" }).appendTo(sectionAll); if( g_loggedInUser != null && ( ((activity.relation & present) > 0) || (activity.containsRelation() == false) ) ) { /* * show list for logged-in users */ refreshBatchEditor(activity); } var onSuccess = function(data){ g_updatingAttendance = false; // update activity.relation by returned value var relationJson = data; activity.relation = parseInt(relationJson[g_keyRelation]); g_sectionAssessmentEditors.empty(); g_sectionAssessmentButtons.empty(); var value = getBinarySwitchState(attendanceSwitch); if(!value) return; // assessed participants cannot edit or re-submit assessments refreshBatchEditor(activity); }; var onError = function(err){ g_updatingAttendance = false; // reset switch status if updating attendance fails var value = getBinarySwitchState(attendanceSwitch); var resetVal = !value; setBinarySwitch(attendanceSwitch, resetVal); }; var onClick = function(evt){ evt.preventDefault(); if(activity.relation == invalid) return; if(!activity.hasBegun()) { alert(ALERTS["activity_not_begun"]); return; } var value = getBinarySwitchState(attendanceSwitch); var newVal = !value; setBinarySwitch(attendanceSwitch, newVal); attendance = activity.relation; if(newVal) attendance = present; else attendance = absent; updateAttendance(activity.id, attendance, onSuccess, onError); }; setBinarySwitchOnClick(attendanceSwitch, onClick); return g_batchAssessmentEditor; } function updateAttendance(activityId, attendance, onSuccess, onError){ // prototypes: onSuccess(data), onError(err) if(g_updatingAttendance) return; var token = $.cookie(g_keyToken); if(token == null) return; var params={}; params[g_keyRelation] = attendance; params[g_keyToken] = token; params[g_keyActivityId] = activityId; g_updatingAttendance = true; $.ajax({ type: "PUT", url: "/activity/mark", data: params, success: function(data, status, xhr) { if (isTokenExpired(data)) { logout(null); return; } onSuccess(data); }, error: function(xhr, status, err) { onError(err); } }); } function generateAssessedView(row, participant, activity) { var btnView = $('<span>', { text: TITLES["view_assessment"], style: "display: inline; color: blue; margin-left: 5pt; cursor: pointer" }).appendTo(row); btnView.click(function(evt){ evt.preventDefault(); queryAssessmentsAndRefresh(participant.id, activity.id); }); } function generateUnassessedView(row, singleEditor, batchEditor) { var lock = $('<input>', { type: "checkbox", "class": "left" }).appendTo(row); var contentInput = $('<input>', { type: 'text' }).appendTo(row); contentInput.on("input paste keyup", singleEditor, function(evt){ evt.data.content = $(this).val(); }); lock.change({input: contentInput, editor: batchEditor}, function(evt){ var aInput = evt.data.input; var aBatchEditor = evt.data.editor; evt.preventDefault(); var checked = isChecked($(this)); if(!checked) { enableField(aInput); --g_lockedCount; if(g_btnSubmit != null) disableField(g_btnSubmit); } else { disableField(aInput); ++g_lockedCount; if(g_lockedCount >= (aBatchEditor.editors.length - 1) && g_btnSubmit != null) enableField(g_btnSubmit); } }); singleEditor.lock = lock; } function refreshBatchEditor(activity) { if (!activity.hasBegun()) return; if(g_batchAssessmentEditor == null || g_sectionAssessmentEditors == null || g_sectionAssessmentButtons == null) return; var editors = generateAssessmentEditors(g_sectionAssessmentEditors, activity, g_batchAssessmentEditor); g_batchAssessmentEditor.editors = editors; g_sectionAssessmentButtons.empty(); if(!activity.containsRelation() || (activity.containsRelation() && (activity.relation & assessed) > 0) || g_batchAssessmentEditor.editors.length <= 1) return; generateAssessmentButtons(g_sectionAssessmentButtons, activity, g_batchAssessmentEditor); }
duanp0128/PlayHongKongResort
public/javascripts/assessment/editor.js
JavaScript
mit
9,652
package edu.purdue.eaps.weatherpipe; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.lang.System; import java.lang.Runtime; import org.apache.commons.io.FileUtils; import org.apache.log4j.PropertyConfigurator; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressListener; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce; import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduceClient; import com.amazonaws.services.elasticmapreduce.model.Cluster; import com.amazonaws.services.elasticmapreduce.model.DescribeClusterRequest; import com.amazonaws.services.elasticmapreduce.model.DescribeClusterResult; import com.amazonaws.services.elasticmapreduce.model.HadoopJarStepConfig; import com.amazonaws.services.elasticmapreduce.model.JobFlowInstancesConfig; import com.amazonaws.services.elasticmapreduce.model.RunJobFlowRequest; import com.amazonaws.services.elasticmapreduce.model.RunJobFlowResult; import com.amazonaws.services.elasticmapreduce.model.StepConfig; import com.amazonaws.services.elasticmapreduce.model.TerminateJobFlowsRequest; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.HeadBucketRequest; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.MultipleFileDownload; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.Upload; public class AWSInterface extends MapReduceInterface { private String jobBucketNamePrefix = "weatherpipe"; private AmazonElasticMapReduce emrClient; private AmazonS3 s3client; private TransferManager transMan; private Region region; private String jobSetupDirName; private String jobLogDirName; //private String defaultInstance = "c3.xlarge"; private String jobBucketName; private String jobID; private int bytesTransfered = 0; public AWSInterface(String job, String bucket){ String weatherPipeBinaryPath = WeatherPipe.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String log4jConfPath = weatherPipeBinaryPath.substring(0, weatherPipeBinaryPath.lastIndexOf("/")) + "/log4j.properties"; PropertyConfigurator.configure(log4jConfPath); jobBucketName = bucket; AwsBootstrap(job); } private void AwsBootstrap(String job) { AWSCredentials credentials; ClientConfiguration conf; String userID; MessageDigest md = null; byte[] shaHash; StringBuffer hexSha; DateFormat df; TimeZone tz; String isoDate; File jobDir; File jobSetupDir; File jobLogDir; int i; conf = new ClientConfiguration(); // 2 minute timeout conf.setConnectionTimeout(120000); credentials = new ProfileCredentialsProvider("default").getCredentials(); // TODO: add better credential searching later region = Region.getRegion(Regions.US_EAST_1); s3client = new AmazonS3Client(credentials, conf); s3client.setRegion(region); transMan = new TransferManager(s3client); emrClient = new AmazonElasticMapReduceClient(credentials, conf); emrClient.setRegion(region); if(jobBucketName == null) { userID = new AmazonIdentityManagementClient(credentials).getUser().getUser().getUserId(); try { md = MessageDigest.getInstance("SHA-256"); md.update(userID.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } shaHash = md.digest(); hexSha = new StringBuffer(); for(byte b : shaHash) { hexSha.append(String.format("%02X", b)); } jobBucketName = jobBucketNamePrefix + "." + hexSha; if(jobBucketName.length() > 63) { jobBucketName = jobBucketName.substring(0,62); } } jobBucketName = jobBucketName.toLowerCase(); if(job == null) { tz = TimeZone.getTimeZone("UTC"); df = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm"); df.setTimeZone(tz); isoDate = df.format(new Date()); jobID = isoDate + "." + Calendar.getInstance().get(Calendar.MILLISECOND); // UUID Code if date isn't good // jobID = UUID.randomUUID().toString(); } else { jobID = job; } jobDirName = "WeatherPipeJob" + jobID; jobDir = new File(jobDirName); i = 0; while(jobDir.exists()) { i++; jobDirName = jobDirName + "-" + i; jobDir = new File(jobDirName); } jobDir.mkdir(); jobSetupDirName = jobDirName + "/" + "job_setup"; jobSetupDir = new File(jobSetupDirName); jobSetupDir.mkdir(); jobLogDirName = jobDirName + "/" + "logs"; jobLogDir = new File(jobLogDirName); jobLogDir.mkdir(); } private void UploadFileToS3(String jobBucketName, String key, File file) { Upload upload; PutObjectRequest request; request = new PutObjectRequest( jobBucketName, key, file); bytesTransfered = 0; // Subscribe to the event and provide event handler. request.setGeneralProgressListener(new ProgressListener() { @Override public void progressChanged(ProgressEvent progressEvent) { bytesTransfered += progressEvent.getBytesTransferred(); } }); System.out.println(); upload = transMan.upload(request); while(!upload.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException e) { continue; } System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + file.length()/1024 + "K"); } // If we got an error the count could be off System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K"); System.out.println(); System.out.println("Transfer Complete"); } public String FindOrCreateWeatherPipeJobDirectory() { String bucketLocation = null; try { if(!(s3client.doesBucketExist(jobBucketName))) { // Note that CreateBucketRequest does not specify region. So bucket is // created in the region specified in the client. s3client.createBucket(new CreateBucketRequest( jobBucketName)); } else { s3client.headBucket(new HeadBucketRequest(jobBucketName)); } bucketLocation = "s3n://" + jobBucketName + "/"; } catch (AmazonServiceException ase) { if(ase.getStatusCode() == 403) { System.out.println("You do not have propper permissions to access " + jobBucketName + ". S3 uses a global name space, please make sure you are using a unique bucket name."); System.exit(1); } else { System.out.println("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } System.exit(1); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); System.exit(1); } return bucketLocation; } public String UploadInputFileList(ArrayList<String> fileList, String dataDirName) { String key = jobID + "_input"; String uploadFileString = ""; PrintWriter inputFile = null; File file = new File(jobSetupDirName + "/" + key); for (String s : fileList) uploadFileString += dataDirName + " " + s + "\n"; try { inputFile = new PrintWriter(file); inputFile.print(uploadFileString); inputFile.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } UploadFileToS3(jobBucketName, key, file); return "s3n://" + jobBucketName + "/" + key; } public String UploadMPJarFile(String fileLocation) { String key = jobID + "WeatherPipeMapreduce.jar"; File jarFile = new File(fileLocation); UploadFileToS3(jobBucketName, key, jarFile); try { FileUtils.copyFile(new File(fileLocation), new File(jobSetupDirName + "/" + key)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } return "s3n://" + jobBucketName + "/" + key; } public void CreateMRJob(String jobInputLocation, String jobJarLocation, int numInstances, String instanceType) { // Modified from https://mpouttuclarke.wordpress.com/2011/06/24/how-to-run-an-elastic-mapreduce-job-using-the-java-sdk/ // first run aws emr create-default-roles String hadoopVersion = "2.4.0"; String flowName = "WeatherPipe_" + jobID; String logS3Location = "s3n://" + jobBucketName + "/" + jobID + ".log"; String outS3Location = "s3n://" + jobBucketName + "/" + jobID + "_output"; String[] arguments = new String[] {jobInputLocation, outS3Location}; List<String> jobArguments = Arrays.asList(arguments); DescribeClusterRequest describeClusterRequest = new DescribeClusterRequest(); DescribeClusterResult describeClusterResult; File rawOutputFile = new File(jobDirName + "/" + jobID + "_raw_map_reduce_output"); File localLogDir = new File(jobLogDirName); int normalized_hours; double cost; long startTimeOfProgram, endTimeOfProgram, elapsedTime; final String resultId; String line, lastStateMsg; StringBuilder jobOutputBuild; int i; Download download; int fileLength; BufferedReader lineRead; MultipleFileDownload logDirDownload; startTimeOfProgram = System.currentTimeMillis(); if(instanceType == null) { instanceType = "c3.xlarge"; System.out.println("Instance type is set to default: " + instanceType); System.out.println(); } try { // Configure instances to use JobFlowInstancesConfig instances = new JobFlowInstancesConfig(); System.out.println("Using EMR Hadoop v" + hadoopVersion); instances.setHadoopVersion(hadoopVersion); System.out.println("Using instance count: " + numInstances); instances.setInstanceCount(numInstances); System.out.println("Using master instance type: " + instanceType); instances.setMasterInstanceType("c3.xlarge"); // do these need to be different?? System.out.println("Using slave instance type: " + instanceType); instances.setSlaveInstanceType(instanceType); // Configure the job flow System.out.println("Configuring flow: " + flowName); RunJobFlowRequest request = new RunJobFlowRequest(flowName, instances); System.out.println("\tusing log URI: " + logS3Location); request.setLogUri(logS3Location); request.setServiceRole("EMR_DefaultRole"); request.setAmiVersion("3.1.0"); // this may change for some people request.setJobFlowRole("EMR_EC2_DefaultRole"); System.out.println("\tusing jar URI: " + jobJarLocation); HadoopJarStepConfig jarConfig = new HadoopJarStepConfig(jobJarLocation); System.out.println("\tusing args: " + jobArguments); jarConfig.setArgs(jobArguments); StepConfig stepConfig = new StepConfig(jobJarLocation.substring(jobJarLocation.indexOf('/') + 1), jarConfig); request.setSteps(Arrays.asList(new StepConfig[] { stepConfig })); System.out.println("Configured hadoop jar succesfully!\n"); //Run the job flow RunJobFlowResult result = emrClient.runJobFlow(request); System.out.println("Trying to run job flow!\n"); describeClusterRequest.setClusterId(result.getJobFlowId()); resultId = result.getJobFlowId(); //Check the status of the running job String lastState = ""; Runtime.getRuntime().addShutdownHook(new Thread() {public void run() { List<String> jobIds = new ArrayList<String>(); jobIds.add(resultId); TerminateJobFlowsRequest tjfr = new TerminateJobFlowsRequest(jobIds); emrClient.terminateJobFlows(tjfr); System.out.println(); System.out.println("Amazon EMR job shutdown"); }}); while (true) { describeClusterResult = emrClient.describeCluster(describeClusterRequest); Cluster cluster = describeClusterResult.getCluster(); lastState = cluster.getStatus().getState(); lastStateMsg = "\rCurrent State of Cluster: " + lastState; System.out.print(lastStateMsg + " "); if(!lastState.startsWith("TERMINATED")) { lastStateMsg = lastStateMsg + " "; for(i = 0; i < 10; i++) { lastStateMsg = lastStateMsg + "."; System.out.print(lastStateMsg); Thread.sleep(1000); } continue; } else { lastStateMsg = lastStateMsg + " "; System.out.print(lastStateMsg); } // it reaches here when the emr has "terminated" normalized_hours = cluster.getNormalizedInstanceHours(); cost = normalized_hours * 0.011; endTimeOfProgram = System.currentTimeMillis(); // returns milliseconds elapsedTime = (endTimeOfProgram - startTimeOfProgram)/(1000); logDirDownload = transMan.downloadDirectory(jobBucketName, jobID + ".log", localLogDir); while(!logDirDownload.isDone()) { Thread.sleep(1000); } System.out.println(); if(!lastState.endsWith("ERRORS")) { bytesTransfered = 0; fileLength = (int)s3client.getObjectMetadata(jobBucketName, jobID + "_output" + "/part-r-00000").getContentLength(); GetObjectRequest fileRequest = new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000"); fileRequest.setGeneralProgressListener(new ProgressListener() { @Override public void progressChanged(ProgressEvent progressEvent) { bytesTransfered += progressEvent.getBytesTransferred(); } }); download = transMan.download(new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000"), rawOutputFile); System.out.println("Downloading Output"); while(!download.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException e) { continue; } // System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + fileLength/1024 + "K "); } /* Printing this stuff isn't working // If we got an error the count could be off System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K "); System.out.println(); */ System.out.println("Transfer Complete"); System.out.println("The job has ended and output has been downloaded to " + jobDirName); System.out.printf("Normalized instance hours: %d\n", normalized_hours); System.out.printf("Approximate cost of this run: $%2.02f\n", cost); System.out.println("The job took " + elapsedTime + " seconds to finish" ); lineRead = new BufferedReader(new FileReader(rawOutputFile)); jobOutputBuild = new StringBuilder(""); while((line = lineRead.readLine()) != null) { if(line.startsWith("Run#")) { jobOutputBuild = new StringBuilder(""); jobOutputBuild.append(line.split("\t")[1]); } else { jobOutputBuild.append("\n"); jobOutputBuild.append(line); } } jobOutput = jobOutputBuild.toString(); break; } jobOutput = "FAILED"; System.out.println("The job has ended with errors, please check the log in " + localLogDir); System.out.printf("Normalized instance hours: %d\n", normalized_hours); System.out.printf("Approximate cost of this run = $%2.02f\n", cost); System.out.println("The job took " + elapsedTime + " seconds to finish" ); break; } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addJobBucketName (String jobBucketName){ this.jobBucketName = jobBucketName; } protected void close() { transMan.shutdownNow(); } }
stephenlienharrell/WeatherPipe
WeatherPipe/src/main/java/edu/purdue/eaps/weatherpipe/AWSInterface.java
Java
mit
19,505
# -*- coding: utf-8 -*- require 'spec_helper' describe RailwayCompany do describe :import do let(:file_path) do tempfile = Tempfile.new('railway_companies.csv') tempfile << <<EOS company_cd,rr_cd,company_name,company_name_k,company_name_h,company_name_r,company_url,company_type,e_status,e_sort 1,11,JR北海道,ジェイアールホッカイドウ,北海道旅客鉄道株式会社,JR北海道,http://www.jrhokkaido.co.jp/,1,0,1 2,11,JR東日本,ジェイアールヒガシニホン,東日本旅客鉄道株式会社,JR東日本,http://www.jreast.co.jp/,1,0,2 3,11,JR東海,ジェイアールトウカイ,東海旅客鉄道株式会社,JR東海,http://jr-central.co.jp/,1,0,3 4,11,JR西日本,ジェイアールニシニホン,西日本旅客鉄道株式会社,JR西日本,http://www.westjr.co.jp/,1,1,4 5,11,JR四国,ジェイアールシコク,四国旅客鉄道株式会社,JR四国,http://www.jr-shikoku.co.jp/,1,2,5 6,11,JR九州,ジェイアールキュウシュウ,九州旅客鉄道株式会社,JR九州,http://www.jrkyushu.co.jp/,1,2,6 EOS tempfile.close return tempfile.path end before do RailwayCompany.import(file_path) end describe :imported_count do subject { RailwayCompany.pluck(:id) } it { should match_array [1, 2, 3] } end describe :first_company do subject { RailwayCompany.find(1) } its(:name) { should eq 'JR北海道' } its(:railway_id) { should eq 11 } its(:kana_name) { should eq 'ジェイアールホッカイドウ' } its(:official_name) { should eq '北海道旅客鉄道株式会社' } its(:abbreviated_name) { should eq 'JR北海道' } its(:url) { should eq 'http://www.jrhokkaido.co.jp/' } its(:company_type) { should eq 1 } its(:sort) { should eq 1 } end end end
aonashi/jpstation
spec/models/railway_company_spec.rb
Ruby
mit
1,833
<?php /** * PHPSpec * * LICENSE * * This file is subject to the GNU Lesser General Public License Version 3 * that is bundled with this package in the file LICENSE. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/lgpl-3.0.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@phpspec.net so we can send you a copy immediately. * * @category PHPSpec * @package PHPSpec * @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood * @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood, * Marcello Duarte * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3 */ namespace PHPSpec\Runner\Formatter; use \PHPSpec\Runner\Reporter; /** * @category PHPSpec * @package PHPSpec * @copyright Copyright (c) 2007-2009 Pádraic Brady, Travis Swicegood * @copyright Copyright (c) 2010-2012 Pádraic Brady, Travis Swicegood, * Marcello Duarte * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public Licence Version 3 */ class Factory { /** * Available formatters * * @var array */ protected $_formatters = array( 'p' => 'Progress', 'd' => 'Documentation', 'h' => 'Html', 'j' => 'Junit' ); /** * Creates a formatter class, looks for built in and returns custom one if * one is not found * * @param string $formatter * @param \PHPSpec\Runner\Reporter $reporter * @return \PHPSpec\Runner\Formatter */ public function create($formatter, Reporter $reporter) { if (in_array($formatter, array_keys($this->_formatters)) || in_array(ucfirst($formatter), array_values($this->_formatters))) { $formatter = $this->_formatters[strtolower($formatter[0])]; $formatterClass = '\PHPSpec\Runner\Formatter\\' . $formatter; return new $formatterClass($reporter); } return new $formatter; } }
manufy/PHP-BDD-YaCMS
Lib/PHPSpec-1.3.0beta/PHPSpec/Runner/Formatter/Factory.php
PHP
mit
2,204
package framework.org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having <code>get</code> and <code>opt</code> * methods for accessing the values by index, and <code>put</code> methods for * adding or replacing values. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the * <code>JSONObject.NULL object</code>. * <p> * The constructor can convert a JSON text into a Java object. The * <code>toString</code> method converts to JSON text. * <p> * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing bracket.</li> * <li>The <code>null</code> value will be inserted when there is <code>,</code> * &nbsp;<small>(comma)</small> elision.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, and * if they do not contain any of these characters: * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and * if they are not the reserved words <code>true</code>, <code>false</code>, or * <code>null</code>.</li> * </ul> * * @author JSON.org * @version 2014-05-03 */ public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private final ArrayList<Object> myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList<Object>(); } /** * Construct a JSONArray from a JSONTokener. * * @param x * A JSONTokener * @throws JSONException * If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() != ']') { x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); } else { x.back(); this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } } /** * Construct a JSONArray from a source JSON text. * * @param source * A string that begins with <code>[</code>&nbsp;<small>(left * bracket)</small> and ends with <code>]</code> * &nbsp;<small>(right bracket)</small>. * @throws JSONException * If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * * @param collection * A Collection. */ public JSONArray(Collection<Object> collection) { this.myArrayList = new ArrayList<Object>(); if (collection != null) { Iterator<Object> iter = collection.iterator(); while (iter.hasNext()) { this.myArrayList.add(JSONObject.wrap(iter.next())); } } } /** * Construct a JSONArray from an array * * @throws JSONException * If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException * If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return object; } /** * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * * @param index * The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException * If there is no value for the index or if the value is not * convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } /** * Get the double value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value cannot be converted * to a number. */ public double getDouble(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the JSONArray associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException * If there is no value for the index. or if the value is not a * JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONArray) { return (JSONArray) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * * @param index * subscript * @return A JSONObject value. * @throws JSONException * If there is no value for the index or if the value is not a * JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONObject) { return (JSONObject) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return The value. * @throws JSONException * If the key is not found or if the value cannot be converted * to a number. */ public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the string associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException * If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { return (String) object; } throw new JSONException("JSONArray[" + index + "] not a string."); } /** * Determine if the value is null. * * @param index * The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(this.opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * * @param separator * A string that will be inserted between the elements. * @return a string. * @throws JSONException * If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * * @param index * The index must be between 0 and length() - 1. * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { return (index < 0 || index >= this.length()) ? null : this.myArrayList .get(index); } /** * Get the optional boolean value associated with an index. It returns false * if there is no value at that index, or if the value is not Boolean.TRUE * or the String "true". * * @param index * The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } /** * Get the optional boolean value associated with an index. It returns the * defaultValue if there is no value at that index or if it is not a Boolean * or the String "true" or "false" (case insensitive). * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return this.getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. NaN is returned * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * subscript * @param defaultValue * The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return this.getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } /** * Get the optional int value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return this.getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * * @param index * subscript * @return A JSONArray value, or null if the index has no value, or if the * value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } /** * Get the optional JSONObject associated with an index. Null is returned if * the key is not found, or null if the index has no value, or if the value * is not a JSONObject. * * @param index * The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } /** * Get the optional long value associated with an index. Zero is returned if * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } /** * Get the optional long value associated with an index. The defaultValue is * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return this.getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a * string and is not null, then it is coverted to a string. * * @param index * The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } /** * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * * @param index * The index must be between 0 and length() - 1. * @param defaultValue * The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object object = this.opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object .toString(); } /** * Append a boolean value. This increases the array's length by one. * * @param value * A boolean value. * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value * A Collection value. * @return this. */ public JSONArray put(Collection<Object> value) { this.put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value * A double value. * @throws JSONException * if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); this.put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value * An int value. * @return this. */ public JSONArray put(int value) { this.put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value * A long value. * @return this. */ public JSONArray put(long value) { this.put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value * A Map value. * @return this. */ public JSONArray put(Map<String, Object> value) { this.put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * * @param value * An object value. The value should be a Boolean, Double, * Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index * The subscript. * @param value * A boolean value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param index * The subscript. * @param value * A Collection value. * @return this. * @throws JSONException * If the index is negative or if the value is not finite. */ public JSONArray put(int index, Collection<Object> value) throws JSONException { this.put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * A double value. * @return this. * @throws JSONException * If the index is negative or if the value is not finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * An int value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad it * out. * * @param index * The subscript. * @param value * A long value. * @return this. * @throws JSONException * If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * * @param index * The subscript. * @param value * The Map value. * @return this. * @throws JSONException * If the index is negative or if the the value is an invalid * number. */ public JSONArray put(int index, Map<String, Object> value) throws JSONException { this.put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * * @param index * The subscript. * @param value * The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or * String, or the JSONObject.NULL object. * @return this. * @throws JSONException * If the index is negative or if the the value is an invalid * number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { this.myArrayList.set(index, value); } else { while (index != this.length()) { this.put(JSONObject.NULL); } this.put(value); } return this; } /** * Remove an index and close the hole. * * @param index * The index of the element to be removed. * @return The value that was associated with the index, or null if there * was no value. */ public Object remove(int index) { return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; } /** * Determine if two JSONArrays are similar. * They must contain similar sequences. * * @param other The other JSONArray * @return true if they are equal */ public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; } /** * Produce a JSONObject by combining a JSONArray of names with the values of * this JSONArray. * * @param names * A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException * If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no unnecessary * whitespace is added. If it is not possible to produce a syntactically * correct JSON text then null will be returned instead. This could occur if * the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the * array. */ public String toString() { try { return this.toString(0); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor * The number of spaces to add to each level of indentation. * @return a printable, displayable, transmittable representation of the * object, beginning with <code>[</code>&nbsp;<small>(left * bracket)</small> and ending with <code>]</code> * &nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { StringWriter sw = new StringWriter(); synchronized (sw.getBuffer()) { return this.write(sw, indentFactor, 0).toString(); } } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor * The number of spaces to add to each level of indentation. * @param indent * The indention of the top level. * @return The writer. * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean commanate = false; int length = this.length(); writer.write('['); if (length == 1) { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } else if (length != 0) { final int newindent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (commanate) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newindent); JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); commanate = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
marcossilva/IFAdventure
EnsaioRetentivo/src/framework/org/json/JSONArray.java
Java
mit
32,203
#include "abstract_serializable.h" using namespace json; json::__abstract_serializable__::__abstract_serializable__() {} std::map<std::string, std::function<json::__abstract_serializable__*()> > json::__abstract_serializable__::dictionary;
Dariasteam/JSON-cpp
src/abstract_serializable.cpp
C++
mit
243
module CalculableAttrs VERSION = "0.0.15" end
dmitrysharkov/calculable_attrs
lib/calculable_attrs/version.rb
Ruby
mit
48
# -*- coding: utf-8 -*- import pack_command import pack_command_python import timeit import cProfile import pstats import pycallgraph def format_time(seconds): v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: scale = u'μs' v = int(round(v*1000*1000)) elif v * 1000 < 1000: scale = u'ms' v = round(v*1000, 4) else: scale = u'sec' v = int(v) return u'{} {}'.format(v, scale) # profiler size number = 100000 sample = 7 # profiler type profile = False graph = False timer = True def runit(): pack_command.pack_command("ZADD", "foo", 1369198341, 10000) def runitp(): pack_command_python.pack_command("ZADD", "foo", 1369198341, 10000) if profile: pr = cProfile.Profile() pr.enable() if graph: pycallgraph.start_trace() if timer: for name, t in (("Python", runitp), ("cython", runit)): res = timeit.Timer(t).repeat(sample, number) min_run = min(res) per_loop = min_run/number print u'{}'.format(name) print u'{} total run'.format(format_time(min_run)) print u'{} per/loop'.format(format_time(per_loop)) #print u'{} per/friend'.format(format_time(per_loop/friends_cnt)) else: for j in xrange(number): runit() if graph: pycallgraph.make_dot_graph('example.png') if profile: pr.disable() ps = pstats.Stats(pr) sort_by = 'cumulative' ps.strip_dirs().sort_stats(sort_by).print_stats(20)
simonz05/pack-command
misc/bench.py
Python
mit
1,564
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SerializationJsonModule.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel { using IoC; using Runtime.Serialization.Json; /// <summary> /// Core module which allows the registration of default services in the service locator. /// </summary> public class SerializationJsonModule : IServiceLocatorInitializer { #region Methods /// <summary> /// Initializes the specified service locator. /// </summary> /// <param name="serviceLocator">The service locator.</param> public void Initialize(IServiceLocator serviceLocator) { Argument.IsNotNull(() => serviceLocator); serviceLocator.RegisterType<IJsonSerializer, JsonSerializer>(); } #endregion } }
blebougge/Catel
src/Catel.Serialization.Json/Catel.Serialization.Json.Shared/SerializationJsonModule.cs
C#
mit
1,132
var fs = require('fs'); var mysql = require('mysql'); var qs = require('querystring'); var express = require('express'); var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8')); // ----------------------------------------------------------------------------- // Keep a persistant connection to the database (reconnect after an error or disconnect) // ----------------------------------------------------------------------------- if (typeof config.databaseConnection == 'undefined' || typeof config.databaseConnection.retryMinTimeout == 'undefined') config.databaseConnection = {retryMinTimeout: 2000, retryMaxTimeout: 60000}; var connection, retryTimeout = config.databaseConnection.retryMinTimeout; function persistantConnection(){ connection = mysql.createConnection(config.database); connection.connect( function (err){ if (err){ console.log('Error connecting to database: '+err.code); setTimeout(persistantConnection, retryTimeout); console.log('Retrying in '+(retryTimeout / 1000)+' seconds'); if (retryTimeout < config.databaseConnection.retryMaxTimeout) retryTimeout += 1000; } else{ retryTimeout = config.databaseConnection.retryMinTimeout; console.log('Connected to database'); } }); connection.on('error', function (err){ console.log('Database error: '+err.code); if (err.code === 'PROTOCOL_CONNECTION_LOST') persistantConnection(); }); } //persistantConnection(); var app = express(); // ----------------------------------------------------------------------------- // Deliver the base template of SPA // ----------------------------------------------------------------------------- app.get('/', function (req, res){ res.send(loadTemplatePart('base.html', req)); }); app.get('/images/:id', function (req, res){ res.send(dataStore.images); }); // ----------------------------------------------------------------------------- // Deliver static assets // ----------------------------------------------------------------------------- app.use('/static/', express.static('static')); // ================================================== // Below this point are URIs that are accesible from outside, in REST API calls // ================================================== app.use(function(req, res, next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // ----------------------------------------------------------------------------- // API Endpoint to receive data // ----------------------------------------------------------------------------- var dataStore = {}; app.post('/api/put', function (req, res){ // Needs to authenticate the RPi module // handlePost(req, function(data){ //console.log(data); for (var i = 0; i < 4; i++){ //var img = Buffer.from(, 'base64'); fs.writeFile('./static/images/'+data.id+'/'+i+'.png', 'data:image/png;base64,'+data.images[i], function(err){ if (err) console.log(err); } ); } // //dataStore[data.id] = data; dataStore = data; res.send('ok'); }); }); app.listen(config.listenPort, function (){ console.log('RainCatcher server is listening on port '+config.listenPort); }); // -------------------------------------------------------------------------- // Handler for multipart POST request/response body function handlePost(req, callback){ var body = ''; req.on('data', function (data){ body += data; if (body.length > 1e8) req.connection.destroy(); }); req.on('end', function (data){ var post = body; try{ post = JSON.parse(post); } catch(e){ try{ post = qs.parse(post); } catch(e){} } callback(post); }); } function loadTemplatePart(template, req){ try{ return fs.readFileSync('./templates/'+template, 'utf8'); } catch(e){ return '<h2>Page Not Found</h2>'; } } Date.prototype.sqlFormatted = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); var dd = this.getDate().toString(); return yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); }; function isset(obj){ return typeof obj != 'undefined'; }
vishva8kumara/rain-catcher
server/sky.js
JavaScript
mit
4,212
import SuccessPage from '../index'; import expect from 'expect'; import { shallow } from 'enzyme'; import React from 'react'; describe('<SuccessPage />', () => { });
Luandro-com/repsparta-web-app
app/components/SuccessPage/tests/index.test.js
JavaScript
mit
169
<?php namespace Application\Core; use \DateTime; /** * The LogHandler handles writing and clearing logs */ class LogHandler { public static function clear() { $files = App::logs()->files(); foreach ($files as $file) { $file->remove(); } } public static function clean() { $files = App::logs()->files(); sort($files); $files_to_remove = count($files) - App::logLimit(); if($files_to_remove>0) { $i=0; while($i<$files_to_remove) { $files[$i]->remove(); ++$i; } } } /** * Writes a log * * @param StatusCode $err * @param string $additional */ public static function write($err, $additional = '') { $dt = new DateTime(); $file=App::logs()->file('log_'.$dt->format('Y-m-d').'.log'); $log=$dt->format('H:i:s')."\t".$err->status()."\t$additional\r\n"; if($file->exists()) { $file->append($log); } else { $file->write($log); } self::clean(); } }
LiamMartens/xTend
dist/Application/Core/LogHandler.php
PHP
mit
1,177
namespace CSReader.Command { /// <summary> /// ヘルプを表示するコマンド /// </summary> public class HelpCommand : ICommand { public const string COMMAND_NAME = "help"; /// <summary> /// コマンドを実行する /// </summary> /// <returns>ヘルプ文字列</returns> public string Execute() { return @"usage: csr [command_name] [command_args] ..."; } } }
yobiya/CSReader
CSReader/CSReader/Command/HelpCommand.cs
C#
mit
494
//The MIT License(MIT) // //Copyright(c) 2016 universalappfactory // //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 Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Sharpend.UAP.Controls.Buttons { [TemplatePart(Name = IconButton.PART_Symbol,Type = typeof(SymbolIcon))] public class IconButton : Button { public const string PART_Symbol = "PART_Symbol"; //Symbol public Symbol Symbol { get { return (Symbol)GetValue(SymbolProperty); } set { SetValue(SymbolProperty, value); } } public static readonly DependencyProperty SymbolProperty = DependencyProperty.Register("Symbol", typeof(Symbol), typeof(IconButton), new PropertyMetadata(0, SymbolChanged)); //IconWidth public double IconWidth { get { return (double)GetValue(IconWidthProperty); } set { SetValue(IconWidthProperty, value); } } // Using a DependencyProperty as the backing store for IconWidth. This enables animation, styling, binding, etc... public static readonly DependencyProperty IconWidthProperty = DependencyProperty.Register("IconWidth", typeof(double), typeof(IconButton), new PropertyMetadata(15)); //IconHeight public double IconHeight { get { return (double)GetValue(IconHeightProperty); } set { SetValue(IconHeightProperty, value); } } // Using a DependencyProperty as the backing store for IconHeight. This enables animation, styling, binding, etc... public static readonly DependencyProperty IconHeightProperty = DependencyProperty.Register("IconHeight", typeof(double), typeof(IconButton), new PropertyMetadata(15)); //IconPadding public Thickness IconPadding { get { return (Thickness)GetValue(IconPaddingProperty); } set { SetValue(IconPaddingProperty, value); } } // Using a DependencyProperty as the backing store for IconPadding. This enables animation, styling, binding, etc... public static readonly DependencyProperty IconPaddingProperty = DependencyProperty.Register("IconPadding", typeof(Thickness), typeof(IconButton), new PropertyMetadata(new Thickness(0))); public IconButton() { } private static void SymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var btn = d as IconButton; if ((btn != null) && (btn.Content != null)) { var symbolIcon = (btn.Content as SymbolIcon); if (symbolIcon != null) { symbolIcon.Symbol = btn.Symbol; } } else if (btn != null) { var symbolIcon = btn.GetTemplateChild("PART_Symbol") as SymbolIcon; if (symbolIcon != null) { symbolIcon.Symbol = btn.Symbol; } } } protected override void OnApplyTemplate() { base.OnApplyTemplate(); var symbolIcon = GetTemplateChild(PART_Symbol) as SymbolIcon; if (symbolIcon == null) { symbolIcon = new SymbolIcon(); this.Content = symbolIcon; } symbolIcon.Symbol = this.Symbol; } } }
universalappfactory/Sharpend.UAP
Sharpend.UAP/Controls/Buttons/IconButton.cs
C#
mit
4,533
Given /^I am in the "(.*?)" directory$/ do |dir| @dir = dir @project = RemoteTerminal::Project.find(@dir) end When /^I get the path from my location$/ do @path = @project.path_from(@dir) end Then /^I should see "(.*?)"$/ do |path| @path.should be == path end When /^I get the path to my location$/ do @path = @project.path_to(@dir) end
igorbonadio/remote-terminal
features/step_definitions/project_step.rb
Ruby
mit
348
require "test_helper" class FHeapTest < ActiveSupport::TestCase def setup @heap = FHeap.new end def setup_sample_heap @node_1 = @heap.insert!(1) @node_2 = @heap.insert!(2) @node_6 = @heap.insert!(6) @node_5 = @node_2.add_child!(5) @node_3 = @node_1.add_child!(3) @node_4 = @node_1.add_child!(4) @node_7 = @node_1.add_child!(7) @node_8 = @node_7.add_child!(8) @node_9 = @node_8.add_child!(9) assert_equal 3, @heap.trees.length assert_equal 1, @heap.min_node.value end test "min_node with no trees" do assert_nil @heap.min_node end test "insert updates min_node" do @heap.insert!(1) assert_equal 1, @heap.min_node.value @heap.insert!(2) assert_equal 1, @heap.min_node.value @heap.insert!(0) assert_equal 0, @heap.min_node.value end test "extract minimum (nothing in the heap)" do assert_nil @heap.extract_minimum! end test "extract minimum (one item in heap)" do @heap.insert!(1) assert_equal 1, @heap.extract_minimum!.value end test "extract minimum (calling after extracting the last node)" do @heap.insert!(1) assert_equal 1, @heap.extract_minimum!.value assert_nil @heap.extract_minimum! end test "extract minimum (restructures correctly)" do setup_sample_heap assert_equal 1, @heap.extract_minimum!.value assert_equal 2, @heap.min_node.value assert_equal ["(2 (5), (3 (6)))", "(4)", "(7 (8 (9)))"], @heap.to_s assert @node_2.root? assert @node_4.root? assert @node_7.root? assert_equal @node_2, @node_5.root assert_equal @node_2, @node_3.root assert_equal @node_2, @node_6.root assert_equal @node_7, @node_8.root assert_equal @node_7, @node_9.root assert_equal @node_2, @node_2.parent assert_equal @node_4, @node_4.parent assert_equal @node_7, @node_7.parent assert_equal @node_2, @node_5.parent assert_equal @node_2, @node_3.parent assert_equal @node_3, @node_6.parent assert_equal @node_7, @node_8.parent assert_equal @node_8, @node_9.parent end test "decrease value (can't set higher than the existing value)" do setup_sample_heap assert_raises ArgumentError do @heap.decrease_value!(@node_9, 100) end end test "decrease value (doesn't do anything if you don't change the value)" do setup_sample_heap structure = @heap.to_s @heap.decrease_value!(@node_9, @node_9.value) assert_equal structure, @heap.to_s end test "decrease value (restructures correctly)" do setup_sample_heap @node_4.marked = true @node_7.marked = true @node_8.marked = true @heap.decrease_value!(@node_0 = @node_9, 0) assert_equal 0, @heap.min_node.value assert_equal ["(1 (3), (4))", "(2 (5))", "(6)", "(0)", "(8)", "(7)"], @heap.to_s assert ((0..8).to_a - [4]).all? { |number| !instance_variable_get(:"@node_#{number}").marked } assert @node_4.marked assert @node_1.root? assert @node_2.root? assert @node_6.root? assert @node_0.root? assert @node_8.root? assert @node_7.root? assert_equal @node_1, @node_3.root assert_equal @node_1, @node_4.root assert_equal @node_2, @node_5.root assert_equal @node_1, @node_3.parent assert_equal @node_1, @node_4.parent assert_equal @node_2, @node_5.parent end test "delete" do setup_sample_heap assert_equal @node_9, @heap.delete(@node_9) assert_equal 1, @heap.min_node.value assert_equal ["(1 (3), (4), (7 (8)))", "(2 (5))", "(6)"], @heap.to_s assert ((1..9).to_a - [8]).all? { |number| !instance_variable_get(:"@node_#{number}").marked } assert @node_8.marked assert @node_1.root? assert @node_2.root? assert @node_6.root? assert_equal @node_1, @node_3.root assert_equal @node_1, @node_4.root assert_equal @node_1, @node_7.root assert_equal @node_1, @node_8.root assert_equal @node_2, @node_5.root assert_equal @node_1, @node_3.parent assert_equal @node_1, @node_4.parent assert_equal @node_1, @node_7.parent assert_equal @node_7, @node_8.parent assert_equal @node_2, @node_5.parent end end
evansenter/f_heap
test/f_heap_test.rb
Ruby
mit
4,332
using SuperScript.Configuration; using SuperScript.Emitters; using SuperScript.Modifiers; using SuperScript.Modifiers.Converters; using SuperScript.Modifiers.Post; using SuperScript.Modifiers.Pre; using SuperScript.Modifiers.Writers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace SuperScript.ExtensionMethods { /// <summary> /// Contains extension methods which can be invoked upon the classes which are implemented in the web.config &lt;superScript&gt; section. /// </summary> public static class ConfigurationExtensions { /// <summary> /// Enumerates the <see cref="PropertyCollection"/> and populates the properties specified therein on the specified <see cref="host"/> object. /// </summary> /// <param name="propertyElmnts">A <see cref="PropertyCollection"/> object containing a collection of <see cref="PropertyElement"/> objects.</param> /// <param name="host">The object to which the value of each <see cref="PropertyElement"/> object should be transferred to. </param> public static void AssignProperties(this PropertyCollection propertyElmnts, object host) { if (propertyElmnts == null || propertyElmnts.Count == 0) { return; } foreach (PropertyElement propertyElmnt in propertyElmnts) { // a Type may be specified on the <property> element for the following reasons: // - to assign a derived type to the specified property // - if no value is specified on the <property> element then a new instance (using the default constructor) // will be created and assigned to the specified property. This branch will throw an exception if the // specified type is a value type or does not have a public default constructor. if (propertyElmnt.Type != null) { // enums have to be handled differently if (propertyElmnt.Type.IsEnum) { if (!Enum.IsDefined(propertyElmnt.Type, propertyElmnt.Value)) { throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name); } var enumInfo = host.GetType().GetProperty(propertyElmnt.Name); if (enumInfo == null) { if (propertyElmnt.ExceptionIfMissing) { throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name); } continue; } enumInfo.SetValue(host, Enum.Parse(propertyElmnt.Type, propertyElmnt.Value)); continue; } // in the following call, passing customProperty.Type might be more secure, but cannot be done in case // the target property has been specified using an interface. var propInfo = host.GetType().GetProperty(propertyElmnt.Name, propertyElmnt.Type); if (propInfo == null) { if (propertyElmnt.ExceptionIfMissing) { throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name); } continue; } // if no value has been specified then assume that the intention is to assign a new instance of the // specified type to the specified property. if (String.IsNullOrWhiteSpace(propertyElmnt.Value) && !propertyElmnt.Type.IsValueType) { // check that the specified type has a public default (parameterless) constructor if (propertyElmnt.Type.GetConstructor(Type.EmptyTypes) != null) { propInfo.SetValue(host, Activator.CreateInstance(propertyElmnt.Type), null); } } else { // a Type and a value have been specified // if the Type is System.TimeSpan then this needs to be parsed in a specific manner if (propertyElmnt.Type == typeof (TimeSpan)) { TimeSpan ts; TimeSpan.TryParse(propertyElmnt.Value, out ts); propInfo.SetValue(host, ts, null); } else { propInfo.SetValue(host, Convert.ChangeType(propertyElmnt.Value, propertyElmnt.Type), null); } } } else { var propInfo = host.GetType().GetProperty(propertyElmnt.Name); if (propInfo == null) { if (propertyElmnt.ExceptionIfMissing) { throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name); } continue; } propInfo.SetValue(host, Convert.ChangeType(propertyElmnt.Value, propInfo.PropertyType), null); } } } /// <summary> /// Compares the specified <see cref="EmitMode"/> enumeration with the current context. /// </summary> /// <param name="emitMode">Determines for which modes (i.e., debug, live, or forced on or off) a property should be emitted.</param> /// <returns><c>True</c> if the current context covers the specified <see cref="EmitMode"/>.</returns> public static bool IsCurrentlyEmittable(this EmitMode emitMode) { if (emitMode == EmitMode.Always) { return true; } if (emitMode == EmitMode.Never) { return false; } if (Settings.IsDebuggingEnabled) { return emitMode == EmitMode.DebugOnly; } return emitMode == EmitMode.LiveOnly; } /// <summary> /// Determines whether the specified <see cref="ModifierBase"/> should be implemented in the current emitting context. /// </summary> /// <param name="modifier">An instance of <see cref="ModifierBase"/> whose <see cref="EmitMode"/> property will be checked against the current emitting context.</param> /// <returns><c>true</c> if the specified instance of <see cref="ModifierBase"/> should be emitted in the current emitting context.</returns> public static bool ShouldEmitForCurrentContext(this ModifierBase modifier) { return modifier.EmitMode.IsCurrentlyEmittable(); } /// <summary> /// Converts the specified <see cref="AttributesCollection"/> into an <see cref="ICollection{KeyValuePair}"/>. /// </summary> public static ICollection<KeyValuePair<string, string>> ToAttributeCollection(this AttributesCollection attributeElmnts) { var attrs = new Collection<KeyValuePair<string, string>>(); foreach (AttributeElement attrElmnt in attributeElmnts) { attrs.Add(new KeyValuePair<string, string>(attrElmnt.Name, attrElmnt.Value)); } return attrs; } /// <summary> /// Creates an instance of <see cref="EmitterBundle"/> from the specified <see cref="EmitterBundleElement"/> object. /// </summary> /// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception> public static EmitterBundle ToEmitterBundle(this EmitterBundleElement bundledEmitterElmnt) { // create the instance... var instance = new EmitterBundle(bundledEmitterElmnt.Key); // instantiate the CustomObject, if declared if (bundledEmitterElmnt.CustomObject != null && bundledEmitterElmnt.CustomObject.Type != null) { var coType = bundledEmitterElmnt.CustomObject.Type; // rule out abstract and static classes // - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property. if (coType.IsAbstract) { throw new ConfigurationException("Static or abstract types are not permitted for the custom object."); } var customObject = Activator.CreateInstance(coType); // if the developer has configured custom property values in the config then set them here bundledEmitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject); instance.CustomObject = customObject; } var bundledKeys = new List<string>(bundledEmitterElmnt.BundleKeys.Count); bundledKeys.AddRange(bundledEmitterElmnt.BundleKeys.Cast<string>()); instance.EmitterKeys = bundledKeys; // instantiate the collection processors instance.PostModifiers = bundledEmitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>(); instance.HtmlWriter = bundledEmitterElmnt.Writers.ToModifier<HtmlWriter>(required: true); return instance; } /// <summary> /// Creates an <see cref="ICollection{EmitterBundle}"/> containing the instances of <see cref="EmitterBundle"/> specified by the <see cref="EmitterBundlesCollection"/>. /// </summary> public static IList<EmitterBundle> ToEmitterBundles(this EmitterBundlesCollection bundledEmitterElmnts) { var bundledEmitters = new Collection<EmitterBundle>(); foreach (EmitterBundleElement bundledEmitterElmnt in bundledEmitterElmnts) { // check that no existing BundledEmitters have the same key as we're about to assign if (bundledEmitters.Any(e => e.Key == bundledEmitterElmnt.Key)) { throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + bundledEmitterElmnt.Key + ")."); } bundledEmitters.Add(bundledEmitterElmnt.ToEmitterBundle()); } return bundledEmitters; } /// <summary> /// Creates an instance of <see cref="IEmitter"/> from the specified <see cref="EmitterElement"/> object. /// </summary> /// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception> public static IEmitter ToEmitter(this EmitterElement emitterElmnt) { // create the instance... var instance = emitterElmnt.ToInstance<IEmitter>(); instance.IsDefault = emitterElmnt.IsDefault; instance.Key = emitterElmnt.Key; // instantiate the CustomObject, if declared if (emitterElmnt.CustomObject != null && emitterElmnt.CustomObject.Type != null) { var coType = emitterElmnt.CustomObject.Type; // rule out abstract and static classes // - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property. if (coType.IsAbstract) { throw new ConfigurationException("Static or abstract types are not permitted for the custom object."); } var customObject = Activator.CreateInstance(coType); // if the developer has configured custom property values in the config then set them here emitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject); instance.CustomObject = customObject; } // instantiate the collection processors instance.PreModifiers = emitterElmnt.PreModifiers.ToModifiers<CollectionPreModifier>(); instance.Converter = emitterElmnt.Converters.ToModifier<CollectionConverter>(required: true); instance.PostModifiers = emitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>(); instance.HtmlWriter = emitterElmnt.Writers.ToModifier<HtmlWriter>(); return instance; } /// <summary> /// Creates an <see cref="IList{IEmitter}"/> containing instances of the Emitters specified by the <see cref="EmittersCollection"/>. /// </summary> public static IList<IEmitter> ToEmitterCollection(this EmittersCollection emitterElmnts) { var emitters = new Collection<IEmitter>(); foreach (var emitterElmnt in from EmitterElement emitterElement in emitterElmnts select emitterElement.ToEmitter()) { // should we check if any other Emitters have been set to isDefault=true if (emitterElmnt.IsDefault && emitters.Any(e => e.IsDefault)) { throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with 'isDefault' set to TRUE."); } // check that no existing emitters have the same key as we're about to assign if (emitters.Any(e => e.Key == emitterElmnt.Key)) { throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + emitterElmnt.Key + ")."); } emitters.Add(emitterElmnt); } return emitters; } /// <summary> /// Returns the first instance of T which is eligible for the context emit mode (i.e., <see cref="EmitMode.Always"/>, <see cref="EmitMode.DebugOnly"/>, etc.). /// </summary> /// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam> /// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param> /// <param name="required">Indicates whether this method must return a <see cref="ModifierBase"/> or whether these are optional.</param> /// <exception cref="ConfigurationException">Thrown if multiple declarations have been made for the context emit mode.</exception> /// <exception cref="ConfigurablePropertyNotSpecifiedException">Thrown if no declarations have been made for the context emit mode.</exception> public static T ToModifier<T>(this ModifiersCollection modifierElmnts, bool required = false) where T : ModifierBase { T instanceToBeUsed = null; foreach (ModifierElement modifierElmnt in modifierElmnts) { var modInstance = modifierElmnt.ToInstance<T>(); modInstance.EmitMode = modifierElmnt.EmitMode; if (!modInstance.ShouldEmitForCurrentContext()) { continue; } if (instanceToBeUsed != null) { throw new ConfigurationException("Only one instance of HtmlWriter (in a <writer> element) may be specified per context mode."); } modifierElmnt.ModifierProperties.AssignProperties(modInstance); var bundled = modInstance as IUseWhenBundled; if (bundled != null) { bundled.UseWhenBundled = modifierElmnt.UseWhenBundled; instanceToBeUsed = (T) bundled; } else { instanceToBeUsed = modInstance; } } if (required && instanceToBeUsed == null) { throw new ConfigurablePropertyNotSpecifiedException("writer"); } return instanceToBeUsed; } /// <summary> /// Creates an <see cref="ICollection{T}"/> containing instances of objects specified in each <see cref="ModifierElement"/>. /// </summary> /// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam> /// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param> public static ICollection<T> ToModifiers<T>(this ModifiersCollection modifierElmnts) where T : ModifierBase { var instances = new Collection<T>(); foreach (ModifierElement modifierElmnt in modifierElmnts) { var modInstance = modifierElmnt.ToInstance<T>(); modInstance.EmitMode = modifierElmnt.EmitMode; if (!modInstance.ShouldEmitForCurrentContext()) { continue; } modifierElmnt.ModifierProperties.AssignProperties(modInstance); var bundled = modInstance as IUseWhenBundled; if (bundled != null) { bundled.UseWhenBundled = modifierElmnt.UseWhenBundled; modInstance = (T) bundled; } instances.Add(modInstance); } return instances; } /// <summary> /// Returns the <see cref="Type"/> specified in the <see cref="IAssemblyElement"/>. /// </summary> public static T ToInstance<T>(this IAssemblyElement element) { return (T) Activator.CreateInstance(element.Type); } } }
Supertext/SuperScript.Common
ExtensionMethods/ConfigurationExtensions.cs
C#
mit
16,291
using Cofoundry.Core; using Cofoundry.Domain; using System; using System.Collections.Generic; using System.Linq; namespace Cofoundry.Web.Admin { public class CustomEntitiesRouteLibrary : AngularModuleRouteLibrary { public const string RoutePrefix = "custom-entities"; private readonly AdminSettings _adminSettings; public CustomEntitiesRouteLibrary(AdminSettings adminSettings) : base(adminSettings, RoutePrefix, RouteConstants.InternalModuleResourcePathPrefix) { _adminSettings = adminSettings; } #region routes public string List(CustomEntityDefinitionSummary definition) { return GetCustomEntityRoute(definition?.NamePlural); } public string List(ICustomEntityDefinition definition) { return GetCustomEntityRoute(definition?.NamePlural); } public string New(CustomEntityDefinitionSummary definition) { if (definition == null) return string.Empty; return List(definition) + "new"; } public string Details(CustomEntityDefinitionSummary definition, int id) { if (definition == null) return string.Empty; return List(definition) + id.ToString(); } private string GetCustomEntityRoute(string namePlural, string route = null) { if (namePlural == null) return string.Empty; return "/" + _adminSettings.DirectoryName + "/" + SlugFormatter.ToSlug(namePlural) + "#/" + route; } #endregion } }
cofoundry-cms/cofoundry
src/Cofoundry.Web.Admin/Admin/Modules/CustomEntities/Constants/CustomEntitiesRouteLibrary.cs
C#
mit
1,605
/* eslint-disable no-undef,no-unused-expressions */ const request = require('supertest') const expect = require('chai').expect const app = require('../../bin/www') const fixtures = require('../data/fixtures') describe('/api/mappings', () => { beforeEach(() => { this.Sample = require('../../models').Sample this.Instrument = require('../../models').Instrument this.InstrumentMapping = require('../../models').InstrumentMapping this.ValidationError = require('../../models').sequelize.ValidationError expect(this.Sample).to.exist expect(this.Instrument).to.exist expect(this.InstrumentMapping).to.exist expect(this.ValidationError).to.exist return require('../../models').sequelize .sync({force: true, logging: false}) .then(() => { console.log('db synced') return this.Sample .bulkCreate(fixtures.samples) }) .then(samples => { this.samples = samples return this.Instrument .bulkCreate(fixtures.instruments) }) .then(instruments => { return this.InstrumentMapping.bulkCreate(fixtures.instrumentMappings) }) .then(() => console.log('Fixtures loaded')) }) it('should return 200 on GET /api/instruments/:instrumentId/mappings', () => { return request(app) .get('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res) => { expect(res.body, 'body should be an array').to.be.an('array') expect(res.body, 'body should contain 2 items').to.have.lengthOf(2) expect(res.body[0], 'item 0 should be an object').to.be.an('object') }) }) it('should return 201 on POST /api/instruments/:instrumentId/mappings', () => { return request(app) .post('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings') .send({ lowerRank: 55, upperRank: 56, referenceRank: 55, sampleId: '636f247a-dc88-4b52-b8e8-78448b5e5790' }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(201) .then(res => { expect(res.body, 'body should be an object') expect(res.body.lowerRank, 'lowerRank should equal 55').to.equal(55) expect(res.body.upperRank, 'upperRank should equal 56').to.equal(56) expect(res.body.referenceRank, 'referenceRank should equal 55').to.equal(55) expect(res.body.sampleId).to.equal('636f247a-dc88-4b52-b8e8-78448b5e5790', 'sampleId should equal 636f247a-dc88-4b52-b8e8-78448b5e5790') expect(res.body.instrumentId).to.equal('a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45', 'instrumentId should equal a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45') }) }) it('should return 200 GET /api/mappings/:id', () => { return request(app) .get('/api/mappings/1bcab515-ed82-4449-aec9-16a6142b0d15') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res) => { expect(res.body, 'body should be an object').to.be.an('object') expect(res.body.id, 'id should equal 1bcab515-ed82-4449-aec9-16a6142b0d15').to.equal('1bcab515-ed82-4449-aec9-16a6142b0d15') }) }) it('should return 200 on PUT /api/mappings/:id', () => { return request(app) .put('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565') .send({ lowerRank: 45, upperRank: 46, referenceRank: 45, sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892' }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then(res => { expect(res.body.lowerRank, 'lowerRank should equal 45').to.equal(45) expect(res.body.upperRank, 'upperRank should equal 46').to.equal(46) expect(res.body.referenceRank, 'referenceRank should equal 45').to.equal(45) expect(res.body.sampleId).to.equal('0f1ed577-955a-494d-868c-cf4dc5c3c892', 'sampleId should equal 0f1ed577-955a-494d-868c-cf4dc5c3c892') }) }) it('should return 404 on PUT /api/mappings/:id when id is unknown', () => { return request(app) .put('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c') .send({ sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892' }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(404) .then((res) => { expect(res.body, 'body should be a object').to.be.an('object') expect(res.body).to.include({ msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c', name: 'DatabaseError' }) }) }) it('should return 204 on DELETE /api/mappings/:id', () => { return request(app) .delete('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565') .expect(204) .then((res) => { expect(res.body, 'body should be empty').to.be.empty }) }) it('should return 404 on DELETE /api/mappings/:id when id is unknown', () => { return request(app) .delete('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(404) .then((res) => { expect(res.body, 'body should be a object').to.be.an('object') expect(res.body).to.include({ msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c', name: 'DatabaseError' }) }) }) })
lighting-perspectives/jams
server/test/integration/instrument-mappings.test.js
JavaScript
mit
5,577
#include "FunctionCallOperatorNode.h" #include "compiler/Parser/Parser.h" #include "compiler/AST/Variables/VariableNode.h" #include <assert.h> namespace Three { FunctionCallOperatorNode* FunctionCallOperatorNode::parse(Parser& parser, ASTNode* receiver, ASTNode* firstArg) { assert(parser.helper()->peek().type() == Token::Type::PunctuationOpenParen); assert(receiver); FunctionCallOperatorNode* node = new FunctionCallOperatorNode(); node->setReceiver(receiver); if (!CallableOperatorNode::parseArguments(parser, node)) { assert(0 && "Message: Unable to parse function arguments"); } return node; } std::string FunctionCallOperatorNode::nodeName() const { return "Function Call Operator"; } void FunctionCallOperatorNode::accept(ASTVisitor& visitor) { visitor.visit(*this); } }
mattmassicotte/three
compiler/AST/Operators/Callable/FunctionCallOperatorNode.cpp
C++
mit
895
/** * @license Highcharts JS v9.0.1 (2021-02-16) * @module highcharts/modules/dependency-wheel * @requires highcharts * @requires highcharts/modules/sankey * * Dependency wheel module * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/DependencyWheel/DependencyWheelSeries.js';
cdnjs/cdnjs
ajax/libs/highcharts/9.0.1/es-modules/masters/modules/dependency-wheel.src.js
JavaScript
mit
349
/*! * OOUI v0.40.3 * https://www.mediawiki.org/wiki/OOUI * * Copyright 2011–2020 OOUI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2020-09-02T15:42:49Z */ ( function ( OO ) { 'use strict'; /** * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action. * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability * of the actions. * * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * Please see the [OOUI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.mixin.PendingElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method * for more information about setting modes. * @cfg {boolean} [framed=false] Render the action button with a frame */ OO.ui.ActionWidget = function OoUiActionWidget( config ) { // Configuration initialization config = $.extend( { framed: false }, config ); // Parent constructor OO.ui.ActionWidget.super.call( this, config ); // Mixin constructors OO.ui.mixin.PendingElement.call( this, config ); // Properties this.action = config.action || ''; this.modes = config.modes || []; this.width = 0; this.height = 0; // Initialization this.$element.addClass( 'oo-ui-actionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement ); /* Methods */ /** * Check if the action is configured to be available in the specified `mode`. * * @param {string} mode Name of mode * @return {boolean} The action is configured with the mode */ OO.ui.ActionWidget.prototype.hasMode = function ( mode ) { return this.modes.indexOf( mode ) !== -1; }; /** * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * * @return {string} */ OO.ui.ActionWidget.prototype.getAction = function () { return this.action; }; /** * Get the symbolic name of the mode or modes for which the action is configured to be available. * * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method. * Only actions that are configured to be available in the current mode will be visible. * All other actions are hidden. * * @return {string[]} */ OO.ui.ActionWidget.prototype.getModes = function () { return this.modes.slice(); }; /* eslint-disable no-unused-vars */ /** * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that * comprise them. * Actions can be made available for specific contexts (modes) and circumstances * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * * ActionSets contain two types of actions: * * - Special: Special actions are the first visible actions with special flags, such as 'safe' and * 'primary', the default special flags. Additional special flags can be configured in subclasses * with the static #specialFlags property. * - Other: Other actions include all non-special visible actions. * * See the [OOUI documentation on MediaWiki][1] for more information. * * @example * // Example: An action set used in a process dialog * function MyProcessDialog( config ) { * MyProcessDialog.super.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * MyProcessDialog.static.title = 'An action set in a process dialog'; * MyProcessDialog.static.name = 'myProcessDialog'; * // An action set that uses modes ('edit' and 'help' mode, in this example). * MyProcessDialog.static.actions = [ * { * action: 'continue', * modes: 'edit', * label: 'Continue', * flags: [ 'primary', 'progressive' ] * }, * { action: 'help', modes: 'edit', label: 'Help' }, * { modes: 'edit', label: 'Cancel', flags: 'safe' }, * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.super.prototype.initialize.apply( this, arguments ); * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, ' + * 'cancel, back) configured with modes. This is edit mode. Click \'help\' to see ' + * 'help mode.</p>' ); * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget ' + * 'is configured to be visible here. Click \'back\' to return to \'edit\' mode.' + * '</p>' ); * this.stackLayout = new OO.ui.StackLayout( { * items: [ this.panel1, this.panel2 ] * } ); * this.$body.append( this.stackLayout.$element ); * }; * MyProcessDialog.prototype.getSetupProcess = function ( data ) { * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data ) * .next( function () { * this.actions.setMode( 'edit' ); * }, this ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * if ( action === 'help' ) { * this.actions.setMode( 'help' ); * this.stackLayout.setItem( this.panel2 ); * } else if ( action === 'back' ) { * this.actions.setMode( 'edit' ); * this.stackLayout.setItem( this.panel1 ); * } else if ( action === 'continue' ) { * var dialog = this; * return new OO.ui.Process( function () { * dialog.close(); * } ); * } * return MyProcessDialog.super.prototype.getActionProcess.call( this, action ); * }; * MyProcessDialog.prototype.getBodyHeight = function () { * return this.panel1.$element.outerHeight( true ); * }; * var windowManager = new OO.ui.WindowManager(); * $( document.body ).append( windowManager.$element ); * var dialog = new MyProcessDialog( { * size: 'medium' * } ); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets * * @abstract * @class * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ActionSet = function OoUiActionSet( config ) { // Configuration initialization config = config || {}; // Mixin constructors OO.EventEmitter.call( this ); // Properties this.list = []; this.categories = { actions: 'getAction', flags: 'getFlags', modes: 'getModes' }; this.categorized = {}; this.special = {}; this.others = []; this.organized = false; this.changing = false; this.changed = false; }; /* eslint-enable no-unused-vars */ /* Setup */ OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the flags used to identify special actions. Special actions are displayed in the * header of a {@link OO.ui.ProcessDialog process dialog}. * See the [OOUI documentation on MediaWiki][2] for more information and examples. * * [2]:https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs * * @abstract * @static * @inheritable * @property {string} */ OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ]; /* Events */ /** * @event click * * A 'click' event is emitted when an action is clicked. * * @param {OO.ui.ActionWidget} action Action that was clicked */ /** * @event add * * An 'add' event is emitted when actions are {@link #method-add added} to the action set. * * @param {OO.ui.ActionWidget[]} added Actions added */ /** * @event remove * * A 'remove' event is emitted when actions are {@link #method-remove removed} * or {@link #clear cleared}. * * @param {OO.ui.ActionWidget[]} added Actions removed */ /** * @event change * * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared}, * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} * is changed. * */ /* Methods */ /** * Handle action change events. * * @private * @fires change */ OO.ui.ActionSet.prototype.onActionChange = function () { this.organized = false; if ( this.changing ) { this.changed = true; } else { this.emit( 'change' ); } }; /** * Check if an action is one of the special actions. * * @param {OO.ui.ActionWidget} action Action to check * @return {boolean} Action is special */ OO.ui.ActionSet.prototype.isSpecial = function ( action ) { var flag; for ( flag in this.special ) { if ( action === this.special[ flag ] ) { return true; } } return false; }; /** * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’, * or ‘disabled’. * * @param {Object} [filters] Filters to use, omit to get all actions * @param {string|string[]} [filters.actions] Actions that action widgets must have * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe') * @param {string|string[]} [filters.modes] Modes that action widgets must have * @param {boolean} [filters.visible] Action widgets must be visible * @param {boolean} [filters.disabled] Action widgets must be disabled * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria */ OO.ui.ActionSet.prototype.get = function ( filters ) { var i, len, list, category, actions, index, match, matches; if ( filters ) { this.organize(); // Collect category candidates matches = []; for ( category in this.categorized ) { list = filters[ category ]; if ( list ) { if ( !Array.isArray( list ) ) { list = [ list ]; } for ( i = 0, len = list.length; i < len; i++ ) { actions = this.categorized[ category ][ list[ i ] ]; if ( Array.isArray( actions ) ) { matches.push.apply( matches, actions ); } } } } // Remove by boolean filters for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; if ( ( filters.visible !== undefined && match.isVisible() !== filters.visible ) || ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled ) ) { matches.splice( i, 1 ); len--; i--; } } // Remove duplicates for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; index = matches.lastIndexOf( match ); while ( index !== i ) { matches.splice( index, 1 ); len--; index = matches.lastIndexOf( match ); } } return matches; } return this.list.slice(); }; /** * Get 'special' actions. * * Special actions are the first visible action widgets with special flags, such as 'safe' and * 'primary'. * Special flags can be configured in subclasses by changing the static #specialFlags property. * * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets. */ OO.ui.ActionSet.prototype.getSpecial = function () { this.organize(); return $.extend( {}, this.special ); }; /** * Get 'other' actions. * * Other actions include all non-special visible action widgets. * * @return {OO.ui.ActionWidget[]} 'Other' action widgets */ OO.ui.ActionSet.prototype.getOthers = function () { this.organize(); return this.others.slice(); }; /** * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured * to be available in the specified mode will be made visible. All other actions will be hidden. * * @param {string} mode The mode. Only actions configured to be available in the specified * mode will be made visible. * @chainable * @return {OO.ui.ActionSet} The widget, for chaining * @fires toggle * @fires change */ OO.ui.ActionSet.prototype.setMode = function ( mode ) { var i, len, action; this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.toggle( action.hasMode( mode ) ); } this.organized = false; this.changing = false; this.emit( 'change' ); return this; }; /** * Set the abilities of the specified actions. * * Action widgets that are configured with the specified actions will be enabled * or disabled based on the boolean values specified in the `actions` * parameter. * * @param {Object.<string,boolean>} actions A list keyed by action name with boolean * values that indicate whether or not the action should be enabled. * @chainable * @return {OO.ui.ActionSet} The widget, for chaining */ OO.ui.ActionSet.prototype.setAbilities = function ( actions ) { var i, len, action, item; for ( i = 0, len = this.list.length; i < len; i++ ) { item = this.list[ i ]; action = item.getAction(); if ( actions[ action ] !== undefined ) { item.setDisabled( !actions[ action ] ); } } return this; }; /** * Executes a function once per action. * * When making changes to multiple actions, use this method instead of iterating over the actions * manually to defer emitting a #change event until after all actions have been changed. * * @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get * @param {Function} callback Callback to run for each action; callback is invoked with three * arguments: the action, the action's index, the list of actions being iterated over * @chainable * @return {OO.ui.ActionSet} The widget, for chaining */ OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) { this.changed = false; this.changing = true; this.get( filter ).forEach( callback ); this.changing = false; if ( this.changed ) { this.emit( 'change' ); } return this; }; /** * Add action widgets to the action set. * * @param {OO.ui.ActionWidget[]} actions Action widgets to add * @chainable * @return {OO.ui.ActionSet} The widget, for chaining * @fires add * @fires change */ OO.ui.ActionSet.prototype.add = function ( actions ) { var i, len, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; action.connect( this, { click: [ 'emit', 'click', action ], toggle: [ 'onActionChange' ] } ); this.list.push( action ); } this.organized = false; this.emit( 'add', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove action widgets from the set. * * To remove all actions, you may wish to use the #clear method instead. * * @param {OO.ui.ActionWidget[]} actions Action widgets to remove * @chainable * @return {OO.ui.ActionSet} The widget, for chaining * @fires remove * @fires change */ OO.ui.ActionSet.prototype.remove = function ( actions ) { var i, len, index, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; index = this.list.indexOf( action ); if ( index !== -1 ) { action.disconnect( this ); this.list.splice( index, 1 ); } } this.organized = false; this.emit( 'remove', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove all action widgets from the set. * * To remove only specified actions, use the {@link #method-remove remove} method instead. * * @chainable * @return {OO.ui.ActionSet} The widget, for chaining * @fires remove * @fires change */ OO.ui.ActionSet.prototype.clear = function () { var i, len, action, removed = this.list.slice(); this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.disconnect( this ); } this.list = []; this.organized = false; this.emit( 'remove', removed ); this.changing = false; this.emit( 'change' ); return this; }; /** * Organize actions. * * This is called whenever organized information is requested. It will only reorganize the actions * if something has changed since the last time it ran. * * @private * @chainable * @return {OO.ui.ActionSet} The widget, for chaining */ OO.ui.ActionSet.prototype.organize = function () { var i, iLen, j, jLen, flag, action, category, list, item, special, specialFlags = this.constructor.static.specialFlags; if ( !this.organized ) { this.categorized = {}; this.special = {}; this.others = []; for ( i = 0, iLen = this.list.length; i < iLen; i++ ) { action = this.list[ i ]; if ( action.isVisible() ) { // Populate categories for ( category in this.categories ) { if ( !this.categorized[ category ] ) { this.categorized[ category ] = {}; } list = action[ this.categories[ category ] ](); if ( !Array.isArray( list ) ) { list = [ list ]; } for ( j = 0, jLen = list.length; j < jLen; j++ ) { item = list[ j ]; if ( !this.categorized[ category ][ item ] ) { this.categorized[ category ][ item ] = []; } this.categorized[ category ][ item ].push( action ); } } // Populate special/others special = false; for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) { flag = specialFlags[ j ]; if ( !this.special[ flag ] && action.hasFlag( flag ) ) { this.special[ flag ] = action; special = true; break; } } if ( !special ) { this.others.push( action ); } } } this.organized = true; } return this; }; /** * Errors contain a required message (either a string or jQuery selection) that is used to describe * what went wrong in a {@link OO.ui.Process process}. The error's #recoverable and #warning * configurations are used to customize the appearance and functionality of the error interface. * * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' * and 'Try again' (i.e., the error is 'recoverable' by default). If the error is not recoverable, * the 'Try again' button will not be rendered and the widget that initiated the failed process will * be disabled. * * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, * which will try the process again. * * For an example of error interfaces, please see the [OOUI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Processes_and_errors * * @class * * @constructor * @param {string|jQuery} message Description of error * @param {Object} [config] Configuration options * @cfg {boolean} [recoverable=true] Error is recoverable. * By default, errors are recoverable, and users can try the process again. * @cfg {boolean} [warning=false] Error is a warning. * If the error is a warning, the error interface will include a * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the * warning is not triggered a second time if the user chooses to continue. */ OO.ui.Error = function OoUiError( message, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( message ) && config === undefined ) { config = message; message = config.message; } // Configuration initialization config = config || {}; // Properties this.message = message instanceof $ ? message : String( message ); this.recoverable = config.recoverable === undefined || !!config.recoverable; this.warning = !!config.warning; }; /* Setup */ OO.initClass( OO.ui.Error ); /* Methods */ /** * Check if the error is recoverable. * * If the error is recoverable, users are able to try the process again. * * @return {boolean} Error is recoverable */ OO.ui.Error.prototype.isRecoverable = function () { return this.recoverable; }; /** * Check if the error is a warning. * * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button. * * @return {boolean} Error is warning */ OO.ui.Error.prototype.isWarning = function () { return this.warning; }; /** * Get error message as DOM nodes. * * @return {jQuery} Error message in DOM nodes */ OO.ui.Error.prototype.getMessage = function () { return this.message instanceof $ ? this.message.clone() : $( '<div>' ).text( this.message ).contents(); }; /** * Get the error message text. * * @return {string} Error message */ OO.ui.Error.prototype.getMessageText = function () { return this.message instanceof $ ? this.message.text() : this.message; }; /** * A Process is a list of steps that are called in sequence. The step can be a number, a * promise (jQuery, native, or any other “thenable”), or a function: * * - **number**: the process will wait for the specified number of milliseconds before proceeding. * - **promise**: the process will continue to the next step when the promise is successfully * resolved or stop if the promise is rejected. * - **function**: the process will execute the function. The process will stop if the function * returns either a boolean `false` or a promise that is rejected; if the function returns a * number, the process will wait for that number of milliseconds before proceeding. * * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is * configured, users can dismiss the error and try the process again, or not. If a process is * stopped, its remaining steps will not be performed. * * @class * * @constructor * @param {number|jQuery.Promise|Function} step Number of milliseconds to wait before proceeding, * promise that must be resolved before proceeding, or a function to execute. See #createStep for * more information. See #createStep for more information. * @param {Object} [context=null] Execution context of the function. The context is ignored if the * step is a number or promise. */ OO.ui.Process = function ( step, context ) { // Properties this.steps = []; // Initialization if ( step !== undefined ) { this.next( step, context ); } }; /* Setup */ OO.initClass( OO.ui.Process ); /* Methods */ /** * Start the process. * * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed. * If any of the steps return a promise that is rejected or a boolean false, this promise is * rejected and any remaining steps are not performed. */ OO.ui.Process.prototype.execute = function () { var i, len, promise; /** * Continue execution. * * @ignore * @param {Array} step A function and the context it should be called in * @return {Function} Function that continues the process */ function proceed( step ) { return function () { // Execute step in the correct context var deferred, result = step.callback.call( step.context ); if ( result === false ) { // Use rejected promise for boolean false results return $.Deferred().reject( [] ).promise(); } if ( typeof result === 'number' ) { if ( result < 0 ) { throw new Error( 'Cannot go back in time: flux capacitor is out of service' ); } // Use a delayed promise for numbers, expecting them to be in milliseconds deferred = $.Deferred(); setTimeout( deferred.resolve, result ); return deferred.promise(); } if ( result instanceof OO.ui.Error ) { // Use rejected promise for error return $.Deferred().reject( [ result ] ).promise(); } if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) { // Use rejected promise for list of errors return $.Deferred().reject( result ).promise(); } // Duck-type the object to see if it can produce a promise if ( result && typeof result.then === 'function' ) { // Use a promise generated from the result return $.when( result ).promise(); } // Use resolved promise for other results return $.Deferred().resolve().promise(); }; } if ( this.steps.length ) { // Generate a chain reaction of promises promise = proceed( this.steps[ 0 ] )(); for ( i = 1, len = this.steps.length; i < len; i++ ) { promise = promise.then( proceed( this.steps[ i ] ) ); } } else { promise = $.Deferred().resolve().promise(); } return promise; }; /** * Create a process step. * * @private * @param {number|jQuery.Promise|Function} step * * - Number of milliseconds to wait before proceeding * - Promise that must be resolved before proceeding * - Function to execute * - If the function returns a boolean false the process will stop * - If the function returns a promise, the process will continue to the next * step when the promise is resolved or stop if the promise is rejected * - If the function returns a number, the process will wait for that number of * milliseconds before proceeding * @param {Object} [context=null] Execution context of the function. The context is * ignored if the step is a number or promise. * @return {Object} Step object, with `callback` and `context` properties */ OO.ui.Process.prototype.createStep = function ( step, context ) { if ( typeof step === 'number' || typeof step.then === 'function' ) { return { callback: function () { return step; }, context: null }; } if ( typeof step === 'function' ) { return { callback: step, context: context }; } throw new Error( 'Cannot create process step: number, promise or function expected' ); }; /** * Add step to the beginning of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.first = function ( step, context ) { this.steps.unshift( this.createStep( step, context ) ); return this; }; /** * Add step to the end of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.next = function ( step, context ) { this.steps.push( this.createStep( step, context ) ); return this; }; /** * A window instance represents the life cycle for one single opening of a window * until its closing. * * While OO.ui.WindowManager will reuse OO.ui.Window objects, each time a window is * opened, a new lifecycle starts. * * For more information, please see the [OOUI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows * * @class * * @constructor */ OO.ui.WindowInstance = function OoUiWindowInstance() { var deferreds = { opening: $.Deferred(), opened: $.Deferred(), closing: $.Deferred(), closed: $.Deferred() }; /** * @private * @property {Object} */ this.deferreds = deferreds; // Set these up as chained promises so that rejecting of // an earlier stage automatically rejects the subsequent // would-be stages as well. /** * @property {jQuery.Promise} */ this.opening = deferreds.opening.promise(); /** * @property {jQuery.Promise} */ this.opened = this.opening.then( function () { return deferreds.opened; } ); /** * @property {jQuery.Promise} */ this.closing = this.opened.then( function () { return deferreds.closing; } ); /** * @property {jQuery.Promise} */ this.closed = this.closing.then( function () { return deferreds.closed; } ); }; /* Setup */ OO.initClass( OO.ui.WindowInstance ); /** * Check if window is opening. * * @return {boolean} Window is opening */ OO.ui.WindowInstance.prototype.isOpening = function () { return this.deferreds.opened.state() === 'pending'; }; /** * Check if window is opened. * * @return {boolean} Window is opened */ OO.ui.WindowInstance.prototype.isOpened = function () { return this.deferreds.opened.state() === 'resolved' && this.deferreds.closing.state() === 'pending'; }; /** * Check if window is closing. * * @return {boolean} Window is closing */ OO.ui.WindowInstance.prototype.isClosing = function () { return this.deferreds.closing.state() === 'resolved' && this.deferreds.closed.state() === 'pending'; }; /** * Check if window is closed. * * @return {boolean} Window is closed */ OO.ui.WindowInstance.prototype.isClosed = function () { return this.deferreds.closed.state() === 'resolved'; }; /** * Window managers are used to open and close {@link OO.ui.Window windows} and control their * presentation. Managed windows are mutually exclusive. If a new window is opened while a current * window is opening or is opened, the current window will be closed and any on-going * {@link OO.ui.Process process} will be cancelled. Windows * themselves are persistent and—rather than being torn down when closed—can be repopulated with the * pertinent data and reused. * * Over the lifecycle of a window, the window manager makes available three promises: `opening`, * `opened`, and `closing`, which represent the primary stages of the cycle: * * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window. * * - an `opening` event is emitted with an `opening` promise * - the #getSetupDelay method is called and the returned value is used to time a pause in execution * before the window’s {@link OO.ui.Window#method-setup setup} method is called which executes * OO.ui.Window#getSetupProcess. * - a `setup` progress notification is emitted from the `opening` promise * - the #getReadyDelay method is called the returned value is used to time a pause in execution * before the window’s {@link OO.ui.Window#method-ready ready} method is called which executes * OO.ui.Window#getReadyProcess. * - a `ready` progress notification is emitted from the `opening` promise * - the `opening` promise is resolved with an `opened` promise * * **Opened**: the window is now open. * * **Closing**: the closing stage begins when the window manager's #closeWindow or the * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins * to close the window. * * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted * - the #getHoldDelay method is called and the returned value is used to time a pause in execution * before the window's {@link OO.ui.Window#getHoldProcess getHoldProcess} method is called on the * window and its result executed * - a `hold` progress notification is emitted from the `closing` promise * - the #getTeardownDelay() method is called and the returned value is used to time a pause in * execution before the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method * is called on the window and its result executed * - a `teardown` progress notification is emitted from the `closing` promise * - the `closing` promise is resolved. The window is now closed * * See the [OOUI documentation on MediaWiki][1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation * Note that window classes that are instantiated with a factory must have * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name. * @cfg {boolean} [modal=true] Prevent interaction outside the dialog */ OO.ui.WindowManager = function OoUiWindowManager( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.WindowManager.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.factory = config.factory; this.modal = config.modal === undefined || !!config.modal; this.windows = {}; // Deprecated placeholder promise given to compatOpening in openWindow() // that is resolved in closeWindow(). this.compatOpened = null; this.preparingToOpen = null; this.preparingToClose = null; this.currentWindow = null; this.globalEvents = false; this.$returnFocusTo = null; this.$ariaHidden = null; this.onWindowResizeTimeout = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); this.afterWindowResizeHandler = this.afterWindowResize.bind( this ); // Initialization this.$element .addClass( 'oo-ui-windowManager' ) .toggleClass( 'oo-ui-windowManager-modal', this.modal ); if ( this.modal ) { this.$element.attr( 'aria-hidden', true ); } }; /* Setup */ OO.inheritClass( OO.ui.WindowManager, OO.ui.Element ); OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter ); /* Events */ /** * An 'opening' event is emitted when the window begins to be opened. * * @event opening * @param {OO.ui.Window} win Window that's being opened * @param {jQuery.Promise} opened A promise resolved with a value when the window is opened * successfully. This promise also emits `setup` and `ready` notifications. When this promise is * resolved, the first argument of the value is an 'closed' promise, the second argument is the * opening data. * @param {Object} data Window opening data */ /** * A 'closing' event is emitted when the window begins to be closed. * * @event closing * @param {OO.ui.Window} win Window that's being closed * @param {jQuery.Promise} closed A promise resolved with a value when the window is closed * successfully. This promise also emits `hold` and `teardown` notifications. When this promise is * resolved, the first argument of its value is the closing data. * @param {Object} data Window closing data */ /** * A 'resize' event is emitted when a window is resized. * * @event resize * @param {OO.ui.Window} win Window that was resized */ /* Static Properties */ /** * Map of the symbolic name of each window size and its CSS properties. * * @static * @inheritable * @property {Object} */ OO.ui.WindowManager.static.sizes = { small: { width: 300 }, medium: { width: 500 }, large: { width: 700 }, larger: { width: 900 }, full: { // These can be non-numeric because they are never used in calculations width: '100%', height: '100%' } }; /** * Symbolic name of the default window size. * * The default size is used if the window's requested size is not recognized. * * @static * @inheritable * @property {string} */ OO.ui.WindowManager.static.defaultSize = 'medium'; /* Methods */ /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.onWindowResize = function () { clearTimeout( this.onWindowResizeTimeout ); this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 ); }; /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.afterWindowResize = function () { var currentFocusedElement = document.activeElement; if ( this.currentWindow ) { this.updateWindowSize( this.currentWindow ); // Restore focus to the original element if it has changed. // When a layout change is made on resize inputs lose focus // on Android (Chrome and Firefox), see T162127. if ( currentFocusedElement !== document.activeElement ) { currentFocusedElement.focus(); } } }; /** * Check if window is opening. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is opening */ OO.ui.WindowManager.prototype.isOpening = function ( win ) { return win === this.currentWindow && !!this.lifecycle && this.lifecycle.isOpening(); }; /** * Check if window is closing. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is closing */ OO.ui.WindowManager.prototype.isClosing = function ( win ) { return win === this.currentWindow && !!this.lifecycle && this.lifecycle.isClosing(); }; /** * Check if window is opened. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is opened */ OO.ui.WindowManager.prototype.isOpened = function ( win ) { return win === this.currentWindow && !!this.lifecycle && this.lifecycle.isOpened(); }; /** * Check if a window is being managed. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is being managed */ OO.ui.WindowManager.prototype.hasWindow = function ( win ) { var name; for ( name in this.windows ) { if ( this.windows[ name ] === win ) { return true; } } return false; }; /** * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getSetupDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ * process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getReadyDelay = function () { return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0; }; /** * Get the number of milliseconds to wait after closing has begun before executing the 'hold' * process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getHoldDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after the ‘hold’ process has finished before * executing the ‘teardown’ process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getTeardownDelay = function () { return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0; }; /** * Get a window by its symbolic name. * * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will * be instantiated and added to the window manager automatically. Please see the [OOUI documentation * on MediaWiki][3] for more information about using factories. * [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers * * @param {string} name Symbolic name of the window * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory. * @throws {Error} An error is thrown if the named window is not recognized as a managed window. */ OO.ui.WindowManager.prototype.getWindow = function ( name ) { var deferred = $.Deferred(), win = this.windows[ name ]; if ( !( win instanceof OO.ui.Window ) ) { if ( this.factory ) { if ( !this.factory.lookup( name ) ) { deferred.reject( new OO.ui.Error( 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory' ) ); } else { win = this.factory.create( name ); this.addWindows( [ win ] ); deferred.resolve( win ); } } else { deferred.reject( new OO.ui.Error( 'Cannot get unmanaged window: symbolic name unrecognized as a managed window' ) ); } } else { deferred.resolve( win ); } return deferred.promise(); }; /** * Get current window. * * @return {OO.ui.Window|null} Currently opening/opened/closing window */ OO.ui.WindowManager.prototype.getCurrentWindow = function () { return this.currentWindow; }; /** * Open a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to open * @param {Object} [data] Window opening data * @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when * closed. Defaults the current activeElement. If set to null, focus isn't changed on close. * @param {OO.ui.WindowInstance} [lifecycle] Used internally * @param {jQuery.Deferred} [compatOpening] Used internally * @return {OO.ui.WindowInstance} A lifecycle object representing this particular * opening of the window. For backwards-compatibility, then object is also a Thenable that is * resolved when the window is done opening, with nested promise for when closing starts. This * behaviour is deprecated and is not compatible with jQuery 3, see T163510. * @fires opening */ OO.ui.WindowManager.prototype.openWindow = function ( win, data, lifecycle, compatOpening ) { var error, manager = this; data = data || {}; // Internal parameter 'lifecycle' allows this method to always return // a lifecycle even if the window still needs to be created // asynchronously when 'win' is a string. lifecycle = lifecycle || new OO.ui.WindowInstance(); compatOpening = compatOpening || $.Deferred(); // Turn lifecycle into a Thenable for backwards-compatibility with // the deprecated nested-promise behaviour, see T163510. [ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ] .forEach( function ( method ) { lifecycle[ method ] = function () { OO.ui.warnDeprecation( 'Using the return value of openWindow as a promise is deprecated. ' + 'Use .openWindow( ... ).opening.' + method + '( ... ) instead.' ); return compatOpening[ method ].apply( this, arguments ); }; } ); // Argument handling if ( typeof win === 'string' ) { this.getWindow( win ).then( function ( w ) { manager.openWindow( w, data, lifecycle, compatOpening ); }, function ( err ) { lifecycle.deferreds.opening.reject( err ); } ); return lifecycle; } // Error handling if ( !this.hasWindow( win ) ) { error = 'Cannot open window: window is not attached to manager'; } else if ( this.lifecycle && this.lifecycle.isOpened() ) { error = 'Cannot open window: another window is open'; } else if ( this.preparingToOpen || ( this.lifecycle && this.lifecycle.isOpening() ) ) { error = 'Cannot open window: another window is opening'; } if ( error ) { compatOpening.reject( new OO.ui.Error( error ) ); lifecycle.deferreds.opening.reject( new OO.ui.Error( error ) ); return lifecycle; } // If a window is currently closing, wait for it to complete this.preparingToOpen = $.when( this.lifecycle && this.lifecycle.closed ); // Ensure handlers get called after preparingToOpen is set this.preparingToOpen.done( function () { if ( manager.modal ) { manager.toggleGlobalEvents( true ); manager.toggleAriaIsolation( true ); } manager.$returnFocusTo = data.$returnFocusTo !== undefined ? data.$returnFocusTo : $( document.activeElement ); manager.currentWindow = win; manager.lifecycle = lifecycle; manager.preparingToOpen = null; manager.emit( 'opening', win, compatOpening, data ); lifecycle.deferreds.opening.resolve( data ); setTimeout( function () { manager.compatOpened = $.Deferred(); win.setup( data ).then( function () { compatOpening.notify( { state: 'setup' } ); setTimeout( function () { win.ready( data ).then( function () { compatOpening.notify( { state: 'ready' } ); lifecycle.deferreds.opened.resolve( data ); compatOpening.resolve( manager.compatOpened.promise(), data ); manager.togglePreventIosScrolling( true ); }, function ( dataOrErr ) { lifecycle.deferreds.opened.reject(); compatOpening.reject(); manager.closeWindow( win ); if ( dataOrErr instanceof Error ) { setTimeout( function () { throw dataOrErr; } ); } } ); }, manager.getReadyDelay() ); }, function ( dataOrErr ) { lifecycle.deferreds.opened.reject(); compatOpening.reject(); manager.closeWindow( win ); if ( dataOrErr instanceof Error ) { setTimeout( function () { throw dataOrErr; } ); } } ); }, manager.getSetupDelay() ); } ); return lifecycle; }; /** * Close a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to close * @param {Object} [data] Window closing data * @return {OO.ui.WindowInstance} A lifecycle object representing this particular * opening of the window. For backwards-compatibility, the object is also a Thenable that is * resolved when the window is done closing, see T163510. * @fires closing */ OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) { var error, manager = this, compatClosing = $.Deferred(), lifecycle = this.lifecycle, compatOpened; // Argument handling if ( typeof win === 'string' ) { win = this.windows[ win ]; } else if ( !this.hasWindow( win ) ) { win = null; } // Error handling if ( !lifecycle ) { error = 'Cannot close window: no window is currently open'; } else if ( !win ) { error = 'Cannot close window: window is not attached to manager'; } else if ( win !== this.currentWindow || this.lifecycle.isClosed() ) { error = 'Cannot close window: window already closed with different data'; } else if ( this.preparingToClose || this.lifecycle.isClosing() ) { error = 'Cannot close window: window already closing with different data'; } if ( error ) { // This function was called for the wrong window and we don't want to mess with the current // window's state. lifecycle = new OO.ui.WindowInstance(); // Pretend the window has been opened, so that we can pretend to fail to close it. lifecycle.deferreds.opening.resolve( {} ); lifecycle.deferreds.opened.resolve( {} ); } // Turn lifecycle into a Thenable for backwards-compatibility with // the deprecated nested-promise behaviour, see T163510. [ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ] .forEach( function ( method ) { lifecycle[ method ] = function () { OO.ui.warnDeprecation( 'Using the return value of closeWindow as a promise is deprecated. ' + 'Use .closeWindow( ... ).closed.' + method + '( ... ) instead.' ); return compatClosing[ method ].apply( this, arguments ); }; } ); if ( error ) { compatClosing.reject( new OO.ui.Error( error ) ); lifecycle.deferreds.closing.reject( new OO.ui.Error( error ) ); return lifecycle; } // If the window is currently opening, close it when it's done this.preparingToClose = $.when( this.lifecycle.opened ); // Ensure handlers get called after preparingToClose is set this.preparingToClose.always( function () { manager.preparingToClose = null; manager.emit( 'closing', win, compatClosing, data ); lifecycle.deferreds.closing.resolve( data ); compatOpened = manager.compatOpened; manager.compatOpened = null; compatOpened.resolve( compatClosing.promise(), data ); manager.togglePreventIosScrolling( false ); setTimeout( function () { win.hold( data ).then( function () { compatClosing.notify( { state: 'hold' } ); setTimeout( function () { win.teardown( data ).then( function () { compatClosing.notify( { state: 'teardown' } ); if ( manager.modal ) { manager.toggleGlobalEvents( false ); manager.toggleAriaIsolation( false ); } if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) { manager.$returnFocusTo[ 0 ].focus(); } manager.currentWindow = null; manager.lifecycle = null; lifecycle.deferreds.closed.resolve( data ); compatClosing.resolve( data ); } ); }, manager.getTeardownDelay() ); } ); }, manager.getHoldDelay() ); } ); return lifecycle; }; /** * Add windows to the window manager. * * Windows can be added by reference, symbolic name, or explicitly defined symbolic names. * See the [OOUI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers * * This function can be called in two manners: * * 1. `.addWindows( [ winA, winB, ... ] )` (where `winA`, `winB` are OO.ui.Window objects) * * This syntax registers windows under the symbolic names defined in their `.static.name` * properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling * `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the * static name to be set, otherwise an exception will be thrown. * * This is the recommended way, as it allows for an easier switch to using a window factory. * * 2. `.addWindows( { nameA: winA, nameB: winB, ... } )` * * This syntax registers windows under the explicitly given symbolic names. In this example, * calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what * its `.static.name` is set to. The static name is not required to be set. * * This should only be used if you need to override the default symbolic names. * * Example: * * var windowManager = new OO.ui.WindowManager(); * $( document.body ).append( windowManager.$element ); * * // Add a window under the default name: see OO.ui.MessageDialog.static.name * windowManager.addWindows( [ new OO.ui.MessageDialog() ] ); * // Add a window under an explicit name * windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } ); * * // Open window by default name * windowManager.openWindow( 'message' ); * // Open window by explicitly given name * windowManager.openWindow( 'myMessageDialog' ); * * * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified * by reference, symbolic name, or explicitly defined symbolic names. * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an * explicit nor a statically configured symbolic name. */ OO.ui.WindowManager.prototype.addWindows = function ( windows ) { var i, len, win, name, list; if ( Array.isArray( windows ) ) { // Convert to map of windows by looking up symbolic names from static configuration list = {}; for ( i = 0, len = windows.length; i < len; i++ ) { name = windows[ i ].constructor.static.name; if ( !name ) { throw new Error( 'Windows must have a `name` static property defined.' ); } list[ name ] = windows[ i ]; } } else if ( OO.isPlainObject( windows ) ) { list = windows; } // Add windows for ( name in list ) { win = list[ name ]; this.windows[ name ] = win.toggle( false ); this.$element.append( win.$element ); win.setManager( this ); } }; /** * Remove the specified windows from the windows manager. * * Windows will be closed before they are removed. If you wish to remove all windows, you may wish * to use the #clearWindows method instead. If you no longer need the window manager and want to * ensure that it no longer listens to events, use the #destroy method. * * @param {string[]} names Symbolic names of windows to remove * @return {jQuery.Promise} Promise resolved when window is closed and removed * @throws {Error} An error is thrown if the named windows are not managed by the window manager. */ OO.ui.WindowManager.prototype.removeWindows = function ( names ) { var promises, manager = this; function cleanup( name, win ) { delete manager.windows[ name ]; win.$element.detach(); } promises = names.map( function ( name ) { var cleanupWindow, win = manager.windows[ name ]; if ( !win ) { throw new Error( 'Cannot remove window' ); } cleanupWindow = cleanup.bind( null, name, win ); return manager.closeWindow( name ).closed.then( cleanupWindow, cleanupWindow ); } ); return $.when.apply( $, promises ); }; /** * Remove all windows from the window manager. * * Windows will be closed before they are removed. Note that the window manager, though not in use, * will still listen to events. If the window manager will not be used again, you may wish to use * the #destroy method instead. To remove just a subset of windows, use the #removeWindows method. * * @return {jQuery.Promise} Promise resolved when all windows are closed and removed */ OO.ui.WindowManager.prototype.clearWindows = function () { return this.removeWindows( Object.keys( this.windows ) ); }; /** * Set dialog size. In general, this method should not be called directly. * * Fullscreen mode will be used if the dialog is too wide to fit in the screen. * * @param {OO.ui.Window} win Window to update, should be the current window * @chainable * @return {OO.ui.WindowManager} The manager, for chaining */ OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) { var isFullscreen; // Bypass for non-current, and thus invisible, windows if ( win !== this.currentWindow ) { return; } isFullscreen = win.getSize() === 'full'; this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen ); this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen ); win.setDimensions( win.getSizeProperties() ); this.emit( 'resize', win ); return this; }; /** * Prevent scrolling of the document on iOS devices that don't respect `body { overflow: hidden; }`. * * This function is called when the window is opened (ready), and so the background is covered up, * and the user won't see that we're doing weird things to the scroll position. * * @private * @param {boolean} on * @chainable * @return {OO.ui.WindowManager} The manager, for chaining */ OO.ui.WindowManager.prototype.togglePreventIosScrolling = function ( on ) { var isIos = /ipad|iphone|ipod/i.test( navigator.userAgent ), $body = $( this.getElementDocument().body ), scrollableRoot = OO.ui.Element.static.getRootScrollableElement( $body[ 0 ] ), stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0; // Only if this is the first/last WindowManager (see #toggleGlobalEvents) if ( !isIos || stackDepth !== 1 ) { return this; } if ( on ) { // We can't apply this workaround for non-fullscreen dialogs, because the user would see the // scroll position change. If they have content that needs scrolling, you're out of luck… // Always remember the scroll position in case dialog is closed with different size. this.iosOrigScrollPosition = scrollableRoot.scrollTop; if ( this.getCurrentWindow().getSize() === 'full' ) { $body.add( $body.parent() ).addClass( 'oo-ui-windowManager-ios-modal-ready' ); } } else { // Always restore ability to scroll in case dialog was opened with different size. $body.add( $body.parent() ).removeClass( 'oo-ui-windowManager-ios-modal-ready' ); if ( this.getCurrentWindow().getSize() === 'full' ) { scrollableRoot.scrollTop = this.iosOrigScrollPosition; } } return this; }; /** * Bind or unbind global events for scrolling. * * @private * @param {boolean} [on] Bind global events * @chainable * @return {OO.ui.WindowManager} The manager, for chaining */ OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) { var scrollWidth, bodyMargin, $body = $( this.getElementDocument().body ), // We could have multiple window managers open so only modify // the body css at the bottom of the stack stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0; on = on === undefined ? !!this.globalEvents : !!on; if ( on ) { if ( !this.globalEvents ) { $( this.getElementWindow() ).on( { // Start listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); if ( stackDepth === 0 ) { scrollWidth = window.innerWidth - document.documentElement.clientWidth; bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0; $body.addClass( 'oo-ui-windowManager-modal-active' ); $body.css( 'margin-right', bodyMargin + scrollWidth ); } stackDepth++; this.globalEvents = true; } } else if ( this.globalEvents ) { $( this.getElementWindow() ).off( { // Stop listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); stackDepth--; if ( stackDepth === 0 ) { $body.removeClass( 'oo-ui-windowManager-modal-active' ); $body.css( 'margin-right', '' ); } this.globalEvents = false; } $body.data( 'windowManagerGlobalEvents', stackDepth ); return this; }; /** * Toggle screen reader visibility of content other than the window manager. * * @private * @param {boolean} [isolate] Make only the window manager visible to screen readers * @chainable * @return {OO.ui.WindowManager} The manager, for chaining */ OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) { var $topLevelElement; isolate = isolate === undefined ? !this.$ariaHidden : !!isolate; if ( isolate ) { if ( !this.$ariaHidden ) { // Find the top level element containing the window manager or the // window manager's element itself in case its a direct child of body $topLevelElement = this.$element.parentsUntil( 'body' ).last(); $topLevelElement = $topLevelElement.length === 0 ? this.$element : $topLevelElement; // In case previously set by another window manager this.$element.removeAttr( 'aria-hidden' ); // Hide everything other than the window manager from screen readers this.$ariaHidden = $( document.body ) .children() .not( 'script' ) .not( $topLevelElement ) .attr( 'aria-hidden', true ); } } else if ( this.$ariaHidden ) { // Restore screen reader visibility this.$ariaHidden.removeAttr( 'aria-hidden' ); this.$ariaHidden = null; // and hide the window manager this.$element.attr( 'aria-hidden', true ); } return this; }; /** * Destroy the window manager. * * Destroying the window manager ensures that it will no longer listen to events. If you would like * to continue using the window manager, but wish to remove all windows from it, use the * #clearWindows method instead. */ OO.ui.WindowManager.prototype.destroy = function () { this.toggleGlobalEvents( false ); this.toggleAriaIsolation( false ); this.clearWindows(); this.$element.remove(); }; /** * A window is a container for elements that are in a child frame. They are used with * a window manager (OO.ui.WindowManager), which is used to open and close the window and control * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, * ‘medium’, ‘large’), which is interpreted by the window manager. If the requested size is not * recognized, the window manager will choose a sensible fallback. * * The lifecycle of a window has three primary stages (opening, opened, and closing) in which * different processes are executed: * * **opening**: The opening stage begins when the window manager's * {@link OO.ui.WindowManager#openWindow openWindow} or the window's {@link #open open} methods are * used, and the window manager begins to open the window. * * - {@link #getSetupProcess} method is called and its result executed * - {@link #getReadyProcess} method is called and its result executed * * **opened**: The window is now open * * **closing**: The closing stage begins when the window manager's * {@link OO.ui.WindowManager#closeWindow closeWindow} * or the window's {@link #close} methods are used, and the window manager begins to close the * window. * * - {@link #getHoldProcess} method is called and its result executed * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed * * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and * #getTeardownProcess methods. Note that each {@link OO.ui.Process process} is executed in series, * so asynchronous processing can complete. Always assume window processes are executed * asynchronously. * * For more information, please see the [OOUI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or * `full`. If omitted, the value of the {@link #static-size static size} property will be used. */ OO.ui.Window = function OoUiWindow( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Window.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.manager = null; this.size = config.size || this.constructor.static.size; this.$frame = $( '<div>' ); /** * Overlay element to use for the `$overlay` configuration option of widgets that support it. * Things put inside it are overlaid on top of the window and are not bound to its dimensions. * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>. * * MyDialog.prototype.initialize = function () { * ... * var popupButton = new OO.ui.PopupButtonWidget( { * $overlay: this.$overlay, * label: 'Popup button', * popup: { * $content: $( '<p>Popup content.</p><p>More content.</p><p>Yet more content.</p>' ), * padded: true * } * } ); * ... * }; * * @property {jQuery} */ this.$overlay = $( '<div>' ); this.$content = $( '<div>' ); this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 ); this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 ); this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter ); // Initialization this.$overlay.addClass( 'oo-ui-window-overlay' ); this.$content .addClass( 'oo-ui-window-content' ) .attr( 'tabindex', -1 ); this.$frame .addClass( 'oo-ui-window-frame' ) .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter ); this.$element .addClass( 'oo-ui-window' ) .append( this.$frame, this.$overlay ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.Window, OO.ui.Element ); OO.mixinClass( OO.ui.Window, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`. * * The static size is used if no #size is configured during construction. * * @static * @inheritable * @property {string} */ OO.ui.Window.static.size = 'medium'; /* Methods */ /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.onMouseDown = function ( e ) { // Prevent clicking on the click-block from stealing focus if ( e.target === this.$element[ 0 ] ) { return false; } }; /** * Check if the window has been initialized. * * Initialization occurs when a window is added to a manager. * * @return {boolean} Window has been initialized */ OO.ui.Window.prototype.isInitialized = function () { return !!this.manager; }; /** * Check if the window is visible. * * @return {boolean} Window is visible */ OO.ui.Window.prototype.isVisible = function () { return this.visible; }; /** * Check if the window is opening. * * This method is a wrapper around the window manager's * {@link OO.ui.WindowManager#isOpening isOpening} method. * * @return {boolean} Window is opening */ OO.ui.Window.prototype.isOpening = function () { return this.manager.isOpening( this ); }; /** * Check if the window is closing. * * This method is a wrapper around the window manager's * {@link OO.ui.WindowManager#isClosing isClosing} method. * * @return {boolean} Window is closing */ OO.ui.Window.prototype.isClosing = function () { return this.manager.isClosing( this ); }; /** * Check if the window is opened. * * This method is a wrapper around the window manager's * {@link OO.ui.WindowManager#isOpened isOpened} method. * * @return {boolean} Window is opened */ OO.ui.Window.prototype.isOpened = function () { return this.manager.isOpened( this ); }; /** * Get the window manager. * * All windows must be attached to a window manager, which is used to open * and close the window and control its presentation. * * @return {OO.ui.WindowManager} Manager of window */ OO.ui.Window.prototype.getManager = function () { return this.manager; }; /** * Get the symbolic name of the window size (e.g., `small` or `medium`). * * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full` */ OO.ui.Window.prototype.getSize = function () { var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ), sizes = this.manager.constructor.static.sizes, size = this.size; if ( !sizes[ size ] ) { size = this.manager.constructor.static.defaultSize; } if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) { size = 'full'; } return size; }; /** * Get the size properties associated with the current window size * * @return {Object} Size properties */ OO.ui.Window.prototype.getSizeProperties = function () { return this.manager.constructor.static.sizes[ this.getSize() ]; }; /** * Disable transitions on window's frame for the duration of the callback function, then enable them * back. * * @private * @param {Function} callback Function to call while transitions are disabled */ OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) { // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. // We need to build the transition CSS properties using these specific properties since // Firefox doesn't return anything useful when asked just for 'transition'. var oldTransition = this.$frame.css( 'transition-property' ) + ' ' + this.$frame.css( 'transition-duration' ) + ' ' + this.$frame.css( 'transition-timing-function' ) + ' ' + this.$frame.css( 'transition-delay' ); this.$frame.css( 'transition', 'none' ); callback(); // Force reflow to make sure the style changes done inside callback // really are not transitioned this.$frame.height(); this.$frame.css( 'transition', oldTransition ); }; /** * Get the height of the full window contents (i.e., the window head, body and foot together). * * What constitutes the head, body, and foot varies depending on the window type. * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body, * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title * and special actions in the head, and dialog content in the body. * * To get just the height of the dialog body, use the #getBodyHeight method. * * @return {number} The height of the window contents (the dialog head, body and foot) in pixels */ OO.ui.Window.prototype.getContentHeight = function () { var bodyHeight, win = this, bodyStyleObj = this.$body[ 0 ].style, frameStyleObj = this.$frame[ 0 ].style; // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. this.withoutSizeTransitions( function () { var oldHeight = frameStyleObj.height, oldPosition = bodyStyleObj.position; frameStyleObj.height = '1px'; // Force body to resize to new width bodyStyleObj.position = 'relative'; bodyHeight = win.getBodyHeight(); frameStyleObj.height = oldHeight; bodyStyleObj.position = oldPosition; } ); return ( // Add buffer for border ( this.$frame.outerHeight() - this.$frame.innerHeight() ) + // Use combined heights of children ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) ) ); }; /** * Get the height of the window body. * * To get the height of the full window contents (the window body, head, and foot together), * use #getContentHeight. * * When this function is called, the window will temporarily have been resized * to height=1px, so .scrollHeight measurements can be taken accurately. * * @return {number} Height of the window body in pixels */ OO.ui.Window.prototype.getBodyHeight = function () { return this.$body[ 0 ].scrollHeight; }; /** * Get the directionality of the frame (right-to-left or left-to-right). * * @return {string} Directionality: `'ltr'` or `'rtl'` */ OO.ui.Window.prototype.getDir = function () { return OO.ui.Element.static.getDir( this.$content ) || 'ltr'; }; /** * Get the 'setup' process. * * The setup process is used to set up a window for use in a particular context, based on the `data` * argument. This method is called during the opening phase of the window’s lifecycle (before the * opening animation). You can add elements to the window in this process or set their default * values. * * Override this method to add additional steps to the ‘setup’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * To add window content that persists between openings, you may wish to use the #initialize method * instead. * * @param {Object} [data] Window opening data * @return {OO.ui.Process} Setup process */ OO.ui.Window.prototype.getSetupProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘ready’ process. * * The ready process is used to ready a window for use in a particular context, based on the `data` * argument. This method is called during the opening phase of the window’s lifecycle, after the * window has been {@link #getSetupProcess setup} (after the opening animation). You can focus * elements in the window in this process, or open their dropdowns. * * Override this method to add additional steps to the ‘ready’ process the parent method * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} * methods of OO.ui.Process. * * @param {Object} [data] Window opening data * @return {OO.ui.Process} Ready process */ OO.ui.Window.prototype.getReadyProcess = function () { return new OO.ui.Process(); }; /** * Get the 'hold' process. * * The hold process is used to keep a window from being used in a particular context, based on the * `data` argument. This method is called during the closing phase of the window’s lifecycle (before * the closing animation). You can close dropdowns of elements in the window in this process, if * they do not get closed automatically. * * Override this method to add additional steps to the 'hold' process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @param {Object} [data] Window closing data * @return {OO.ui.Process} Hold process */ OO.ui.Window.prototype.getHoldProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘teardown’ process. * * The teardown process is used to teardown a window after use. During teardown, user interactions * within the window are conveyed and the window is closed, based on the `data` argument. This * method is called during the closing phase of the window’s lifecycle (after the closing * animation). You can remove elements in the window in this process or clear their values. * * Override this method to add additional steps to the ‘teardown’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @param {Object} [data] Window closing data * @return {OO.ui.Process} Teardown process */ OO.ui.Window.prototype.getTeardownProcess = function () { return new OO.ui.Process(); }; /** * Set the window manager. * * This will cause the window to initialize. Calling it more than once will cause an error. * * @param {OO.ui.WindowManager} manager Manager for this window * @throws {Error} An error is thrown if the method is called more than once * @chainable * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.setManager = function ( manager ) { if ( this.manager ) { throw new Error( 'Cannot set window manager, window already has a manager' ); } this.manager = manager; this.initialize(); return this; }; /** * Set the window size by symbolic name (e.g., 'small' or 'medium') * * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or * `full` * @chainable * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.setSize = function ( size ) { this.size = size; this.updateSize(); return this; }; /** * Update the window size. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.updateSize = function () { if ( !this.manager ) { throw new Error( 'Cannot update window size, must be attached to a manager' ); } this.manager.updateWindowSize( this ); return this; }; /** * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager} * when the window is opening. In general, setDimensions should not be called directly. * * To set the size of the window, use the #setSize method. * * @param {Object} dim CSS dimension properties * @param {string|number} [dim.width] Width * @param {string|number} [dim.minWidth] Minimum width * @param {string|number} [dim.maxWidth] Maximum width * @param {string|number} [dim.height] Height, omit to set based on height of contents * @param {string|number} [dim.minHeight] Minimum height * @param {string|number} [dim.maxHeight] Maximum height * @chainable * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.setDimensions = function ( dim ) { var height, win = this, styleObj = this.$frame[ 0 ].style; // Calculate the height we need to set using the correct width if ( dim.height === undefined ) { this.withoutSizeTransitions( function () { var oldWidth = styleObj.width; win.$frame.css( 'width', dim.width || '' ); height = win.getContentHeight(); styleObj.width = oldWidth; } ); } else { height = dim.height; } this.$frame.css( { width: dim.width || '', minWidth: dim.minWidth || '', maxWidth: dim.maxWidth || '', height: height || '', minHeight: dim.minHeight || '', maxHeight: dim.maxHeight || '' } ); return this; }; /** * Initialize window contents. * * Before the window is opened for the first time, #initialize is called so that content that * persists between openings can be added to the window. * * To set up a window with new content each time the window opens, use #getSetupProcess. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable * @return {OO.ui.Window} The window, for chaining */ OO.ui.Window.prototype.initialize = function () { if ( !this.manager ) { throw new Error( 'Cannot initialize window, must be attached to a manager' ); } // Properties this.$head = $( '<div>' ); this.$body = $( '<div>' ); this.$foot = $( '<div>' ); this.$document = $( this.getElementDocument() ); // Events this.$element.on( 'mousedown', this.onMouseDown.bind( this ) ); // Initialization this.$head.addClass( 'oo-ui-window-head' ); this.$body.addClass( 'oo-ui-window-body' ); this.$foot.addClass( 'oo-ui-window-foot' ); this.$content.append( this.$head, this.$body, this.$foot ); return this; }; /** * Called when someone tries to focus the hidden element at the end of the dialog. * Sends focus back to the start of the dialog. * * @param {jQuery.Event} event Focus event */ OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) { var backwards = this.$focusTrapBefore.is( event.target ), element = OO.ui.findFocusable( this.$content, backwards ); if ( element ) { // There's a focusable element inside the content, at the front or // back depending on which focus trap we hit; select it. element.focus(); } else { // There's nothing focusable inside the content. As a fallback, // this.$content is focusable, and focusing it will keep our focus // properly trapped. It's not a *meaningful* focus, since it's just // the content-div for the Window, but it's better than letting focus // escape into the page. this.$content.trigger( 'focus' ); } }; /** * Open the window. * * This method is a wrapper around a call to the window * manager’s {@link OO.ui.WindowManager#openWindow openWindow} method. * * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess. * * @param {Object} [data] Window opening data * @return {OO.ui.WindowInstance} See OO.ui.WindowManager#openWindow * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.open = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot open window, must be attached to a manager' ); } return this.manager.openWindow( this, data ); }; /** * Close the window. * * This method is a wrapper around a call to the window * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method. * * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing * phase of the window’s lifecycle and can be used to specify closing behavior each time * the window closes. * * @param {Object} [data] Window closing data * @return {OO.ui.WindowInstance} See OO.ui.WindowManager#closeWindow * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.close = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot close window, must be attached to a manager' ); } return this.manager.closeWindow( this, data ); }; /** * Setup window. * * This is called by OO.ui.WindowManager during window opening (before the animation), and should * not be called directly by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is setup */ OO.ui.Window.prototype.setup = function ( data ) { var win = this; this.toggle( true ); this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this ); this.$focusTraps.on( 'focus', this.focusTrapHandler ); return this.getSetupProcess( data ).execute().then( function () { win.updateSize(); // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width(); win.$content.addClass( 'oo-ui-window-content-setup' ).width(); } ); }; /** * Ready window. * * This is called by OO.ui.WindowManager during window opening (after the animation), and should not * be called directly by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is ready */ OO.ui.Window.prototype.ready = function ( data ) { var win = this; this.$content.trigger( 'focus' ); return this.getReadyProcess( data ).execute().then( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-ready' ).width(); win.$content.addClass( 'oo-ui-window-content-ready' ).width(); } ); }; /** * Hold window. * * This is called by OO.ui.WindowManager during window closing (before the animation), and should * not be called directly by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is held */ OO.ui.Window.prototype.hold = function ( data ) { var win = this; return this.getHoldProcess( data ).execute().then( function () { // Get the focused element within the window's content var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement ); // Blur the focused element if ( $focus.length ) { $focus[ 0 ].blur(); } // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-ready oo-ui-window-setup' ).width(); win.$content.removeClass( 'oo-ui-window-content-ready oo-ui-window-content-setup' ).width(); } ); }; /** * Teardown window. * * This is called by OO.ui.WindowManager during window closing (after the animation), and should not * be called directly by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is torn down */ OO.ui.Window.prototype.teardown = function ( data ) { var win = this; return this.getTeardownProcess( data ).execute().then( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-active' ).width(); win.$focusTraps.off( 'focus', win.focusTrapHandler ); win.toggle( false ); } ); }; /** * The Dialog class serves as the base class for the other types of dialogs. * Unless extended to include controls, the rendered dialog box is a simple window * that users can close by hitting the Escape key. Dialog windows are used with OO.ui.WindowManager, * which opens, closes, and controls the presentation of the window. See the * [OOUI documentation on MediaWiki] [1] for more information. * * @example * // A simple dialog window. * function MyDialog( config ) { * MyDialog.super.call( this, config ); * } * OO.inheritClass( MyDialog, OO.ui.Dialog ); * MyDialog.static.name = 'myDialog'; * MyDialog.prototype.initialize = function () { * MyDialog.super.prototype.initialize.call( this ); * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.content.$element.append( '<p>A simple dialog window. Press Escape key to ' + * 'close.</p>' ); * this.$body.append( this.content.$element ); * }; * MyDialog.prototype.getBodyHeight = function () { * return this.content.$element.outerHeight( true ); * }; * var myDialog = new MyDialog( { * size: 'medium' * } ); * // Create and append a window manager, which opens and closes the window. * var windowManager = new OO.ui.WindowManager(); * $( document.body ).append( windowManager.$element ); * windowManager.addWindows( [ myDialog ] ); * // Open the window! * windowManager.openWindow( myDialog ); * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Dialogs * * @abstract * @class * @extends OO.ui.Window * @mixins OO.ui.mixin.PendingElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Dialog = function OoUiDialog( config ) { // Parent constructor OO.ui.Dialog.super.call( this, config ); // Mixin constructors OO.ui.mixin.PendingElement.call( this ); // Properties this.actions = new OO.ui.ActionSet(); this.attachedActions = []; this.currentAction = null; this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this ); // Events this.actions.connect( this, { click: 'onActionClick', change: 'onActionsChange' } ); // Initialization this.$element .addClass( 'oo-ui-dialog' ) .attr( 'role', 'dialog' ); }; /* Setup */ OO.inheritClass( OO.ui.Dialog, OO.ui.Window ); OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement ); /* Static Properties */ /** * Symbolic name of dialog. * * The dialog class must have a symbolic name in order to be registered with OO.Factory. * Please see the [OOUI documentation on MediaWiki] [3] for more information. * * [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Dialog.static.name = ''; /** * The dialog title. * * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, * or a function that will produce a Label node or string. The title can also be specified with data * passed to the constructor (see #getSetupProcess). In this case, the static value will be * overridden. * * @abstract * @static * @inheritable * @property {jQuery|string|Function} */ OO.ui.Dialog.static.title = ''; /** * An array of configured {@link OO.ui.ActionWidget action widgets}. * * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this * case, the static value will be overridden. * * [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets * * @static * @inheritable * @property {Object[]} */ OO.ui.Dialog.static.actions = []; /** * Close the dialog when the Escape key is pressed. * * @static * @abstract * @inheritable * @property {boolean} */ OO.ui.Dialog.static.escapable = true; /* Methods */ /** * Handle frame document key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) { var actions; if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) { this.executeAction( '' ); e.preventDefault(); e.stopPropagation(); } else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) { actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } ); if ( actions.length > 0 ) { this.executeAction( actions[ 0 ].getAction() ); e.preventDefault(); e.stopPropagation(); } } }; /** * Handle action click events. * * @private * @param {OO.ui.ActionWidget} action Action that was clicked */ OO.ui.Dialog.prototype.onActionClick = function ( action ) { if ( !this.isPending() ) { this.executeAction( action.getAction() ); } }; /** * Handle actions change event. * * @private */ OO.ui.Dialog.prototype.onActionsChange = function () { this.detachActions(); if ( !this.isClosing() ) { this.attachActions(); if ( !this.isOpening() ) { // If the dialog is currently opening, this will be called automatically soon. this.updateSize(); } } }; /** * Get the set of actions used by the dialog. * * @return {OO.ui.ActionSet} */ OO.ui.Dialog.prototype.getActions = function () { return this.actions; }; /** * Get a process for taking action. * * When you override this method, you can create a new OO.ui.Process and return it, or add * additional accept steps to the process the parent method provides using the * {@link OO.ui.Process#first 'first'} and {@link OO.ui.Process#next 'next'} methods of * OO.ui.Process. * * @param {string} [action] Symbolic name of action * @return {OO.ui.Process} Action process */ OO.ui.Dialog.prototype.getActionProcess = function ( action ) { return new OO.ui.Process() .next( function () { if ( !action ) { // An empty action always closes the dialog without data, which should always be // safe and make no changes this.close(); } }, this ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use * the {@link #static-title static title} * @param {Object[]} [data.actions] List of configuration options for each * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}. */ OO.ui.Dialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data ) .next( function () { var config = this.constructor.static, actions = data.actions !== undefined ? data.actions : config.actions, title = data.title !== undefined ? data.title : config.title; this.title.setLabel( title ).setTitle( title ); this.actions.add( this.getActionWidgets( actions ) ); this.$element.on( 'keydown', this.onDialogKeyDownHandler ); }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data ) .first( function () { this.$element.off( 'keydown', this.onDialogKeyDownHandler ); this.actions.clear(); this.currentAction = null; }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.initialize = function () { // Parent method OO.ui.Dialog.super.prototype.initialize.call( this ); // Properties this.title = new OO.ui.LabelWidget(); // Initialization this.$content.addClass( 'oo-ui-dialog-content' ); this.$element.attr( 'aria-labelledby', this.title.getElementId() ); this.setPendingElement( this.$head ); }; /** * Get action widgets from a list of configs * * @param {Object[]} actions Action widget configs * @return {OO.ui.ActionWidget[]} Action widgets */ OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) { var i, len, widgets = []; for ( i = 0, len = actions.length; i < len; i++ ) { widgets.push( this.getActionWidget( actions[ i ] ) ); } return widgets; }; /** * Get action widget from config * * Override this method to change the action widget class used. * * @param {Object} config Action widget config * @return {OO.ui.ActionWidget} Action widget */ OO.ui.Dialog.prototype.getActionWidget = function ( config ) { return new OO.ui.ActionWidget( this.getActionWidgetConfig( config ) ); }; /** * Get action widget config * * Override this method to modify the action widget config * * @param {Object} config Initial action widget config * @return {Object} Action widget config */ OO.ui.Dialog.prototype.getActionWidgetConfig = function ( config ) { return config; }; /** * Attach action actions. * * @protected */ OO.ui.Dialog.prototype.attachActions = function () { // Remember the list of potentially attached actions this.attachedActions = this.actions.get(); }; /** * Detach action actions. * * @protected * @chainable * @return {OO.ui.Dialog} The dialog, for chaining */ OO.ui.Dialog.prototype.detachActions = function () { var i, len; // Detach all actions that may have been previously attached for ( i = 0, len = this.attachedActions.length; i < len; i++ ) { this.attachedActions[ i ].$element.detach(); } this.attachedActions = []; return this; }; /** * Execute an action. * * @param {string} action Symbolic name of action to execute * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails */ OO.ui.Dialog.prototype.executeAction = function ( action ) { this.pushPending(); this.currentAction = action; return this.getActionProcess( action ).execute() .always( this.popPending.bind( this ) ); }; /** * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box * consists of a header that contains the dialog title, a body with the message, and a footer that * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type * of {@link OO.ui.Dialog dialog} that is usually instantiated directly. * * There are two basic types of message dialogs, confirmation and alert: * * - **confirmation**: the dialog title describes what a progressive action will do and the message * provides more details about the consequences. * - **alert**: the dialog title describes which event occurred and the message provides more * information about why the event occurred. * * The MessageDialog class specifies two actions: ‘accept’, the primary * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window, * passing along the selected action. * * For more information and examples, please see the [OOUI documentation on MediaWiki][1]. * * @example * // Example: Creating and opening a message dialog window. * var messageDialog = new OO.ui.MessageDialog(); * * // Create and append a window manager. * var windowManager = new OO.ui.WindowManager(); * $( document.body ).append( windowManager.$element ); * windowManager.addWindows( [ messageDialog ] ); * // Open the window. * windowManager.openWindow( messageDialog, { * title: 'Basic message dialog', * message: 'This is the message' * } ); * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Message_Dialogs * * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MessageDialog = function OoUiMessageDialog( config ) { // Parent constructor OO.ui.MessageDialog.super.call( this, config ); // Properties this.verticalActionLayout = null; // Initialization this.$element.addClass( 'oo-ui-messageDialog' ); }; /* Setup */ OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.name = 'message'; /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.size = 'small'; /** * Dialog title. * * The title of a confirmation dialog describes what a progressive action will do. The * title of an alert dialog describes which event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.title = null; /** * The message displayed in the dialog body. * * A confirmation message describes the consequences of a progressive action. An alert * message describes why an event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.message = null; /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.actions = [ // Note that OO.ui.alert() and OO.ui.confirm() rely on these. { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' }, { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' } ]; /* Methods */ /** * Toggle action layout between vertical and horizontal. * * @private * @param {boolean} [value] Layout actions vertically, omit to toggle * @chainable * @return {OO.ui.MessageDialog} The dialog, for chaining */ OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) { value = value === undefined ? !this.verticalActionLayout : !!value; if ( value !== this.verticalActionLayout ) { this.verticalActionLayout = value; this.$actions .toggleClass( 'oo-ui-messageDialog-actions-vertical', value ) .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value ); } return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) { if ( action ) { return new OO.ui.Process( function () { this.close( { action: action } ); }, this ); } return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence * @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each * action item */ OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data ) .next( function () { this.title.setLabel( data.title !== undefined ? data.title : this.constructor.static.title ); this.message.setLabel( data.message !== undefined ? data.message : this.constructor.static.message ); this.size = data.size !== undefined ? data.size : this.constructor.static.size; }, this ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.MessageDialog.super.prototype.getReadyProcess.call( this, data ) .next( function () { // Focus the primary action button var actions = this.actions.get(); actions = actions.filter( function ( action ) { return action.getFlags().indexOf( 'primary' ) > -1; } ); if ( actions.length > 0 ) { actions[ 0 ].focus(); } }, this ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getBodyHeight = function () { var bodyHeight, oldOverflow, $scrollable = this.container.$element; oldOverflow = $scrollable[ 0 ].style.overflow; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); bodyHeight = this.text.$element.outerHeight( true ); $scrollable[ 0 ].style.overflow = oldOverflow; return bodyHeight; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) { var dialog = this, $scrollable = this.container.$element; OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim ); // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced. // Need to do it after transition completes (250ms), add 50ms just in case. setTimeout( function () { var oldOverflow = $scrollable[ 0 ].style.overflow, activeElement = document.activeElement; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); // Check reconsiderScrollbars didn't destroy our focus, as we // are doing this after the ready process. if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) { activeElement.focus(); } $scrollable[ 0 ].style.overflow = oldOverflow; }, 300 ); dialog.fitActions(); // Wait for CSS transition to finish and do it again :( setTimeout( function () { dialog.fitActions(); }, 300 ); return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.initialize = function () { // Parent method OO.ui.MessageDialog.super.prototype.initialize.call( this ); // Properties this.$actions = $( '<div>' ); this.container = new OO.ui.PanelLayout( { scrollable: true, classes: [ 'oo-ui-messageDialog-container' ] } ); this.text = new OO.ui.PanelLayout( { padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ] } ); this.message = new OO.ui.LabelWidget( { classes: [ 'oo-ui-messageDialog-message' ] } ); // Initialization this.title.$element.addClass( 'oo-ui-messageDialog-title' ); this.$content.addClass( 'oo-ui-messageDialog-content' ); this.container.$element.append( this.text.$element ); this.text.$element.append( this.title.$element, this.message.$element ); this.$body.append( this.container.$element ); this.$actions.addClass( 'oo-ui-messageDialog-actions' ); this.$foot.append( this.$actions ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getActionWidgetConfig = function ( config ) { // Force unframed return $.extend( {}, config, { framed: false } ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.attachActions = function () { var i, len, special, others; // Parent method OO.ui.MessageDialog.super.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.safe ) { this.$actions.append( special.safe.$element ); special.safe.toggleFramed( true ); } for ( i = 0, len = others.length; i < len; i++ ) { this.$actions.append( others[ i ].$element ); others[ i ].toggleFramed( true ); } if ( special.primary ) { this.$actions.append( special.primary.$element ); special.primary.toggleFramed( true ); } }; /** * Fit action actions into columns or rows. * * Columns will be used if all labels can fit without overflow, otherwise rows will be used. * * @private */ OO.ui.MessageDialog.prototype.fitActions = function () { var i, len, action, previous = this.verticalActionLayout, actions = this.actions.get(); // Detect clipping this.toggleVerticalActionLayout( false ); for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; if ( action.$element[ 0 ].scrollWidth > action.$element[ 0 ].clientWidth ) { this.toggleVerticalActionLayout( true ); break; } } // Move the body out of the way of the foot this.$body.css( 'bottom', this.$foot.outerHeight( true ) ); if ( this.verticalActionLayout !== previous ) { // We changed the layout, window height might need to be updated. this.updateSize(); } }; /** * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error * interface} alerts users to the trouble, permitting the user to dismiss the error and try again * when relevant. The ProcessDialog class is always extended and customized with the actions and * content required for each process. * * The process dialog box consists of a header that visually represents the ‘working’ state of long * processes with an animation. The header contains the dialog title as well as * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and * a ‘primary’ action on the right (e.g., ‘Done’). * * Like other windows, the process dialog is managed by a * {@link OO.ui.WindowManager window manager}. * Please see the [OOUI documentation on MediaWiki][1] for more information and examples. * * @example * // Example: Creating and opening a process dialog window. * function MyProcessDialog( config ) { * MyProcessDialog.super.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * * MyProcessDialog.static.name = 'myProcessDialog'; * MyProcessDialog.static.title = 'Process dialog'; * MyProcessDialog.static.actions = [ * { action: 'save', label: 'Done', flags: 'primary' }, * { label: 'Cancel', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.super.prototype.initialize.apply( this, arguments ); * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.content.$element.append( '<p>This is a process dialog window. The header ' + * 'contains the title and two buttons: \'Cancel\' (a safe action) on the left and ' + * '\'Done\' (a primary action) on the right.</p>' ); * this.$body.append( this.content.$element ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * var dialog = this; * if ( action ) { * return new OO.ui.Process( function () { * dialog.close( { action: action } ); * } ); * } * return MyProcessDialog.super.prototype.getActionProcess.call( this, action ); * }; * * var windowManager = new OO.ui.WindowManager(); * $( document.body ).append( windowManager.$element ); * * var dialog = new MyProcessDialog(); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs * * @abstract * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ProcessDialog = function OoUiProcessDialog( config ) { // Parent constructor OO.ui.ProcessDialog.super.call( this, config ); // Properties this.fitOnOpen = false; // Initialization this.$element.addClass( 'oo-ui-processDialog' ); if ( OO.ui.isMobile() ) { this.$element.addClass( 'oo-ui-isMobile' ); } }; /* Setup */ OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog ); /* Methods */ /** * Handle dismiss button click events. * * Hides errors. * * @private */ OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () { this.hideErrors(); }; /** * Handle retry button click events. * * Hides errors and then tries again. * * @private */ OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () { this.hideErrors(); this.executeAction( this.currentAction ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.initialize = function () { // Parent method OO.ui.ProcessDialog.super.prototype.initialize.call( this ); // Properties this.$navigation = $( '<div>' ); this.$location = $( '<div>' ); this.$safeActions = $( '<div>' ); this.$primaryActions = $( '<div>' ); this.$otherActions = $( '<div>' ); this.dismissButton = new OO.ui.ButtonWidget( { label: OO.ui.msg( 'ooui-dialog-process-dismiss' ) } ); this.retryButton = new OO.ui.ButtonWidget(); this.$errors = $( '<div>' ); this.$errorsTitle = $( '<div>' ); // Events this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } ); this.retryButton.connect( this, { click: 'onRetryButtonClick' } ); this.title.connect( this, { labelChange: 'fitLabel' } ); // Initialization this.title.$element.addClass( 'oo-ui-processDialog-title' ); this.$location .append( this.title.$element ) .addClass( 'oo-ui-processDialog-location' ); this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' ); this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' ); this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' ); this.$errorsTitle .addClass( 'oo-ui-processDialog-errors-title' ) .text( OO.ui.msg( 'ooui-dialog-process-error' ) ); this.$errors .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' ) .append( this.$errorsTitle, $( '<div>' ).addClass( 'oo-ui-processDialog-errors-actions' ).append( this.dismissButton.$element, this.retryButton.$element ) ); this.$content .addClass( 'oo-ui-processDialog-content' ) .append( this.$errors ); this.$navigation .addClass( 'oo-ui-processDialog-navigation' ) // Note: Order of appends below is important. These are in the order // we want tab to go through them. Display-order is handled entirely // by CSS absolute-positioning. As such, primary actions like "done" // should go first. .append( this.$primaryActions, this.$location, this.$safeActions ); this.$head.append( this.$navigation ); this.$foot.append( this.$otherActions ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getActionWidgetConfig = function ( config ) { function checkFlag( flag ) { return config.flags === flag || ( Array.isArray( config.flags ) && config.flags.indexOf( flag ) !== -1 ); } config = $.extend( { framed: true }, config ); if ( checkFlag( 'close' ) ) { // Change close buttons to icon only. $.extend( config, { icon: 'close', invisibleLabel: true } ); } else if ( checkFlag( 'back' ) ) { // Change back buttons to icon only. $.extend( config, { icon: 'previous', invisibleLabel: true } ); } return config; }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.attachActions = function () { var i, len, other, special, others; // Parent method OO.ui.ProcessDialog.super.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.primary ) { this.$primaryActions.append( special.primary.$element ); } for ( i = 0, len = others.length; i < len; i++ ) { other = others[ i ]; this.$otherActions.append( other.$element ); } if ( special.safe ) { this.$safeActions.append( special.safe.$element ); } }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.executeAction = function ( action ) { var dialog = this; return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action ) .fail( function ( errors ) { dialog.showErrors( errors || [] ); } ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.setDimensions = function () { var dialog = this; // Parent method OO.ui.ProcessDialog.super.prototype.setDimensions.apply( this, arguments ); this.fitLabel(); // If there are many actions, they might be shown on multiple lines. Their layout can change // when resizing the dialog and when changing the actions. Adjust the height of the footer to // fit them. dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) ); // Wait for CSS transition to finish and do it again :( setTimeout( function () { dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) ); }, 300 ); }; /** * Fit label between actions. * * @private * @chainable * @return {OO.ui.MessageDialog} The dialog, for chaining */ OO.ui.ProcessDialog.prototype.fitLabel = function () { var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth, size = this.getSizeProperties(); if ( typeof size.width !== 'number' ) { if ( this.isOpened() ) { navigationWidth = this.$head.width() - 20; } else if ( this.isOpening() ) { if ( !this.fitOnOpen ) { // Size is relative and the dialog isn't open yet, so wait. // FIXME: This should ideally be handled by setup somehow. this.manager.lifecycle.opened.done( this.fitLabel.bind( this ) ); this.fitOnOpen = true; } return; } else { return; } } else { navigationWidth = size.width - 20; } safeWidth = this.$safeActions.width(); primaryWidth = this.$primaryActions.width(); biggerWidth = Math.max( safeWidth, primaryWidth ); labelWidth = this.title.$element.width(); if ( !OO.ui.isMobile() && 2 * biggerWidth + labelWidth < navigationWidth ) { // We have enough space to center the label leftWidth = rightWidth = biggerWidth; } else { // Let's hope we at least have enough space not to overlap, because we can't wrap // the label. if ( this.getDir() === 'ltr' ) { leftWidth = safeWidth; rightWidth = primaryWidth; } else { leftWidth = primaryWidth; rightWidth = safeWidth; } } this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } ); return this; }; /** * Handle errors that occurred during accept or reject processes. * * @private * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled */ OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) { var i, len, actions, items = [], abilities = {}, recoverable = true, warning = false; if ( errors instanceof OO.ui.Error ) { errors = [ errors ]; } for ( i = 0, len = errors.length; i < len; i++ ) { if ( !errors[ i ].isRecoverable() ) { recoverable = false; } if ( errors[ i ].isWarning() ) { warning = true; } items.push( new OO.ui.MessageWidget( { type: 'error', label: errors[ i ].getMessage() } ).$element[ 0 ] ); } this.$errorItems = $( items ); if ( recoverable ) { abilities[ this.currentAction ] = true; // Copy the flags from the first matching action. actions = this.actions.get( { actions: this.currentAction } ); if ( actions.length ) { this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() ); } } else { abilities[ this.currentAction ] = false; this.actions.setAbilities( abilities ); } if ( warning ) { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) ); } else { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) ); } this.retryButton.toggle( recoverable ); this.$errorsTitle.after( this.$errorItems ); this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 ); }; /** * Hide errors. * * @private */ OO.ui.ProcessDialog.prototype.hideErrors = function () { this.$errors.addClass( 'oo-ui-element-hidden' ); if ( this.$errorItems ) { this.$errorItems.remove(); this.$errorItems = null; } }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data ) .first( function () { // Make sure to hide errors. this.hideErrors(); this.fitOnOpen = false; }, this ); }; /** * @class OO.ui */ /** * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and * OO.ui.confirm. * * @private * @return {OO.ui.WindowManager} */ OO.ui.getWindowManager = function () { if ( !OO.ui.windowManager ) { OO.ui.windowManager = new OO.ui.WindowManager(); $( document.body ).append( OO.ui.windowManager.$element ); OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] ); } return OO.ui.windowManager; }; /** * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog * has only one action button, labelled "OK", clicking it will simply close the dialog. * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.alert( 'Something happened!' ).done( function () { * console.log( 'User closed the dialog.' ); * } ); * * OO.ui.alert( 'Something larger happened!', { size: 'large' } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @return {jQuery.Promise} Promise resolved when the user closes the dialog */ OO.ui.alert = function ( text, options ) { return OO.ui.getWindowManager().openWindow( 'message', $.extend( { message: text, actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ] }, options ) ).closed.then( function () { return undefined; } ); }; /** * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open, * the rest of the page will be dimmed out and the user won't be able to interact with it. The * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it * (labelled "Cancel"). * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) { * if ( confirmed ) { * console.log( 'User clicked "OK"!' ); * } else { * console.log( 'User clicked "Cancel" or closed the dialog.' ); * } * } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean * `false`. */ OO.ui.confirm = function ( text, options ) { return OO.ui.getWindowManager().openWindow( 'message', $.extend( { message: text }, options ) ).closed.then( function ( data ) { return !!( data && data.action === 'accept' ); } ); }; /** * Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open, * the rest of the page will be dimmed out and the user won't be able to interact with it. The * dialog has a text input widget and two action buttons, one to confirm an operation * (labelled "OK") and one to cancel it (labelled "Cancel"). * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.prompt( 'Choose a line to go to', { * textInput: { placeholder: 'Line number' } * } ).done( function ( result ) { * if ( result !== null ) { * console.log( 'User typed "' + result + '" then clicked "OK".' ); * } else { * console.log( 'User clicked "Cancel" or closed the dialog.' ); * } * } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @param {Object} [options.textInput] Additional options for text input widget, * see OO.ui.TextInputWidget * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to * confirm, the promise will resolve with the value of the text input widget; otherwise, it will * resolve to `null`. */ OO.ui.prompt = function ( text, options ) { var instance, manager = OO.ui.getWindowManager(), textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ), textField = new OO.ui.FieldLayout( textInput, { align: 'top', label: text } ); instance = manager.openWindow( 'message', $.extend( { message: textField.$element }, options ) ); // TODO: This is a little hacky, and could be done by extending MessageDialog instead. instance.opened.then( function () { textInput.on( 'enter', function () { manager.getCurrentWindow().close( { action: 'accept' } ); } ); textInput.focus(); } ); return instance.closed.then( function ( data ) { return data && data.action === 'accept' ? textInput.getValue() : null; } ); }; }( OO ) ); //# sourceMappingURL=oojs-ui-windows.js.map.json
cdnjs/cdnjs
ajax/libs/oojs-ui/0.40.3/oojs-ui-windows.js
JavaScript
mit
117,418
<?php namespace Report; use Illuminate\Support\Collection; class Datareport { protected static $instance = NULL; protected $id = NULL; protected $caption = NULL; protected $icon = NULL; // protected $rowSourceUrl = NULL; // server side row source url // protected $columns = NULL; // protected $displayStart = 0; // DT parameter // protected $displayLength = 10; // DT parameter // protected $dom = ''; // protected $defaultOrder = "0, 'asc'"; protected $styles = NULL; // page styles protected $scripts = NULL; // page scripts // protected $name = NULL; protected $custom_styles = NULL; protected $custom_scripts = NULL; public function __construct() { $this->styles = new Collection(); $this->scripts = new Collection(); } public static function make() { return self::$instance = new Datareport(); } public function addStyleFile($file) { $this->styles->push($file); return $this; } public function addScriptFile($file) { $this->scripts->push($file); return $this; } public function __call($method, $args) { if(! property_exists($this, $method)) { throw new \Exception('Method: ' . __METHOD__ . '. File: ' . __FILE__ . '. Message: Property "' . $method . '" unknown.'); } if( isset($args[0]) ) { $this->{$method} = $args[0]; return $this; } return $this->{$method}; } protected function addCustomStyles() { if( $this->custom_styles ) { foreach( explode(',', $this->custom_styles) as $i => $file) { $this->addStyleFile(trim($file)); } } } protected function addCustomScripts() { if( $this->custom_scripts ) { foreach( explode(',', $this->custom_scripts) as $i => $file) { $this->addScriptFile(trim($file)); } } } public function styles() { $this->addCustomStyles(); $result = ''; foreach($this->styles as $i => $file) { $result .= \HTML::style($file); } return $result; } public function scripts() { $this->addCustomScripts(); $result = ''; foreach($this->scripts as $i => $file) { $result .= \HTML::script($file); } return $result; } }
binaryk/pedia
app/~Libs/~system/reports/Datareport.php
PHP
mit
2,191
<?php namespace App\Support\Http\Routing; use App\Support\Facades\Request; use App\Support\Traits\ClassNameTrait; /** * Class Router * @package App\Support\Routing * @author Fruty <ed.fruty@gmail.com> */ class Router { use ClassNameTrait; /** * Registered routes * * @access protected * @var array */ protected $routes = []; /** * @var \Closure */ protected $action404; /** * Register route * * @access public * @param string $uri * @param mixed [string|\Closure] $action */ public function map($uri, $action) { $route = new Route(); $route->setUri($uri); $route->setAction($action); $this->routes[] = $route; } /** * @return mixed */ public function handle() { foreach ($this->routes as $route) { if ($this->matchRequest($route)) { /** @var Route $route */ return $route->dispatch(); } } return $this->show404(); } /** * @param $route * @return int */ protected function matchRequest(Route $route) { return preg_match($route->getRegex(), Request::getUri()); } /** * @param callable $closure * @return mixed */ public function show404(\Closure $closure = null) { if ($closure) { $this->action404 = $closure; } else { $closure = $this->action404; if (! is_callable($closure)) { throw new \InvalidArgumentException("404 page handler not defined"); } return $closure(); } } }
ed-fruty/test
app/Support/Http/Routing/Router.php
PHP
mit
1,695
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Dulcet.Twitter; using Inscribe.Common; using Inscribe.Configuration; using Inscribe.Util; using Inscribe.Subsystems; using Inscribe.ViewModels.PartBlocks.MainBlock.TimelineChild; using Livet; namespace Inscribe.Storage { /// <summary> /// ツイートの存在状態 /// </summary> public enum TweetExistState { Unreceived, EmptyExists, Exists, ServerDeleted, } /// <summary> /// ツイートデータ(ViewModel)保持ベースクラス /// </summary> public static class TweetStorage { /// <summary> /// ディクショナリのロック /// </summary> static ReaderWriterLockWrap lockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion); /// <summary> /// 登録済みステータスディクショナリ /// </summary> static SortedDictionary<long, TweetViewModel> dictionary = new SortedDictionary<long, TweetViewModel>(); static ReaderWriterLockWrap vmLockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion); /// <summary> /// ViewModel一覧の参照の高速化のためのリスト /// </summary> static List<TweetViewModel> viewmodels = new List<TweetViewModel>(); /// <summary> /// empties/deleteReserveds用ロックラップ /// </summary> static ReaderWriterLockWrap elockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion); /// <summary> /// 仮登録ステータスディクショナリ /// </summary> static SortedDictionary<long, TweetViewModel> empties = new SortedDictionary<long, TweetViewModel>(); /// <summary> /// 削除予約されたツイートIDリスト /// </summary> static LinkedList<long> deleteReserveds = new LinkedList<long>(); /// <summary> /// ツイートストレージの作業用スレッドディスパッチャ /// </summary> static QueueTaskDispatcher operationDispatcher; static TweetStorage() { operationDispatcher = new QueueTaskDispatcher(1); ThreadHelper.Halt += () => operationDispatcher.Dispose(); } /// <summary> /// ツイートを受信したか、また明示的削除などが行われたかを確認します。 /// </summary> public static TweetExistState Contains(long id) { using (lockWrap.GetReaderLock()) { if (dictionary.ContainsKey(id)) return TweetExistState.Exists; } using (elockWrap.GetReaderLock()) { if (deleteReserveds.Contains(id)) return TweetExistState.ServerDeleted; else if (empties.ContainsKey(id)) return TweetExistState.EmptyExists; else return TweetExistState.Unreceived; } } /// <summary> /// ツイートデータを取得します。 /// </summary> /// <param name="id">ツイートID</param> /// <param name="createEmpty">存在しないとき、空のViewModelを作って登録して返す</param> public static TweetViewModel Get(long id, bool createEmpty = false) { TweetViewModel ret; using (lockWrap.GetReaderLock()) { if (dictionary.TryGetValue(id, out ret)) return ret; } using (createEmpty ? elockWrap.GetUpgradableReaderLock() : elockWrap.GetReaderLock()) { if (empties.TryGetValue(id, out ret)) return ret; if (createEmpty) { using (elockWrap.GetWriterLock()) { var nvm = new TweetViewModel(id); empties.Add(id, nvm); return nvm; } } else { return null; } } } /// <summary> /// 登録されているステータスを抽出します。 /// </summary> /// <param name="predicate">抽出条件</param> /// <returns>条件にマッチするステータス、または登録されているすべてのステータス</returns> public static IEnumerable<TweetViewModel> GetAll(Func<TweetViewModel, bool> predicate = null) { IEnumerable<TweetViewModel> tvms; using (vmLockWrap.GetReaderLock()) { tvms = viewmodels.ToArray(); } if (predicate == null) return tvms; else return tvms.AsParallel().Where(predicate); } private static volatile int _count; /// <summary> /// 登録されているツイートの個数を取得します。 /// </summary> public static int Count() { return _count; } /// <summary> /// 受信したツイートを登録します。<para /> /// 諸々の処理を自動で行います。 /// </summary> public static TweetViewModel Register(TwitterStatusBase statusBase) { TweetViewModel robj; using (lockWrap.GetReaderLock()) { if (dictionary.TryGetValue(statusBase.Id, out robj)) return robj; } var status = statusBase as TwitterStatus; if (status != null) { return RegisterStatus(status); } else { var dmsg = statusBase as TwitterDirectMessage; if (dmsg != null) { return RegisterDirectMessage(dmsg); } else { throw new InvalidOperationException("不明なステータスを受信しました: " + statusBase); } } } /// <summary> /// ステータスの追加に際しての処理 /// </summary> private static TweetViewModel RegisterStatus(TwitterStatus status) { if (status.RetweetedOriginal != null) { // リツイートのオリジナルステータスを登録 var vm = Register(status.RetweetedOriginal); // リツイートユーザーに登録 var user = UserStorage.Get(status.User); var tuser = UserStorage.Get(status.RetweetedOriginal.User); if (vm.RegisterRetweeted(user)) { if (!vm.IsStatusInfoContains) vm.SetStatus(status.RetweetedOriginal); // 自分が関係していれば if (AccountStorage.Contains(status.RetweetedOriginal.User.ScreenName) || AccountStorage.Contains(user.TwitterUser.ScreenName)) EventStorage.OnRetweeted(vm, user); } } UserStorage.Register(status.User); var registered = RegisterCore(status); // 返信先の登録 if (status.InReplyToStatusId != 0) { Get(status.InReplyToStatusId, true).RegisterInReplyToThis(status.Id); } if (TwitterHelper.IsMentionOfMe(status)) { EventStorage.OnMention(registered); } return registered; } /// <summary> /// ダイレクトメッセージの追加に際しての処理 /// </summary> private static TweetViewModel RegisterDirectMessage(TwitterDirectMessage dmsg) { UserStorage.Register(dmsg.Sender); UserStorage.Register(dmsg.Recipient); var vm = RegisterCore(dmsg); EventStorage.OnDirectMessage(vm); return vm; } /// <summary> /// ステータスベースの登録処理 /// </summary> private static TweetViewModel RegisterCore(TwitterStatusBase statusBase) { TweetViewModel viewModel; using (elockWrap.GetUpgradableReaderLock()) { if (empties.TryGetValue(statusBase.Id, out viewModel)) { // 既にViewModelが生成済み if (!viewModel.IsStatusInfoContains) viewModel.SetStatus(statusBase); using (elockWrap.GetWriterLock()) { empties.Remove(statusBase.Id); } } else { // 全く初めて触れるステータス viewModel = new TweetViewModel(statusBase); } } if (ValidateTweet(viewModel)) { // プリプロセッシング PreProcess(statusBase); bool delr = false; using (elockWrap.GetReaderLock()) { delr = deleteReserveds.Contains(statusBase.Id); } if (!delr) { using (lockWrap.GetUpgradableReaderLock()) { if (dictionary.ContainsKey(statusBase.Id)) { return viewModel; // すでにKrile内に存在する } else { using (lockWrap.GetWriterLock()) { dictionary.Add(statusBase.Id, viewModel); } _count++; } } Task.Factory.StartNew(() => RaiseStatusAdded(viewModel)).ContinueWith(_ => { // delay add using (vmLockWrap.GetWriterLock()) { viewmodels.Add(viewModel); } }); } } return viewModel; } /// <summary> /// 登録可能なツイートか判定 /// </summary> /// <returns></returns> public static bool ValidateTweet(TweetViewModel viewModel) { if (viewModel.Status == null || viewModel.Status.User == null || String.IsNullOrEmpty(viewModel.Status.User.ScreenName)) throw new ArgumentException("データが破損しています。"); return true; } /// <summary> /// ステータスのプリプロセッシング /// </summary> private static void PreProcess(TwitterStatusBase status) { try { if (status.Entities != null) { // extracting t.co and official image new[] { status.Entities.GetChildNode("urls"), status.Entities.GetChildNode("media") } .Where(n => n != null) .SelectMany(n => n.GetChildNodes("item")) .Where(i => i.GetChildNode("indices") != null) .Where(i => i.GetChildNode("indices").GetChildValues("item") != null) .OrderByDescending(i => i.GetChildNode("indices").GetChildValues("item") .Select(s => int.Parse(s.Value)).First()) .ForEach(i => { String expand = null; if (i.GetChildValue("media_url") != null) expand = i.GetChildValue("media_url").Value; if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("expanded_url") != null) expand = i.GetChildValue("expanded_url").Value; if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("url") != null) expand = i.GetChildValue("url").Value; if (!String.IsNullOrWhiteSpace(expand)) { var indices = i.GetChildNode("indices").GetChildValues("item") .Select(v => int.Parse(v.Value)).OrderBy(v => v).ToArray(); if (indices.Length == 2) { //一旦内容を元の状態に戻す(参照:XmlParser.ParseString) string orgtext = status.Text.Replace("&", "&amp;").Replace(">", "&gt;").Replace("<", "&lt;"); // Considering surrogate pairs and Combining Character. string text = SubstringForSurrogatePaire(orgtext, 0, indices[0]) + expand + SubstringForSurrogatePaire(orgtext, indices[1]); //再度処理を施す status.Text = text.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&"); } } }); } } catch { } } private static string SubstringForSurrogatePaire(string str, int startIndex, int length = -1) { var s = GetLengthForSurrogatePaire(str, startIndex, 0); if (length == -1) { return str.Substring(s); } var l = GetLengthForSurrogatePaire(str, length, s); return str.Substring(s, l); } private static int GetLengthForSurrogatePaire(string str, int len, int s) { var l = 0; for (int i = 0; i < len; i++) { if (char.IsHighSurrogate(str[l + s])) { l++; } l++; } return l; } /// <summary> /// ツイートをツイートストレージから除去 /// </summary> /// <param name="id">ツイートID</param> public static void Trim(long id) { TweetViewModel remobj = null; using (elockWrap.GetWriterLock()) { empties.Remove(id); } using (lockWrap.GetWriterLock()) { if (dictionary.TryGetValue(id, out remobj)) { dictionary.Remove(id); _count--; } } if (remobj != null) { using (vmLockWrap.GetWriterLock()) { viewmodels.Remove(remobj); } Task.Factory.StartNew(() => RaiseStatusRemoved(remobj)); } } /// <summary> /// ツイートの削除 /// </summary> /// <param name="id">削除するツイートID</param> public static void Remove(long id) { TweetViewModel remobj = null; using (elockWrap.GetWriterLock()) { empties.Remove(id); } using (lockWrap.GetWriterLock()) { // 削除する deleteReserveds.AddLast(id); if (dictionary.TryGetValue(id, out remobj)) { if (remobj.IsRemoved) { dictionary.Remove(id); _count--; } } } if (remobj != null) { using (vmLockWrap.GetWriterLock()) { if (remobj.IsRemoved) viewmodels.Remove(remobj); } Task.Factory.StartNew(() => RaiseStatusRemoved(remobj)); // リツイート判定 var status = remobj.Status as TwitterStatus; if (status != null && status.RetweetedOriginal != null) { var ros = TweetStorage.Get(status.RetweetedOriginal.Id); if (ros != null) ros.RemoveRetweeted(UserStorage.Get(status.User)); } } } /// <summary> /// ツイートの内部状態が変化したことを通知します。<para /> /// (例えば、ふぁぼられたりRTされたり返信貰ったりなど。) /// </summary> public static void NotifyTweetStateChanged(TweetViewModel tweet) { Task.Factory.StartNew(() => RaiseStatusStateChanged(tweet)); } #region TweetStorageChangedイベント public static event EventHandler<TweetStorageChangedEventArgs> TweetStorageChanged; private static Notificator<TweetStorageChangedEventArgs> _TweetStorageChangedEvent; public static Notificator<TweetStorageChangedEventArgs> TweetStorageChangedEvent { get { if (_TweetStorageChangedEvent == null) _TweetStorageChangedEvent = new Notificator<TweetStorageChangedEventArgs>(); return _TweetStorageChangedEvent; } set { _TweetStorageChangedEvent = value; } } private static void OnTweetStorageChanged(TweetStorageChangedEventArgs e) { var threadSafeHandler = Interlocked.CompareExchange(ref TweetStorageChanged, null, null); if (threadSafeHandler != null) threadSafeHandler(null, e); TweetStorageChangedEvent.Raise(e); } #endregion static void RaiseStatusAdded(TweetViewModel added) { // Mention通知設定がないか、 // 自分へのMentionでない場合にのみRegisterする // + // Retweet通知設定がないか、 // 自分のTweetのRetweetでない場合にのみRegisterする if ((!Setting.Instance.NotificationProperty.NotifyMention || !TwitterHelper.IsMentionOfMe(added.Status)) && (!Setting.Instance.NotificationProperty.NotifyRetweet || !(added.Status is TwitterStatus) || ((TwitterStatus)added.Status).RetweetedOriginal == null || !AccountStorage.Contains(((TwitterStatus)added.Status).RetweetedOriginal.User.ScreenName))) NotificationCore.RegisterNotify(added); OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Added, added)); NotificationCore.DispatchNotify(added); } static void RaiseStatusRemoved(TweetViewModel removed) { OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Removed, removed)); } static void RaiseStatusStateChanged(TweetViewModel changed) { OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Changed, changed)); } static void RaiseRefreshTweets() { OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Refresh)); } internal static void UpdateMute() { if (Setting.Instance.TimelineFilteringProperty.MuteFilterCluster == null) return; GetAll(t => Setting.Instance.TimelineFilteringProperty.MuteFilterCluster.Filter(t.Status)) .ForEach(t => { if (!AccountStorage.Contains(t.Status.User.ScreenName)) Remove(t.bindingId); }); } } public class TweetStorageChangedEventArgs : EventArgs { public TweetStorageChangedEventArgs(TweetActionKind act, TweetViewModel added = null) { this.ActionKind = act; this.Tweet = added; } public TweetViewModel Tweet { get; set; } public TweetActionKind ActionKind { get; set; } } public enum TweetActionKind { /// <summary> /// ツイートが追加された /// </summary> Added, /// <summary> /// ツイートが削除された /// </summary> Removed, /// <summary> /// ツイートの固有情報が変更された /// </summary> Changed, /// <summary> /// ストレージ全体に変更が入った /// </summary> Refresh, } }
fin-alice/Mystique
Inscribe/Storage/TweetStorage.cs
C#
mit
21,267
'use strict'; /* global angular */ (function() { var aDashboard = angular.module('aDashboard'); aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) { $scope.subState = $scope.$parent; $scope.accountValue; $scope.avgWin; $scope.avgLoss; $scope.avgTradeSize; $scope.$on('tradeActionUpdated', function(event, args) { var tradelist = args.tradelist; calculateValue( tradelist ); $scope.avgWin = calculateAvgWin( tradelist ).avg; $scope.winCount = calculateAvgWin( tradelist ).count; $scope.avgLoss = calculateAvgLoss( tradelist ).avg; $scope.lossCount = calculateAvgLoss( tradelist ).count; calculateAvgTradeSize( tradelist ); }); var getTradelist = function() { tradelistFactory.getTradelist() .then(function(tradelist) { }); }; getTradelist(); function calculateValue( tradelist ){ var sum = 0; tradelist.forEach(function(entry) { if( entry.tradeValue ){ sum += Number(entry.tradeValue); } }); $scope.accountValue = sum; }; function calculateAvgWin( tradelist ){ var sum = 0; var count = 0; tradelist.forEach(function(entry) { if( entry.tradeValue > 0 ){ ++count; sum += Number(entry.tradeValue); } }); return {avg: (sum / count).toFixed(2), count: count}; }; function calculateAvgLoss( tradelist ){ var sum = 0; var count = 0; tradelist.forEach(function(entry) { if( entry.tradeValue < 0 ){ ++count sum += Number(entry.tradeValue); } }); console.log('sum: ', sum); return {avg: (sum / count).toFixed(2), count: count}; }; function calculateAvgTradeSize( tradelist ){ var actionCount = 0; var sum = 0; tradelist.forEach(function(entry) { var actions = entry.actions; actions.forEach(function(action) { if( action.price && action.quantity ){ ++actionCount; sum = sum + (Math.abs(action.price * action.quantity)); } }); }); if( actionCount == 0 ){ actionCount = 1; } $scope.avgTradeSize = (sum / actionCount).toFixed(2); }; }); })();
LAzzam2/tradeTracker-client
app/common-components/directives/a-dashboard/a-dashboard_controller.js
JavaScript
mit
2,143
'use strict'; // MODULES // var isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), deepSet = require( 'utils-deep-set' ).factory, deepGet = require( 'utils-deep-get' ).factory; // FUNCTIONS var POW = require( './number.js' ); // POWER // /** * FUNCTION: power( arr, y, path[, sep] ) * Computes an element-wise power or each element and deep sets the input array. * * @param {Array} arr - input array * @param {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number} y - either an array of equal length or a scalar * @param {String} path - key path used when deep getting and setting * @param {String} [sep] - key path separator * @returns {Array} input array */ function power( x, y, path, sep ) { var len = x.length, opts = {}, dget, dset, v, i; if ( arguments.length > 3 ) { opts.sep = sep; } if ( len ) { dget = deepGet( path, opts ); dset = deepSet( path, opts ); if ( isTypedArrayLike( y ) ) { for ( i = 0; i < len; i++ ) { v = dget( x[ i ] ); if ( typeof v === 'number' ) { dset( x[ i ], POW( v, y[ i ] ) ); } else { dset( x[ i ], NaN ); } } } else if ( isArrayLike( y ) ) { for ( i = 0; i < len; i++ ) { v = dget( x[ i ] ); if ( typeof v === 'number' && typeof y[ i ] === 'number' ) { dset( x[ i ], POW( v, y[ i ] ) ); } else { dset( x[ i ], NaN ); } } } else { if ( typeof y === 'number' ) { for ( i = 0; i < len; i++ ) { v = dget( x[ i ] ); if ( typeof v === 'number' ) { dset( x[ i ], POW( v, y ) ); } else { dset( x[ i ], NaN ); } } } else { for ( i = 0; i < len; i++ ) { dset( x[ i ], NaN ); } } } } return x; } // end FUNCTION power() // EXPORTS // module.exports = power;
compute-io/power
lib/deepset.js
JavaScript
mit
1,889
<?php namespace repositorio\estudianteBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Sede * * @ORM\Table(name="sede") * @ORM\Entity */ class Sede { /** * @var string * * @ORM\Column(name="codigo_sede", type="string", length=5, nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $codigoSede; /** * @var string * * @ORM\Column(name="nombre_sede", type="string", length=50, nullable=false) */ private $nombreSede; /** * Get codigoSede * * @return string */ public function getCodigoSede() { return $this->codigoSede; } public function setCodigoSede($codigosede) { $this->codigosede = $codigosede; return $this; } /** * Set nombreSede * * @param string $nombreSede * @return Sede */ public function setNombreSede($nombreSede) { $this->nombreSede = $nombreSede; return $this; } /** * Get nombreSede * * @return string */ public function getNombreSede() { return $this->nombreSede; } }
dasilva93/RDDT
src/repositorio/estudianteBundle/Entity/Sede.php
PHP
mit
1,180
/** * Created by avinashvundyala on 09/07/16. */ public class SelectionSort { public int[] iterativeSelectionSort(int[] arr) { int temp, smallIdx; for(int i = 0; i < arr.length; i++) { smallIdx = i; for(int j = i; j < arr.length; j++) { if(arr[smallIdx] > arr[j]) { smallIdx = j; } } temp = arr[i]; arr[i] = arr[smallIdx]; arr[smallIdx] = temp; } return arr; } public int[] recursiveSelectionSort(int[] arr, int startIdx) { if(startIdx == arr.length) { return arr; } int temp, smallIdx; smallIdx = startIdx; for(int j = startIdx; j < arr.length; j++) { if(arr[smallIdx] > arr[j]) { smallIdx = j; } } temp = arr[startIdx]; arr[startIdx] = arr[smallIdx]; arr[smallIdx] = temp; return recursiveSelectionSort(arr, startIdx + 1); } public void printArray(int[] array) { for(int number: array) { System.out.print(String.valueOf(number) + " "); } } public static void main(String args[]) { SelectionSort ss = new SelectionSort(); int[] unsortedArray1 = {6,4,2,1,9,0}; System.out.print("Unsoreted Array Sorting: "); ss.printArray(ss.iterativeSelectionSort(unsortedArray1)); int[] unsortedArray2 = {1,2,3,4,5,6}; System.out.print("\nAlready Soreted Array Sorting: "); ss.printArray(ss.iterativeSelectionSort(unsortedArray2)); int[] unsortedArray3 = {6,5,4,3,2,1}; System.out.print("\nUnsoreted Array Sorting: "); ss.printArray(ss.iterativeSelectionSort(unsortedArray3)); int[] unsortedArray4 = {6,4,2,1,9,0}; System.out.print("\nUnsoreted Array Sorting: "); ss.printArray(ss.recursiveSelectionSort(unsortedArray4, 0)); int[] unsortedArray5 = {1,2,3,4,5,6}; System.out.print("\nAlready Soreted Array Sorting: "); ss.printArray(ss.recursiveSelectionSort(unsortedArray5, 0)); int[] unsortedArray6 = {6,5,4,3,2,1}; System.out.print("\nUnsoreted Array Sorting: "); ss.printArray(ss.recursiveSelectionSort(unsortedArray6, 0)); } }
vundyalaavinash/Algorithms
BasicSorting/SelectionSort.java
Java
mit
2,176
'use strict'; function getReferenceMatrix (matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); return matrix.clone({ axes: [ Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])}) ], data: referenceMatrix.map(r => r[1]) }); } function complexSort () {//matrix, direction, strategy, dimension) { // const referenceMatrix = getReferenceMatrix(matrix.reduce(strategy, dimension), direction); } module.exports.ascending = function (strategy, dimension) { if (this.dimension === 1) { return simpleSort(this, 'asc'); } else if (this.dimension === 2) { throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!'); return complexSort(this, 'asc', strategy, dimension); } else { throw new Error('Cannot sort tables of dimesnion greater than 2'); } } module.exports.descending = function (strategy, dimension) { if (this.dimension === 1) { return simpleSort(this, 'desc'); } else if (this.dimension === 2) { throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!'); return complexSort(this, 'desc', strategy, dimension); } else { throw new Error('Cannot sort tables of dimesnion greater than 2'); } } function getReferenceMatrix (matrix, direction) { return matrix.unflatten().rows.sort((r1, r2) => { return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1); }); } function simpleSort (matrix, direction) { const referenceMatrix = getReferenceMatrix(matrix, direction); return matrix.clone({ axes: [ Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])}) ], data: referenceMatrix.map(r => r[1]) }); } module.exports.property = function (prop) { const order = [].slice.call(arguments, 1); const dimension = this.getAxis(prop); if (dimension === -1) { throw new Error(`Attempting to do a custom sort on the property ${prop}, which doesn't exist`); } const originalValues = this.axes.find(a => a.property === prop).values; // this makes it easier to put the not found items last as the order // will go n = first, n-1 = second, ... , 0 = last, -1 = not found // we simply exchange 1 and -1 in the function below :o order.reverse(); const orderedValues = originalValues.slice().sort((v1, v2) => { const i1 = order.indexOf(v1); const i2 = order.indexOf(v2); return i1 > i2 ? -1 : i1 < i2 ? 1 : 0; }); const mapper = originalValues.map(v => orderedValues.indexOf(v)) const newAxes = this.axes.slice(); newAxes[dimension] = Object.assign({}, this.axes[dimension], { values: orderedValues }); return this.clone({ axes: newAxes, data: Object.keys(this.data).reduce((obj, k) => { const coords = k.split(','); coords[dimension] = mapper[coords[dimension]]; obj[coords.join(',')] = this.data[k]; return obj; }, {}) }); }
Financial-Times/keen-query
lib/post-processing/sort.js
JavaScript
mit
3,082
""" Initialize Flask app """ from flask import Flask import os from flask_debugtoolbar import DebugToolbarExtension from werkzeug.debug import DebuggedApplication app = Flask('application') if os.getenv('FLASK_CONF') == 'DEV': # Development settings app.config.from_object('application.settings.Development') # Flask-DebugToolbar toolbar = DebugToolbarExtension(app) # Google app engine mini profiler # https://github.com/kamens/gae_mini_profiler app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) from gae_mini_profiler import profiler, templatetags @app.context_processor def inject_profiler(): return dict(profiler_includes=templatetags.profiler_includes()) app.wsgi_app = profiler.ProfilerWSGIMiddleware(app.wsgi_app) elif os.getenv('FLASK_CONF') == 'TEST': app.config.from_object('application.settings.Testing') else: app.config.from_object('application.settings.Production') # Enable jinja2 loop controls extension app.jinja_env.add_extension('jinja2.ext.loopcontrols') # Pull in URL dispatch routes import urls
nwinter/bantling
src/application/__init__.py
Python
mit
1,104
/* * @(#)Function2Arg.cs 3.0.0 2016-05-07 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ using System; namespace org.mariuszgromada.math.mxparser.parsertokens { /** * Binary functions (2 arguments) - mXparser tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 3.0.0 */ [CLSCompliant(true)] public sealed class Function2Arg { /* * BinaryFunction - token type id. */ public const int TYPE_ID = 5; public const String TYPE_DESC = "Binary Function"; /* * BinaryFunction - tokens id. */ public const int LOG_ID = 1; public const int MOD_ID = 2; public const int BINOM_COEFF_ID = 3; public const int BERNOULLI_NUMBER_ID = 4; public const int STIRLING1_NUMBER_ID = 5; public const int STIRLING2_NUMBER_ID = 6; public const int WORPITZKY_NUMBER_ID = 7; public const int EULER_NUMBER_ID = 8; public const int KRONECKER_DELTA_ID = 9; public const int EULER_POLYNOMIAL_ID = 10; public const int HARMONIC_NUMBER_ID = 11; public const int RND_UNIFORM_CONT_ID = 12; public const int RND_UNIFORM_DISCR_ID = 13; public const int ROUND_ID = 14; public const int RND_NORMAL_ID = 15; /* * BinaryFunction - tokens key words. */ public const String LOG_STR = "log"; public const String MOD_STR = "mod"; public const String BINOM_COEFF_STR = "C"; public const String BERNOULLI_NUMBER_STR = "Bern"; public const String STIRLING1_NUMBER_STR = "Stirl1"; public const String STIRLING2_NUMBER_STR = "Stirl2"; public const String WORPITZKY_NUMBER_STR = "Worp"; public const String EULER_NUMBER_STR = "Euler"; public const String KRONECKER_DELTA_STR = "KDelta"; public const String EULER_POLYNOMIAL_STR = "EulerPol"; public const String HARMONIC_NUMBER_STR = "Harm"; public const String RND_UNIFORM_CONT_STR = "rUni"; public const String RND_UNIFORM_DISCR_STR = "rUnid"; public const String ROUND_STR = "round"; public const String RND_NORMAL_STR = "rNor"; /* * BinaryFunction - tokens description. */ public const String LOG_DESC = "logarithm function"; public const String MOD_DESC = "modulo function"; public const String BINOM_COEFF_DESC = "binomial coefficient function"; public const String BERNOULLI_NUMBER_DESC = "Bernoulli numbers"; public const String STIRLING1_NUMBER_DESC = "Stirling numbers of the first kind"; public const String STIRLING2_NUMBER_DESC = "Stirling numbers of the second kind"; public const String WORPITZKY_NUMBER_DESC = "Worpitzky number"; public const String EULER_NUMBER_DESC = "Euler number"; public const String KRONECKER_DELTA_DESC = "Kronecker delta"; public const String EULER_POLYNOMIAL_DESC = "EulerPol"; public const String HARMONIC_NUMBER_DESC = "Harmonic number"; public const String RND_UNIFORM_CONT_DESC = "(3.0) Random variable - Uniform continuous distribution U(a,b), usage example: 2*rUni(2,10)"; public const String RND_UNIFORM_DISCR_DESC = "(3.0) Random variable - Uniform discrete distribution U{a,b}, usage example: 2*rUnid(2,100)"; public const String ROUND_DESC = "(3.0) Half-up rounding, usage examples: round(2.2, 0) = 2, round(2.6, 0) = 3, round(2.66,1) = 2.7"; public const String RND_NORMAL_DESC = "(3.0) Random variable - Normal distribution N(m,s) m - mean, s - stddev, usage example: 3*rNor(0,1)"; } }
Domiii/UnityLoopyLoops
Assets/Scripts/mXparser/parsertokens/Function2Arg.cs
C#
mit
7,388
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Dapper; using MicroOrm.Dapper.Repositories.Extensions; namespace MicroOrm.Dapper.Repositories { /// <summary> /// Base Repository /// </summary> public partial class DapperRepository<TEntity> where TEntity : class { /// <inheritdoc /> public bool BulkUpdate(IEnumerable<TEntity> instances) { return BulkUpdate(instances, null); } /// <inheritdoc /> public bool BulkUpdate(IEnumerable<TEntity> instances, IDbTransaction transaction) { var queryResult = SqlGenerator.GetBulkUpdate(instances); var result = TransientDapperExtentions.ExecuteWithRetry(() => Connection.Execute(queryResult.GetSql(), queryResult.Param, transaction)) > 0; return result; } /// <inheritdoc /> public Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances) { return BulkUpdateAsync(instances, null); } /// <inheritdoc /> public async Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances, IDbTransaction transaction) { var queryResult = SqlGenerator.GetBulkUpdate(instances); var result = (await TransientDapperExtentions.ExecuteWithRetryAsync(() => Connection.ExecuteAsync(queryResult.GetSql(), queryResult.Param, transaction))) > 0; return result; } } }
digitalmedia34/MicroOrm.Dapper.Repositories
src/MicroOrm.Dapper.Repositories/DapperRepository.BulkUpdate.cs
C#
mit
1,489
import watch from 'gulp-watch'; import browserSync from 'browser-sync'; import path from 'path'; /** * Gulp task to watch files * @return {function} Function task */ export default function watchFilesTask() { const config = this.config; const runSequence = require('run-sequence').use(this.gulp); return () => { if (config.entryHTML) { watch( path.join( config.basePath, config.browsersync.server.baseDir, config.entryHTML ), () => { runSequence('build', browserSync.reload); } ); } if (config.postcss) { watch(path.join(config.sourcePath, '**/*.{css,scss,less}'), () => { runSequence('postcss'); }); } if (config.customWatch) { if (typeof config.customWatch === 'function') { config.customWatch(config, watch, browserSync); } else { watch(config.customWatch, () => { runSequence('build', browserSync.reload); }); } } }; }
geut/gulp-appfy-tasks
src/tasks/watch-files.js
JavaScript
mit
1,211
<?php namespace MiniGameMessageApp\Parser; use MiniGame\Entity\MiniGameId; use MiniGame\Entity\PlayerId; interface ParsingPlayer { /** * @return PlayerId */ public function getPlayerId(); /** * @return MiniGameId */ public function getGameId(); }
remi-san/mini-game-message-app
src/Parser/ParsingPlayer.php
PHP
mit
287
import { Editor, EditorState, RichUtils } from "draft-js" import { debounce } from "lodash" import React, { Component } from "react" import ReactDOM from "react-dom" import styled from "styled-components" import { TextInputUrl } from "../components/text_input_url" import { TextNav } from "../components/text_nav" import { decorators } from "../shared/decorators" import { confirmLink, linkDataFromSelection, removeLink } from "../shared/links" import { handleReturn, insertPastedState, styleMapFromNodes, styleNamesFromMap, } from "../shared/shared" import { AllowedStyles, StyleMap, StyleNamesParagraph } from "../typings" import { convertDraftToHtml, convertHtmlToDraft } from "./utils/convert" import { allowedStylesParagraph, blockRenderMap, keyBindingFn, } from "./utils/utils" interface Props { allowedStyles?: AllowedStyles allowEmptyLines?: boolean // Users can insert br tags html?: string hasLinks: boolean onChange: (html: string) => void placeholder?: string stripLinebreaks: boolean // Return a single p block isDark?: boolean isReadOnly?: boolean } interface State { editorPosition: ClientRect | null editorState: EditorState html: string showNav: boolean showUrlInput: boolean urlValue: string } /** * Supports HTML with bold and italic styles in <p> blocks. * Allowed styles can be limited by passing allowedStyles. * Optionally supports links, and linebreak stripping. */ export class Paragraph extends Component<Props, State> { private editor private allowedStyles: StyleMap private debouncedOnChange static defaultProps = { allowEmptyLines: false, hasLinks: false, stripLinebreaks: false, } constructor(props: Props) { super(props) this.allowedStyles = styleMapFromNodes( props.allowedStyles || allowedStylesParagraph ) this.state = { editorPosition: null, editorState: this.setEditorState(), html: props.html || "", showNav: false, showUrlInput: false, urlValue: "", } this.debouncedOnChange = debounce((html: string) => { props.onChange(html) }, 250) } setEditorState = () => { const { hasLinks, html } = this.props if (html) { return this.editorStateFromHTML(html) } else { return EditorState.createEmpty(decorators(hasLinks)) } } editorStateToHTML = (editorState: EditorState) => { const { allowEmptyLines, stripLinebreaks } = this.props const currentContent = editorState.getCurrentContent() return convertDraftToHtml( currentContent, this.allowedStyles, stripLinebreaks, allowEmptyLines ) } editorStateFromHTML = (html: string) => { const { hasLinks, allowEmptyLines } = this.props const contentBlocks = convertHtmlToDraft( html, hasLinks, this.allowedStyles, allowEmptyLines ) return EditorState.createWithContent(contentBlocks, decorators(hasLinks)) } onChange = (editorState: EditorState) => { const html = this.editorStateToHTML(editorState) this.setState({ editorState, html }) if (html !== this.props.html) { // Return html if changed this.debouncedOnChange(html) } } focus = () => { this.editor.focus() this.checkSelection() } handleReturn = e => { const { editorState } = this.state const { stripLinebreaks, allowEmptyLines } = this.props if (stripLinebreaks) { // Do nothing if linebreaks are disallowed return "handled" } else if (allowEmptyLines) { return "not-handled" } else { // Maybe split-block, but don't create empty paragraphs return handleReturn(e, editorState) } } handleKeyCommand = (command: string) => { const { hasLinks } = this.props switch (command) { case "link-prompt": { if (hasLinks) { // Open link input if links are supported return this.promptForLink() } break } case "bold": case "italic": { return this.keyCommandInlineStyle(command) } } // let draft defaults or browser handle return "not-handled" } keyCommandInlineStyle = (command: "italic" | "bold") => { // Handle style changes from key command const { editorState } = this.state const styles = styleNamesFromMap(this.allowedStyles) if (styles.includes(command.toUpperCase())) { const newState = RichUtils.handleKeyCommand(editorState, command) // If an updated state is returned, command is handled if (newState) { this.onChange(newState) return "handled" } } else { return "not-handled" } } toggleInlineStyle = (command: StyleNamesParagraph) => { // Handle style changes from menu click const { editorState } = this.state const styles = styleNamesFromMap(this.allowedStyles) let newEditorState if (styles.includes(command)) { newEditorState = RichUtils.toggleInlineStyle(editorState, command) } if (newEditorState) { this.onChange(newEditorState) } } handlePastedText = (text: string, html?: string) => { const { editorState } = this.state if (!html) { // Wrap pasted plain text in html html = "<p>" + text + "</p>" } const stateFromPastedFragment = this.editorStateFromHTML(html) const stateWithPastedText = insertPastedState( stateFromPastedFragment, editorState ) this.onChange(stateWithPastedText) return true } promptForLink = () => { // Opens a popup link input populated with selection data if link is selected const { editorState } = this.state const linkData = linkDataFromSelection(editorState) const urlValue = linkData ? linkData.url : "" const editor = ReactDOM.findDOMNode(this.editor) as Element const editorPosition: ClientRect = editor.getBoundingClientRect() this.setState({ editorPosition, showUrlInput: true, showNav: false, urlValue, }) return "handled" } confirmLink = (url: string) => { const { editorState } = this.state const newEditorState = confirmLink(url, editorState) this.setState({ editorPosition: null, showNav: false, showUrlInput: false, urlValue: "", }) this.onChange(newEditorState) } removeLink = () => { const editorState = removeLink(this.state.editorState) if (editorState) { this.setState({ editorPosition: null, showUrlInput: false, urlValue: "", }) this.onChange(editorState) } } checkSelection = () => { let showNav = false let editorPosition: ClientRect | null = null const hasSelection = !window.getSelection().isCollapsed if (hasSelection) { showNav = true const editor = ReactDOM.findDOMNode(this.editor) as Element editorPosition = editor.getBoundingClientRect() } this.setState({ showNav, editorPosition }) } render() { const { hasLinks, isDark, isReadOnly, placeholder } = this.props const { editorPosition, editorState, showNav, showUrlInput, urlValue, } = this.state const promptForLink = hasLinks ? this.promptForLink : undefined return ( <ParagraphContainer> {showNav && ( <TextNav allowedStyles={this.allowedStyles} editorPosition={editorPosition} onClickOff={() => this.setState({ showNav: false })} promptForLink={promptForLink} toggleStyle={this.toggleInlineStyle} /> )} {showUrlInput && ( <TextInputUrl backgroundColor={isDark ? "white" : undefined} editorPosition={editorPosition} onClickOff={() => this.setState({ showUrlInput: false })} onConfirmLink={this.confirmLink} onRemoveLink={this.removeLink} urlValue={urlValue} /> )} <div onClick={this.focus} onMouseUp={this.checkSelection} onKeyUp={this.checkSelection} > <Editor blockRenderMap={blockRenderMap as any} editorState={editorState} keyBindingFn={keyBindingFn} handleKeyCommand={this.handleKeyCommand as any} handlePastedText={this.handlePastedText as any} handleReturn={this.handleReturn} onChange={this.onChange} placeholder={placeholder || "Start typing..."} readOnly={isReadOnly} ref={ref => { this.editor = ref }} spellCheck /> </div> </ParagraphContainer> ) } } const ParagraphContainer = styled.div` position: relative; `
eessex/positron
src/client/components/draft/paragraph/paragraph.tsx
TypeScript
mit
8,791
<?php namespace Demo\TaskBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class CustomerControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/demo_taskcustomer/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /demo_taskcustomer/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'demo_taskbundle_customertype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'demo_taskbundle_customertype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
prabhucomo/symfonytask
src/Demo/TaskBundle/Tests/Controller/CustomerControllerTest.php
PHP
mit
1,959
// load package date-util require('../libs/sugar-date') module.exports = (pluginContext) => { return { respondsTo: (query) => { return true }, search: (query = '', env = {}) => { // check if timestamp given let isTimestamp = !isNaN(parseFloat(query)) && isFinite(query); // default settings let outputFormat = env['outputFormat'] || '{full}'; let timestampUnit = 'seconds'; // override timestamp unit if (env['timestampUnit'] && env['timestampUnit'] == 'milliseconds') { timestampUnit = 'milliseconds'; } // check if string or timestamp is given if (!isTimestamp) { // handle timestamp unit if (timestampUnit == 'seconds') { // timestamp in seconds outputFormat = '{X}'; } else { // timestamp in milliseconds outputFormat = '{x}'; } } else { // parse query query = parseFloat(query); // convert given timestamp in seconds to milliseconds if (timestampUnit == 'seconds') { query *= 1000; } } // create Sugar Date var sugarDate = Sugar.Date.create(query); // check if valid date if (!Sugar.Date.isValid(sugarDate)) { return Promise.reject(); } // set result value const value = Sugar.Date.format(sugarDate, outputFormat); // set result subtitle const subtitle = `Select to copy ` + (isTimestamp ? `the formatted date` : `the timestamp in ${timestampUnit}`) + `.`; // return results return new Promise((resolve, reject) => { resolve([ { id: 'zazu-utime', icon: 'fa-clock-o', title: value, subtitle: subtitle, value: value, } ]) }) } } }
puyt/zazu-utime
src/utime.js
JavaScript
mit
2,252
<?php /** * @package jelix * @subpackage utils * @author Laurent Jouanneau * @contributor Julien Issler * @copyright 2006-2009 Laurent Jouanneau * @copyright 2008 Julien Issler * @link http://www.jelix.org * @licence http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * utility class to check values * @package jelix * @subpackage utils * @since 1.0b1 */ class jFilter { private function _construct() {} static public function usePhpFilter(){ return true; } /** * check if the given value is an integer * @param string $val the value * @param int $min minimum value (optional), null if no minimum * @param int $max maximum value (optional), null if no maximum * @return boolean true if it is valid */ static public function isInt ($val, $min=null, $max=null){ // @FIXME pas de doc sur la façon d'utiliser les min/max sur les filters if(filter_var($val, FILTER_VALIDATE_INT) === false) return false; if($min !== null && intval($val) < $min) return false; if($max !== null && intval($val) > $max) return false; return true; } /** * check if the given value is an hexadecimal integer * @param string $val the value * @param int $min minimum value (optional), null if no minimum * @param int $max maximum value (optional), null if no maximum * @return boolean true if it is valid */ static public function isHexInt ($val, $min=null, $max=null){ // @FIXME pas de doc sur la façon d'utiliser les min/max sur les filters if(filter_var($val, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX) === false) return false; if($min !== null && intval($val,16) < $min) return false; if($max !== null && intval($val,16) > $max) return false; return true; } /** * check if the given value is a boolean * @param string $val the value * @return boolean true if it is valid */ static public function isBool ($val){ // we don't use filter_var because it return false when a boolean is "false" or "FALSE" etc.. //return filter_var($val, FILTER_VALIDATE_BOOLEAN); return in_array($val, array('true','false','1','0','TRUE', 'FALSE','on','off')); } /** * check if the given value is a float * @param string $val the value * @param int $min minimum value (optional), null if no minimum * @param int $max maximum value (optional), null if no maximum * @return boolean true if it is valid */ static public function isFloat ($val, $min=null, $max=null){ // @FIXME pas de doc sur la façon d'utiliser les min/max sur les filters if(filter_var($val, FILTER_VALIDATE_FLOAT) === false) return false; if($min !== null && floatval($val) < $min) return false; if($max !== null && floatval($val) > $max) return false; return true; } /** * check if the given value is * @param string $url the url * @return boolean true if it is valid */ static public function isUrl ($url, $schemeRequired=false, $hostRequired=false, $pathRequired=false, $queryRequired=false ){ /* because of a bug in filter_var (error when no scheme even if there isn't FILTER_FLAG_SCHEME_REQUIRED flag), we don't use filter_var here $flag=0; if($schemeRequired) $flag |= FILTER_FLAG_SCHEME_REQUIRED; if($hostRequired) $flag |= FILTER_FLAG_HOST_REQUIRED; if($pathRequired) $flag |= FILTER_FLAG_PATH_REQUIRED; if($queryRequired) $flag |= FILTER_FLAG_QUERY_REQUIRED; return filter_var($url, FILTER_VALIDATE_URL, $flag); */ // php filter use in fact parse_url, so we use the same function to have same result. // however, note that it doesn't validate all bad url... $res=@parse_url($url); if($res === false) return false; if($schemeRequired && !isset($res['scheme'])) return false; if($hostRequired && !isset($res['host'])) return false; if($pathRequired && !isset($res['path'])) return false; if($queryRequired && !isset($res['query'])) return false; return true; } /** * check if the given value is an IP version 4 * @param string $val the value * @return boolean true if it is valid */ static public function isIPv4 ($val){ return filter_var($val, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; } /** * check if the given value is an IP version 6 * @param string $val the value * @return boolean true if it is valid */ static public function isIPv6 ($val){ return filter_var($val, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; } /** * check if the given value is an email * @param string $val the value * @return boolean true if it is valid */ static public function isEmail ($val){ return filter_var($val, FILTER_VALIDATE_EMAIL) !== false; } const INVALID_HTML = 1; const BAD_SAVE_HTML = 2; /** * remove all javascript things in a html content * The html content should be a subtree of a body tag, not a whole document * @param string $html html content * @return string the cleaned html content * @since 1.1 */ static public function cleanHtml($html, $isXhtml = false) { global $gJConfig; $doc = new DOMDocument('1.0',$gJConfig->charset); $foot = '</body></html>'; if (strpos($html, "\r") !== false) { $html = str_replace("\r\n", "\n", $html); // removed \r $html = str_replace("\r", "\n", $html); // removed standalone \r } /*if($isXhtml) { $head = '<?xml version="1.0" encoding=""?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset='.$gJConfig->charset.'"/><title></title></head><body>'; if(!$doc->loadXML($head.$html.$foot)) { return 1; } }else{*/ $head = '<html><head><meta http-equiv="Content-Type" content="text/html; charset='.$gJConfig->charset.'"/><title></title></head><body>'; if(!@$doc->loadHTML($head.$html.$foot)) { return jFilter::INVALID_HTML; } //} $items = $doc->getElementsByTagName('script'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('applet'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('base'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('basefont'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('frame'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('frameset'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('noframes'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('isindex'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('iframe'); foreach ($items as $item) { $item->parentNode->removeChild($item); } $items = $doc->getElementsByTagName('noscript'); foreach ($items as $item) { $item->parentNode->removeChild($item); } self::cleanAttr($doc->getElementsByTagName('body')->item(0)); $doc->formatOutput = true; if ($isXhtml) { $result = $doc->saveXML(); } else { $result = $doc->saveHTML(); } if(!preg_match('!<body>(.*)</body>!smU', $result, $m)) return jFilter::BAD_SAVE_HTML; return $m[1]; } static protected function cleanAttr($node) { $child=$node->firstChild; while($child) { if($child->nodeType == XML_ELEMENT_NODE) { $attrs = $child->attributes; foreach($attrs as $attr) { if(strtolower(substr($attr->localName,0,2)) == 'on') $child->removeAttributeNode($attr); else if(strtolower($attr->localName) == 'href') { if(preg_match("/^([a-z\-]+)\:.*/i",trim($attr->nodeValue), $m)) { if(!preg_match('/^http|https|mailto|ftp|irc|about|news/i', $m[1])) $child->removeAttributeNode($attr); } } } self::cleanAttr($child); } $child = $child->nextSibling; } } }
yvestan/sendui
app/lib/jelix/utils/jFilter.class.php
PHP
mit
9,383
namespace KitchenPC.DB.Models { using System; using FluentNHibernate.Mapping; public class RecipeRatingsMap : ClassMap<RecipeRatings> { public RecipeRatingsMap() { this.Id(x => x.RatingId) .GeneratedBy.GuidComb() .UnsavedValue(Guid.Empty); this.Map(x => x.UserId).Not.Nullable().Index("IDX_RecipeRatings_UserId").UniqueKey("UserRating"); this.Map(x => x.Rating).Not.Nullable(); this.References(x => x.Recipe).Not.Nullable().Index("IDX_RecipeRatings_RecipeId").UniqueKey("UserRating"); } } }
Derneuca/KitchenPCTeamwork
KitchenPC/DB/Models/RecipeRatingsMap.cs
C#
mit
638
<?php defined('SYSPATH') OR die('No direct access allowed.'); /** * OAuth2 Controller * * @author Ushahidi Team <team@ushahidi.com> * @package Ushahidi\Koauth * @copyright Ushahidi - http://www.ushahidi.com * @license MIT License http://opensource.org/licenses/MIT */ abstract class Koauth_Controller_OAuth extends Controller { protected $_oauth2_server; protected $_skip_oauth_response = FALSE; /** * @var array Map of HTTP methods -> actions */ protected $_action_map = array ( Http_Request::POST => 'post', // Typically Create.. Http_Request::GET => 'get', Http_Request::PUT => 'put', // Typically Update.. Http_Request::DELETE => 'delete', ); public function before() { parent::before(); // Get the basic verb based action.. $action = $this->_action_map[$this->request->method()]; // If this is a custom action, lets make sure we use it. if ($this->request->action() != '_none') { $action .= '_'.$this->request->action(); } // Override the action $this->request->action($action); // Set up OAuth2 objects $this->_oauth2_server = new Koauth_OAuth2_Server(); } public function after() { if (! $this->_skip_oauth_response) { $this->_oauth2_server->processResponse($this->response); } } /** * Authorize Requests */ public function action_get_authorize() { if (! ($params = $this->_oauth2_server->validateAuthorizeRequest(Koauth_OAuth2_Request::createFromRequest($this->request), new OAuth2_Response())) ) { return; } // Show authorize yes/no $this->_skip_oauth_response = TRUE; $view = View::factory('oauth/authorize'); $view->scopes = explode(',', $params['scope']); $view->params = $params; $this->response->body($view->render()); } /** * Authorize Requests */ public function action_post_authorize() { $authorized = (bool) $this->request->post('authorize'); $this->_oauth2_server->handleAuthorizeRequest(Koauth_OAuth2_Request::createFromRequest($this->request), new OAuth2_Response(), $authorized); } /** * Token Requests */ public function action_get_token() { $this->_oauth2_server->handleTokenRequest(Koauth_OAuth2_Request::createFromRequest($this->request), new OAuth2_Response()); } /** * Token Requests */ public function action_post_token() { $this->_oauth2_server->handleTokenRequest(Koauth_OAuth2_Request::createFromRequest($this->request), new OAuth2_Response()); } }
ushahidi/koauth
classes/Koauth/Controller/OAuth.php
PHP
mit
2,457
package adasim.algorithm.routing; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Stack; import org.apache.log4j.Logger; import org.jdom.Element; import adasim.model.AdasimMap; import adasim.model.ConfigurationException; import adasim.model.RoadSegment; import adasim.model.TrafficSimulator; import adasim.model.internal.FilterMap; import adasim.model.internal.SimulationXMLReader; import adasim.model.internal.VehicleManager; public class QLearningRoutingAlgorithm extends AbstractRoutingAlgorithm { private boolean finished = false; private final double alpha = 0.1; // Learning rate private final double gamma = 0.9; // Eagerness - 0 looks in the near future, 1 looks in the distant future private int statesCount ; private final int reward = 100; private final int penalty = -10; private int[][] R; // Reward lookup private double[][] Q; // Q learning private final int lookahead; private final int recompute; private int steps; private List<RoadSegment> path; RoadSegment currentSource =null; private final static Logger logger = Logger.getLogger(LookaheadShortestPathRoutingAlgorithm.class); public QLearningRoutingAlgorithm() { this(2,2); } public QLearningRoutingAlgorithm( int lookahead, int recomp ){ this.lookahead = lookahead; this.recompute = recomp; this.steps = 0; logger.info( "QLearningRoutingAlgorithm(" + lookahead + "," + recompute +")" ); } /* * Map Road segment to 2d array for q learninig to work on * * */ public void mapSegmentToArray(List<RoadSegment> listOfRoadSegment ) { Collections.sort(listOfRoadSegment); // Make sure we alwasy loading sorted Map //int dim = listOfRoadSegment.size() +1; // dimention of 2d array R = new int[statesCount][statesCount]; Q = new double[statesCount][statesCount]; // set all cells with -1 for the impossible transitions for(int i=0;i<statesCount ;i++) { for(int j=0;j<statesCount ;j++) { R[i][j]= -1; } } // set cells with 0 where agent could move for (RoadSegment roadSegment : listOfRoadSegment) { for (RoadSegment roadSegmentNeighbors : roadSegment.getNeighbors()) { R[roadSegment.getID()][roadSegmentNeighbors.getID()]= 0; // forword drive // R[roadSegmentNeighbors.getID()][roadSegment.getID()]= 0; //backword drive // set reword for reaching the target if(roadSegmentNeighbors.getID() == target.getID() ) { R[roadSegment.getID()][roadSegmentNeighbors.getID()]= reward; } // if(roadSegment.getID() == target ) { // R[roadSegmentNeighbors.getID()][roadSegment.getID()]= reward; // } } } // set reword for reaching goal //R[target][target]= reward; initializeQ(); } //Set Q values to R values void initializeQ() { for (int i = 0; i < statesCount; i++){ for(int j = 0; j < statesCount; j++){ Q[i][j] = (double)R[i][j]; } } } // Used for debug void printR() { System.out.printf("%25s", "States: "); for (int i = 0; i < statesCount; i++) { System.out.printf("%4s", i); } System.out.println(); for (int i = 0; i < statesCount; i++) { System.out.print("Possible states from " + i + " :["); for (int j = 0; j < statesCount; j++) { System.out.printf("%4s", R[i][j]); } System.out.println("]"); } } void calculateQ() { Random rand = new Random(); for (int i = 0; i < 1000; i++) { // Train cycles // Select random initial state int crtState = currentSource.getID();// set source base on input rand.nextInt(statesCount); while (!isFinalState(crtState)) { int[] actionsFromCurrentState = possibleActionsFromState(crtState); // Pick a random action from the ones possible int index = rand.nextInt(actionsFromCurrentState.length); int nextState = actionsFromCurrentState[index]; // Q(state,action)= Q(state,action) + alpha * (R(state,action) + gamma * Max(next state, all actions) - Q(state,action)) double q = Q[crtState][nextState]; double maxQ = maxQ(nextState); int r = R[crtState][nextState]; double value = q + alpha * (r + gamma * maxQ - q); Q[crtState][nextState] = value; crtState = nextState; } } } boolean isFinalState(int state) { return state == target.getID(); } int[] possibleActionsFromState(int state) { ArrayList<Integer> result = new ArrayList<>(); for (int i = 0; i < statesCount; i++) { if (R[state][i] != -1) { result.add(i); } } return result.stream().mapToInt(i -> i).toArray(); } double maxQ(int nextState) { int[] actionsFromState = possibleActionsFromState(nextState); //the learning rate and eagerness will keep the W value above the lowest reward double maxValue = -10; for (int nextAction : actionsFromState) { double value = Q[nextState][nextAction]; if (value > maxValue) maxValue = value; } return maxValue; } void printPolicy() { System.out.println("\nPrint policy"); for (int i = 0; i < statesCount; i++) { System.out.println("From state " + i + " goto state " + getPolicyFromState(i)); } } int getPolicyFromState(int state) { int[] actionsFromState = possibleActionsFromState(state); double maxValue = Double.MIN_VALUE; int policyGotoState = state; // Pick to move to the state that has the maximum Q value for (int nextState : actionsFromState) { double value = Q[state][nextState]; if (value > maxValue) { maxValue = value; policyGotoState = nextState; } } return policyGotoState; } void printQ() { System.out.println("\nQ matrix"); for (int i = 0; i < Q.length; i++) { System.out.print("From state " + i + ": "); for (int j = 0; j < Q[i].length; j++) { System.out.printf("%6.2f ", (Q[i][j])); } System.out.println(); } } @Override public List<RoadSegment> getPath(RoadSegment from, RoadSegment to) { currentSource = from; // get path List<RoadSegment> nodes = graph.getRoadSegments(); statesCount = nodes.size(); mapSegmentToArray(nodes); // convert segments to 2d array calculateQ(); // calculate q-learninig System.out.println("========================Source: " + currentSource.getID() +", Target: "+ target.getID() + "==============================="); printR(); printQ(); printPolicy(); List<RoadSegment> newListOfNodes = new ArrayList<RoadSegment>( ); // get path using stack Stack<Integer> st= new Stack<Integer>(); st.add(getPolicyFromState(from.getID())); while( !st.isEmpty()){ int currentState= st.pop(); newListOfNodes.add(nodes.get(currentState)); if(currentState == to.getID()) { break; } int nextSate = getPolicyFromState(currentState); st.add(nextSate); } System.out.println("\nRoadSegments: "); for (RoadSegment roadSegment : newListOfNodes) { System.out.println("\tSegment ID:"+roadSegment.getID()); System.out.println("\t \tNeighbors: "+ roadSegment.getNeighbors()); } System.out.println("======================================================="); if ( newListOfNodes == null ) { finished = true; } return newListOfNodes; } @Override public RoadSegment getNextNode() { if ( finished ) return null; if ( path == null ) { path = getPath(source); logger.info( pathLogMessage() ); } assert path != null || finished; if ( path == null || path.size() == 0 ) { finished = true; return null; } if ( ++steps == recompute ) { RoadSegment next = path.remove(0); path = getPath(next); logger.info( "UPDATE: " + pathLogMessage() ); steps = 0; return next; } else { return path.remove(0); } } /** * Computes a path to the configured target node starting from * the passed <code>start</code> node. * @param start */ private List<RoadSegment> getPath(RoadSegment start) { List<RoadSegment> p = getPath( start, target ); if ( p == null ) { finished = true; } return p; } private String pathLogMessage() { StringBuffer buf = new StringBuffer( "PATH: Vehicle: " ); buf.append( vehicle.getID() ); buf.append( " From: " ); buf.append( source.getID() ); buf.append( " To: " ); buf.append( target.getID() ); buf.append( " Path: " ); buf.append( path == null ? "[]" : path ); return buf.toString(); } }
brunyuriy/adasim
src/adasim/algorithm/routing/QLearningRoutingAlgorithm.java
Java
mit
9,693
'use strict'; describe('Directive: cssCode', function () { // load the directive's module and view beforeEach(module('googleWebfontsHelperApp')); beforeEach(module('app/cssCode/cssCode.html')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<css-code></css-code>'); element = $compile(element)(scope); scope.$apply(); expect(element.text()).toBe('this is the cssCode directive'); })); });
majodev/google-webfonts-helper
client/app/cssCode/cssCode.directive.spec.js
JavaScript
mit
573
using Android.OS; using GetAllLinks.Core.ViewModels; using MvvmCross.Droid.Shared.Attributes; using Android.Views; namespace GetAllLinks.Droid.Views { [MvxFragment(typeof(MainActivityViewModel), Resource.Layout.settingsView, ViewModelType = typeof(SettingsViewModel), IsCacheableFragment = false)] public class SettingsFragment : BaseFragment<SettingsViewModel> { public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { var view = base.OnCreateView(inflater, container, savedInstanceState); return view; } } }
spanishprisoner/GetAllLinks
src/GetAllLinks.Droid/Views/SettingsFragment.cs
C#
mit
580
<?php /** * This file is part of Cacheable. * * (c) Eric Chow <yateric@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Yateric\Tests\Stubs; use Yateric\Cacheable\Cacheable; class DecoratedObject { use Cacheable; public function nonStaticMethod($parameter = '') { return "nonstatic{$parameter}"; } public static function staticMethod($parameter = '') { return "static{$parameter}"; } }
yateric/cacheable
tests/Stubs/DecoratedObject.php
PHP
mit
544
var assert = require('assert'); var keys = require("cmd/common/keys/user.js"); var userKeysNock = require('test/fixtures/user/fixture_user_keys'); module.exports = { setUp : function(cb){ return cb(); }, 'list keys' : function(cb){ keys({ _ : ['list'] }, function(err, list){ assert.equal(err, null, err); assert.ok(list); assert.equal(list.list.length, 1); return cb(); }); }, 'create keys' : function(cb){ keys({ _ : ['add'] }, function(err){ assert.ok(!err, err); keys({ _ : ['add', 'UserKey'] }, function(err, key){ assert.equal(err, null, err); assert.ok(key.apiKey); assert.ok(key.apiKey.label); assert.ok(key.apiKey.key); return cb(); }); }); }, 'revoke keys' : function(cb){ keys.skipPrompt = true; keys({ _ : ['delete'] }, function(err){ assert.ok(err); keys({ _ : ['delete', 'UserKey'] }, function(err, key){ assert.equal(err, null, err); assert.ok(key.apiKey); assert.ok(key.apiKey.label); assert.ok(key.apiKey.key); return cb(); }); }); }, 'update keys' : function (cb) { keys.skipPrompt = true; keys({ _ : ['update'] }, function(err){ assert.ok(err); keys({ _ : ['update', 'UserKey', 'UserKey-Updated'] }, function(err, key){ assert.ok(!err, err); assert.ok(key.apiKey); assert.ok(key.apiKey.label); assert.equal('UserKey-Updated', key.apiKey.label); keys({ _ : ['update', '1239jncjjcd'] }, function(err){ assert.ok(err); return cb(); }); }); }); }, 'target keys' : function(cb){ var key_val = "pviryBwt22iZ0iInufMYBuVV"; keys({ _ : ['target', 'UserKey'] }, function(err, r){ assert.equal(err, null, err); assert.equal(r, key_val); keys({ _ : ['target'] }, function(err, r){ assert.equal(err, null); assert.equal(r, key_val); return cb(); }); }); }, tearDown : function(cb){ userKeysNock.done(); return cb(); } };
shannonmpoole/fh-fhc
test/unit/legacy/test_user_keys.js
JavaScript
mit
2,115
module.exports = { audioFilter: require('./audioFilter'), destination: require('./destination'), filename: require('./filename'), multer: require('./multer') }
lighting-perspectives/jams
server/middlewares/sample/index.js
JavaScript
mit
168
package com.am.docker.study.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RestDockerExample { @RequestMapping("/") public String home() { return "Hello Docker World"; } }
augustomarinho/springboot-docker
src/main/java/com/am/docker/study/controller/RestDockerExample.java
Java
mit
299
package com.elmakers.mine.bukkit.api.event; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.spell.Spell; /** * A custom event that the Magic plugin will fire any time a * Mage casts a Spell. */ public class PreCastEvent extends Event implements Cancellable { private boolean cancelled; private final Mage mage; private final Spell spell; private static final HandlerList handlers = new HandlerList(); public PreCastEvent(Mage mage, Spell spell) { this.mage = mage; this.spell = spell; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } public Mage getMage() { return mage; } public Spell getSpell() { return spell; } }
elBukkit/MagicPlugin
MagicAPI/src/main/java/com/elmakers/mine/bukkit/api/event/PreCastEvent.java
Java
mit
1,149
using Physics2DDotNet; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Interfaces { public interface IHaveConnectionSlots { IEnumerable<IConnectionSlot> Slots { get; } ALVector2D Position { get; } } }
homoluden/fukami
demos/FukamiDemo/Interfaces/IHaveConnectionSlots.cs
C#
mit
311
#include <iostream> #include <string> // time complexity O(1) - constant // space complexity O(1) - constant bool is_unique (std::string s) { if (s.length() > 128) return false; bool char_list[128] = {0}; for (int i = 0; i < s.length(); i++) { if (char_list[s[i]]) return false; char_list[s[i]] = true; } return true; } int main () { std::cout << is_unique("ABCDEFGA") << std::endl; }
harveyc95/ProgrammingProblems
CTCI/Ch1/is_unique.cpp
C++
mit
399
module PrettyShortUrls module Routes def pretty_short_urls connect ":name", :controller => "pretty_short_urls_redirect", :action => "redirect", :conditions => { :method => :get } end end end
baldwindavid/pretty_short_urls
lib/pretty_short_urls_routes.rb
Ruby
mit
208
package com.naosim.rtm.lib; import java.math.BigInteger; import java.security.MessageDigest; public class MD5 { public static String md5(String str) { try { byte[] str_bytes = str.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5_bytes = md.digest(str_bytes); BigInteger big_int = new BigInteger(1, md5_bytes); return big_int.toString(16); }catch(Exception e){ throw new RuntimeException(e); } } }
naosim/rtmjava
src/main/java/com/naosim/rtm/lib/MD5.java
Java
mit
538
// The MIT License (MIT) // Copyright (c) 2014 Philipp Neugebauer package main import ( "bufio" "fmt" "os" "math/rand" "strconv" ) func computer(inputChannel chan int, resultChannel chan string){ for human_choice := range inputChannel { computer_choice := rand.Intn(3) evaluation(computer_choice, human_choice, resultChannel) } } func evaluation(computer_choice int, human_choice int, resultChannel chan string){ switch human_choice { case 0: switch computer_choice { case 0: resultChannel <- "draw" case 1: resultChannel <- "loss" case 2: resultChannel <- "win" } case 1: switch computer_choice { case 0: resultChannel <- "win" case 1: resultChannel <- "draw" case 2: resultChannel <- "loss" } case 2: switch computer_choice { case 0: resultChannel <- "loss" case 1: resultChannel <- "win" case 2: resultChannel <- "draw" } default: resultChannel <- "Only numbers between 0 and 2 are valid!" } close(resultChannel) } func main() { computerChannel := make(chan int) resultChannel := make(chan string) go computer(computerChannel, resultChannel) reader := bufio.NewReader(os.Stdin) fmt.Println("Choose: \n 0 = rock\n 1 = paper\n 2 = scissors") text, _ := reader.ReadString('\n') choice, _ := strconv.Atoi(text) computerChannel <- choice close(computerChannel) for message := range resultChannel { fmt.Println("Result:", message) } }
philippneugebauer/go-code
rock_paper_scissors.go
GO
mit
1,463
import random import numpy as np import math from time import perf_counter import os import sys from collections import deque import gym import cntk from cntk.layers import Convolution, MaxPooling, Dense from cntk.models import Sequential, LayerStack from cntk.initializer import glorot_normal env = gym.make("Breakout-v0") NUM_ACTIONS = env.action_space.n SCREEN_H_ORIG, SCREEN_W_ORIG, NUM_COLOUR_CHANNELS = env.observation_space.shape def preprocess_image(screen_image): # crop the top and bottom screen_image = screen_image[35:195] # down sample by a factor of 2 screen_image = screen_image[::2, ::2] # convert to grey scale grey_image = np.zeros(screen_image.shape[0:2]) for i in range(len(screen_image)): for j in range(len(screen_image[i])): grey_image[i][j] = np.mean(screen_image[i][j]) return np.array([grey_image.astype(np.float)]) CHANNELS, IMAGE_H, IMAGE_W = preprocess_image(np.zeros((SCREEN_H_ORIG, SCREEN_W_ORIG))).shape STATE_DIMS = (1, IMAGE_H, IMAGE_W) class Brain: BATCH_SIZE = 5 def __init__(self): #### Construct the model #### observation = cntk.ops.input_variable(STATE_DIMS, np.float32, name="s") q_target = cntk.ops.input_variable(NUM_ACTIONS, np.float32, name="q") # Define the structure of the neural network self.model = self.create_convolutional_neural_network(observation, NUM_ACTIONS) #### Define the trainer #### self.learning_rate = cntk.learner.training_parameter_schedule(0.0001, cntk.UnitType.sample) self.momentum = cntk.learner.momentum_as_time_constant_schedule(0.99) self.loss = cntk.ops.reduce_mean(cntk.ops.square(self.model - q_target), axis=0) mean_error = cntk.ops.reduce_mean(cntk.ops.square(self.model - q_target), axis=0) learner = cntk.adam_sgd(self.model.parameters, self.learning_rate, momentum=self.momentum) self.trainer = cntk.Trainer(self.model, self.loss, mean_error, learner) def train(self, x, y): data = dict(zip(self.loss.arguments, [y, x])) self.trainer.train_minibatch(data, outputs=[self.loss.output]) def predict(self, s): return self.model.eval([s]) @staticmethod def create_multi_layer_neural_network(input_vars, out_dims, num_hidden_layers): num_hidden_neurons = 128 hidden_layer = lambda: Dense(num_hidden_neurons, activation=cntk.ops.relu) output_layer = Dense(out_dims, activation=None) model = Sequential([LayerStack(num_hidden_layers, hidden_layer), output_layer])(input_vars) return model @staticmethod def create_convolutional_neural_network(input_vars, out_dims): convolutional_layer_1 = Convolution((5, 5), 32, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_1 = MaxPooling((2, 2), strides=(2, 2), pad=True) convolutional_layer_2 = Convolution((5, 5), 64, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_2 = MaxPooling((2, 2), strides=(2, 2), pad=True) convolutional_layer_3 = Convolution((5, 5), 128, strides=1, activation=cntk.ops.relu, pad=True, init=glorot_normal(), init_bias=0.1) pooling_layer_3 = MaxPooling((2, 2), strides=(2, 2), pad=True) fully_connected_layer = Dense(1024, activation=cntk.ops.relu, init=glorot_normal(), init_bias=0.1) output_layer = Dense(out_dims, activation=None, init=glorot_normal(), init_bias=0.1) model = Sequential([convolutional_layer_1, pooling_layer_1, convolutional_layer_2, pooling_layer_2, #convolutional_layer_3, pooling_layer_3, fully_connected_layer, output_layer])(input_vars) return model class Memory: def __init__(self, capacity): self.examplers = deque(maxlen=capacity) self.capacity = capacity def add(self, sample): self.examplers.append(sample) def get_random_samples(self, num_samples): num_samples = min(num_samples, len(self.examplers)) return random.sample(tuple(self.examplers), num_samples) def get_stack(self, start_index, stack_size): end_index = len(self.examplers) - stack_size if end_index < 0: stack = list(self.examplers) + [self.examplers[-1] for _ in range(-end_index)] else: start_index = min(start_index, end_index) stack = [self.examplers[i + start_index] for i in range(stack_size)] return np.stack(stack, axis=-1) def get_random_stacks(self, num_samples, stack_size): start_indices = random.sample(range(len(self.examplers)), num_samples) return [self.get_stack(start_index, stack_size) for start_index in start_indices] def get_latest_stack(self, stack_size): return self.get_stack(len(self.examplers), stack_size) class Agent: MEMORY_CAPACITY = 100000 DISCOUNT_FACTOR = 0.99 MAX_EXPLORATION_RATE = 1.0 MIN_EXPLORATION_RATE = 0.01 DECAY_RATE = 0.0001 def __init__(self): self.explore_rate = self.MAX_EXPLORATION_RATE self.brain = Brain() self.memory = Memory(self.MEMORY_CAPACITY) self.steps = 0 def act(self, s): if random.random() < self.explore_rate: return random.randint(0, NUM_ACTIONS - 1) else: return np.argmax(self.brain.predict(s)) def observe(self, sample): self.steps += 1 self.memory.add(sample) # Reduces exploration rate linearly self.explore_rate = self.MIN_EXPLORATION_RATE + (self.MAX_EXPLORATION_RATE - self.MIN_EXPLORATION_RATE) * math.exp(-self.DECAY_RATE * self.steps) def replay(self): batch = self.memory.get_random_samples(self.brain.BATCH_SIZE) batch_len = len(batch) states = np.array([sample[0] for sample in batch], dtype=np.float32) no_state = np.zeros(STATE_DIMS) resultant_states = np.array([(no_state if sample[3] is None else sample[3]) for sample in batch], dtype=np.float32) q_values_batch = self.brain.predict(states) future_q_values_batch = self.brain.predict(resultant_states) x = np.zeros((batch_len, ) + STATE_DIMS).astype(np.float32) y = np.zeros((batch_len, NUM_ACTIONS)).astype(np.float32) for i in range(batch_len): state, action, reward, resultant_state = batch[i] q_values = q_values_batch[0][i] if resultant_state is None: q_values[action] = reward else: q_values[action] = reward + self.DISCOUNT_FACTOR * np.amax(future_q_values_batch[0][i]) x[i] = state y[i] = q_values self.brain.train(x, y) @classmethod def action_from_output(cls, output_array): return np.argmax(output_array) def run_simulation(agent, solved_reward_level): state = env.reset() state = preprocess_image(state) total_rewards = 0 time_step = 0 while True: #env.render() time_step += 1 action = agent.act(state.astype(np.float32)) resultant_state, reward, done, info = env.step(action) resultant_state = preprocess_image(resultant_state) if done: # terminal state resultant_state = None agent.observe((state, action, reward, resultant_state)) agent.replay() state = resultant_state total_rewards += reward if total_rewards > solved_reward_level or done: return total_rewards, time_step def test(model_path, num_episodes=10): root = cntk.load_model(model_path) observation = env.reset() # reset environment for new episode done = False for episode in range(num_episodes): while not done: try: env.render() except Exception: # this might fail on a VM without OpenGL pass observation = preprocess_image(observation) action = np.argmax(root.eval(observation.astype(np.float32))) observation, reward, done, info = env.step(action) if done: observation = env.reset() # reset environment for new episode if __name__ == "__main__": # Ensure we always get the same amount of randomness np.random.seed(0) GYM_ENABLE_UPLOAD = False GYM_VIDEO_PATH = os.path.join(os.getcwd(), "videos", "atari_breakout_dpn_cntk") GYM_API_KEY = "sk_93AMQvdmReWCi8pdL4m6Q" MAX_NUM_EPISODES = 1000 STREAK_TO_END = 120 DONE_REWARD_LEVEL = 50 TRAINED_MODEL_DIR = os.path.join(os.getcwd(), "trained_models") if not os.path.exists(TRAINED_MODEL_DIR): os.makedirs(TRAINED_MODEL_DIR) TRAINED_MODEL_NAME = "atari_breakout_dpn.mod" EPISODES_PER_PRINT_PROGRESS = 1 EPISODES_PER_SAVE = 5 if len(sys.argv) < 2 or sys.argv[1] != "test_only": if GYM_ENABLE_UPLOAD: env.monitor.start(GYM_VIDEO_PATH, force=True) agent = Agent() episode_number = 0 num_streaks = 0 reward_sum = 0 time_step_sum = 0 solved_episode = -1 training_start_time = perf_counter() while episode_number < MAX_NUM_EPISODES: # Run the simulation and train the agent reward, time_step = run_simulation(agent, DONE_REWARD_LEVEL*2) reward_sum += reward time_step_sum += time_step episode_number += 1 if episode_number % EPISODES_PER_PRINT_PROGRESS == 0: t = perf_counter() - training_start_time print("(%d s) Episode: %d, Average reward = %.3f, Average number of time steps = %.3f." % (t, episode_number, reward_sum / EPISODES_PER_PRINT_PROGRESS, time_step_sum/EPISODES_PER_PRINT_PROGRESS)) reward_sum = 0 time_step_sum = 0 # It is considered solved when the sum of reward is over 200 if reward > DONE_REWARD_LEVEL: num_streaks += 1 solved_episode = episode_number else: num_streaks = 0 solved_episode = -1 # It's considered done when it's solved over 120 times consecutively if num_streaks > STREAK_TO_END: print("Task solved in %d episodes and repeated %d times." % (episode_number, num_streaks)) break if episode_number % EPISODES_PER_SAVE == 0: agent.brain.model.save_model(os.path.join(TRAINED_MODEL_DIR, TRAINED_MODEL_NAME), False) agent.brain.model.save_model(os.path.join(TRAINED_MODEL_DIR, TRAINED_MODEL_NAME), False) if GYM_ENABLE_UPLOAD: env.monitor.close() gym.upload(GYM_VIDEO_PATH, api_key=GYM_API_KEY) # testing the model test(os.path.join(TRAINED_MODEL_DIR, TRAINED_MODEL_NAME), num_episodes=10)
tuzzer/ai-gym
atari_breakout/atari_breakout_dqn_cntk.py
Python
mit
11,222
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * 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. */ package reborncore.client.gui.slots; import net.minecraft.inventory.Inventory; import net.minecraft.item.ItemStack; public class SlotFake extends BaseSlot { public boolean mCanInsertItem; public boolean mCanStackItem; public int mMaxStacksize = 127; public SlotFake(Inventory itemHandler, int par2, int par3, int par4, boolean aCanInsertItem, boolean aCanStackItem, int aMaxStacksize) { super(itemHandler, par2, par3, par4); this.mCanInsertItem = aCanInsertItem; this.mCanStackItem = aCanStackItem; this.mMaxStacksize = aMaxStacksize; } @Override public boolean canInsert(ItemStack par1ItemStack) { return this.mCanInsertItem; } @Override public int getMaxStackAmount() { return this.mMaxStacksize; } @Override public boolean hasStack() { return false; } @Override public ItemStack takeStack(int par1) { return !this.mCanStackItem ? ItemStack.EMPTY : super.takeStack(par1); } @Override public boolean canWorldBlockRemove() { return false; } }
TechReborn/RebornCore
src/main/java/reborncore/client/gui/slots/SlotFake.java
Java
mit
2,200
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using System.Reflection; namespace Pomona.Routing { public class DefaultQueryProviderCapabilityResolver : IQueryProviderCapabilityResolver { public bool PropertyIsMapped(PropertyInfo propertyInfo) { return true; } } }
Pomona/Pomona
app/Pomona/Routing/DefaultQueryProviderCapabilityResolver.cs
C#
mit
450
#include "uritests.h" #include "../guiutil.h" #include "../walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString("Wikipedia Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Wikipedia Example")); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("AnonymousCoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); // We currently don't implement the message parameter (ok, yea, we break spec...) uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("AnonymousCoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
anonymousdevx/anonymouscoin
src/qt/test/uritests.cpp
C++
mit
2,908
<?php /** * 财付通支付方式插件 * * @author Garbin * @usage none */ class TenpayPayment extends BasePayment { /* 财付通网关 */ var $_gateway = 'https://www.tenpay.com/cgi-bin/med/show_opentrans.cgi'; var $_code = 'tenpay'; /** * 获取支付表单 * * @author Garbin * @param array $order_info 待支付的订单信息,必须包含总费用及唯一外部交易号 * @return array */ function get_payform($order_info) { /* 版本号 */ $version = '2'; /* 任务代码,定值:12 */ $cmdno = '12'; /* 编码标准 */ if (!defined('CHARSET')) { $encode_type = 2; } else { if (CHARSET == 'utf-8') { $encode_type = 2; } else { $encode_type = 1; } } /* 平台提供者,代理商的财付通账号 */ $chnid = $this->_config['tenpay_account']; /* 收款方财付通账号 */ $seller = $this->_config['tenpay_account']; /* 商品名称 */ $mch_name = $this->_get_subject($order_info); /* 总金额 */ $mch_price = floatval($order_info['order_amount']) * 100; /* 物流配送说明 */ $transport_desc = ''; $transport_fee = ''; /* 交易说明 */ $mch_desc = $this->_get_subject($order_info); $need_buyerinfo = '2' ; /* 交易类型:2、虚拟交易,1、实物交易 */ $mch_type = $this->_config['tenpay_type']; /* 生成一个随机扰码 */ $rand_num = rand(1,9); for ($i = 1; $i < 10; $i++) { $rand_num .= rand(0,9); } /* 获得订单的流水号,补零到10位 */ $mch_vno = $this->_get_trade_sn($order_info); /* 返回的路径 */ $mch_returl = $this->_create_notify_url($order_info['order_id']); $show_url = $this->_create_return_url($order_info['order_id']); $attach = $rand_num; /* 数字签名 */ $sign_text = "attach=" . $attach . "&chnid=" . $chnid . "&cmdno=" . $cmdno . "&encode_type=" . $encode_type . "&mch_desc=" . $mch_desc . "&mch_name=" . $mch_name . "&mch_price=" . $mch_price ."&mch_returl=" . $mch_returl . "&mch_type=" . $mch_type . "&mch_vno=" . $mch_vno . "&need_buyerinfo=" . $need_buyerinfo ."&seller=" . $seller . "&show_url=" . $show_url . "&version=" . $version . "&key=" . $this->_config['tenpay_key']; $sign =md5($sign_text); /* 交易参数 */ $parameter = array( 'attach' => $attach, 'chnid' => $chnid, 'cmdno' => $cmdno, // 业务代码, 财付通支付支付接口填 1 'encode_type' => $encode_type, //编码标准 'mch_desc' => $mch_desc, 'mch_name' => $mch_name, 'mch_price' => $mch_price, // 订单金额 'mch_returl' => $mch_returl, // 接收财付通返回结果的URL 'mch_type' => $mch_type, //交易类型 'mch_vno' => $mch_vno, // 交易号(订单号),由商户网站产生(建议顺序累加) 'need_buyerinfo' => $need_buyerinfo, //是否需要在财付通填定物流信息 'seller' => $seller, // 商家的财付通商户号 'show_url' => $show_url, 'transport_desc' => $transport_desc, 'transport_fee' => $transport_fee, 'version' => $version, //版本号 2 'key' => $this->_config['tenpay_key'], 'sign' => $sign, // MD5签名 'sys_id' => '542554970' //ECMall C账号 不参与签名 ); return $this->_create_payform('GET', $parameter); } /** * 返回通知结果 * * @author Garbin * @param array $order_info * @param bool $strict * @return array 返回结果 * false 失败时返回 */ function verify_notify($order_info, $strict = false) { /*取返回参数*/ $cmd_no = $_GET['cmdno']; $retcode = $_GET['retcode']; $status = $_GET['status']; $seller = $_GET['seller']; $total_fee = $_GET['total_fee']; $trade_price = $_GET['trade_price']; $transport_fee = $_GET['transport_fee']; $buyer_id = $_GET['buyer_id']; $chnid = $_GET['chnid']; $cft_tid = $_GET['cft_tid']; $mch_vno = $_GET['mch_vno']; $attach = !empty($_GET['attach']) ? $_GET['attach'] : ''; $version = $_GET['version']; $sign = $_GET['sign']; $log_id = $mch_vno; //取得支付的log_id /* 如果$retcode大于0则表示支付失败 */ if ($retcode > 0) { //echo '操作失败'; return false; } $order_amount = $total_fee / 100; /* 检查支付的金额是否相符 */ if ($order_info['order_amount'] != $order_amount) { /* 支付的金额与实际金额不一致 */ $this->_error('price_inconsistent'); return false; } if ($order_info['out_trade_sn'] != $log_id) { /* 通知中的订单与欲改变的订单不一致 */ $this->_error('order_inconsistent'); return false; } /* 检查数字签名是否正确 */ $sign_text = "attach=" . $attach . "&buyer_id=" . $buyer_id . "&cft_tid=" . $cft_tid . "&chnid=" . $chnid . "&cmdno=" . $cmd_no . "&mch_vno=" . $mch_vno . "&retcode=" . $retcode . "&seller=" .$seller . "&status=" . $status . "&total_fee=" . $total_fee . "&trade_price=" . $trade_price . "&transport_fee=" . $transport_fee . "&version=" . $version . "&key=" . $this->_config['tenpay_key']; $sign_md5 = strtoupper(md5($sign_text)); if ($sign_md5 != $sign) { /* 若本地签名与网关签名不一致,说明签名不可信 */ $this->_error('sign_inconsistent'); return false; } if ($status != 3) { return false; } return array( 'target' => ORDER_ACCEPTED, ); } /** * 获取外部交易号 覆盖基类 * * @author huibiaoli * @param array $order_info * @return string */ function _get_trade_sn($order_info) { if (!$order_info['out_trade_sn'] || $order_info['pay_alter']) { $out_trade_sn = $this->_gen_trade_sn(); } else { $out_trade_sn = $order_info['out_trade_sn']; } /* 将此数据写入订单中 */ $model_order =& m('order'); $model_order->edit(intval($order_info['order_id']), array('out_trade_sn' => $out_trade_sn, 'pay_alter' => 0)); return $out_trade_sn; } /** * 生成外部交易号 * * @author huibiaoli * @return string */ function _gen_trade_sn() { /* 选择一个随机的方案 */ mt_srand((double) microtime() * 1000000); $timestamp = gmtime(); $y = date('y', $timestamp); $z = date('z', $timestamp); $out_trade_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); $model_order =& m('order'); $orders = $model_order->find('out_trade_sn=' . $out_trade_sn); if (empty($orders)) { /* 否则就使用这个交易号 */ return $out_trade_sn; } /* 如果有重复的,则重新生成 */ return $this->_gen_trade_sn(); } } ?>
kitboy/docker-shop
html/ecmall/upload/includes/payments/tenpay/tenpay.payment.php
PHP
mit
8,267
import Event = require('./Event'); /* * Signal1 * * 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. */ import SignalAbstract = require('./SignalAbstract'); /** * @namespace createts.events * @module createts * @class Signal1 */ class Signal1<T> extends SignalAbstract { /** * Emit the signal, notifying each connected listener. * * @method emit */ public emit(arg1:T) { if(this.dispatching()) { this.defer(() => this.emitImpl(arg1)); } else { this.emitImpl(arg1); } } private emitImpl(arg1:T) { var head = this.willEmit(); var p = head; while(p != null) { p._listener(arg1); if(!p.stayInList) { p.dispose(); } p = p._next; } this.didEmit(head); } } export = Signal1;
markknol/EaselTS
src/createts/event/Signal1.ts
TypeScript
mit
1,773
package cassandra // read statements var selectIntStmt = ` SELECT metric_timestamp, value FROM metrics_int WHERE metric_name = ? AND tags = ? ` var selectIntByStartEndTimeStmt = ` SELECT metric_timestamp, value FROM metrics_int WHERE metric_name = ? AND tags = ? AND metric_timestamp >= ? AND metric_timestamp <= ? ` // write statements var insertIntStmt = ` INSERT INTO metrics_int (metric_name, metric_timestamp, tags, value) VALUES (?, ?, ?, ?) ` var insertDoubleStmt = ` INSERT INTO metrics_double (metric_name, metric_timestamp, tags, value) VALUES (?, ?, ?, ?) `
xephonhq/xephon-k
_legacy/pkg/storage/cassandra/stmt.go
GO
mit
583
using Xunit; using Shouldly; using System.Linq; using System; using System.Text.RegularExpressions; namespace AutoMapper.UnitTests { public class MapFromReverseResolveUsing : AutoMapperSpecBase { public class Source { public int Total { get; set; } } public class Destination { public int Total { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(c => { c.CreateMap<Destination, Source>() .ForMember(dest => dest.Total, opt => opt.MapFrom(x => x.Total)) .ReverseMap() .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>()); }); public class CustomResolver : IValueResolver<Source, Destination, int> { public int Resolve(Source source, Destination destination, int member, ResolutionContext context) { return Int32.MaxValue; } } [Fact] public void Should_use_the_resolver() { Mapper.Map<Destination>(new Source()).Total.ShouldBe(int.MaxValue); } } public class MethodsWithReverse : AutoMapperSpecBase { class Order { public OrderItem[] OrderItems { get; set; } } class OrderItem { public string Product { get; set; } } class OrderDto { public int OrderItemsCount { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(c=> { c.CreateMap<Order, OrderDto>().ReverseMap(); }); [Fact] public void ShouldMapOk() { Mapper.Map<Order>(new OrderDto()); } } public class ReverseForPath : AutoMapperSpecBase { public class Order { public CustomerHolder CustomerHolder { get; set; } } public class CustomerHolder { public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } public decimal Total { get; set; } } public class OrderDto { public string CustomerName { get; set; } public decimal Total { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<OrderDto, Order>() .ForPath(o => o.CustomerHolder.Customer.Name, o => o.MapFrom(s => s.CustomerName)) .ForPath(o => o.CustomerHolder.Customer.Total, o => o.MapFrom(s => s.Total)) .ReverseMap(); }); [Fact] public void Should_flatten() { var model = new Order { CustomerHolder = new CustomerHolder { Customer = new Customer { Name = "George Costanza", Total = 74.85m } } }; var dto = Mapper.Map<OrderDto>(model); dto.CustomerName.ShouldBe("George Costanza"); dto.Total.ShouldBe(74.85m); } } public class ReverseMapFrom : AutoMapperSpecBase { public class Order { public CustomerHolder CustomerHolder { get; set; } } public class CustomerHolder { public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } public decimal Total { get; set; } } public class OrderDto { public string CustomerName { get; set; } public decimal Total { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<Order, OrderDto>() .ForMember(d => d.CustomerName, o => o.MapFrom(s => s.CustomerHolder.Customer.Name)) .ForMember(d => d.Total, o => o.MapFrom(s => s.CustomerHolder.Customer.Total)) .ReverseMap(); }); [Fact] public void Should_unflatten() { var dto = new OrderDto { CustomerName = "George Costanza", Total = 74.85m }; var model = Mapper.Map<Order>(dto); model.CustomerHolder.Customer.Name.ShouldBe("George Costanza"); model.CustomerHolder.Customer.Total.ShouldBe(74.85m); } } public class ReverseDefaultFlatteningWithIgnoreMember : AutoMapperSpecBase { public class Order { public CustomerHolder Customerholder { get; set; } } public class CustomerHolder { public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } public decimal Total { get; set; } } public class OrderDto { public string CustomerholderCustomerName { get; set; } public decimal CustomerholderCustomerTotal { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<Order, OrderDto>() .ReverseMap() .ForMember(d=>d.Customerholder, o=>o.Ignore()) .ForPath(d=>d.Customerholder.Customer.Total, o=>o.MapFrom(s=>s.CustomerholderCustomerTotal)); }); [Fact] public void Should_unflatten() { var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m }; var model = Mapper.Map<Order>(dto); model.Customerholder.Customer.Name.ShouldBeNull(); model.Customerholder.Customer.Total.ShouldBe(74.85m); } } public class ReverseDefaultFlattening : AutoMapperSpecBase { public class Order { public CustomerHolder Customerholder { get; set; } } public class CustomerHolder { public Customer Customer { get; set; } } public class Customer { public string Name { get; set; } public decimal Total { get; set; } } public class OrderDto { public string CustomerholderCustomerName { get; set; } public decimal CustomerholderCustomerTotal { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.CreateMap<Order, OrderDto>() .ReverseMap(); }); [Fact] public void Should_unflatten() { var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m }; var model = Mapper.Map<Order>(dto); model.Customerholder.Customer.Name.ShouldBe("George Costanza"); model.Customerholder.Customer.Total.ShouldBe(74.85m); } } public class ReverseMapConventions : AutoMapperSpecBase { Rotator_Ad_Run _destination; DateTime _startDate = DateTime.Now, _endDate = DateTime.Now.AddHours(2); public class Rotator_Ad_Run { public DateTime Start_Date { get; set; } public DateTime End_Date { get; set; } public bool Enabled { get; set; } } public class RotatorAdRunViewModel { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public bool Enabled { get; set; } } public class UnderscoreNamingConvention : INamingConvention { public Regex SplittingExpression { get; } = new Regex(@"\p{Lu}[a-z0-9]*(?=_?)"); public string SeparatorCharacter => "_"; public string ReplaceValue(Match match) { return match.Value; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateProfile("MyMapperProfile", prf => { prf.SourceMemberNamingConvention = new UnderscoreNamingConvention(); prf.CreateMap<Rotator_Ad_Run, RotatorAdRunViewModel>(); }); cfg.CreateProfile("MyMapperProfile2", prf => { prf.DestinationMemberNamingConvention = new UnderscoreNamingConvention(); prf.CreateMap<RotatorAdRunViewModel, Rotator_Ad_Run>(); }); }); protected override void Because_of() { _destination = Mapper.Map<RotatorAdRunViewModel, Rotator_Ad_Run>(new RotatorAdRunViewModel { Enabled = true, EndDate = _endDate, StartDate = _startDate }); } [Fact] public void Should_apply_the_convention_in_reverse() { _destination.Enabled.ShouldBeTrue(); _destination.End_Date.ShouldBe(_endDate); _destination.Start_Date.ShouldBe(_startDate); } } public class When_reverse_mapping_classes_with_simple_properties : AutoMapperSpecBase { private Source _source; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ReverseMap(); }); protected override void Because_of() { var dest = new Destination { Value = 10 }; _source = Mapper.Map<Destination, Source>(dest); } [Fact] public void Should_create_a_map_with_the_reverse_items() { _source.Value.ShouldBe(10); } } public class When_validating_only_against_source_members_and_source_matches : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } public int Value2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); [Fact] public void Should_only_map_source_members() { var typeMap = ConfigProvider.FindTypeMapFor<Source, Destination>(); typeMap.GetPropertyMaps().Count().ShouldBe(1); } [Fact] public void Should_not_throw_any_configuration_validation_errors() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_source_does_not_match : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); [Fact] public void Should_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value2)); }); [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped_with_resolvers : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.ResolveUsing(src => src.Value2)) .ForSourceMember(src => src.Value2, opt => opt.Ignore()); }); [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid); } } public class When_reverse_mapping_and_ignoring_via_method : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } public int Ignored { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Dest>() .ForMember(d => d.Ignored, opt => opt.Ignore()) .ReverseMap(); }); [Fact] public void Should_show_valid() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid()); } } public class When_reverse_mapping_and_ignoring : SpecBase { public class Foo { public string Bar { get; set; } public string Baz { get; set; } } public class Foo2 { public string Bar { get; set; } public string Boo { get; set; } } [Fact] public void GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange var config = new MapperConfiguration(cfg => { cfg.CreateMap<Foo, Foo2>(); }); var typeMap = config.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo) && x.DestinationType == typeof(Foo2)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldBe("Boo"); } [Fact] public void WhenSecondCallTo_GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange var config = new MapperConfiguration(cfg => { cfg.CreateMap<Foo, Foo2>().ReverseMap(); }); var typeMap = config.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo2) && x.DestinationType == typeof(Foo)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldBe("Boo"); } } public class When_reverse_mapping_open_generics : AutoMapperSpecBase { private Source<int> _source; public class Source<T> { public T Value { get; set; } } public class Destination<T> { public T Value { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap(typeof(Source<>), typeof(Destination<>)) .ReverseMap(); }); protected override void Because_of() { var dest = new Destination<int> { Value = 10 }; _source = Mapper.Map<Destination<int>, Source<int>>(dest); } [Fact] public void Should_create_a_map_with_the_reverse_items() { _source.Value.ShouldBe(10); } } }
mjalil/AutoMapper
src/UnitTests/ReverseMapping.cs
C#
mit
17,050
import * as fs from "fs"; import * as path from "path"; import * as commander from "commander"; import { ConsoleLogger } from "@akashic/akashic-cli-commons"; import { promiseExportHTML } from "./exportHTML"; import { promiseExportAtsumaru } from "./exportAtsumaru"; interface CommandParameterObject { cwd?: string; source?: string; force?: boolean; quiet?: boolean; output?: string; exclude?: string[]; strip?: boolean; hashFilename?: number | boolean; minify?: boolean; bundle?: boolean; magnify?: boolean; injects?: string[]; atsumaru?: boolean; } function cli(param: CommandParameterObject): void { const logger = new ConsoleLogger({ quiet: param.quiet }); const exportParam = { cwd: !param.cwd ? process.cwd() : path.resolve(param.cwd), source: param.source, force: param.force, quiet: param.quiet, output: param.output, exclude: param.exclude, logger: logger, strip: (param.strip != null) ? param.strip : true, hashLength: !param.hashFilename && !param.atsumaru ? 0 : (param.hashFilename === true || param.hashFilename === undefined) ? 20 : Number(param.hashFilename), minify: param.minify, bundle: param.bundle || param.atsumaru, magnify: param.magnify || param.atsumaru, injects: param.injects, unbundleText: !param.bundle || param.atsumaru, lint: !param.atsumaru }; Promise.resolve() .then(() => { if (param.output === undefined) { throw new Error("--output option must be specified."); } if (param.atsumaru) { return promiseExportAtsumaru(exportParam); } else { return promiseExportHTML(exportParam); } }) .then(() => logger.info("Done!")) .catch((err: any) => { logger.error(err); process.exit(1); }); } const ver = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")).version; commander .version(ver); commander .description("convert your Akashic game runnable standalone.") .option("-C, --cwd <dir>", "The directory to export from") .option("-s, --source <dir>", "Source directory to export from cwd/current directory") .option("-f, --force", "Overwrites existing files") .option("-q, --quiet", "Suppress output") .option("-o, --output <fileName>", "Name of output file or directory") .option("-S, --no-strip", "output fileset without strip") .option("-H, --hash-filename [length]", "Rename asset files with their hash values") .option("-M, --minify", "minify JavaScript files") .option("-b, --bundle", "bundle assets and scripts in index.html (to reduce the number of files)") .option("-m, --magnify", "fit game area to outer element size") .option("-i, --inject [fileName]", "specify injected file content into index.html", inject, []) .option("-a, --atsumaru", "generate files that can be posted to RPG-atsumaru"); export function run(argv: string[]): void { // Commander の制約により --strip と --no-strip 引数を両立できないため、暫定対応として Commander 前に argv を処理する const argvCopy = dropDeprecatedArgs(argv); commander.parse(argvCopy); cli({ cwd: commander["cwd"], force: commander["force"], quiet: commander["quiet"], output: commander["output"], source: commander["source"], strip: commander["strip"], minify: commander["minify"], bundle: commander["bundle"], magnify: commander["magnify"], hashFilename: commander["hashFilename"], injects: commander["inject"], atsumaru: commander["atsumaru"] }); } function dropDeprecatedArgs(argv: string[]): string[] { const filteredArgv = argv.filter(v => !/^(-s|--strip)$/.test(v)); if (argv.length !== filteredArgv.length) { console.log("WARN: --strip option is deprecated. strip is applied by default."); console.log("WARN: If you do not need to apply it, use --no-strip option."); } return filteredArgv; } function inject(val: string, injects: string[]): string[] { injects.push(val); return injects; }
akashic-games/akashic-cli-export-html
src/app/cli.ts
TypeScript
mit
3,890
import * as types from 'constants/ActionTypes' import jsCookie from 'js-cookie' import history from 'history' export const setUser = (user) => (dispatch) => { dispatch({ type: types.SET_USER, payload: { ...user } }) }
oct16/Blog-FE
src/actions/user.js
JavaScript
mit
230
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-f6dedff */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.bottomSheet * @description * BottomSheet */ MdBottomSheetDirective['$inject'] = ["$mdBottomSheet"]; MdBottomSheetProvider['$inject'] = ["$$interimElementProvider"]; angular .module('material.components.bottomSheet', [ 'material.core', 'material.components.backdrop' ]) .directive('mdBottomSheet', MdBottomSheetDirective) .provider('$mdBottomSheet', MdBottomSheetProvider); /* ngInject */ function MdBottomSheetDirective($mdBottomSheet) { return { restrict: 'E', link : function postLink(scope, element) { element.addClass('_md'); // private md component indicator for styling // When navigation force destroys an interimElement, then // listen and $destroy() that interim instance... scope.$on('$destroy', function() { $mdBottomSheet.destroy(); }); } }; } /** * @ngdoc service * @name $mdBottomSheet * @module material.components.bottomSheet * * @description * `$mdBottomSheet` opens a bottom sheet over the app and provides a simple promise API. * * ## Restrictions * * - The bottom sheet's template must have an outer `<md-bottom-sheet>` element. * - Add the `md-grid` class to the bottom sheet for a grid layout. * - Add the `md-list` class to the bottom sheet for a list layout. * * @usage * <hljs lang="html"> * <div ng-controller="MyController"> * <md-button ng-click="openBottomSheet()"> * Open a Bottom Sheet! * </md-button> * </div> * </hljs> * <hljs lang="js"> * var app = angular.module('app', ['ngMaterial']); * app.controller('MyController', function($scope, $mdBottomSheet) { * $scope.openBottomSheet = function() { * $mdBottomSheet.show({ * template: '<md-bottom-sheet>Hello!</md-bottom-sheet>' * }); * }; * }); * </hljs> */ /** * @ngdoc method * @name $mdBottomSheet#show * * @description * Show a bottom sheet with the specified options. * * @param {object} options An options object, with the following properties: * * - `templateUrl` - `{string=}`: The url of an html template file that will * be used as the content of the bottom sheet. Restrictions: the template must * have an outer `md-bottom-sheet` element. * - `template` - `{string=}`: Same as templateUrl, except this is an actual * template string. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope. * This scope will be destroyed when the bottom sheet is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `controller` - `{string=}`: The controller to associate with this bottom sheet. * - `locals` - `{string=}`: An object containing key/value pairs. The keys will * be used as names of values to inject into the controller. For example, * `locals: {three: 3}` would inject `three` into the controller with the value * of 3. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the bottom sheet to * close it. Default true. * - `bindToController` - `{boolean=}`: When set to true, the locals will be bound to the controller instance. * - `disableBackdrop` - `{boolean=}`: When set to true, the bottomsheet will not show a backdrop. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the bottom sheet. * Default true. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values * and the bottom sheet will not open until the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the bottom sheet to. The `parent` may be a `function`, `string`, * `object`, or null. Defaults to appending to the body of the root element (or the root element) of the application. * e.g. angular.element(document.getElementById('content')) or "#content" * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the bottom sheet is open. * Default true. * * @returns {promise} A promise that can be resolved with `$mdBottomSheet.hide()` or * rejected with `$mdBottomSheet.cancel()`. */ /** * @ngdoc method * @name $mdBottomSheet#hide * * @description * Hide the existing bottom sheet and resolve the promise returned from * `$mdBottomSheet.show()`. This call will close the most recently opened/current bottomsheet (if any). * * @param {*=} response An argument for the resolved promise. * */ /** * @ngdoc method * @name $mdBottomSheet#cancel * * @description * Hide the existing bottom sheet and reject the promise returned from * `$mdBottomSheet.show()`. * * @param {*=} response An argument for the rejected promise. * */ function MdBottomSheetProvider($$interimElementProvider) { // how fast we need to flick down to close the sheet, pixels/ms bottomSheetDefaults['$inject'] = ["$animate", "$mdConstant", "$mdUtil", "$mdTheming", "$mdBottomSheet", "$rootElement", "$mdGesture", "$log"]; var CLOSING_VELOCITY = 0.5; var PADDING = 80; // same as css return $$interimElementProvider('$mdBottomSheet') .setDefaults({ methods: ['disableParentScroll', 'escapeToClose', 'clickOutsideToClose'], options: bottomSheetDefaults }); /* ngInject */ function bottomSheetDefaults($animate, $mdConstant, $mdUtil, $mdTheming, $mdBottomSheet, $rootElement, $mdGesture, $log) { var backdrop; return { themable: true, onShow: onShow, onRemove: onRemove, disableBackdrop: false, escapeToClose: true, clickOutsideToClose: true, disableParentScroll: true }; function onShow(scope, element, options, controller) { element = $mdUtil.extractElementByName(element, 'md-bottom-sheet'); // prevent tab focus or click focus on the bottom-sheet container element.attr('tabindex',"-1"); // Once the md-bottom-sheet has `ng-cloak` applied on his template the opening animation will not work properly. // This is a very common problem, so we have to notify the developer about this. if (element.hasClass('ng-cloak')) { var message = '$mdBottomSheet: using `<md-bottom-sheet ng-cloak >` will affect the bottom-sheet opening animations.'; $log.warn( message, element[0] ); } if (!options.disableBackdrop) { // Add a backdrop that will close on click backdrop = $mdUtil.createBackdrop(scope, "md-bottom-sheet-backdrop md-opaque"); // Prevent mouse focus on backdrop; ONLY programatic focus allowed. // This allows clicks on backdrop to propogate to the $rootElement and // ESC key events to be detected properly. backdrop[0].tabIndex = -1; if (options.clickOutsideToClose) { backdrop.on('click', function() { $mdUtil.nextTick($mdBottomSheet.cancel,true); }); } $mdTheming.inherit(backdrop, options.parent); $animate.enter(backdrop, options.parent, null); } var bottomSheet = new BottomSheet(element, options.parent); options.bottomSheet = bottomSheet; $mdTheming.inherit(bottomSheet.element, options.parent); if (options.disableParentScroll) { options.restoreScroll = $mdUtil.disableScrollAround(bottomSheet.element, options.parent); } return $animate.enter(bottomSheet.element, options.parent, backdrop) .then(function() { var focusable = $mdUtil.findFocusTarget(element) || angular.element( element[0].querySelector('button') || element[0].querySelector('a') || element[0].querySelector($mdUtil.prefixer('ng-click', true)) ) || backdrop; if (options.escapeToClose) { options.rootElementKeyupCallback = function(e) { if (e.keyCode === $mdConstant.KEY_CODE.ESCAPE) { $mdUtil.nextTick($mdBottomSheet.cancel,true); } }; $rootElement.on('keyup', options.rootElementKeyupCallback); focusable && focusable.focus(); } }); } function onRemove(scope, element, options) { var bottomSheet = options.bottomSheet; if (!options.disableBackdrop) $animate.leave(backdrop); return $animate.leave(bottomSheet.element).then(function() { if (options.disableParentScroll) { options.restoreScroll(); delete options.restoreScroll; } bottomSheet.cleanup(); }); } /** * BottomSheet class to apply bottom-sheet behavior to an element */ function BottomSheet(element, parent) { var deregister = $mdGesture.register(parent, 'drag', { horizontal: false }); parent.on('$md.dragstart', onDragStart) .on('$md.drag', onDrag) .on('$md.dragend', onDragEnd); return { element: element, cleanup: function cleanup() { deregister(); parent.off('$md.dragstart', onDragStart); parent.off('$md.drag', onDrag); parent.off('$md.dragend', onDragEnd); } }; function onDragStart(ev) { // Disable transitions on transform so that it feels fast element.css($mdConstant.CSS.TRANSITION_DURATION, '0ms'); } function onDrag(ev) { var transform = ev.pointer.distanceY; if (transform < 5) { // Slow down drag when trying to drag up, and stop after PADDING transform = Math.max(-PADDING, transform / 2); } element.css($mdConstant.CSS.TRANSFORM, 'translate3d(0,' + (PADDING + transform) + 'px,0)'); } function onDragEnd(ev) { if (ev.pointer.distanceY > 0 && (ev.pointer.distanceY > 20 || Math.abs(ev.pointer.velocityY) > CLOSING_VELOCITY)) { var distanceRemaining = element.prop('offsetHeight') - ev.pointer.distanceY; var transitionDuration = Math.min(distanceRemaining / ev.pointer.velocityY * 0.75, 500); element.css($mdConstant.CSS.TRANSITION_DURATION, transitionDuration + 'ms'); $mdUtil.nextTick($mdBottomSheet.cancel,true); } else { element.css($mdConstant.CSS.TRANSITION_DURATION, ''); element.css($mdConstant.CSS.TRANSFORM, ''); } } } } } })(window, window.angular);
ohmygodvt95/wevivu
vendor/assets/components/angular-material/modules/js/bottomSheet/bottomSheet.js
JavaScript
mit
10,698
the_count = [1, 2, 3, 4, 5] fruits = ['apple', 'oranges', 'pears', 'apricots',] change = [1, 'pennies', 2, 'dimes', 3, 'quarters',] #this first kind of for-loop goes through a list for number in the_count: print("This is count %d" % number) # same as above for fruit in fruits: print("A fruit of type: %s" % fruit) # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print("I got %r " % i) # we can alse build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0,6): print("Adding %d to the list." % i) # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print("Element was: %d" % i)
sunrin92/LearnPython
1-lpthw/ex32.py
Python
mit
812