answer stringlengths 15 1.25M |
|---|
//needed for testing
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
//other stuff needed
#define GLM_FORCE_RADIANS
#include <glm/vec3.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cmath>
#include <iostream>
//include classes for testing
//Shapes
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "composite.hpp"
//DTOs
#include "material.hpp"
#include "color.hpp"
#include "ray.hpp"
//raytracing-related DTOs
#include "scene.hpp"
#include "hit.hpp"
#include "camera.hpp"
#include "light.hpp"
//the hard working classes
#include "sdfloader.hpp"
#include "renderer.hpp"
// SHAPE TESTS
TEST_CASE("getter shape","[shape]")
{
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
REQUIRE(s.get_name() == "name");
Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f};
REQUIRE(s.get_material() == c); //added operator == in color.hpp
}
TEST_CASE("operator<< and print shape","[shape]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
//trolololo
}
// SPHERE TESTS
TEST_CASE("constructors of sphere","[sphere]")
{
Sphere s1 {"name"};
Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s1.get_center() == s2.get_center());
REQUIRE(s1.get_radius() == s2.get_radius());
}
TEST_CASE("get_center and get_radius","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s.get_radius() == 1.0f);
REQUIRE(s.get_center() == glm::vec3{0.0f});
}
TEST_CASE("area","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(12.566f == Approx(s.area()).epsilon(0.001));
}
TEST_CASE("volume","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001));
}
TEST_CASE("print sphere","[sphere]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
}
// BOX TESTS
TEST_CASE("constructors of box","[box]")
{
Box b1 {"name"};
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b1.get_min() == b2.get_min());
REQUIRE(b1.get_max() == b2.get_max());
}
TEST_CASE("get_min and get_max","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b2.get_min() == glm::vec3{0.0f});
REQUIRE(b2.get_max() == glm::vec3{1.0f});
}
TEST_CASE("area of box","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001));
}
TEST_CASE("volume of box","[box]")
{
Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001));
}
TEST_CASE("print box","[box]")
{
Box eb {"empty_box"};
std::cout << eb;
Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
std::cout << b;
}
// AUFGABE 5.8 TEST
TEST_CASE("virtual", "[Destructors]")
{
std::cout << "\ntesting virtual and non-virtual construction and destruction\n";
Color c_red {255.0f, 0.0f, 0.0f};
Material red {"", c_red, c_red, c_red, 0.0f};
glm::vec3 position {0.0f,0.0f,0.0f};
std::cout << "Create s1\n";
Sphere* s1 = new Sphere("sphere0",red,position,1.2f);
std::cout << "Create s2\n";
Shape* s2 = new Sphere("sphere1",red,position,1.2f);
std::cout << "Printing objects: \n";
std::cout << *s1;
std::cout << *s2 << "\n";
std::cout << "Delete s1\n";
delete s1;
std::cout << "Delete s2\n";
delete s2;
}
// MATERIAL Tests
TEST_CASE("material in place of color struct", "Material")
{
Color c{0.0f,0.0f,0.0f};
Material mate1 {};
std::cout << mate1;
Material mate2 {"some material",c,c,c,0.0f};
std::cout << mate2;
}
TEST_CASE("vektor normalization", "glm::vec3")
{
glm::vec3 v {0.0f,0.0f,2.0f};
glm::vec3 norm {0.0f};
std::cout << "\n" << v.x << ", " << v.y
<< ", " << v.z;
norm = glm::normalize(v);
std::cout << "\n" << norm.x << ", " << norm.y
<< ", " << norm.z;
}
TEST_CASE("SDFloader test", "[SDFloader]")
{
std::cout << "\n ~~~~~~~~~~ SDF LOADER TEST ~~~~~~~~\n";
SDFloader loader{};
/*
load.sdfLoad("/Users/lissyscholz/Documents/
programmiersprachen/raytracer/programmiers./prachen-
raytracer/source/material_input.txt")""
*/
//Scene s1 {};
//std::string karo_file_path = "/home/karoline/Documents/studium/17_sose/<API key>/<API key>/source/material_input.txt";
//s1 = loader.load(karo_file_path);
/*
Scene s2 {};
std::string bla = "/bla";
s2 = loader.load(bla);
*/
loader.load("/home/lissy/Dokumente/raytracer/<API key>/source/simplescene");
// loader.load("/home/karoline/Documents/studium/17_sose/programmiersprachen/raytracer/<API key>/source/simplescene");
std::cout << "\n ~~~~~~~~~~ END ~~~~~~~~\n";
}
//lissylissylissy <33333
// SDF LOADER TESTS
/*
Lissy
load.load("/Users/lissyscholz/Documents/
programmiersprachen/raytracer/programmiers./prachen-
raytracer/source/material_input.txt")
*/
/*
Karo
*/
/*
Scene s2 {};
s2 = loader.load("/home/karoline/Documents/studium/17_sose/programmiersprachen/raytracer/<API key>/source/material_input.txt");
for (std::shared_ptr<Shape> s : s2.m_shapes)
{
std::cout << *s;
}
for (Material m : s2.m_materials)
{
std::cout << m;
}
}
*/
TEST_CASE("new intersect tests", "intersect")
{
SECTION("sphere")
{
Color c {0.0f,0.0f,0.0f};
Ray ray1 {glm::vec3{0.0f}, //from koordinatenursprung
glm::vec3{1.0f,1.0f,-1.0f}};
Ray ray2 {glm::vec3{0.0f}, //aus koordinatenursprung
glm::vec3{1.0f,1.0f,-2.0f}};
Ray ray3 {glm::vec3{0.0f,0.0f,0.0f}, //von innerhalb der Box aus
glm::vec3{0.0f,0.0f,-1.0f}}; // gerade in -z Richtung schauend
Ray ray3b {glm::vec3{1.0f,1.0f,-2.0f}, //von innerhalb der Box aus
glm::vec3{1.0f,1.0f,-1.0f}};
Ray ray4 {glm::vec3{0.0f}, //aus koordinatenursprung
glm::vec3{0.0f,0.0f,-2.0f}}; //entlang -z Achse
Ray ray4b {glm::vec3{1.0f,1.0f,0.0f}, //from (1|1|0)
glm::vec3{0.0f,0.0f,-2.0f}}; //parallel -z Achse, gerade
Sphere sphere{"testsphere", Material{"",c,c,c, 0.0f}, glm::vec3{0.0f, 0.0f, -2.0f}, 1.0f};
std::cout << "ray 1: " << sphere.intersect(ray1) << std::endl;
std::cout << "ray 2: " << sphere.intersect(ray2) << std::endl;
std::cout << "ray 3: " << sphere.intersect(ray3) << std::endl;
std::cout << "ray 3b: " << sphere.intersect(ray3b) << std::endl;
std::cout << "ray 4: " << sphere.intersect(ray4) << std::endl;
std::cout << "ray 4b: " << sphere.intersect(ray4b) << std::endl;
}
SECTION("box")
{
Color c {0.0f,0.0f,0.0f};
Ray ray1 {glm::vec3{0.0f}, //from koordinatenursprung
glm::vec3{1.0f,1.0f,-1.0f}};
Ray ray2 {glm::vec3{0.0f}, //aus koordinatenursprung
glm::vec3{1.0f,1.0f,-2.0f}};
Ray ray3 {glm::vec3{0.0f,0.0f,0.0f}, //von innerhalb der Box aus
glm::vec3{2.0f,2.0f,-1.0f}}; // gerade in -z Richtung schauend
Ray ray3b {glm::vec3{1.0f,1.0f,-2.0f}, //von innerhalb der Box aus
glm::vec3{1.0f,1.0f,-1.0f}};
Ray ray4 {glm::vec3{0.0f}, //aus koordinatenursprung
glm::vec3{0.0f,0.0f,-2.0f}}; //entlang -z Achse
Ray ray4b {glm::vec3{1.0f,1.0f,0.0f}, //from (1|1|0)
glm::vec3{0.0f,0.0f,-2.0f}}; //parallel -z Achse, gerade
Box box {"test_box",
Material{"",c,c,c, 0.0f},
glm::vec3{0.0f,0.0f,-1.0f}, //min
glm::vec3{2.0f,2.0f,-3.0f}}; //max
std::cout << "ray 1: " << box.intersect(ray1) << std::endl;
std::cout << "ray 2: " << box.intersect(ray2) << std::endl;
std::cout << "ray 3: " << box.intersect(ray3) << std::endl;
std::cout << "ray 3b: " << box.intersect(ray3b) << std::endl;
std::cout << "ray 4: " << box.intersect(ray4) << std::endl;
std::cout << "ray 4b: " << box.intersect(ray4b) << std::endl;
}
SECTION("composite")
{
Color c {0.0f,0.0f,0.0f};
Ray ray1{glm::vec3(0.0f), glm::vec3(1.0f)}; //should meet sphere first
Ray ray2{glm::vec3(9.0f), glm::vec3(-1.0f)}; //should meet box first
Ray ray3{glm::vec3(0.0f), glm::vec3(-1.0f)}; //should meet nothing
auto sphereptr = std::make_shared<Sphere>("testsphere", Material{"",c,c,c, 0.0f}, glm::vec3{2.0f}, 1.0f);
auto boxptr = std::make_shared<Box>("testbox", Material{"",c,c,c, 0.0f}, glm::vec3{5.0f}, glm::vec3{8.0f});
Composite composite{"testcomposite"};
composite.add_shape(boxptr);
composite.add_shape(sphereptr);
std::cout << " \n~~ Composite Test ~~\n";
std::cout << "\nray 1: " << composite.intersect(ray1) << std::endl;
std::cout << "\nray 2: " << composite.intersect(ray2) << std::endl;
std::cout << "\nay 3: " << composite.intersect(ray3) << std::endl;
std::cout << " \n~~ Composite Test Ende ~~\n";
}
}
TEST_CASE("hit methods", "hit_struct")
{
Hit default_hit;
REQUIRE(default_hit.m_hit == false);
REQUIRE(default_hit.m_distance == INFINITY);
REQUIRE(default_hit.m_intersection == glm::vec3(INFINITY));
REQUIRE(default_hit.m_shape == nullptr);
auto s = std::make_shared<Box>("some_box");
Hit no_hit(s);
REQUIRE(no_hit.m_hit == false);
REQUIRE(no_hit.m_distance == INFINITY);
REQUIRE(no_hit.m_intersection == glm::vec3(INFINITY));
REQUIRE(no_hit.m_shape == s);
Hit hit(true,0.123f,glm::vec3{1.789f},s);
REQUIRE(hit.m_hit == true);
REQUIRE(hit.m_distance == 0.123f);
REQUIRE(hit.m_intersection == glm::vec3(1.789f));
REQUIRE(hit.m_shape == s);
default_hit.m_shape = s;
REQUIRE(default_hit == no_hit);
Hit copy_hit = hit;
REQUIRE(copy_hit == hit);
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
TEST_CASE("intersect", "box")
{
Ray ray1{glm::vec3{1.0f}, glm::vec3{1.0f}};
Ray ray2{glm::vec3{0.0f}, glm::vec3{1.0f}};
Ray ray3{glm::vec3{1.5f, 1.5f,0.0f}, glm::vec3{0.0f, 0.0f, 2.0f}};
Color c {0.0f,0.0f,0.0f};
Box box {"test_box",
Material{"",c,c,c, 0.0f},
glm::vec3{1.0f}, //min
glm::vec3{2.0f}}; //max
std::cout << "ray 1 : " << box.intersect(ray1) << std::endl;
std::cout << "ray 2 : " << box.intersect(ray2) << std::endl;
std::cout << "ray 3 : " << box.intersect(ray3) << std::endl;
}
TEST_CASE("test glm reflect", "lala")
{
glm::vec3 v1(-0.4f, -0.4f, -0.8f);
glm::vec3 v2(0.0f, 0.0f, -1.0f);
glm::vec3 reflected = glm::reflect(v1, v2);
std::cout << reflected.x << reflected.y << reflected.z << std::endl;
}
TEST_CASE("new color stuff", "color")
{
Color c1(0.5f, 0.5f, 0.5f);
Color c2(1.0f, 0.8f, 0.4f);
Color c3(0.0f, 0.1f, 0.4f);
float f1 = 2.0f;
float f2 = 0.5f;
float f3 = 6.5f;
std::cout << c1 << " * " << f1 << " = " << c1*f1 << std::endl;
std::cout << c2 << " * " << f2 << " = " << c2*f2 << std::endl;
std::cout << c3 << " * " << f3 << " = " << c3*f3 << std::endl;
}
TEST_CASE("raytrace", "renderer")
{
Color a{0.9f, 0.0f, 0.0f};
Color b{0.8f, 0.1f, 0.1f};
Color c {0.5f,0.5f,0.5f};
Material d("", a, b, c, 0.8f);
Material e("", c, a, b, 0.2f);
Ray ray1{glm::vec3(3.0f, 3.0f, 0.0f), glm::vec3(3.0f, 3.0f, 6.0f)}; //should meet sphere first
Ray ray2{glm::vec3(10.0f), glm::vec3(-1.0f)}; //should meet box first
Ray ray3{glm::vec3(0.0f), glm::vec3(1.0f)}; //should meet nothing
auto sphereptr = std::make_shared<Sphere>("testsphere", Material{"",a,b,c, 0.8f}, glm::vec3{2.0f}, 1.0f);
auto boxptr = std::make_shared<Box>("testbox", Material{"",c,a,b, 0.2f}, glm::vec3{5.0f}, glm::vec3{8.0f});
Composite composite{"testcomposite"};
composite.add_shape(boxptr);
composite.add_shape(sphereptr);
auto compositeptr = std::make_shared<Composite> (composite);
Camera camera("", 100.0f);
Color ambient{0.9, 0.9, 0.9};
auto lightptr1 = std::make_shared<Light>(" ", glm::vec3{3.0f, 3.0f, 0.0f}, Color{1.0f, 1.0f, 1.0f}, 1.0f);
auto lightptr2= std::make_shared<Light>(" ", glm::vec3{0.0f}, Color{1.0f, 1.0f, 0.0f}, 1.0f);
std::vector<std::shared_ptr<Light>> lights;
lights.push_back(lightptr1);
lights.push_back(lightptr2);
std::map<std::string, Material> materials;
materials["1st"] = d;
materials["2nd"] = e;
std::vector<std::shared_ptr<Shape>> shapes;
shapes.push_back(sphereptr);
shapes.push_back(boxptr);
std::string filename = "";
Scene scene(camera, ambient, lights, materials, shapes, compositeptr, 100, 100, filename);
Renderer renderer(100, 100, " ", scene);
std::cout << "ray1: " << renderer.raytrace(ray1, 1) << std::endl;
std::cout << "ray2: " << renderer.raytrace(ray2, 1) << std::endl;
std::cout << "ray3: " << renderer.raytrace(ray3, 1) << std::endl;
//std::cout << composite.intersect(ray1) << std::endl;
}
/*
TEST_CASE("simplescene", "raytrace")
{
SDFloader loader{};
Scene scene = loader.load("/home/lissy/Dokumente/raytracer/<API key>/source/simplescene");
Renderer app{scene.m_x_res, scene.m_y_res, scene.m_fileOut, scene};
app.render();
}
*/
TEST_CASE("glm::transform, rotate")
{
glm::vec3 transl(1.0f, 2.0f, 3.0f);
auto translated = glm::translate(glm::mat4(), transl);
std::cout << "translated:" << std::endl;
std::cout << "\n" << translated[0].x << translated[1].x << translated[2].x << translated[3].x << std::endl;
std::cout << translated[0].y << translated[1].y << translated[2].y << translated[3].y << std::endl;
std::cout << translated[0].z << translated[1].z << translated[2].z << translated[3].z << std::endl;
std::cout << translated[0].w << translated[1].w << translated[2].w << translated[3].w << std::endl;
glm::vec3 rotate(1.0f, 2.0f, 3.0f);
auto rotated = glm::rotate(glm::mat4(), 180.0f, rotate);
std::cout << "rotated:" << std::endl;
std::cout << "\n" << rotated[0].x << rotated[1].x << rotated[2].x << rotated[3].x << std::endl;
std::cout << rotated[0].y << rotated[1].y << rotated[2].y << rotated[3].y << std::endl;
std::cout << rotated[0].z << rotated[1].z << rotated[2].z << rotated[3].z << std::endl;
std::cout << rotated[0].w << rotated[1].w << rotated[2].w << rotated[3].w << std::endl;
}
TEST_CASE("transformations")
{
Color c {0.0f,0.0f,0.0f};
Sphere sphere{"testsphere", Material{"",c,c,c, 0.0f}, glm::vec3{0.0f, 0.0f, 0.0f}, 1.0f};
auto mat = sphere.<API key>();
std::cout << "\n" << mat[0].x << mat[1].x << mat[2].x << mat[3].x << std::endl;
std::cout << mat[0].y << mat[1].y << mat[2].y << mat[3].y << std::endl;
std::cout << mat[0].z << mat[1].z << mat[2].z << mat[3].z << std::endl;
std::cout << mat[0].w << mat[1].w << mat[2].w << mat[3].w << std::endl;
sphere.translate(glm::vec3(1.0f, 0.0f, 0.0f));
mat = sphere.<API key>();
std::cout << "\n" << mat[0].x << mat[1].x << mat[2].x << mat[3].x << std::endl;
std::cout << mat[0].y << mat[1].y << mat[2].y << mat[3].y << std::endl;
std::cout << mat[0].z << mat[1].z << mat[2].z << mat[3].z << std::endl;
std::cout << mat[0].w << mat[1].w << mat[2].w << mat[3].w << std::endl;
mat = glm::inverse(mat);
std::cout << "\n" << mat[0].x << mat[1].x << mat[2].x << mat[3].x << std::endl;
std::cout << mat[0].y << mat[1].y << mat[2].y << mat[3].y << std::endl;
std::cout << mat[0].z << mat[1].z << mat[2].z << mat[3].z << std::endl;
std::cout << mat[0].w << mat[1].w << mat[2].w << mat[3].w << std::endl;
Ray ray{glm::vec3{0.0f, 0.0f, 0.0f}, glm::vec3{2.0f, 3.0f, 4.0f}};
auto newRay = transform_ray(mat, ray);
std::cout << newRay << std::endl;
}
TEST_CASE("mat4 ausgabe")
{
glm::mat4 testmat { 5.0f, 0.0f, 0.0f, 6.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0};
std::cout << testmat[0].x;
std::cout << testmat[0].w;
} |
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end |
const gulp = require('gulp')
const config = require('../utils/config.service').config
const browserSync = require('browser-sync')
const path = require('path')
module.exports = () => {
const bs = browserSync.get('SIM')
gulp.watch([
path.join(config.scss, '**/*.scss')
], gulp.series('build:scss'))
gulp.watch(config.files.map((file) => {
return file.source
}), gulp.series('build:files'))
gulp.watch([
path.join(config.data, '**/*.json'),
path.join(config.pages, '**/*.hbs'),
path.join(config.helpers, '**/*.js'),
path.join(config.partials, '**/*.hbs')
], gulp.series('build:hbs'))
.on('change', bs.reload)
} |
import { Component, OnInit } from '@angular/core';
import { <API key>, SignInData } from 'angular2-token';
@Component({
selector: 'sign-in',
templateUrl: 'sign-in.component.html'
})
export class SignInComponent {
signInData: SignInData = <SignInData>{};
output: any;
constructor(private _tokenService: <API key>) { }
// Submit Data to Backend
onSubmit() {
this.output = null;
this._tokenService.signIn(this.signInData).subscribe(
res => {
this.signInData = <SignInData>{};
this.output = res;
}, error => {
this.signInData = <SignInData>{};
this.output = error;
}
);
}
} |
class <API key> < ActiveRecord::Migration[5.1]
def change
<API key>(:rotations, :description, "")
end
end |
package com.pmc.UserInfo.action;
import com.mongodb.WriteResult;
import com.pmc.UserInfo.service.<API key>;
import com.pmc.utils.PMCJSONUtils;
import org.apache.struts2.<API key>;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
public class UserLoginAction {
private <API key> <API key> = new <API key>();
static final int PMC_LOGINFAIL = -1;
static final int PMC_OK = 0;
private String userName;
private String userPassword;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public void execute()throws JSONException, IOException {
// String jsonStr = PMCJSONUtils.<API key>(<API key>.getRequest());
// JSONObject object = new JSONObject(jsonStr);
// if(jsonStr == null)
// return;
JSONObject userLoginInfo = new JSONObject();
userLoginInfo.put("userName", getUserName());
userLoginInfo.put("userPassword", getUserPassword());
int resultStatus = <API key>.userLoginInfo(userLoginInfo.toString());
PrintWriter writer = <API key>.getResponse().getWriter();
<API key>.getResponse().addHeader("<API key>", "*");
JSONObject resultObject = new JSONObject();
if (resultStatus == PMC_LOGINFAIL) {
resultObject.put("result","FAIL");
writer.print(resultObject.toString());
} else {
resultObject.put("result", "OK");
//HttpServletSession session = <API key>.getActionContext(<API key>.getRequest()).getSession();
HttpSession session = <API key>.getRequest().getSession();
session.setAttribute("USER_NAME", userLoginInfo.get("userName"));
System.out.println(session.getAttribute("USER_NAME"));
writer.print(resultObject.toString());
}
}
} |
#include "../Engine/stdafx.h"
class WindowObject;
#pragma once
class Application
{
public:
// :: Type Definitions ::
struct Pixel{ unsigned char r, g, b; };
// :: Constructors ::
Application();
virtual ~Application();
// :: Variables ::
WindowObject *Window;
// :: Methods ::
virtual void Init();
bool SaveBMP(unsigned char* data, DWORD data_size, int width, int height, char* filepath);
}; |
/**
* GameActions
*
* In charge of playing the game.
*/
import { AbstractActions, alt } from "../alt";
interface IGameActions {
fetchGameText(): void;
startGame(stats?: any): void;
endGame(): void;
sayCurrentWord(): void;
spellCurrentWord(): void;
spellInput(): void;
disableButtons(): void;
enableButtons(): void;
checkCharsSoFar(word: string): void;
}
class GameActions extends AbstractActions {
constructor(config: AltJS.Alt) {
super(config);
this.generateActions(
"fetchGameText",
"startGame",
"endGame",
"sayCurrentWord",
"spellCurrentWord",
"spellInput",
"disableButtons",
"enableButtons",
"checkCharsSoFar",
);
}
}
export default alt.createActions<IGameActions>(GameActions); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Headfirst.Csharp.Leftover3
{
<summary>
A guy with a name, age and a wallet full of bucks
</summary>
public class Guy
{
/*
* Notice how Name and Age are properties with backing fields that are
* marked readonly. That means those backing fields can only be set when
* the object is initialized (in their declarations or in the constructor).
*/
<summary>
Read-only backing field for the Name property
</summary>
private readonly string name;
<summary>
The name of the guy
</summary>
public string Name { get { return name; } }
<summary>
Read-only backing field for the Age property
</summary>
private readonly int age;
<summary>
The guy's age
</summary>
public int Age { get { return age; } }
/*
* Cash is not readonly because it might change during the life of the Guy.
*/
<summary>
The number of bucks the guy has
</summary>
public int Cash { get; private set; }
<summary>
The constructor sets the name, age and cash
</summary>
<param name="name">The name of the guy</param>
<param name="age">The guy's age</param>
<param name="cash">The amount of cash the guy starts with</param>
public Guy(string name, int age, int cash)
{
this.name = name;
this.age = age;
Cash = cash;
}
public override string ToString()
{
return String.Format("{0} is {1} years old and has {2} bucks", Name, Age, Cash);
}
<summary>
Give cash from my wallet
</summary>
<param name="amount">The amount of cash to give</param>
<returns>The amount of cash I gave, or 0 if I don't have enough cash</returns>
public int GiveCash(int amount)
{
if (amount <= Cash && amount > 0)
{
Cash -= amount;
return amount;
}
else
{
return 0;
}
}
<summary>
Receive some cash into my wallet
</summary>
<param name="amount">Amount to receive</param>
<returns>The amount of cash received, or 0 if no cash was received</returns>
public int ReceiveCash(int amount)
{
if (amount > 0)
{
Cash += amount;
return amount;
}
Console.WriteLine("{0} says: {1} isn't an amount I'll take", Name, amount);
return 0;
}
}
} |
# Features flags API
All methods require administrator authorization.
Notice that currently the API only supports boolean and percentage-of-time gate
values.
## List all features
Get a list of all persisted features, with its gate values.
GET /features
bash
curl --header "PRIVATE-TOKEN: <your_access_token>" https://gitlab.example.com/api/v4/features
Example response:
json
[
{
"name": "<API key>",
"state": "off",
"gates": [
{
"key": "boolean",
"value": false
}
]
},
{
"name": "new_library",
"state": "on",
"gates": [
{
"key": "boolean",
"value": true
}
]
}
]
## Set or create a feature
Set a feature's gate value. If a feature with the given name doesn't exist yet
it will be created. The value can be a boolean, or an integer to indicate
percentage of time.
POST /features/:name
| Attribute | Type | Required | Description |
|
| `name` | string | yes | Name of the feature to create or update |
| `value` | integer/string | yes | `true` or `false` to enable/disable, or an integer for percentage of time |
| `feature_group` | string | no | A Feature group name |
| `user` | string | no | A GitLab username |
| `group` | string | no | A GitLab group's path, for example 'gitlab-org' |
| `project` | string | no | A projects path, for example 'gitlab-org/gitlab-ce' |
Note that you can enable or disable a feature for a `feature_group`, a `user`,
a `group`, and a `project` in a single API call.
bash
curl --data "value=30" --header "PRIVATE-TOKEN: <your_access_token>" https://gitlab.example.com/api/v4/features/new_library
Example response:
json
{
"name": "new_library",
"state": "conditional",
"gates": [
{
"key": "boolean",
"value": false
},
{
"key": "percentage_of_time",
"value": 30
}
]
}
## Delete a feature
Removes a feature gate. Response is equal when the gate exists, or doesn't.
DELETE /features/:name |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http:
<html>
<head>
<title></title>
</head>
<body>
<script src="../analytic.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script src="../../download/matrix.debug.js"></script>
<script type="text/javascript">
matrix.hash( true );
matrix.baseUrl = "../js/";
matrix( "hello.tmpl" ).done( function() {
$.tmpl( "hello", "fred" ).appendTo( "body" );
} );
</script>
</body>
</html> |
package de.mwg.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.<API key>;
import org.springframework.web.servlet.config.annotation.<API key>;
@Configuration
public class <API key> extends <API key> {
@Override
public void addFormatters(FormatterRegistry registry) {
<API key> registrar = new <API key>();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
} |
# <API key>: true
Rails.application.routes.draw do
resources :model_mocks
mount Alerter::Engine => '/alerts'
end |
Package.describe({
name: "nova:newsletter",
summary: "Telescope email newsletter package",
version: "0.26.0-nova",
git: "https://github.com/TelescopeJS/<API key>.git"
});
Npm.depends({
"html-to-text": "1.3.1"
});
Package.onUse(function (api) {
api.versionsFrom("METEOR@1.0");
api.use([
'nova:core@0.26.0-nova',
'nova:posts@0.26.0-nova',
'nova:comments@0.26.0-nova',
'nova:users@0.26.0-nova',
'nova:email@0.26.0-nova',
'miro:mailchimp@1.1.0',
]);
api.addFiles([
// 'package-tap.i18n',
// 'lib/collection.js',
'lib/callbacks.js',
'lib/custom_fields.js',
'lib/emails.js'
], ['client', 'server']);
api.addFiles([
'lib/server/cron.js',
'lib/server/emails.js',
'lib/server/methods.js'
], ['server']);
api.mainModule('lib/server.js', 'server');
api.mainModule('lib/client.js', 'client');
// var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "id", "it", "ja", "kk", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sl", "sv", "th", "tr", "vi", "zh-CN"];
// var languagesPaths = languages.map(function (language) {
// return "i18n/"+language+".i18n.json";
// api.addFiles(languagesPaths, ["client", "server"]);
}); |
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
} |
using Newtonsoft.Json;
namespace JSend.WebApi.Tests.TestTypes
{
public class Model
{
[JsonProperty("name")]
public string Name { get; set; }
}
} |
require 'sinatra'
require 'twitter'
helpers do
def twitter
@twitter ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV.fetch("<TwitterConsumerkey>")
config.consumer_secret = ENV.fetch("<TwitterConsumerkey>")
end
end
end
get "/tweets.css" do
content_type "text/css"
tweets = twitter.search(ENV.fetch("<TwitterConsumerkey>"))
tweetTime = ""
tweetTimeUTC = ""
tweets.take(5).map.with_index do |tweet, i|
<<-CSS
#tweet-#{i + 1} .avatar {
background: url("#{tweet.user.profile_image_url}");
}
#tweet-#{i + 1} .name::before {
content: "#{tweet.user.name}";
}
#tweet-#{i + 1} .handle::after {
content: "@#{tweet.user.screen_name}";
}
#tweet-#{i + 1} .copy::before {
content: "#{tweet.text}";
}
#tweet-#{i + 1} .timestamp::after {
content: "#{tweet.created_at.in_time_zone('local')}";
}
CSS
end
end |
package com.crescentflare.appconfig.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.crescentflare.appconfig.helper.AppConfigViewHelper;
/**
* Library view: editable cell
* Simulates a list view cell as an editable text
*/
public class <API key> extends FrameLayout
{
// Members
private TextView labelView;
private AppCompatEditText editableView;
private boolean isNumberLimit = false;
// Initialization
public <API key>(Context context)
{
super(context);
init(context, null);
}
public <API key>(Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
init(context, attrs);
}
public <API key>(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
{
super(context, attrs);
init(context, attrs);
}
public <API key>(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs)
{
// Prepare container
LinearLayout container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
container.setPadding(dp(10), dp(12), dp(10), dp(12));
addView(container);
// Add label view
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
container.addView(labelView = new TextView(context));
labelView.setLayoutParams(layoutParams);
labelView.setPadding(dp(4), 0, dp(4), 0);
// Add editable view
layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
container.addView(editableView = new AppCompatEditText(context));
editableView.setLayoutParams(layoutParams);
}
// Modify view
public void setDescription(String text)
{
labelView.setText(text);
}
public void setValue(String value)
{
editableView.setText(value);
}
public String getValue()
{
return editableView.getText().toString();
}
public void <API key>(TextWatcher textWatcher)
{
editableView.<API key>(textWatcher);
}
public void setNumberLimit(boolean numbersOnly)
{
if (numbersOnly)
{
editableView.setInputType(InputType.TYPE_CLASS_NUMBER);
editableView.setKeyListener(DigitsKeyListener.getInstance(true, false));
}
else
{
AppCompatEditText defaults = new AppCompatEditText(getContext());
editableView.setInputType(defaults.getInputType());
editableView.setKeyListener(defaults.getKeyListener());
}
isNumberLimit = numbersOnly;
}
public boolean isNumberLimit()
{
return isNumberLimit;
}
// Helper
private int dp(int dp)
{
return AppConfigViewHelper.dp(dp);
}
} |
const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('<API key>')
const resourcesRule = {
test: /\.(jpeg|png|svg|ico|cur)$/,
use: {
loader: 'url-loader',
options: {
limit: 1000,
name: '[name].[hash:6].[ext]'
}
}
};
const fontRule = {
test: /\.(eot|ttf|woff|woff2)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[hash:6].[ext]'
}
}
};
module.exports = function(UglifyJsPluginCache) {
return {
mode: 'production',
output: {
filename: '[name].[chunkhash:6].js'
},
plugins: [
new webpack.optimize.<API key>(),
],
module: {
rules: [
resourcesRule,
fontRule,
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: UglifyJsPluginCache,
parallel: true,
sourceMap: true,
uglifyOptions: {
compress: false
}
})
]
},
resolve: {
alias: {
'goog/asserts': path.resolve(__dirname, '../src/goog.asserts.prod.js'),
'goog/asserts.js': path.resolve(__dirname, '../src/goog.asserts.prod.js'),
}
},
};
} |
package org.zalando.intellij.swagger.completion.field.completion.swagger.json;
import com.intellij.openapi.vfs.VirtualFile;
import org.zalando.intellij.swagger.<API key>;
import org.zalando.intellij.swagger.assertion.AssertableList;
public class <API key> extends <API key> {
private static final String PARTIAL_FILES_PATH = "completion/field/swagger/partial/json";
public void <API key>() {
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/pet.json", "pet.json");
final VirtualFile swaggerFile =
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/swagger.json", "swagger.json");
myFixture.<API key>(swaggerFile);
final AssertableList completions =
new AssertableList(myFixture.<API key>("pet.json"));
<API key>(completions);
}
public void <API key>() {
myFixture.copyFileToProject(
PARTIAL_FILES_PATH + "/definitions_in_root.json", "definitions_in_root.json");
final VirtualFile swaggerFile =
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/swagger.json", "swagger.json");
myFixture.<API key>(swaggerFile);
final AssertableList completions =
new AssertableList(myFixture.<API key>("definitions_in_root.json"));
<API key>(completions);
}
public void <API key>() {
myFixture.copyFileToProject(
PARTIAL_FILES_PATH + "/<API key>.json", "<API key>.json");
final VirtualFile swaggerFile =
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/swagger.json", "swagger.json");
myFixture.<API key>(swaggerFile);
final AssertableList completions =
new AssertableList(myFixture.<API key>("<API key>.json"));
<API key>(completions);
}
public void <API key>() {
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/pet.yaml", "pet.yaml");
final VirtualFile swaggerFile =
myFixture.copyFileToProject(PARTIAL_FILES_PATH + "/swagger.json", "swagger.json");
myFixture.<API key>(swaggerFile);
final AssertableList completions =
new AssertableList(myFixture.<API key>("pet.yaml"));
<API key>(completions);
}
private void <API key>(final AssertableList completions) {
completions
.assertContains(
"$ref",
"format",
"title",
"description",
"default",
"multipleOf",
"maximum",
"exclusiveMaximum",
"minimum",
"exclusiveMinimum",
"maxLength",
"minLength",
"pattern",
"maxItems",
"minItems",
"uniqueItems",
"maxProperties",
"minProperties",
"required",
"enum",
"type",
"items",
"allOf",
"properties",
"<API key>",
"discriminator",
"readOnly",
"xml",
"externalDocs",
"example")
.isOfSize(30);
}
} |
<?php
class NotificationFactory {
/*
Helper class to generate notifications
*/
const UNREAD = 0;
const READ = 1;
public static $<API key> = array(
'JoinDiscussion' => 1,
'ApproveJoinRequest' => 2,
'JoinBadmintonDate' => 3,
'<API key>' => 4,
'LeaveBadmintonDate' => 5,
'WithdrawAbsence' => 6
);
}
class Notification {
/*
Some sort of notification in the database that has not been read
*/
public $a_href, $message, $date_notified, $read_status, $notification_id;
public static $defaults = array(
'notification_id' => null,
'a_href' => null,
'message' => null,
'date_notified' => null,
'read_status' => 1);
public function __construct(array $args = array()) {
$defaults = self::$defaults;
$args = array_merge($defaults, $args);
$this->notification_id = $args['notification_id'];
$this->read_status = $args['read_status'];
$this->message = $args['message'];
$this->date_notified = $args['date_notified'];
$this->a_href = $args['a_href'];
}
}
class NotificationPusher {
/*
Helper class to push notifications
*/
public static $<API key> = array(
'JoinDiscussion' => '%s has requested to join this conversation "%s"',
'ApproveJoinRequest' => '%s has approved %s request to join the discussion',
'JoinBadmintonDate' => '%s has joined your badminton date "%s"',
'LeaveBadmintonDate' => '%s can no longer attend your badminton date "%s"',
'<API key>' => '%s has posted a comment in a thread you are in',
'WithdrawAbsence' => '%s has withdrawn their absence and can now attend your badminton date %s'
);
public static function push_notification(Action $action) {
$class = get_class($action);
switch ($class) {
case 'JoinDiscussion':
case 'ApproveJoinRequest':
<API key>::push_notification($action);
break;
case 'JoinBadmintonDate':
case 'LeaveBadmintonDate':
case 'WithdrawAbsence':
<API key>::push_notification($action);
break;
case '<API key>':
case 'PostedThread':
<API key>::push_notification($action);
break;
default:
throw new <API key>("$class is not a valid action class, tried to push in NotificaionPusher");
}
}
}
class <API key> {
/*
Class for pushing notifications related to hreads
*/
public static function push_notification(Action $action) {
$mysqli = Database::connection();
$class = get_class($action);
switch ($class) {
case '<API key>':
$message = sprintf(NotificationPusher::$<API key>[$class], $action->commenter->username);
$a_href = 'therad.php?id=' . $action->thread->thread_id;
list($message, $a_href) = Database::sanitize(array($message, $a_href));
$participants = $action->thread-><API key>();
foreach ($participants as $participant) {
if ($participant->user_id != $action->commenter->user_id) {
//No need to notify the commenter...
$insert = "INSERT INTO `notifications` (message, user_id, type, a_href, read_status, date_notified) VALUES ('$message', '$participant->user_id', '" . NotificationFactory::$<API key>[$class] . "', '$a_href', '" . NotificationFactory::UNREAD . "', NOW())";
$result = $mysqli->query($insert)
or die ($mysqli->error);
}
}
return true;
break;
default:
throw new OutOfRangeException('OutOfRangeException occured on pushing notification in <API key>');
}
}
}
class <API key> {
/*
Class for pushing notifications related to badminton dates
*/
public static function push_notification(Action $action) {
$mysqli = Database::connection();
//var_dump($mysqli);
$class = get_class($action);
switch ($class) {
case 'JoinBadmintonDate':
$action->badminton_date->get_datename();
$message = sprintf(NotificationPusher::$<API key>[$class], $action->joiner->username, $action->badminton_date->datename);
$a_href = $action->badminton_date->date_id;
list($message, $a_href) = Database::sanitize(array($message, $a_href));
$action->badminton_date->get_attendees(array(
$action->joiner)
);
//print_r($action->badminton_date->attendees);
foreach ($action->badminton_date->attendees as $attendant) {
$a_href = "date.php?id=$a_href";
$insert = "INSERT INTO `notifications` (message, user_id, type, a_href, read_status, date_notified) VALUES ('$message', '$attendant->user_id', '" . NotificationFactory::$<API key>[$class] . "', '$a_href', '" . NotificationFactory::UNREAD . "', NOW())";
$result = $mysqli->query($insert)
or die ($mysqli->error);
}
return true;
break;
case 'LeaveBadmintonDate':
$message = sprintf(NotificationPusher::$<API key>[$class], $action->leaver->username, $action->badminton_date->datename);
$a_href = $action->badminton_date->date_id;
list($message, $a_href) = Database::sanitize(array($message, $a_href));
$action->badminton_date->get_attendees();
foreach ($action->badminton_date->attendees as $attendant) {
if ($attendant->user_id != $action->leaver->user_id) {
$a_href = "date.php?id=$a_href";
$insert = "INSERT INTO `notifications` (message, user_id, type, a_href, read_status, date_notified) VALUES ('$message', '$attendant->user_id', '" . NotificationFactory::$<API key>[$class] . "', '$a_href', '" . NotificationFactory::UNREAD . "', NOW())";
$result = $mysqli->query($insert)
or die ($mysqli->error);
}
}
return true;
break;
case 'WithdrawAbsence':
$message = sprintf(NotificationPusher::$<API key>[$class], $action->withdrawer->username, $action->badminton_date->datename);
$a_href = $action->badminton_date->date_id;
list($message, $a_href) = Database::sanitize(array($message, $a_href));
$action->badminton_date->get_attendees();
foreach ($action->badminton_date->attendees as $attendant) {
if ($attendant->user_id != $action->withdrawer->user_id) {
$a_href = "date.php?id=$a_href";
$insert = "INSERT INTO `notifications` (message, user_id, type, a_href, read_status, date_notified) VALUES ('$message', '$attendant->user_id', '" . NotificationFactory::$<API key>[$class] . "', '$a_href', '" . NotificationFactory::UNREAD . "', NOW())";
$result = $mysqli->query($insert)
or die ($mysqli->error);
}
}
return true;
break;
default:
throw new <API key>("$class is not a valid action class, tried to push in <API key>");
}
}
}
class <API key> {
/*
Pushes notifcation into the conversation
*/
public static function push_notification(MessageAction $action) {
$class = get_class($action);
$dbc = Database::connection();
switch ($class) {
case 'JoinDiscussion':
$message = sprintf(NotificationPusher::$<API key>[$class], $action->joiner->email, $action->conversation->conversation_name);
$sql = "INSERT INTO `<API key>` (conversation_id, type, message_text) VALUES ('$action->conversation->conversation_id', '" . Conversation::NOTIFICATION_TYPE . "', '$message')";
$result = $dbc->query($sql)
or die ($dbc->error);
return true;
break;
case 'ApproveJoinRequest':
$message = sprintf(NotificationPusher::$<API key>[$class], $action->approver->email, $action->joiner->email);
$sql = "INSERT INTO `<API key>` (conversation_id, type, message_text) VALUES ('$action->conversation->conversation_id', '" . Conversation::NOTIFICATION_TYPE . "', '$message')";
$result = $dbc->query($sql)
or die ($dbc->error);
return true;
break;
default:
throw new <API key>("$class is not a valid action, tried to push in <API key>");
}
}
}
class <API key> {
const <API key> = 2;
}
?> |
#!/usr/bin/env python
import errno
import os
import platform
import sys
BASE_URL = os.getenv('<API key>') or \
'https://s3.amazonaws.com/<API key>/libchromiumcontent'
<API key> = os.getenv('<API key>') or \
'<SHA1-like>'
PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def get_platform_key():
if os.environ.has_key('MAS_BUILD'):
return 'mas'
else:
return PLATFORM
def get_target_arch():
try:
target_arch_path = os.path.join(__file__, '..', '..', '..', 'vendor',
'brightray', 'vendor', 'download',
'libchromiumcontent', '.target_arch')
with open(os.path.normpath(target_arch_path)) as f:
return f.read().strip()
except IOError as e:
if e.errno != errno.ENOENT:
raise
return 'x64'
def <API key>():
return 'v2.21'
def get_env_var(name):
value = os.environ.get('ELECTRON_' + name, '')
if not value:
# TODO Remove ATOM_SHELL_* fallback values
value = os.environ.get('ATOM_SHELL_' + name, '')
if value:
print 'Warning: Use $ELECTRON_' + name + ' instead of $ATOM_SHELL_' + name
return value
def s3_config():
config = (get_env_var('S3_BUCKET'),
get_env_var('S3_ACCESS_KEY'),
get_env_var('S3_SECRET_KEY'))
message = ('Error: Please set the $ELECTRON_S3_BUCKET, '
'$<API key>, and '
'$<API key> environment variables')
assert all(len(c) for c in config), message
return config
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
def get_zip_name(name, version, suffix=''):
arch = get_target_arch()
if arch == 'arm':
arch += 'v7l'
zip_name = '{0}-{1}-{2}-{3}'.format(name, version, get_platform_key(), arch)
if suffix:
zip_name += '-' + suffix
return zip_name + '.zip' |
namespace HotelSystem.Web.Areas.Administration.ViewModels.Hotels
{
using System;
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using HotelSystem.Common;
using HotelSystem.Data.Models;
using HotelSystem.Web.Infrastructure.Mapping;
public class HotelInputModel : IMapTo<Hotel>
{
[Required]
[StringLength(
ModelConstraints.NameMaxLength,
ErrorMessage = <API key>.<API key>,
MinimumLength = ModelConstraints.NameMinLength)]
public string Name { get; set; }
[Required]
[StringLength(
ModelConstraints.<API key>,
ErrorMessage = <API key>.<API key>,
MinimumLength = ModelConstraints.<API key>)]
public string Description { get; set; }
[Required]
[StringLength(
ModelConstraints.LocationMaxLength,
ErrorMessage = <API key>.<API key>)]
public string Country { get; set; }
[Required]
[StringLength(
ModelConstraints.LocationMaxLength,
ErrorMessage = <API key>.<API key>)]
public string City { get; set; }
[Required]
[StringLength(
ModelConstraints.LocationMaxLength,
ErrorMessage = <API key>.<API key>)]
public string Address { get; set; }
[Required]
[StringLength(
ModelConstraints.<API key>,
ErrorMessage = <API key>.<API key>)]
public string Phone { get; set; }
[StringLength(
ModelConstraints.NameMaxLength,
ErrorMessage = <API key>.<API key>)]
public string Fax { get; set; }
[Required]
[StringLength(
ModelConstraints.EmailMaxLength,
ErrorMessage = <API key>.<API key>)]
[EmailAddress]
public string Email { get; set; }
[StringLength(
ModelConstraints.FacebookMaxLength,
ErrorMessage = <API key>.<API key>)]
public string Facebook { get; set; }
[Required]
[Range(ModelConstraints.HotelMinStars, ModelConstraints.HotelMaxStars)]
public int Stars { get; set; }
}
} |
function OnSpellStart(keys)
local caster = keys.caster
local ability = keys.ability
local point = keys.target_points[1]
local level = ability:GetLevel() - 1
local radius = math.min(ability:<API key>("base_radius", level) + (caster:GetIntellect() * (ability:<API key>("int_to_radius_pct", level) * 0.01)), ability:GetAbilitySpecial("max_radius"))
local enemies = FindUnitsInRadius(caster:GetTeamNumber(), point, nil, radius, <API key>, <API key> + <API key>, <API key>, FIND_ANY_ORDER, false)
for _, enemy in ipairs(enemies) do
ApplyDamage({
victim = enemy,
attacker = caster,
damage = math.min(ability:<API key>("base_damage", level) + (caster:GetIntellect() * (ability:<API key>("int_to_dmg_pct", level) * 0.01)), ability:GetAbilitySpecial("max_damage")),
damage_type = ability:<API key>(),
damage_flags = <API key>,
ability = ability
})
end
local dummy = CreateUnitByName("npc_dummy_unit", point, false, nil, nil, caster:GetTeamNumber())
dummy:EmitSound("Arena.Hero_Stargazer.GammaRay.Cast")
local particle = ParticleManager:CreateParticle("particles/arena/units/heroes/hero_stargazer/gamma_ray_immortal1.vpcf", <API key>, dummy, caster)
ParticleManager:SetParticleControl(particle, 1, Vector(radius, radius, radius))
Timers:CreateTimer(0.5, function()
dummy:RemoveSelf()
end)
end |
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Twig_Extensions_' => array($vendorDir . '/twig/extensions/lib'),
'Twig_' => array($vendorDir . '/twig/twig/lib'),
'Symfony\\Component\\Icu\\' => array($vendorDir . '/symfony/icu'),
'Symfony\\Bundle\\SwiftmailerBundle' => array($vendorDir . '/symfony/swiftmailer-bundle'),
'Symfony\\Bundle\\MonologBundle' => array($vendorDir . '/symfony/monolog-bundle'),
'Symfony\\Bundle\\AsseticBundle' => array($vendorDir . '/symfony/assetic-bundle'),
'Symfony\\' => array($vendorDir . '/symfony/symfony/src'),
'Sensio\\Bundle\\GeneratorBundle' => array($vendorDir . '/sensio/generator-bundle'),
'Sensio\\Bundle\\<API key>' => array($vendorDir . '/sensio/<API key>'),
'Sensio\\Bundle\\DistributionBundle' => array($vendorDir . '/sensio/distribution-bundle'),
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src'),
'PhpCollection' => array($vendorDir . '/phpcollection/phpcollection/src'),
'Monolog' => array($vendorDir . '/monolog/monolog/src'),
'Metadata\\' => array($vendorDir . '/jms/metadata/src'),
'JMS\\SerializerBundle' => array($vendorDir . '/jms/serializer-bundle'),
'JMS\\Serializer' => array($vendorDir . '/jms/serializer/src'),
'JMS\\' => array($vendorDir . '/jms/parser-lib/src'),
'Incenteev\\ParameterHandler' => array($vendorDir . '/incenteev/<API key>'),
'Doctrine\\ORM\\' => array($vendorDir . '/doctrine/orm/lib'),
'Doctrine\\DBAL\\' => array($vendorDir . '/doctrine/dbal/lib'),
'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
'Doctrine\\Common\\DataFixtures' => array($vendorDir . '/doctrine/data-fixtures/lib'),
'Doctrine\\Common\\Collections\\' => array($vendorDir . '/doctrine/collections/lib'),
'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib'),
'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib'),
'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib'),
'Doctrine\\Bundle\\FixturesBundle' => array($vendorDir . '/doctrine/<API key>'),
'Doctrine\\Bundle\\DoctrineBundle' => array($vendorDir . '/doctrine/doctrine-bundle'),
'Assetic' => array($vendorDir . '/kriswallsmith/assetic/src'),
'' => array($baseDir . '/src'),
); |
// skybox.cpp
// mint3d-tests
#include "skybox.h"
#include "supports/utils.h"
#include "application/res_manager.h"
#include "application/scene_manager.h"
#include "components/mesh_renderer.h"
#include "render/material.h"
#include "supports/default_shaders.h"
<API key>
Component::Type Skybox::TYPE = TYPE_SKYBOX;
Skybox::Skybox()
: _material(nullptr)
, _sky(nullptr)
{
}
void Skybox::setTexture(const std::string& name, const std::string& type){
_material = ResManager::instance()->createMaterial("skybox." + name + type);
_material->setShader(DefaultShaders::skybox());
_material->setTexture(ResManager::instance()-><API key>(name, type));
if (!_sky) {
auto sceneManager = SceneManager::instance();
_sky = sceneManager->createObject();
auto com_mesh = _sky->attachComponent<MeshRenderer>();
com_mesh->setMesh(Geometry::ShapeCube);
}
_sky->getComponent<MeshRenderer>()->setMaterial(_material);
}
<API key> |
<div class="commune_descr limited">
<p>
Monterrein est
un village
localisé dans le département de Morbihan en Bretagne. Elle comptait 352 habitants en 2008.</p>
<p>Le nombre de logements, à Monterrein, était réparti en 2011 en treize appartements et 181 maisons soit
un marché plutôt équilibré.</p>
<p>À coté de Monterrein sont positionnées géographiquement les villes de
<a href="{{VLROOT}}/immobilier/augan_56006/">Augan</a> à 7 km, 1 375 habitants,
<a href="{{VLROOT}}/immobilier/saint-abraham_56202/">Saint-Abraham</a> à 4 km, 523 habitants,
<a href="{{VLROOT}}/immobilier/montertelot_56139/">Montertelot</a> à 4 km, 322 habitants,
<a href="{{VLROOT}}/immobilier/gourhel_56065/">Gourhel</a> à 6 km, 496 habitants,
<a href="{{VLROOT}}/immobilier/missiriac_56133/">Missiriac</a> à 4 km, 1 050 habitants,
<a href="{{VLROOT}}/immobilier/caro_56035/">Caro</a> localisée à 3 km, 1 129 habitants,
entre autres. De plus, Monterrein est située à seulement six km de <a href="{{VLROOT}}/immobilier/ploermel_56165/">Ploërmel</a>.</p>
<p>La commune propose quelques équipements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.</p>
<p>Si vous envisagez de emmenager à Monterrein, vous pourrez aisément trouver une maison à vendre. </p>
</div> |
#![allow(dead_code)]
mod gbm;
#[macro_use]
pub mod formats;
pub use self::gbm::*;
#[cfg(test)]
mod tests {
#[test]
fn macro_test() {
assert!(__gbm_fourcc_code!('X', 'R', '2', '4') == 0x34325258);
assert!(__gbm_fourcc_code!('\0', '\0', '\0', '\0') == 0);
assert!(__gbm_fourcc_code!(0xFF, 0x00, 0xFF, 0x00) == 0x00FF00FF);
}
} |
<?php
namespace ForkCMS\Modules\MediaLibrary\Domain\MediaItem;
use ForkCMS\Modules\MediaLibrary\Domain\Manager\FileManager;
use ForkCMS\Modules\MediaLibrary\Domain\MediaItem\MediaItem;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SimpleBus\Message\Bus\MessageBus;
/**
* MediaItem Subscriber
*/
final class MediaItemSubscriber implements EventSubscriber
{
/** @var CacheManager */
protected $cacheManager;
/** @var MessageBus */
protected $commandBus;
/** @var FileManager */
protected $fileManager;
public function __construct(
FileManager $fileManager,
CacheManager $cacheManager,
MessageBus $commandBus
) {
$this->fileManager = $fileManager;
$this->cacheManager = $cacheManager;
$this->commandBus = $commandBus;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::postRemove,
];
}
private function deleteSource(MediaItem $mediaItem): void
{
$this->fileManager->deleteFile($mediaItem->getAbsolutePath());
}
private function deleteThumbnails(MediaItem $mediaItem): void
{
// We have an image, so we have thumbnails to delete
if ($mediaItem->getType()->isImage()) {
// Delete all thumbnails
$this->cacheManager->remove($mediaItem->getWebPath());
}
}
private function generateThumbnails(MediaItem $mediaItem): void
{
// We have an image, so we have a backend thumbnail to generate
if ($mediaItem->getType()->isImage()) {
// Generate Backend thumbnail
$this->cacheManager->getBrowserPath($mediaItem->getWebPath(), '<API key>');
}
}
public function postPersist(LifecycleEventArgs $eventArgs): void
{
$entity = $eventArgs->getObject();
if (!$entity instanceof MediaItem) {
return;
}
$this->generateThumbnails($entity);
}
public function postRemove(LifecycleEventArgs $eventArgs): void
{
$entity = $eventArgs->getObject();
if (!$entity instanceof MediaItem) {
return;
}
$this->deleteSource($entity);
$this->deleteThumbnails($entity);
}
} |
Rails329::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.<API key> = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use <API key>, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.<API key> = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.<API key> = 0.5
end |
import $ from 'jquery';
export default function () {
let jews = {};
['Top', 'Left'].forEach(function (v) {
Object.defineProperty(document.body, 'scroll' + v, {writable: false, value: 0});
});
['By', 'To'].forEach(function (v) {
window['scroll' + v] = function () {};
});
var _filter = function (a) {
return [].filter.apply(a, [].slice.call(arguments, 1));
};
var el_filter = function (el, obj, m) {
if (typeof el==="string") el = $(el)[0].childNodes;
else if (el instanceof Node) el = el.childNodes;
var f;
if (m === true || m === undefined) f = function(v) { return v instanceof obj; };
else f = function(v) { return !(v instanceof obj); };
return _filter(el, f);
};
jews.title = $('.View_Title>strong').text();
jews.subtitle = $('.View_Title>span').text();
jews.timestamp = {
created: new Date(el_filter('.View_Time', HTMLElement, false)[0].textContent.trim().replace(/(\d{4})\.(\d{2})\.(\d{2})\s*/, "$1-$2-$3T")+"+09:00"),
lastModified: undefined
};
var info = $('.View_Info')[0].childNodes;
jews.reporters = [{
name: el_filter(info, HTMLElement, false)[0].textContent.split(/\s*\|\s*/)[0],
mail: el_filter(info, HTMLAnchorElement)[0].textContent
}];
jews.content = document.getElementById('_article').innerHTML.trim();
return jews;
} |
<?php
namespace Baazaar\BaazaarBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\<API key>;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Baazaar\BaazaarBundle\Form\DataTransformer\<API key>;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Baazaar\BaazaarBundle\Form\PriceType;
use Baazaar\LocationBundle\Form\LocationType;
class AdType extends AbstractType {
private $catRepository;
public function __construct(Doctrine $doctrine) {
$this->catRepository = $doctrine->getManager()->getRepository('<API key>:Category');
}
public function buildForm(<API key> $builder, array $options) {
$builder->add('title');
$builder->add('body', TextareaType::class);
$builder->add('categoriesList', ChoiceType::class, array(
'choices' => $this->getCategories(),
'data_class' => null
));
$builder->add('uploads', FileType::class, array(
'multiple' => true,
'data_class' => null
));
$builder->add('object_status', ChoiceType::class, array(
'choices' => $this->getObjectStatusses(),
'data_class' => null
));
$builder->add('delivery_method', ChoiceType::class, array(
'choices' => $this->getDeliveryMethods(),
'data_class' => null
));
$builder->add('locations', TextType::class, array(
'mapped' => false
));
$builder->add('location', HiddenType::class, array(
'mapped' => false
));
$builder->add('price', PriceType::class, array(
'data_class' => 'Baazaar\BaazaarBundle\Entity\Price' //this is needed to convert form array to correct object
));
}
private function getCategories() {
$categories = $this->catRepository->childrenHierarchy();
return $this->buildTreeChoices($categories);
}
protected function buildTreeChoices( $choices , $level = 0 ) {
$result = array();
foreach ( $choices as $choice ){
$result[str_repeat( '-' , $level ) . ' ' . $choice['title']] = $choice['id'];
if ( !empty($choice['__children']) ) {
$result = $result + $this->buildTreeChoices( $choice['__children'] , $level + 1 );
}
}
return $result;
}
/**
* @param <API key> $resolver
*/
public function setDefaultOptions(<API key> $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Baazaar\BaazaarBundle\Entity\Ad'
));
}
protected function getObjectStatusses() {
return array(
'new' => 'new',
'used' => 'used'
);
}
protected function getDeliveryMethods() {
return array(
'send' => 'send',
'pickup' => 'pickup'
);
}
public function getName() {
return 'ad';
}
} |
<?php
if(!defined('SMVC_SQL_NONE'))
/**
* @name SMVC_SQL_NONE ,resource.
*/
define('SMVC_SQL_NONE', 0);
if(!defined('SMVC_SQL_INIT'))
/**
* @name SMVC_SQL_INIT fetch.
*/
define('SMVC_SQL_INIT', 1);
if(!defined('SMVC_SQL_ALL'))
/**
* @name SMVC_SQL_ALL fetchAll.
*/
define('SMVC_SQL_ALL', 2);
class SmallMVCDriverPDO{
/**
* @var string|null $table
*/
private $table = null;
/**
* @var resource|null $pdo pdo
*/
private $pdo = null;
/**
* @var resource|null $result
*/
private $result = null;
/**
* @var resource|PDO::FETCH+ASSOC $fetch_mode fetch
*/
private $fetch_mode = PDO::FETCH_ASSOC;
/**
* @var mixed[] $query_params
*/
private $query_params = array('select' => '*');
/**
* @var string|null $dbname
*/
protected $dbname = null;
/**
*
*
* pdo.
*/
function __destruct(){
$this->pdo = null;
}
/**
*
*
* SmallMVCModel.
* SmallMVCModelfirst_parameter_position.
*
* @param string|null $table
* @param string|null $poolName .
*
* @return resource
*/
function __construct($table = null,$poolName = null){
if(!isset($table)){
$table = '';
}
$config = SMvc::instance(null, 'default')->config;
if(!$poolName)
$poolName = 'database';
if($poolName && isset(SMvc::instance(null, 'default')->dbs[$poolName])){
return SMvc::instance(null, 'default')->dbs[$poolName];
}
if($poolName && isset($config[$poolName]) && !empty($config[$poolName]['plugin'])){
if(!class_exists('PDO',false)){
$e = new SmallMVCException("PHP PDO package is required.", DEBUG);
throw $e;
}
if(empty($config[$poolName])){
$e = new SmallMVCException("database definitions required.", DEBUG);
throw $e;
}
if(empty($config[$poolName]['charset']))
$config[$poolName]['charset'] = $config['charset'];
$this->dbname = $config[$poolName]['name'];
$dsn = !empty($config[$poolName]['dsn']) ? $config[$poolName]['dsn'] : "{$config[$poolName]['type']}:host={$config[$poolName]['host']};port={$config[$poolName]['port']};dbname={$config[$poolName]['name']}";
try{
$this->pdo = new PDO(
$dsn,
$config[$poolName]['user'],
$config[$poolName]['pass'],
array(PDO::ATTR_PERSISTENT => !empty($config[$poolName]['persistent']) ? true : false)
);
$this->pdo->exec("set names '{$config[$poolName]['charset']}'");
}catch (PDOException $e) {
$e = new SmallMVCException(sprintf("Can't connect to PDO database '{$config[$poolName]['type']}'. Error: %s",$e->getMessage()), DEBUG);
throw $e;
}
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
try {
$result = $this->pdo->query("SELECT 1 FROM `$table` LIMIT 1");
$this->table = "`$table`";//set table if it exists
} catch (Exception $e) {
//do nothing because the table doesn't exists
}
}
}
/**
*
*
* @param mxied[] $clause ,.
*
* @return resource
*/
public function select($clause){
$this->query_params['select'] = $clause;
return $this;
}
/**
*
*
* @return boolean
*/
public function exists(){
$retArray = $this->query('all');
if(!empty($retArray))
return true;
return false;
}
/**
* .
*
* @param string $table
*
* @return resource
*/
public function from($table){
$this->query_params['from'] = "`{$table}`";
$this->table = "`{$table}`";
return $this;
}
/**
* .query_params.
*
* @param string $table
*
* @return resource
*/
public function table($table){
$this->table = "`{$table}`";
return $this;
}
public function where($clause = null,$args = null){
if(empty($clause) || is_int($clause)){
$e = new SmallMVCException(sprintf("where cannot be empty and must be a string"), DEBUG);
throw $e;
}
if(!is_array($clause)) $clause = array($clause);
if(!is_array($args)) $args = array($args);
foreach($clause as &$each_clause){
if(preg_match('/(\w*\bis\b(\s*(not)){0,1})|(\w*\blike\b)/i',$each_clause))
$each_clause = ' '.$each_clause.' ';
else if(!preg_match('/[=<>]/',$each_clause))
$each_clause .= ' = ';
if(strpos($each_clause,'?')===false)
$each_clause .= ' ? ';
}
$this->_where($clause,$args,'AND');
return $this;
}
public function orwhere($clause,$args){
if(empty($clause) || is_int($clasue)){
$e = new SmallMVCException(sprintf("where cannot be empty and must be a string"), DEBUG);
throw $e;
}
if(!is_array($clause)) $clause = array($clause);
if(!is_array($args)) $args = array($args);
for($i = 0; $i < count($clause); ++$i){
if(!preg_match('![=<>]!',$clause[$i])) $clause[$i] .= '=';
if(strpos($clause[$i],'?')===false) $clause[$i] .= '?';
}
//if condition is like this: where id=x or id=y or id=c
// expand $clause numbers equal to $args
if(count($clause) === 1 && count($clause) < count($args)){
$repeat_nums = count($args) - count($clause);
for($i = 0; $i < $repeat_nums; ++$i){
$clause[] = $clause[0];
}
}
$this->_where($clause,$args,'OR');
return $this;
}
public function join($join_table,$join_on,$join_type=null){
$clause = "JOIN {$join_table} ON {$join_on}";
if(!empty($join_type))
$clause = $join_type . ' ' . $clause;
if(!isset($this->query_params['join']))
$this->query_params['join'] = array();
$this->query_params['join'][] = $clause;
return $this;
}
public function in($field,$elements,$list=false){
$this->_in($field,$elements,$list,'AND');
return $this;
}
public function orin($field,$elements,$list=false){
$this->_in($field,$elements,$list,'OR');
return $this;
}
public function orderby($clause){
$this->_set_clause('orderby',$clause);
return $this;
}
public function groupby($clause){
$this->_set_clause('groupby',$clause);
return $this;
}
public function limit($limit, $offset=0){
if(!empty($offset))
$this->_set_clause('limit',sprintf('%d,%d',(int)$offset,(int)$limit));
else
$this->_set_clause('limit',sprintf('%d',(int)$limit));
return $this;
}
public function query($type=null, $query = null, $fetch_mode = null){
if(!isset($query)){
$query = $this->_query_assemble($params,$fetch_mode);
}
switch($type){
case 'one':
$this->limit(1);
return $this->_query($query,$params,SMVC_SQL_INIT,$fetch_mode);
case 'none':
return $this->_query($query,$params,SMVC_SQL_NONE,$fetch_mode);
case 'all':
default:
return $this->_query($query,$params,SMVC_SQL_ALL,$fetch_mode);
}
}
public function update($columns){
if(empty($columns)||!is_array($columns)){
$e = new SmallMVCException("Unable to update, at least one column required", DEBUG);
throw $e;
return false;
}
$query[] = "UPDATE ";
$query[] = "{$this->table} SET";
$fields = array();
$params = array();
foreach($columns as $cname => $cvalue){
if(!empty($cname)){
$fields[] = "{$cname}=?";
$params[] = $cvalue;
}
}
$query[] = implode(',',$fields);
// assemble where clause
if($this->_assemble_where($where_string,$where_params)){
$query[] = $where_string;
$params = array_merge($params,$where_params);
}
$this->query_params = array('select' => '*');
return $this->_query($query,$params);
}
public function insert($columns){
if(empty($columns)||!is_array($columns)){
$e = new SmallMVCException("Unable to insert, at least one column required", DEBUG);
throw $e;
}
$column_names = array_keys($columns);
$query[] = 'INSERT INTO ';
$query[] = sprintf("{$this->table} (`%s`) VALUES",implode('`,`',$column_names));
$fields = array();
$params = array();
$is_multi_data = false;
for($i = 0; $i < count($column_names); ++$i){
if(is_array($columns[$column_names[$i]]) && !empty($columns[$column_names[$i]][0])){
$is_multi_data = true;
foreach($columns[$column_names[$i]] as $value_index => $value){
$params[$value_index * count($column_names) + $i] = $value;
$fields[] = '?';
}
}else{
$params[$i] = $columns[$column_names[$i]];
$fields[] = '?';
}
}
ksort($params, SORT_NUMERIC);
for($m = 0; $m < count($fields)/count($column_names); ++$m){
$temp_fields = array();
for($n = 0; $n < count($column_names); ++$n){
$temp_fields = array_slice($fields, $m * count($column_names), count($column_names), false);
}
if($m === 0){
$query[] = '(' . implode(',',$temp_fields) . ')';
}else{
$query[] = ',(' . implode(',',$temp_fields) . ')';
}
}
$this->_query($query,$params);
return $this->lastId();
}
public function delete(){
$query[] = "DELETE ";
$query[] = "FROM {$this->table}";
$params = array();
// assemble where clause
if($this->_assemble_where($where_string,$where_params)){
$query[] = $where_string;
$params = array_merge($params,$where_params);
}
$this->query_params = !empty($this->query_params) ? array_merge(array('select' => '*'),$this->query_params) : array('select' => '*');
$result = $this->_query($query,$params);
$this->query_params = array('select' => '*');
return $result;
}
public function lastId(){
return $this->pdo->lastInsertId();
}
public function numRows(){
return $this->result->rowCount();
}
public function affectedRows(){
return $this->result->rowCount();
}
private function _where($clause = array(), $args=array(), $prefix='AND'){
// sanity check
if(empty($clause) || empty($args)) return false;
//data format check
if(!is_array($clause) || !is_array($args)){
$e = new SmallMVCException("params format error, either clause or args must be an array", DEBUG);
throw $e;
}
// make sure number of ? match number of args
if(count($args) != count($clause)){
$e = new SmallMVCException("Number of where clause args don't match number args", DEBUG);
throw $e;
}
foreach($clause as $each_clause){
$this->query_params['where']['clause'][] = $each_clause;
}
foreach($args as $each_args){
$this->query_params['where']['args'][] = $each_args;
$this->query_params['where']['prefix'][] = $prefix;
}
return $this->query_params['where'];
}
private function _in($field,$elements,$list=false,$prefix='AND')
{
if(!$list)
{
if(!is_array($elements))
$elements = explode(',',$elements);
// quote elements for query
foreach($elements as $idx => $element)
$elements[$idx] = $this->pdo->quote($element);
$clause = sprintf("{$field} IN (%s)", implode(',',$elements));
}
else
$clause = sprintf("{$field} IN (%s)", $elements);
$this->_where($clause,array(),$prefix);
}
//set clasue and args to $this->query_params[$type] array where type is 'gourpby' 'join' 'where' ...
private function _set_clause($type, $clause, $args=array()){
// sanity check
if(empty($type)||empty($clause))
return false;
$this->query_params[$type] = array('clause'=>$clause);
if(isset($args))
$this->query_params[$type]['args'] = $args;
}
private function _query_assemble(&$params,$fetch_mode=null){
if(empty($this->query_params['from'])){
if(empty($this->table)){
$e = new SmallMVCException("Table is not exists in this database or table empty(use ->from(\$table) to set one)", DEBUG);
throw $e;
return false;
}
$this->query_params['from'] = $this->table;
}
$query = array();
$query[] = "SELECT {$this->query_params['select']}";
$query[] = "FROM {$this->query_params['from']}";
// assemble JOIN clause
if(!empty($this->query_params['join']))
foreach($this->query_params['join'] as $cjoin)
$query[] = $cjoin;
// assemble WHERE clause
if($where = $this->_assemble_where($where_string,$params))
$query[] = $where_string;
// assemble GROUPBY clause
if(!empty($this->query_params['groupby']))
$query[] = "GROUP BY {$this->query_params['groupby']['clause']}";
// assemble ORDERBY clause
if(!empty($this->query_params['orderby']))
$query[] = "ORDER BY {$this->query_params['orderby']['clause']}";
// assemble LIMIT clause
if(!empty($this->query_params['limit']))
$query[] = "LIMIT {$this->query_params['limit']['clause']}";
//re-construct a new query_params
$this->query_params = array('select' => '*');
return $query;
}
//make where condition string like this and stored in variable:
// WHERE xx [=<>] ? AND|OR oo [=<>] ? => $where
// array(xx_condition, oo_condition) => $params
private function _assemble_where(&$where,&$params){
if(!empty($this->query_params['where'])){
<API key>($this->query_params['where'], array($this,'filter_query_params'));
$where_parts = array();
empty($params) ? $params = array() : null;
//$query_params['where'] = array(clause => array(), 'args' => array(), 'prefix' = array());
$cwhere = $this->query_params['where'];
$params = array_merge($params,(array)$cwhere['args']);
for($i = 0; $i < count($this->query_params['where']['clause']); ++$i){
if($i == 0) $where_parts[] = " {$this->query_params['where']['clause'][$i]}";
else $where_parts[] = " {$this->query_params['where']['prefix'][$i]} {$this->query_params['where']['clause'][$i]}";
}
$where = 'WHERE '.implode(' ',$where_parts);
return true;
}
return false;
}
private function _query($query,$params=null,$return_type = SMVC_SQL_NONE,$fetch_mode=null){
$checkArray = array();
foreach($query as $each){
preg_match('/^WHERE\s+/', $each) ? null : array_push($checkArray, $each);
}
<API key>($checkArray, array($this,'filter_query_params'));
$query = is_array($query) ? implode(' ',$query) : $query;
/* if no fetch mode, use default */
if(!isset($fetch_mode))
$fetch_mode = PDO::FETCH_ASSOC;
/* prepare the query
query string is something like this:
select * from _table_ where xx = ? AND|OR oo > ?
update _table_ set xx = ?
*/
try {
$this->result = $this->pdo->prepare($query);
} catch (PDOException $e) {
$e = new SmallMVCException(sprintf("PDO Error: %s Query: %s",$e->getMessage(),$query), DEBUG);
throw $e;
}
/* execute with params */
try {
$this->result->execute($params);
} catch (PDOException $e) {
$e = new SmallMVCException(sprintf("PDO Error: %s Query: %s",$e->getMessage(),$query), DEBUG);
throw $e;
}
/* get result with fetch mode */
$this->result->setFetchMode($fetch_mode);
switch($return_type){
case SMVC_SQL_INIT:
return $this->result->fetch();
break;
case SMVC_SQL_ALL:
return $this->result->fetchAll();
break;
case SMVC_SQL_NONE:
default:
return true;
break;
}
}
private function filter_query_params($item, $key){
$regexs = array(
'\b(and|or)\\b\s+(>|<|=|in|like)',
'\\/\\*.+?\\*\\/',
'<\\s*script\\b',
'exec(\s|\+)+(s|x)p\w+',
'UNION.+?Select',
'Update.+?SET',
'Insert\\s+INTO.+?VALUES',
'(Select|Delete).+?FROM',
'(Create|Alter|Drop|TRUNCATE)\\s+(TABLE|DATABASE)',
'char\(.+?\)'
);
foreach($regexs as $regex){
if(preg_match("/{$regex}/is", $item)){
$e = new SmallMVCException("SQL Injection Detected", DEBUG);
throw $e;
}
}
}
}
?> |
package com.mycompany.app;
import org.junit.Ignore;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static junit.framework.Assert.assertEquals;
public class CurrencyTest {
@Test
public void numberFormat() {
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CHINA);
NumberFormat currformat = NumberFormat.getCurrencyInstance(Locale.CHINA);
assertEquals("1,000,000.326", numberFormat.format(1000000.3255));
assertEquals("8,897,555.00", currformat.format(8897555.0009));
NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.CHINA);
assertEquals("26%", percentFormat.format(0.2569));
}
@Test
public void decimalFormat() {
DecimalFormat df = new DecimalFormat("#0.00");
assertEquals("0.00", df.format(0));
assertEquals("2.00", df.format(2));
assertEquals("12.33", df.format(12.333));
assertEquals("5555.32", df.format(5555.3232));
assertEquals("-5555.32", df.format(-5555.3232));
}
@Test
public void dateFormat() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse("2015-01-33 12:33:11");
assertEquals("2015-02-02 12:33:11", sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
@Test
@Ignore
public void accuracy() throws ParseException {
System.out.println(": ");
System.out.println(4.14 * 100.0);
System.out.println(1.00 - 0.42);
System.out.println(0.05 + 0.01);
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.parse(df.format(4.025)));
BigDecimal bd = new BigDecimal(4.065);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
@Test
public void StringFormat() {
long a = 55555555555888L;
System.out.println(a / 100.0);
System.out.println(String.format("%.2f", a / 100.0));
System.out.println(String.format("%.2f", 0.0));
System.out.println(String.format("%.6f", -1000000000000.09 / 10000));
double[] darr = new double[]{0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.17};
double sum = 0.00;
for (int tt = 0 ; tt < 10004; ++tt) {
for (int i = 0; i < darr.length; ++i) {
sum += darr[i];
}
}
BigDecimal bd = new BigDecimal(sum);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(String.format("%.6f", sum));
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.format(sum));
}
} |
/* line 1, C:/Users/ionutr/PhpstormProjects/httpi--sf2-lexmar/src/Httpi/Maritime/Bundle/SiteBundle/Resources/public/css/modules/_layout.sass */
#wrapper {
width: 1200px;
margin: 0 auto; }
/* line 5, C:/Users/ionutr/PhpstormProjects/httpi--sf2-lexmar/src/Httpi/Maritime/Bundle/SiteBundle/Resources/public/css/modules/_layout.sass */
#wrapper #page {
width: 1200px;
height: 500px;
margin-top: 90px;
border: 3px solid #40444f; } |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>dpdgraph: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.2 / dpdgraph - 0.6.8</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
dpdgraph
<small>
0.6.8
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-01-04 10:12:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-04 10:12:16 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 1 Virtual package relying on perl
coq 8.5.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "yves.bertot@inria.fr"
license: "LGPL-2.1-only"
homepage: "https://github.com/karmaki/coq-dpdgraph"
build: [
["./configure"]
["echo" "%{jobs}%" "jobs for the linter"]
[make "-j%{jobs}%" "WARN_ERR="]
]
bug-reports: "https://github.com/karmaki/coq-dpdgraph/issues"
dev-repo: "git+https://github.com/karmaki/coq-dpdgraph.git"
install: [
[make "install" "BINDIR=%{bin}%"]
]
depends: [
"ocaml" {}
"coq" {>= "8.12" & < "8.13~"}
"ocamlgraph"
]
authors: [ "Anne Pacalet" "Yves Bertot"]
synopsis: "Compute dependencies between Coq objects (definitions, theorems) and produce graphs"
url {
src:
"https://github.com/Karmaki/coq-dpdgraph/releases/download/v0.6.8/coq-dpdgraph-0.6.8.tgz"
checksum: "sha256=<SHA256-like>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-dpdgraph.0.6.8 coq.8.5.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2).
The following dependencies couldn't be met:
- coq-dpdgraph -> coq >= 8.12 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dpdgraph.0.6.8</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> |
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifndef NH_FILESYSTEM_H
#define NH_FILESYSTEM_H
namespace filesystem {
enum class Mode {
text,
binary
};
class BaseFilesystem {
public:
virtual uint8_t* get_file_contents(const char* filename, Mode mode = Mode::binary, int* out_length = nullptr) = 0;
virtual void free_file_contents(uint8_t* contents) = 0;
};
extern BaseFilesystem* instance;
}
#endif |
#pragma once
#include <type_traits>
#include <stack>
#include <unordered_map>
#include "../Base/String.hpp"
#include "../Json/JsonDocument.hpp"
#include "Common.hpp"
#include "ArchiveStore.hpp"
namespace ln {
class Serializer; // LuminoEngine
#define <API key>(type, version) \
namespace ln { namespace detail { \
template<> struct <API key><type> \
{ \
static const int value = version; \
}; \
} }
#define <API key>(version) \
template<typename T> friend class ::ln::detail::<API key>; \
template<typename T> friend class ::ln::detail::<API key>; \
friend class ::ln::Archive; \
static const int <API key> = version;
#define <API key>(type, format) \
namespace ln { namespace detail { \
template<> struct <API key><type> \
{ \
static const <API key> value = format; \
}; \
} }
class Archive
{
public:
template<typename TBase>
struct BaseClass
{
TBase* basePtr;
BaseClass(TBase* ptr) : basePtr(ptr) {}
};
static const String ClassNameKey;
static const String ClassVersionKey;
static const String ClassBaseKey;
Serializer* m_serializer; // TODO:
Archive(ArchiveStore* store, ArchiveMode mode)
: Archive()
{
setup(store, mode);
}
~Archive()
{
}
bool isSaving() const { return m_mode == ArchiveMode::Save; }
bool isLoading() const { return m_mode == ArchiveMode::Load; }
int classVersion() const { return m_nodeInfoStack.back().classVersion; }
void setBasePath(const String& path) { m_basePath = path; }
const String& basePath() const { return m_basePath; }
template<typename T>
Archive& operator & (T && value)
{
process(std::forward<T>(value));
return *this;
}
// Entry point
template <class T>
void process(T && head)
{
//bool rootCalled = m_nodeInfoStack.empty();
switch (m_mode)
{
case ArchiveMode::Save:
//if (rootCalled) {
// pushNodeWrite<T>();
processSave(head);
//if (rootCalled) {
// popNodeWrite();
break;
case ArchiveMode::Load:
processLoad(head);
break;
default:
assert(0);
break;
}
}
void makeArrayTag(int* outSize);
void makeMapTag(int* outSize);
template<typename TKey, typename TValue>
void makeMapItem(const TKey& key, TValue& value)
{
if (isSaving()) {
process(makeNVP(key, value));
}
else {
}
}
template<typename TKey, typename TValue>
void makeMapItem(TKey& key, TValue& value)
{
if (isSaving()) {
}
else {
key = m_store->memberKey(m_nodeInfoStack.back().arrayIndex);
NameValuePair<TValue> nvp = makeNVP<TValue>(key, value);
processLoadNVP<TValue>(nvp);
m_nodeInfoStack.back().arrayIndex++; // container Array processLoad()
}
}
// nvp
void makeObjectTag(int* outSize)
{
if (isSaving())
{
moveState(NodeHeadState::Object);
}
else if (isLoading())
{
moveState(NodeHeadState::Object);
// store Container size
preReadValue();
if (outSize) *outSize = m_store-><API key>();
}
}
//template<class TKey, class TValue>
//void makeObjectMember(TKey& key, TValue& value)
// if (isSaving())
// else
// key = m_store->memberKey(m_nodeInfoStack.top().arrayIndex);
// processLoad(makeNVP(key, value));
/*
Note:
serialize()
*/
void makeStringTag(String* str)
{
if (isSaving()) {
moveState(NodeHeadState::PrimitiveValue);
process(*str);
}
else {
// process open
// current
//m_store->closeContainer();
//m_nodeInfoStack.back().containerOpend = false;
// Value process open container
moveState(NodeHeadState::PrimitiveValue);
process(*str);
}
}
// save, load null process
void makeSmartPtrTag(bool* outIsNull)
{
if (isSaving()) {
if ((*outIsNull)) {
processNull();
}
else {
moveState(NodeHeadState::WrapperObject);
}
}
else if (isLoading()) {
//moveState(NodeHeadState::Object);
tryOpenContainer();
*outIsNull = m_store-><API key>() == <API key>::Null;
moveState(NodeHeadState::WrapperObject);
//if ((*outIsNull)) {
// moveState(NodeHeadState::PrimitiveValue);
//else {
// moveState(NodeHeadState::WrapperObject);
}
}
void makeOptionalTag(bool* outHasValue)
{
if (isSaving()) {
if (!(*outHasValue)) {
processNull();
}
else {
moveState(NodeHeadState::WrapperObject);
}
}
else if (isLoading()) {
*outHasValue = m_store->getReadingValueType() != ArchiveNodeType::Null;
//tryOpenContainer();
//if (m_store-><API key>() == <API key>::Array/* &&
// m_nodeInfoStack.back().headState == NodeHeadState::Array*/)
if (!m_nodeInfoStack.empty() && m_nodeInfoStack.back().headState == NodeHeadState::Array)
{
m_store->moveToIndexedMember(m_nodeInfoStack.back().arrayIndex);
}
#if 0
if (m_nodeInfoStack.empty()) {
// write Ready
return true;
}
// stack.top 1
switch (m_nodeInfoStack.back().headState)
{
case NodeHeadState::Ready:
break;
case NodeHeadState::Object:
if (!m_nodeInfoStack.back().containerOpend) {
if (m_nodeInfoStack.size() >= 2 && m_nodeInfoStack[m_nodeInfoStack.size() - 2].headState == NodeHeadState::WrapperObject) {
// WrapperObject
}
else {
// setTagXXXX
m_store->readContainer();
// verify
if (LN_ENSURE(m_store->getContainerType() == <API key>::Object)) return false;
m_nodeInfoStack.back().containerOpend = true;
}
}
break;
case NodeHeadState::Array:
if (!m_nodeInfoStack.back().containerOpend) {
if (m_nodeInfoStack.size() >= 2 && m_nodeInfoStack[m_nodeInfoStack.size() - 2].headState == NodeHeadState::WrapperObject) {
// WrapperObject
}
else {
// setTagXXXX
m_store->readContainer();
// verify
if (LN_ENSURE(m_store->getContainerType() == <API key>::Array)) return false;
m_nodeInfoStack.back().containerOpend = true;
}
}
break;
case NodeHeadState::PrimitiveValue:
break;
case NodeHeadState::WrapperObject:
if (m_store->getReadingValueType() == ArchiveNodeType::Array || m_store->getReadingValueType() == ArchiveNodeType::Object) {
if (!m_nodeInfoStack.back().containerOpend) {
m_store->readContainer();
if (LN_ENSURE(m_store->getContainerType() == <API key>::Object || m_store->getContainerType() == <API key>::Array)) return false;
m_nodeInfoStack.back().containerOpend = true;
}
}
break;
default:
LN_UNREACHABLE();
return false;
}
#endif
return true;
}
// after pop value node. stack top refers to parent container.
void postReadValue()
{
//if (m_store-><API key>() == <API key>::Array)
if (!m_nodeInfoStack.empty() && m_nodeInfoStack.back().headState == NodeHeadState::Array)
{
m_nodeInfoStack.back().arrayIndex++;
}
//if (!m_nodeInfoStack.empty())
// m_nodeInfoStack.back().arrayIndex++;
// if (m_store->getContainerType() == <API key>::Array)
// m_store->setNextIndex(m_nodeInfoStack.back().arrayIndex);
}
template<typename TValue>
bool <API key>(TValue& outValue)
{
auto* nvp = static_cast<NameValuePair<TValue>*>(<API key>);
if (nvp &&
nvp->defaultValue)
{
outValue = *nvp->defaultValue;
return true;
}
return false;
}
void readValue(bool& outValue) { if (!m_store->readValue(&outValue)) { if (!<API key>(outValue)) onError(); return; } }
void readValue(int8_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<int8_t>(tmp); }
void readValue(int16_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<int16_t>(tmp); }
void readValue(int32_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<int32_t>(tmp); }
void readValue(int64_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<int64_t>(tmp); }
void readValue(uint8_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<uint8_t>(tmp); }
void readValue(uint16_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<uint16_t>(tmp); }
void readValue(uint32_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<uint32_t>(tmp); }
void readValue(uint64_t& outValue) { int64_t tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<uint64_t>(tmp); }
void readValue(float& outValue) { double tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<float>(tmp); }
void readValue(double& outValue) { double tmp; if (!m_store->readValue(&tmp)) { if (!<API key>(outValue)) onError(); return; } outValue = static_cast<double>(tmp); }
void readValue(String& outValue) { if (!m_store->readValue(&outValue)) { if (!<API key>(outValue)) onError(); return; } }
// serialize readValue()
template<
typename TValue,
typename std::enable_if<detail::<API key><TValue>::value, std::nullptr_t>::type = nullptr>
void readValue(TValue& outValue)
{
bool baseCall = (m_nodeInfoStack.empty()) ? false : m_nodeInfoStack.back().nextBaseCall;
preLoadSerialize();
// TValue ValueType serialize serialize push
if (!m_nodeInfoStack.empty() && m_nodeInfoStack.back().headState == NodeHeadState::WrapperObject && m_nodeInfoStack.back().containerOpend) {
m_current.<API key> = true;
}
m_nodeInfoStack.push_back(m_current);
m_current = NodeInfo{}; // Ready
if (baseCall)
outValue.TValue::serialize(*this);
else
outValue.serialize(*this);
postLoadSerialize();
}
// serialize readValue()
template<
typename TValue,
typename std::enable_if<detail::<API key><TValue>::value, std::nullptr_t>::type = nullptr>
void readValue(TValue& outValue)
{
preLoadSerialize();
// TValue ValueType serialize serialize push
if (!m_nodeInfoStack.empty() && m_nodeInfoStack.back().headState == NodeHeadState::WrapperObject && m_nodeInfoStack.back().containerOpend) {
m_current.<API key> = true;
}
m_nodeInfoStack.push_back(m_current);
m_current = NodeInfo{};
serialize(*this, outValue);
postLoadSerialize();
}
bool preLoadSerialize()
{
//NodeHeadState parentState = NodeHeadState::Ready;
//if (!m_nodeInfoStack.empty()) {
// parentState = m_nodeInfoStack.back().headState;
/*
<API key> type = m_store-><API key>();
NodeInfo node;
node.<API key> = type;
m_nodeInfoStack.push_back(node);*/
/if (type == ArchiveNodeType::Array || type == ArchiveNodeType::Object) {
//if (parentState == NodeHeadState::WrapperObject) {
// // process open
//else {
// if (!m_nodeInfoStack.back().containerOpend) {
// if (!m_store->openContainer()) {
// return false;
// //if (LN_ENSURE(m_store->getContainerType() == <API key>::Object || m_store->getContainerType() == <API key>::Array)) return false;
// m_nodeInfoStack.back().containerOpend = true;
return true;
}
void postLoadSerialize()
{
//if (m_nodeInfoStack.top().headState == NodeHeadState::Ready)
// // serialized empty object. start container, has not been started.
// preReadValue();
// serialize state
// Object Object
if (m_nodeInfoStack.back().headState == NodeHeadState::Ready) {
moveState(NodeHeadState::Object);
}
// serialize makeArrayTag Tag process
//if (m_nodeInfoStack.back().headState == NodeHeadState::Object ||
// m_nodeInfoStack.back().headState == NodeHeadState::Array) {
// if (!m_nodeInfoStack.back().containerOpend) {
// preReadValue();
//bool taggedValueObject = (m_nodeInfoStack.top().headState == NodeHeadState::PrimitiveValue);
if (m_nodeInfoStack.back().containerOpend) {
m_store->closeContainer();
}
// top (State::Array m_current )
m_current = NodeInfo{};// m_nodeInfoStack.back();
m_nodeInfoStack.pop_back();
if (!m_nodeInfoStack.empty()) {
m_nodeInfoStack.back().nextBaseCall = false;
}
}
//bool <API key>()
// moveState(NodeHeadState::Object);
// NodeHeadState parentState = NodeHeadState::Ready;
// if (m_nodeInfoStack.size() >= 2) {
// parentState = m_nodeInfoStack.back().headState;
// //if (type == ArchiveNodeType::Array || type == ArchiveNodeType::Object) {
// if (parentState == NodeHeadState::WrapperObject) {
// // process open
// else if (m_nodeInfoStack.back().headState == NodeHeadState::PrimitiveValue) {
// else {
// if (!m_nodeInfoStack.back().containerOpend) {
// if (!m_store->openContainer()) {
// return false;
// //if (LN_ENSURE(m_store->getContainerType() == <API key>::Object || m_store->getContainerType() == <API key>::Array)) return false;
// m_nodeInfoStack.back().containerOpend = true;
// return true;
bool tryOpenContainer()
{
//NodeHeadState parentState = NodeHeadState::Ready;
/if (m_nodeInfoStack.size() >= 2) {
//if (m_nodeInfoStack.empty()) {
// parentState = m_nodeInfoStack.back().headState;
//if (type == ArchiveNodeType::Array || type == ArchiveNodeType::Object) {
//if (parentState == NodeHeadState::WrapperObject) {
// // process open
//else
if (m_nodeInfoStack.back().headState == NodeHeadState::PrimitiveValue ||
m_nodeInfoStack.back().headState == NodeHeadState::WrapperObject ||
m_nodeInfoStack.back().<API key>) {
}
else {
//m_nodeInfoStack.push_back(NodeInfo{});
if (!m_nodeInfoStack.back().containerOpend) {
if (!m_store->openContainer()) {
return false;
}
//if (LN_ENSURE(m_store->getContainerType() == <API key>::Object || m_store->getContainerType() == <API key>::Array)) return false;
m_nodeInfoStack.back().containerOpend = true;
}
}
return true;
}
void readClassVersion()
{
m_store->setNextName(ClassVersionKey);
int64_t version;
if (m_store->readValue(&version)) {
m_nodeInfoStack.back().classVersion = static_cast<int>(version);
}
}
const String& readTypeInfo();
void onError(const char* message = nullptr)
{
LN_NOTIMPLEMENTED();
}
ArchiveStore* m_store;
ArchiveMode m_mode;
std::vector<NodeInfo> m_nodeInfoStack; // (Load) m_store serialize
NodeInfo m_current; // (Load) Value serialize current m_nodeInfoStack Node current
int64_t m_archiveVersion;
detail::NameValuePairBase* <API key> = nullptr;
String m_basePath;
};
class <API key>
: public Archive
{
public:
<API key>();
virtual ~<API key>();
template<typename TValue>
void save(TValue && value)
{
if (LN_REQUIRE(!m_processing)) return;
m_processing = true;
Archive::process(std::forward<TValue>(value));
m_processing = false;
}
String toString(JsonFormatting formatting = JsonFormatting::Indented);
private:
JsonDocument m_localDoc;
JsonArchiveStore m_localStore;
bool m_processing;
};
class <API key>
: public Archive
{
public:
<API key>(const String& jsonText);
virtual ~<API key>();
template<typename TValue>
void load(TValue && value)
{
if (LN_REQUIRE(!m_processing)) return;
m_processing = true;
Archive::process(std::forward<TValue>(value));
m_processing = false;
}
private:
JsonDocument m_localDoc;
JsonArchiveStore m_localStore;
bool m_processing;
};
/**
* JSON /
*/
class JsonSerializer
{
public:
/**
* JSON
* @param[in] value :
* @param[in] formatting : JSON
* @return JSON
*/
template<typename TValue>
static String serialize(TValue&& value, JsonFormatting formatting = JsonFormatting::Indented)
{
<API key> ar;
ar.save(std::forward<TValue>(value));
return ar.toString(formatting);
}
template<typename TValue>
static String serialize(TValue&& value, const String& basePath, JsonFormatting formatting = JsonFormatting::Indented)
{
<API key> ar;
ar.setBasePath(basePath);
ar.save(std::forward<TValue>(value));
return ar.toString(formatting);
}
/**
* JSON
* @param[in] jsonText : JSON
* @param[in] value :
*/
template<typename TValue>
static void deserialize(const StringRef& jsonText, TValue& value)
{
<API key> ar(jsonText);
ar.load(value);
}
template<typename TValue>
static void deserialize(const StringRef& jsonText, const String& basePath, TValue& value)
{
<API key> ar(jsonText);
ar.setBasePath(basePath);
ar.load(value);
}
};
} // namespace ln
#include "SerializeTypes.inl" |
class Strom : Entita
{
public Strom(Pozice p, char znak) : base(p, znak, TypEntity.Strom)
{
// strom nic nedela
}
} |
#ifndef BSCCOIN_LEVELDB_H
#define BSCCOIN_LEVELDB_H
#include "serialize.h"
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <boost/filesystem/path.hpp>
class leveldb_error : public std::runtime_error
{
public:
leveldb_error(const std::string &msg) : std::runtime_error(msg) {}
};
void HandleError(const leveldb::Status &status) throw(leveldb_error);
// Batch of changes queued to be written to a CLevelDB
class CLevelDBBatch
{
friend class CLevelDB;
private:
leveldb::WriteBatch batch;
public:
template<typename K, typename V> void Write(const K& key, const V& value) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(ssKey.GetSerializeSize(key));
ssKey << key;
leveldb::Slice slKey(&ssKey[0], ssKey.size());
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(ssValue.GetSerializeSize(value));
ssValue << value;
leveldb::Slice slValue(&ssValue[0], ssValue.size());
batch.Put(slKey, slValue);
}
template<typename K> void Erase(const K& key) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(ssKey.GetSerializeSize(key));
ssKey << key;
leveldb::Slice slKey(&ssKey[0], ssKey.size());
batch.Delete(slKey);
}
};
class CLevelDB
{
private:
// custom environment this database is using (may be NULL in case of default environment)
leveldb::Env *penv;
// database options used
leveldb::Options options;
// options used when reading from the database
leveldb::ReadOptions readoptions;
// options used when iterating over values of the database
leveldb::ReadOptions iteroptions;
// options used when writing to the database
leveldb::WriteOptions writeoptions;
// options used when sync writing to the database
leveldb::WriteOptions syncoptions;
// the database itself
leveldb::DB *pdb;
public:
CLevelDB(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory = false, bool fWipe = false);
~CLevelDB();
template<typename K, typename V> bool Read(const K& key, V& value) throw(leveldb_error) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(ssKey.GetSerializeSize(key));
ssKey << key;
leveldb::Slice slKey(&ssKey[0], ssKey.size());
std::string strValue;
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
if (!status.ok()) {
if (status.IsNotFound())
return false;
printf("LevelDB read failure: %s\n", status.ToString().c_str());
HandleError(status);
}
try {
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
ssValue >> value;
} catch(std::exception &e) {
return false;
}
return true;
}
template<typename K, typename V> bool Write(const K& key, const V& value, bool fSync = false) throw(leveldb_error) {
CLevelDBBatch batch;
batch.Write(key, value);
return WriteBatch(batch, fSync);
}
template<typename K> bool Exists(const K& key) throw(leveldb_error) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(ssKey.GetSerializeSize(key));
ssKey << key;
leveldb::Slice slKey(&ssKey[0], ssKey.size());
std::string strValue;
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
if (!status.ok()) {
if (status.IsNotFound())
return false;
printf("LevelDB read failure: %s\n", status.ToString().c_str());
HandleError(status);
}
return true;
}
template<typename K> bool Erase(const K& key, bool fSync = false) throw(leveldb_error) {
CLevelDBBatch batch;
batch.Erase(key);
return WriteBatch(batch, fSync);
}
bool WriteBatch(CLevelDBBatch &batch, bool fSync = false) throw(leveldb_error);
// not available for LevelDB; provide for compatibility with BDB
bool Flush() {
return true;
}
bool Sync() throw(leveldb_error) {
CLevelDBBatch batch;
return WriteBatch(batch, true);
}
// not exactly clean encapsulation, but it's easiest for now
leveldb::Iterator *NewIterator() {
return pdb->NewIterator(iteroptions);
}
};
#endif // BSCCOIN_LEVELDB_H |
package iso20022
// Choice of format for the statement type.
type <API key> struct {
// Statement type expressed as an ISO 20022 code.
Code *<API key> `xml:"Cd"`
Proprietary *<API key> `xml:"Prtry"`
}
func (s *<API key>) SetCode(value string) {
s.Code = (*<API key>)(&value)
}
func (s *<API key>) AddProprietary() *<API key> {
s.Proprietary = new(<API key>)
return s.Proprietary
} |
-- Put functions in this file to use them in several other scripts.
-- To get access to the functions, you need to put:
-- require "my_directory.my_file"
-- in any script using the functions.
Returns true if the location defined by point is
inside the rectangle defined by the position and size values
function inside(point, position, size, origin)
if origin then
position.x = position.x - (size.x * origin.x)
position.y = position.y - (size.y * origin.y)
end
if point.x > position.x and point.x < position.x + size.x and
point.y > position.y and point.y < position.y + size.y then
return true
end
return false
end |
<?php
namespace IgraalOSL\StatsTable;
use IgraalOSL\StatsTable\Aggregation\<API key>;
use IgraalOSL\StatsTable\Aggregation\StaticAggregation;
use IgraalOSL\StatsTable\Dumper\Format;
use IgraalOSL\StatsTable\DynamicColumn\<API key>;
class StatsTableBuilder
{
/** @var StatsColumnBuilder[] The raw values passed to setTable, associative array */
private $columns;
/** @var mixed[] The lines indexes */
private $indexes;
/**
* @param $table
* @param array $headers
* @param array $formats
* @param array $aggregations
* @param array $columnNames
* @param array $defaultValues
* @param null $indexes
* @param array $metaData
* @throws \<API key>
*/
public function __construct($table, $headers = [], $formats = [], $aggregations = [], $columnNames = [], array $defaultValues = [], $indexes = null, $metaData = [])
{
$this->columns = [];
if (null !== $indexes) {
$this->indexes = $indexes;
} else {
$this->indexes = array_keys($table);
}
$this->defaultValues = $defaultValues;
// Append the values
$this->appendTable($table, $headers, $formats, $aggregations, $columnNames, $defaultValues, $metaData);
}
/**
* Retrieve existing indexes
* @return array
*/
public function getIndexes()
{
return $this->indexes;
}
/**
* Add index of data as a new column
*
* @param $columnName
* @param null $headerName
* @param null $format
* @param <API key> $aggregation
*/
public function addIndexesAsColumn($columnName, $headerName = null, $format = null, <API key> $aggregation = null, $metaData = [])
{
$values = [];
foreach ($this->indexes as $index) {
$values[$index] = $index;
}
$column = new StatsColumnBuilder(
$values,
$headerName,
$format,
$aggregation,
$metaData
);
$columns = array_reverse($this->columns);
$columns[$columnName] = $column;
$this->columns = $columns;
}
/**
* Append columns given a table
*
* @param array $table
* @param string[] $headers
* @param string[] $formats
* @param <API key>[] $aggregations
* @param string[] $columnNames
* @param mixed[] $defaultValues
*/
public function appendTable(
$table,
$headers,
$formats,
$aggregations,
$columnNames = [],
$defaultValues = [],
$metaData = []
) {
$this->defaultValues = array_merge($this->defaultValues, $defaultValues);
if (count($columnNames) === 0 && count($table) !== 0) {
$columnNames = array_keys(reset($table));
}
if (count($columnNames) === 0 && count($headers) !== 0) {
$columnNames = array_keys($headers);
}
foreach ($columnNames as $columnName) {
$column = new StatsColumnBuilder(
$this->getAssocColumn($table, $columnName),
$this->getParameter($headers, $columnName, $columnName),
$this->getParameter($formats, $columnName),
$this->getParameter($aggregations, $columnName),
$this->getParameter($metaData, $columnName, [])
);
if (count($this->defaultValues)) {
$column->insureIsFilled($this->indexes, $this->defaultValues[$columnName]);
}
$this->columns[$columnName] = $column;
}
}
/**
* Get an indexed value in a table. Same as ParameterBag
* @param array $values
* @param mixed $key
* @param mixed $defaultValue
* @return mixed
*/
private function getParameter($values, $key, $defaultValue = null)
{
return array_key_exists($key, $values) ? $values[$key] : $defaultValue;
}
/**
* Returns an associative table only with selected column.
* Fill with default value if column not in a row
* @param array $table
* @param string $columnName
* @param mixed $defaultValue
* @return array The column
*/
public function getAssocColumn($table, $columnName, $defaultValue = null)
{
$values = [];
foreach ($table as $key => $line) {
if (array_key_exists($columnName, $line)) {
$values[$key] = $line[$columnName];
} else {
$values[$key] = $defaultValue;
}
}
return $values;
}
/**
* Retrieve a column
* @return StatsColumnBuilder
* @throws \<API key>
*/
public function getColumn($columnName)
{
if (!array_key_exists($columnName, $this->columns)) {
throw new \<API key>('Unable to find column '.$columnName.' in columns '.join(',', array_keys($this->columns)));
}
return $this->columns[$columnName];
}
/**
* Get registered column names
*
* @return string[]
*/
public function getColumnNames()
{
return array_keys($this->columns);
}
/**
* Add a dynamic column
* @param mixed $columnName
* @param <API key> $dynamicColumn
* @param string $header
* @param string $format
* @param <API key> $aggregation
*/
public function addDynamicColumn($columnName, <API key> $dynamicColumn, $header = '', $format = null, <API key> $aggregation = null, $metaData = [])
{
$values = $dynamicColumn->buildColumnValues($this);
$this->columns[$columnName] = new StatsColumnBuilder($values, $header, $format, $aggregation, $metaData);
}
/**
* Add a column
* @param mixed $columnName
* @param array $values
* @param string $header
* @param string $format
* @param <API key> $aggregation
*/
public function addColumn($columnName, array $values, $header = '', $format = null, <API key> $aggregation = null, $metaData = [])
{
$this->columns[$columnName] = new StatsColumnBuilder($values, $header, $format, $aggregation, $metaData);
}
/**
* Build the data
* @param array $columns Desired columns
* @return StatsTable
*/
public function build($columns = [])
{
$headers = [];
$data = [];
$dataFormats = [];
$aggregations = [];
$aggregationsFormats = [];
$metaData = [];
foreach ($this->indexes as $index) {
$columnsNames = array_keys($this->columns);
$line = [];
foreach ($columnsNames as $columnName) {
$columnValues = $this->columns[$columnName]->getValues();
$line = array_merge($line, [$columnName => $columnValues[$index]]);
}
$data[$index] = $this->orderColumns($line, $columns);
}
foreach ($this->columns as $columnName => $column) {
$dataFormats[$columnName] = $column->getFormat();
$headers = array_merge($headers, [$columnName => $column->getHeaderName()]);
$metaData = array_merge($metaData, [$columnName => $column->getMetaData()]);
$columnAggregation = $column->getAggregation();
if ($columnAggregation) {
$aggregationValue = $columnAggregation->aggregate($this);
$aggregationsFormats[$columnName] = $columnAggregation->getFormat();
} else {
$aggregationValue = null;
}
$aggregations = array_merge($aggregations, [$columnName => $aggregationValue]);
}
$headers = $this->orderColumns($headers, $columns);
$metaData = $this->orderColumns($metaData, $columns);
$aggregations = $this->orderColumns($aggregations, $columns);
return new StatsTable($data, $headers, $aggregations, $dataFormats, $aggregationsFormats, $metaData);
}
/**
* Order table columns given columns table
* @param array $table
* @param array $columns
* @return array
*/
public static function orderColumns($table, $columns)
{
// If no columns given, return table as-is
if (!$columns) {
return $table;
}
// Order
$result = [];
foreach ($columns as $column) {
if (array_key_exists($column, $table)) {
$result[$column] = $table[$column];
}
}
return $result;
}
/**
* @return StatsColumnBuilder[]
*/
public function getColumns()
{
return $this->columns;
}
/**
* Do a groupBy on columns, using aggregations to aggregate data per line
*
* @param string|array $columns Columns to aggregate
* @param array $excludeColumns Irrelevant columns to exclude
*
* @return StatsTableBuilder
*/
public function groupBy($columns, array $excludeColumns = [])
{
$groupedData = [];
$statsTable = $this->build();
foreach ($statsTable->getData() as $line) {
$key = join(
'-_
array_map(
function ($c) use ($line) {
return $line[$c];
},
$columns
)
);
$groupedData[$key][] = $line;
}
$filterLine = function ($line) use ($excludeColumns) {
foreach ($excludeColumns as $c) {
unset($line[$c]);
}
return $line;
};
$headers = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getHeaderName();
},
$this->columns
)
);
$formats = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getFormat();
},
$this->columns
)
);
$aggregations = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getAggregation();
},
$this->columns
)
);
$metaData = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getMetaData();
},
$this->columns
)
);
$data = [];
foreach ($groupedData as $lines) {
$tmpAggregations = $aggregations;
// Add static aggragation for group by fields
foreach ($columns as $column) {
$oneLine = current($lines);
$value = $oneLine[$column];
$tmpAggregations[$column] = new StaticAggregation($value, Format::STRING);
}
$tmpTableBuilder = new StatsTableBuilder(
array_map($filterLine, $lines),
$headers,
$formats,
$tmpAggregations,
[],
[],
null,
$metaData
);
$tmpTable = $tmpTableBuilder->build();
$data[] = $tmpTable->getAggregations();
}
return new StatsTableBuilder(
$data,
$headers,
$formats,
$aggregations,
[],
[],
null,
$metaData
);
}
} |
println("Edad de la persona adscrita a jubilarse")
val Edad=readInt()
println("Antiguedad en su empleo de la persona adscrita a jubilarse")
val Antiguedad=readInt()
if (Edad>= 60 && Antiguedad < 25){
println("El adscrito se jubilara por edad")
}
else if(Edad < 60 && Antiguedad >= 25){
println("El adscrito se jubilara por antiguedad joven ")
}
else if (Edad>= 60 && Antiguedad >= 25) {
println("usted se jubilara por antiguedad adulta")
} |
<?php
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class <API key> extends AbstractTag
{
protected $Id = '0018,9301';
protected $Name = '<API key>';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'CT Acquisition Type Sequence';
} |
(function () {
'use strict';
angular
.module('porttare.config')
.config(function () {
moment.locale('es');
});
})(); |
<?php
namespace SitemapGenerator\Tests\Provider;
use SitemapGenerator\Entity\Url;
use SitemapGenerator\Tests\Fixtures\News;
abstract class <API key> extends \<API key>
{
protected function getRouter(array $results)
{
$router = $this->getMock('\SitemapGenerator\UrlGenerator');
$valueMap = array_map(function(News $news) {
return [
'show_news', ['id' => $news->slug], '/news/' . $news->slug
];
}, $results);
$router
->expects($this->any())
->method('generate')
->will($this->returnValueMap($valueMap));
return $router;
}
public function newsDataProvider()
{
$first = new News();
$first->slug = 'first';
$second = new News();
$second->slug = 'second';
$urlFirst = new Url('/news/first');
$urlSecond = new Url('/news/second');
return [
[[], []],
[[$first, $second], [$urlFirst, $urlSecond]],
];
}
} |
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
header = require('gulp-header'),
uglify = require('gulp-uglify'),
plumber = require('gulp-plumber'),
clean = require('gulp-clean'),
rename = require('gulp-rename'),
package = require('./package.json');
var paths = {
output : 'dist/',
scripts : [
'src/angular-component.js'
],
test: [
'test/spec*.js'
]
};
var banner = [
'\n'
].join('');
gulp.task('scripts', ['clean'], function() {
return gulp.src(paths.scripts)
.pipe(plumber())
.pipe(header(banner, { package : package }))
.pipe(gulp.dest('dist/'))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(header(banner, { package : package }))
.pipe(gulp.dest('dist/'));
});
gulp.task('lint', function () {
return gulp.src(paths.scripts)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('clean', function () {
return gulp.src(paths.output, { read: false })
.pipe(plumber())
.pipe(clean());
});
gulp.task('default', [
'lint',
'clean',
'scripts'
]); |
#include "../Common.h"
#ifndef <API key>
#define <API key>
class EXPORT Mutex {
public:
//friend class Condition;
/** Initializes a mutex class, with <API key> / pthread_mutex_init
*/
Mutex();
/** Deletes the associated critical section / mutex
*/
virtual ~Mutex();
/** Attempts to acquire this mutex. If it cannot be acquired (held by another thread)
* it will return false.
* @return false if cannot be acquired, true if it was acquired.
*/
bool AttemptAcquire();
/** Acquires this mutex. If it cannot be acquired immediately, it will block.
*/
void Acquire();
/** Releases this mutex. No error checking performed
*/
void Release();
protected:
#ifdef WIN32
/** Critical section used for system calls
*/
CRITICAL_SECTION cs;
#else
/** Static mutex attribute
*/
static bool attr_initalized;
static pthread_mutexattr_t attr;
/** pthread struct used in system calls
*/
pthread_mutex_t mutex;
#endif
};
#ifdef WIN32
class EXPORT FastMutex
{
#pragma pack(push,8)
volatile long m_lock;
#pragma pack(pop)
DWORD m_recursiveCount;
public:
FastMutex() : m_lock(0), m_recursiveCount(0) {}
~FastMutex() {}
bool AttemptAcquire();
void Acquire();
void Release();
};
#else
#define FastMutex Mutex
#endif
#endif |
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="canvas" height="200" width="200"></canvas>
<input type="text" id="sentence" value="" placeholder="your text here" />
<script>
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
// var textval =String.fromCharCode(event.keyCode || event.charCode);
document.onkeydown= draw;
var mytext = document.getElementById('sentence') // .style.visibility='hidden';//onkeyup = draw;//style.visibility='hidden';
mytext.onkeyup = draw;
//mytext.focus();
var x = document.createElement("TEXTAREA");
x.id="MyTextArea";
x.value= "mypapa";
var y = document.createElement("INPUT");
y.Id = "MyTextBox";
x.value="dig";
var z = document.getElementById("MyTextBox");
alert(z);
document.getElementById("MyTextArea").value = "Fifth Avenue, New York City";
document.body.appendChild(x);
// y.appendChild(t);
document.body.appendChild(y);
ctx.textAlign = "center"; // required for centered text in demo
//var textval = String.fromCharCode(e.keyCode || e.charCode) ;
function draw(e) {
// var textval = String.fromCharCode(e.keyCode || e.charCode) ;
var textval = mytext.value;
// alert(textval);
var lines = fragmentText(textval , canvas.width * 0.9),
font_size = 12;
ctx.font = "Normal " + font_size + "px Arial";
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
lines.forEach(function(line, i) {
ctx.fillText(line,canvas.width/2 , (i + 1) * font_size);
});
ctx.restore();
}
function fragmentText(text, maxWidth) {
// alert(text.keycode);
var words = text.split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (words.length > 1) {
words[1] = tmp.slice(-1) + words[1];
} else {
words.push(tmp.slice(-1));
}
}
if (ctx.measureText(line + words[0]).width < maxWidth) {
line += words.shift() + " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}
</script>
</body>
</html> |
// <API key>.h
// ToDoApp
#import <Foundation/Foundation.h>
@class <API key>;
@interface <API key> : NSObject
+ (<API key> *)loadToDoData;
+ (void)saveToDoData:(<API key> *)<API key>;
@end |
#!/usr/bin/env python
import jinja2
import os
import re
import shlex
import sys
import mkdocs.build
from mkdocs.build import build
from mkdocs.config import load_config
from urllib2 import urlopen
import subprocess
def line_containing(lines, text):
for i in range(len(lines)):
if text.lower() in lines[i].lower():
return i
raise Exception("could not find {}".format(text))
# Wrap some functions to allow custom commands in markdown
<API key> = mkdocs.build.convert_markdown
def <API key>(source, **kwargs):
def expand(match):
args = shlex.split(match.groups()[0])
# Import external markdown
if args[0] == ".import":
code = ""
try: #Try as a URL
code = urlopen(args[1]).read()
except ValueError: # invalid URL, try as a file
code = open(args[1]).read()
return code
# Run a shell command
elif args[0] == ".run":
result = ""
command = "$ " + match.groups()[0].replace(".run", "").strip()
try:
result = subprocess.check_output(args[1:], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError, e:
result = e.output
return "```\n" + command + "\n" + result.strip() + "\n```"
# Source code embeds
elif args[0] == ".code" or args[0] == ".doc":
code = ""
try: #Try as a URL
code = urlopen(args[1]).read()
except ValueError: # invalid URL, try as a file
code = open("../" + args[1]).read()
lines = code.splitlines()
# Short hand for specifying a region
if len(args) == 3:
region = args[2]
args[2] = "START " + region
args.append("END " + region)
if len(args) == 4:
start = 1
end = len(lines) - 1
try:
if args[2].isdigit(): start = int(args[2])
else:
start = line_containing(lines, args[2]) + 1
if args[3].isdigit(): end = int(args[3])
else: end = line_containing(lines, args[3]) + 1
except Exception, e: # If line_containing fails
print "Error: {}".format(e)
print " in {}".format(args[1])
sys.exit(1)
#TODO: Also allow regex matching
lines = lines[start - 1:end]
# Trim "OMIT" lines. Ignore "*/".
lines = filter(lambda x: not x.strip().rstrip("*/").rstrip().lower().endswith("omit"), lines)
# TODO: Trim leading and trailing empty lines
if args[0] == ".code":
lines.insert(0, "```go")
lines.append("```")
# else: # args[0] == ".doc"
# lines.insert(0, "\n")
# lines.insert("\n")
return "\n".join(lines)
# No matching logic
else:
return match.group(0)
# Process an aritrary number of expansions.
oldSource = ""
while source != oldSource:
oldSource = source
source = re.sub("\[\[(.*)\]\]", expand, oldSource)
return <API key>(source)
# Hotpatch in the markdown conversion wrapper
mkdocs.build.convert_markdown = <API key>
if __name__ == "__main__":
# Build documentation
config = load_config(options=None)
build(config)
# Load templates
template_env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'theme')))
index_template = template_env.get_template('home.html')
community_template = template_env.get_template('community.html')
# Home page
with open('site/index.html', 'w') as f:
f.write(index_template.render(
page="home"
))
# Community page
with open('site/community.html', 'w') as f:
f.write(community_template.render(
page="community"
)) |
#!/usr/bin/python3
# Small script to validate a given IP address
import socket
import sys
def validate_ip(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
return (True,"IPv4")
except socket.error:
try:
socket.inet_pton(socket.AF_INET6, ip)
return(True,"IPv6")
except socket.error:
return(False,"")
if __name__ == "__main__":
try:
ip = sys.argv[1]
state, version = validate_ip(ip)
if state:
print(ip + " is a valid " + version + " address")
except IndexError:
print("No IP given") |
module Pvcglue
class Packages
class MaintenanceMode < Pvcglue::Packages
def installed?
false
end
def install!
if options[:maintenance_mode] == 'on'
connection.run!(user_name, '', "touch #{Pvcglue.cloud.<API key>}")
elsif options[:maintenance_mode] == 'off'
result = connection.run?(user_name, '', "rm #{Pvcglue.cloud.<API key>}")
if result.exitstatus == 1
Pvcglue.logger.warn('Maintenance mode was already off.')
elsif result.exitstatus != 0
raise result.inspect
end
else
raise("Invalid maintenance_mode option: #{options[:maintenance_mode]}")
end
end
def post_install_check?
true
end
end
end
end |
 1
To use the PCMag Product and News Assistant skill, try saying...
* *Alexa, ask PCMag which printer should I buy.*
* *Alexa, ask PCMag what's the best cell phone*
* *Alexa, ask PCMag can you recommend a tablet for me.*
PCMag can recommend the best printer, scanner, camera, laptop, cell phone. Whatever type of product you're looking for, if it's in technology, PCMag can find a review.
***
Skill Details
* **Invocation Name:** p. c. mag
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.<API key>
* **ASIN:** B01DQ12PQ6
* **Author:** Ziff Davis, LLC
* **Release Date:** April 5, 2016 @ 14:32:29
* **Privacy Policy:** http:
* **Terms of Use:** http:
* **In-App Purchasing:** No |
/*
* CONTAINER
* TableTools container element and styles applying to all components
*/
div.DTTT_container {
position: relative;
float: right;
margin-bottom: 1em;
}
@media screen and (max-width: 640px) {
div.DTTT_container {
float: none !important;
text-align: center;
}
div.DTTT_container:after {
visibility: hidden;
display: block;
content: "";
clear: both;
height: 0;
}
}
button.DTTT_button,
div.DTTT_button,
a.DTTT_button {
position: relative;
cursor: pointer;
display: inline-block;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-<API key>: transparent;
vertical-align: middle;
z-index: 1;
will-change: opacity, transform;
-webkit-transition: all .3s ease-out;
-moz-transition: all .3s ease-out;
-o-transition: all .3s ease-out;
-ms-transition: all .3s ease-out;
transition: all .3s ease-out;
text-decoration: none;
color: #fff;
background-color: #5380BD;
text-align: center;
letter-spacing: .5px;
-webkit-transition: .2s ease-out;
-moz-transition: .2s ease-out;
-o-transition: .2s ease-out;
-ms-transition: .2s ease-out;
transition: .2s ease-out;
cursor: pointer;
border: none;
border-radius: 2px;
display: inline-block;
height: 36px;
line-height: 36px;
outline: 0;
padding: 0 2rem;
text-transform: uppercase;
vertical-align: middle;
-<API key>: transparent;
}
a.DTTT_button:hover{
box-shadow: 0 5px 11px 0 rgba(0, 0, 0, 0.18), 0 4px 15px 0 rgba(0, 0, 0, 0.15);
background-color: #5380BD;
}
/* Buttons are cunning border-box sizing - we can't just use that for A and DIV due to IE6/7 */
button.DTTT_button {
height: 30px;
padding: 3px 8px;
}
.DTTT_button embed {
outline: none;
}
button.DTTT_button:active:not(.DTTT_disabled),
div.DTTT_button:active:not(.DTTT_disabled),
a.DTTT_button:active:not(.DTTT_disabled) {
-webkit-box-shadow: inset 1px 1px 3px #999999;
-moz-box-shadow: inset 1px 1px 3px #999999;
box-shadow: inset 1px 1px 3px #999999;
}
button.DTTT_disabled,
div.DTTT_disabled,
a.DTTT_disabled {
color: #999 !important;
border: 1px solid #d0d0d0;
cursor: default;
background: #ffffff; /* Old browsers */
background: -<API key>(top, #ffffff 0%,#f9f9f9 89%,#fafafa 100%); /* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #ffffff 0%,#f9f9f9 89%,#fafafa 100%); /* FF3.6+ */
background: -ms-linear-gradient(top, #ffffff 0%,#f9f9f9 89%,#fafafa 100%); /* IE10+ */
background: -o-linear-gradient(top, #ffffff 0%,#f9f9f9 89%,#fafafa 100%); /* Opera 11.10+ */
background: linear-gradient(top, #ffffff 0%,#f9f9f9 89%,#fafafa 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#fafafa',GradientType=0 ); /* IE6-9 */
}
/*
* BUTTON_STYLES
* Action specific button styles
* If you want images - comment this back in
a.DTTT_button_csv,
a.DTTT_button_xls,
a.DTTT_button_copy,
a.DTTT_button_pdf,
a.DTTT_button_print {
padding-right: 0px;
}
a.DTTT_button_csv span,
a.DTTT_button_xls span,
a.DTTT_button_copy span,
a.DTTT_button_pdf span,
a.DTTT_button_print span {
display: inline-block;
height: 24px;
line-height: 24px;
padding-right: 30px;
}
a.DTTT_button_csv span { background: url(../images/csv.png) no-repeat bottom right; }
a.DTTT_button_csv:hover span { background: url(../images/csv_hover.png) no-repeat center right; }
a.DTTT_button_xls span { background: url(../images/xls.png) no-repeat center right; }
a.DTTT_button_xls:hover span { background: #f0f0f0 url(../images/xls_hover.png) no-repeat center right; }
a.DTTT_button_copy span { background: url(../images/copy.png) no-repeat center right; }
a.DTTT_button_copy:hover span { background: #f0f0f0 url(../images/copy_hover.png) no-repeat center right; }
a.DTTT_button_pdf span { background: url(../images/pdf.png) no-repeat center right; }
a.DTTT_button_pdf:hover span { background: #f0f0f0 url(../images/pdf_hover.png) no-repeat center right; }
a.DTTT_button_print span { background: url(../images/print.png) no-repeat center right; }
a.DTTT_button_print:hover span { background: #f0f0f0 url(../images/print_hover.png) no-repeat center right; }
*/
button.<API key> span {
padding-right: 17px;
background: url(../images/collection.png) no-repeat center right;
}
button.<API key>:hover span {
padding-right: 17px;
background: #f0f0f0 url(../images/collection_hover.png) no-repeat center right;
}
/*
* SELECTING
* Row selection styles
*/
table.DTTT_selectable tbody tr {
cursor: pointer;
*cursor: hand;
}
table.dataTable tr.DTTT_selected.odd {
background-color: #9FAFD1;
}
table.dataTable tr.DTTT_selected.odd td.sorting_1 {
background-color: #9FAFD1;
}
table.dataTable tr.DTTT_selected.odd td.sorting_2 {
background-color: #9FAFD1;
}
table.dataTable tr.DTTT_selected.odd td.sorting_3 {
background-color: #9FAFD1;
}
table.dataTable tr.DTTT_selected.even {
background-color: #B0BED9;
}
table.dataTable tr.DTTT_selected.even td.sorting_1 {
background-color: #B0BED9;
}
table.dataTable tr.DTTT_selected.even td.sorting_2 {
background-color: #B0BED9;
}
table.dataTable tr.DTTT_selected.even td.sorting_3 {
background-color: #B0BED9;
}
/*
* COLLECTIONS
* Drop down list (collection) styles
*/
div.DTTT_collection {
width: 150px;
padding: 8px 8px 4px 8px;
border: 1px solid #ccc;
border: 1px solid rgba( 0, 0, 0, 0.4 );
background-color: #f3f3f3;
background-color: rgba( 255, 255, 255, 0.3 );
overflow: hidden;
z-index: 2002;
-<API key>: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
-ms-box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
-o-box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
}
div.<API key> {
background: black;
z-index: 2001;
}
div.DTTT_collection button.DTTT_button,
div.DTTT_collection div.DTTT_button,
div.DTTT_collection a.DTTT_button {
position: relative;
left: 0;
right: 0;
display: block;
float: none;
margin-bottom: 4px;
-webkit-box-shadow: 1px 1px 3px #999;
-moz-box-shadow: 1px 1px 3px #999;
-ms-box-shadow: 1px 1px 3px #999;
-o-box-shadow: 1px 1px 3px #999;
box-shadow: 1px 1px 3px #999;
}
/*
* PRINTING
* Print display styles
*/
.DTTT_print_info {
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 150px;
margin-left: -200px;
margin-top: -75px;
text-align: center;
color: #333;
padding: 10px 30px;
background: #ffffff; /* Old browsers */
background: -<API key>(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* FF3.6+ */
background: -ms-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* IE10+ */
background: -o-linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* Opera 11.10+ */
background: linear-gradient(top, #ffffff 0%,#f3f3f3 89%,#f9f9f9 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#f9f9f9',GradientType=0 ); /* IE6-9 */
opacity: 0.95;
border: 1px solid black;
border: 1px solid rgba(0, 0, 0, 0.5);
-<API key>: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-ms-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
-o-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.5);
}
.DTTT_print_info h6 {
font-weight: normal;
font-size: 28px;
line-height: 28px;
margin: 1em;
}
.DTTT_print_info p {
font-size: 14px;
line-height: 20px;
}
#tbl-report_filter{
background: none;
border: none;
box-sizing: border-box;
color: #fff;
display: block;
font-size: 0.8em;
height: 36px;
padding-right: 10px;
position: absolute;
width: 92%;
}
#tbl-report_filter input{
background: none;
border: none;
box-sizing: border-box;
color: #fff;
display: block;
font-size: 1.2em;
height: 36px;
text-align: left;
padding-right: 10px;
position: absolute;
width: 100%;
} |
var meroboto = require('../lib');
var sensor = new meroboto.Sensor({
timeInterval: 1000,
fn: function() {
return Math.floor((Math.random() * 10) + 1);
}
});
var sensor_2 = new meroboto.Sensor({
timeInterval: 1000,
fn: function() {
return Math.floor((Math.random() * 20) + 1);
}
});
var action = new meroboto.Action({
fn: function(data) {
if (data > 5)
console.log('good ' + data);
else
console.log('bad ' + data);
}
});
var robot = new meroboto.Robot()
.combine('combine-1', new meroboto.Combine({
sensor: sensor,
action: action
}))
.combine('combine-2', new meroboto.Combine({
sensor: sensor_2,
action: action
})); |
// keepViewController.h
// postcardApp
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface keepViewController : UIViewController <UITextFieldDelegate, UITextViewDelegate, <API key>, <API key>, <API key>>
@property (weak, nonatomic) IBOutlet UIImageView *mainImageView;
@property (nonatomic, strong) UIImage *imageFromPhotoVC;
@property (weak, nonatomic) IBOutlet UITextField *locationTextField;
@property (weak, nonatomic) IBOutlet UITextView *messageTextView;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
- (IBAction)cancelButton:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
- (IBAction)sendButton:(id)sender;
@end |
"""cairo_museum.py"""
from lib.stage import Stage
class CairoMuseum(Stage):
"""Cairo Museum stage"""
def desc(self):
"""Describe action"""
action = """
After getting the first replicant, you call some old friends and some of them
mentions something about a hippie woman that likes no jokes. You get the next
ship to Cairo and go to a big museum. Everything smells dust and there are a
lot of camels and people around. In an isolated corner, you see a different
woman in bad mood, looking to you from time to time...
"""
self.console.simulate_typing(action)
def look(self):
"""Look action"""
action = """
Everyone seens to be busy looking at the art, mainly the big statues, nothing
suspicious, except for a different woman in the corner...
"""
self.console.simulate_typing(action)
def talk(self):
"""Talk action"""
action = """
You say 'hi' to the woman...
"""
self.console.simulate_typing(action)
def joke(self):
"""Joke action"""
action = """
You tell a really good joke and an old mummy start laughing...
"""
self.console.simulate_typing(action)
def fight(self):
"""Fight action"""
action = """
You try to start a fight, but a camel holds you and tells you to calm down...
"""
self.console.simulate_typing(action) |
$(document).ready(function(){
var struktur = {};
$(".submit").addClass("disableWindow");
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
$("#inputKalFra").val(today.toISOString().substring(0, 10));
$("#inputKalTil").val(tomorrow.toISOString().substring(0, 10));
$("#inputKalFra").prop("min", today);
$("#inputKalTil").prop("min", tomorrow);
struktur.fraReise = today.toISOString().substring(0, 10);
struktur.tilReise = tomorrow.toISOString().substring(0, 10);
sessionStorage.setItem("fraReise",struktur.fraReise);
sessionStorage.setItem("tilReise",struktur.tilReise);
$("#inputKalFra").on("input", function () {
struktur.fraReise = document.getElementById("inputKalFra").value;
var date1 = new Date(struktur.fraReise);
var date2 = new Date(struktur.tilReise);
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
if(diffDays < 0) {
console.log("hei");
$("#feilDato").text("Vennligst velg en dato etter reisedato!");
}
else if(diffDays < 3)
$("#feilDato").text("Reisen din er for kort!");
else
$("#feilDato").text("");
sessionStorage.setItem("fraReise",struktur.fraReise);
validerInfo();
});
$("#inputKalTil").on("input", function () {
struktur.tilReise = document.getElementById("inputKalTil").value;
var date1 = new Date(struktur.fraReise);
var date2 = new Date(struktur.tilReise);
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
if(diffDays < 0) {
console.log("hei");
$("#feilDato").text("Vennligst velg en dato etter reisedato!");
} else if(diffDays < 3)
$("#feilDato").text("Reisen din er for kort!");
else
$("#feilDato").text("");
sessionStorage.setItem("tilReise",struktur.tilReise);
validerInfo();
});
//Avslutt Input[type=date] endringer
//Lagre destinasjonsinput
struktur.dest = "";
$("#inputDest").change(function () {
struktur.dest = $(this).val();
console.log(struktur.dest);
validerInfo();
});
//Avslutt destinasjonsinput
//Vise/skjule endre-vinduer
$(".content-shower").hide();
$("#endreReisende").click(function () {
$("#<API key>").slideToggle();
$(".bestilling-wrapper").toggleClass("disableWindow");
});
$("#endreAndreBehov").click(function () {
$("#andre-behov-wrapper").slideToggle();
$(".bestilling-wrapper").toggleClass("disableWindow");
});
$("#endreOvernatting").click(function () {
$("#<API key>").slideToggle();
$(".bestilling-wrapper").toggleClass("disableWindow");
});
//Avslutt kode for vise/skjule endre-vinduer
struktur.voksen = 0;
struktur.barn = 0;
struktur.honnor = 0;
struktur.student = 0;
var liste = ["travellerSelector1", "travellerSelector2", "travellerSelector3",
"travellerSelector4", "travellerSelector5", "travellerSelector6",
"travellerSelector7", "travellerSelector8", "travellerSelector9"];
for (var i = 0; i < liste.length; i++) {
if (i != 0) {
$("#travellerSelector" + (i+1)).hide();
}
}
var antReisende = 1;
var <API key> = 1;
$("#amountOfPassengers:text").val(antReisende);
$("#amountPlus").click(function () {
if (antReisende < 9) {
antReisende++;
$("#travellerSelector" + (antReisende)).show();
$("#amountOfPassengers:text").val(antReisende);
}
});
$("#amountMinus").click(function () {
if (antReisende > 1) {
$("#travellerSelector" + antReisende).hide();
antReisende
$("#amountOfPassengers:text").val(antReisende);
}
});
$("#okReisende").click(function () {
<API key> = antReisende;
$("#<API key>").slideToggle();
$(".bestilling-wrapper").toggleClass("disableWindow");
if (antReisende == 1) {
$("#reisendeLabel").text("1 person");
} else {
$("#reisendeLabel").text(antReisende + " personer");
}
struktur.voksen = 0;
struktur.barn = 0;
struktur.honnor = 0;
struktur.student = 0;
for (var i = 0; i <= antReisende; i++) {
if ($("#travellerSelector" + (i)).val() == "Voksen") {
struktur.voksen++;
} else if ($("#travellerSelector" + i).val() == "Barn") {
struktur.barn++;
} else if ($("
struktur.honnor++;
} else if ($("#travellerSelector" + i).val() == "Student") {
struktur.student++;
}
}
sessionStorage.setItem("voksen", struktur.voksen);
sessionStorage.setItem("barn", struktur.barn);
sessionStorage.setItem("honnor", struktur.honnor);
sessionStorage.setItem("student", struktur.student);
validerInfo();
});
$("#avbrytReisende").click(function () {
antReisende = <API key>;
$("#<API key>").slideToggle("medium", function () {
for (var i = 0; i < liste.length; i++) {
if (i != 0) {
$("#travellerSelector" + i).hide();
}
}
for (var i = 0; i < antReisende; i++) {
$("#travellerSelector" + (i + 1)).show();
$("#amountOfPassengers:text").val(i + 1);
}
});
$(".bestilling-wrapper").toggleClass("disableWindow");
});
// Avslutt kode for antall reisende
//Kode for andre behov
$("#rullestolLabel").hide();
$("#kjaeledyrlLabel").hide();
var rChecked = false;
var kChecked = false;
struktur.rullestol = false;
struktur.kjaeledyr = false;
$("#okBehov").click(function () {
$("#andre-behov-wrapper").slideToggle();
if (document.getElementById("cbRullestol").checked) {
$("#rullestolLabel").show();
rChecked = true;
struktur.rullestol = true;
} else {
$("#rullestolLabel").hide();
rChecked = false;
struktur.rullestol = false;
}
if (document.getElementById("cbKjaeledyr").checked) {
$("#kjaeledyrlLabel").show();
kChecked = true;
struktur.kjaeledyr = true;
} else {
$("#kjaeledyrlLabel").hide();
kChecked = false;
struktur.kjaeledyr = false;
}
$(".bestilling-wrapper").toggleClass("disableWindow");
});
$("#avbrytBehov").click(function () {
$("#andre-behov-wrapper").slideToggle("medium", function () {
if (rChecked == 1) {
$("#cbRullestol").prop("checked", true);
} else {
$("#cbRullestol").prop("checked", false);
}
if (kChecked == 1) {
$("#cbKjaeledyr").prop("checked", true);
} else {
$("#cbKjaeledyr").prop("checked", false);
}
});
$(".bestilling-wrapper").toggleClass("disableWindow");
});
//Avslutt kode for andre behov
/*Overnatting, hyttebilder*/
$(".previousPicture, .nextPicture, .hytteAlbum, .velgHytte").hide();
var imageVariable = 4;
$(".previousPicture").click(function () {
if (imageVariable == 4) {
imageVariable = 6;
var element = document.getElementById("slider");
var imageUrl = 'js/Images/hytte' + imageVariable + '.jpg';
$(element).prop("src", imageUrl);
} else {
imageVariable
var element = document.getElementById("slider");
var imageUrl = 'js/Images/hytte' + imageVariable + '.jpg';
$(element).prop("src", imageUrl);
}
});
$(".nextPicture").click(function () {
if (imageVariable == 6) {
imageVariable = 3;
}
imageVariable++;
var element = document.getElementById("slider");
var imageUrl = 'js/Images/hytte' + imageVariable + '.jpg';
$(element).prop("src", imageUrl);
});
var currentCabin;
var valgtHytte = "";
var hyttePrisen = 0;
struktur.hytte = "";
struktur.hyttePris = 0;
$(".hyttelink").click(function () {
$(".previousPicture, .nextPicture, .hytteAlbum, .velgHytte, #hytteValgt").show();
console.log(this.id);
currentCabin = this.id;
var txt = "";
$.ajax({
type: "GET",
url: "hytter.xml",
dataType: "xml",
success: function (xml) {
txt += "<div id='hytteValgt'>";
$(xml).find(currentCabin).each(function () {
txt += "<h1>" + $(this).find("navn").text() +
"</h1><h3>" + $(this).find("bakkeplassering").text() + "</h3><div><p>" + $(this).find("info").text() +
"</p></div>";
hyttePrisen = parseInt($(this).find("pris").text());
});
txt += "</div>";
console.log(txt);
$(".hytteValgt").html(txt);
}
});
});
$("#avbrytOvernatting").click(function () {
$("#<API key>").slideToggle("medium", function () {
if (valgtHytte == "") {
$(".previousPicture, .nextPicture, .hytteAlbum, .velgHytte, #hytteValgt").hide();
} else if (currentCabin != valgtHytte) {
currentCabin = valgtHytte;
var txt = "";
$.ajax({
type: "GET",
url: "hytter.xml",
dataType: "xml",
success: function (xml) {
txt += "<div id='hytteValgt'>";
$(xml).find(valgtHytte).each(function () {
txt += "<h1>" + $(this).find("navn").text() +
"</h1><h3>" + $(this).find("bakkeplassering").text() + "</h3><div><p>" + $(this).find("info").text() +
"</p></div>";
});
txt += "</div>";
console.log(txt);
$(".hytteValgt").html(txt);
}
});
}
});
$(".bestilling-wrapper").toggleClass("disableWindow");
});
$("#velgHytteKnapp").click(function () {
valgtHytte = currentCabin;
$("#<API key>").slideToggle();
$(".bestilling-wrapper").toggleClass("disableWindow");
$("#overnattingLabel").text("Luksushytte - type " + valgtHytte.substring(5, 6));
struktur.hytte = "Luksushytte - type " + valgtHytte.substring(5, 6);
struktur.hyttePris = hyttePrisen;
sessionStorage.setItem("hytte",struktur.hytte);
sessionStorage.setItem("hyttePris",struktur.hyttePris);
validerInfo();
});
function validerInfo() {
if (struktur.fraReise == "" || struktur.tilReise == "" || struktur.dest == "default" ||
struktur.dest == "" || struktur.barn == 0 && struktur.honnor == 0 &&
struktur.student == 0 && struktur.voksen == 0 || struktur.hytte == "" ||
$("#feilDato").val() != "") {
$(".submit").addClass("disableWindow");
} else {
$(".submit").removeClass("disableWindow");
}
}
var sum = 0;
var faktor = 1;
var reisende = parseInt(sessionStorage.getItem("voksen")) + parseInt(sessionStorage.getItem("barn")) + parseInt(sessionStorage.getItem("honnor")) +
parseInt(sessionStorage.getItem("student"));
var reisendePris = parseInt(sessionStorage.getItem("voksen"))*500 + parseInt(sessionStorage.getItem("barn"))*300 + parseInt(sessionStorage.getItem("honnor")*350) +
parseInt(sessionStorage.getItem("student"))*340;
$("#reiseDatoLabel").text(sessionStorage.getItem("fraReise") + " til " + sessionStorage.getItem("tilReise"));
$("#kvitReise").text(reisende + " person(er):");
$("#kvitHytte").text(sessionStorage.getItem("hytte") + ": ");
$("#kvitReisePris").text(reisendePris + " kr");
$("#kvitHyttePris").text(sessionStorage.getItem("hyttePris") + " kr");
sum += reisendePris;
sum += parseInt(sessionStorage.getItem("hyttePris"));
$("#sumlabel").text(sum + " kr");
$("#medlem").change(function () {
if ($("#medlem").is(':checked')) {
$("#laken, #instruktor, #heiskort").addClass("disableWindow");
$("#sumlabel").text(Math.round(sum*0.8) + " kr");
} else {
$("#laken, #instruktor, #heiskort").removeClass("disableWindow");
$("#sumlabel").text(sum + " kr");
}
})
$("#laken").change(function () {
if ($("#laken").is(':checked')) {
$("#kvitLaken").text("Laken: ");
$("#kvitLakenPris").text("40,-");
sum += 40;
} else if (!$("#laken").is(':checked')) {
$("#kvitLaken").text("");
$("#kvitLakenPris").text("");
sum -= 40;
}
$("#sumlabel").text(sum + " kr");
});
$("#instruktor").change(function () {
if ($("#instruktor").is(':checked')) {
$("
$("#kvitInstruktorPris").text("500,-");
sum += 500;
} else if (!$("#instruktor").is(':checked')) {
$("#kvitInstruktor").text("");
$("#kvitInstruktorPris").text("");
sum -= 500;
}
$("#sumlabel").text(sum + " kr");
});
$("#heiskort").change(function () {
if ($("#heiskort").is(':checked')) {
$("#kvitHeiskort").text("Heiskort: ");
$("#kvitHeiskortPris").text("250,-");
sum += 250;
} else if (!$("#heiskort").is(':checked')) {
$("#kvitHeiskort").text("");
$("#kvitHeiskortPris").text("");
sum -= 250;
}
$("#sumlabel").text(sum + " kr");
});
// Destinasjoner
struktur.currentDestinasjon = "";
$(".dropdown-dest").click(function () {
struktur.currentDestinasjon = this.id;
sessionStorage.setItem("currentDest",struktur.currentDestinasjon);
});
//$(".dropdown-dest").click(function () {
var txt = "";
$.ajax({
type: "GET",
url: "destinasjoner.xml",
dataType: "xml",
success: function (xml) {
txt += "<div id='destinasjon'>";
$(xml).find(sessionStorage.getItem("currentDest")).each(function () {
txt += "<h1>" + $(this).find("navn").text() +
"</h1><div><p>" + $(this).find("info").text() +
"</p><img src='" + $(this).find("picture").text() + "' width='100%' height='auto'><iframe src='" + $(this).find("map").text() + "' width='600' height='450' allowfullscreen></iframe></div>";
hyttePrisen = parseInt($(this).find("pris").text());
});
txt += "</div>";
$("#destinasjon").html(txt);
}
});
}); |
import * as React from 'react';
import {SvgIconProps} from '../../SvgIcon';
export default function AccountBalance(props: SvgIconProps): React.ReactElement<SvgIconProps>; |
var DataTypes = require('../../../lib/db/dataTypes.js');
describe('DataTypes tests', function() {
it('get the enum name', function() {
var name = DataTypes.name(0);
name.should.be.equal('BOOLEAN');
name = DataTypes.name(1);
name.should.be.equal('TINYINT');
name = DataTypes.name(2);
name.should.be.equal('SMALLINT');
name = DataTypes.name(3);
name.should.be.equal('MEDIUMINT');
name = DataTypes.name(4);
name.should.be.equal('INT');
name = DataTypes.name(5);
name.should.be.equal('INTEGER');
name = DataTypes.name(6);
name.should.be.equal('FLOAT');
name = DataTypes.name(7);
name.should.be.equal('DOUBLE');
name = DataTypes.name(8);
name.should.be.equal('REAL');
name = DataTypes.name(9);
name.should.be.equal('TEXT');
name = DataTypes.name(10);
name.should.be.equal('BLOB');
name = DataTypes.name(11);
name.should.be.equal('DATE');
name = DataTypes.name(12);
name.should.be.equal('DATETIME');
name = DataTypes.name(13);
name.should.be.equal('GEOMETRY');
});
it('get the enum values', function() {
var name = DataTypes.fromName('BOOLEAN');
name.should.be.equal(0);
name = DataTypes.fromName('TINYINT');
name.should.be.equal(1);
name = DataTypes.fromName('SMALLINT');
name.should.be.equal(2);
name = DataTypes.fromName('MEDIUMINT');
name.should.be.equal(3);
name = DataTypes.fromName('INT');
name.should.be.equal(4);
name = DataTypes.fromName('INTEGER');
name.should.be.equal(5);
name = DataTypes.fromName('FLOAT');
name.should.be.equal(6);
name = DataTypes.fromName('DOUBLE');
name.should.be.equal(7);
name = DataTypes.fromName('REAL');
name.should.be.equal(8);
name = DataTypes.fromName('TEXT');
name.should.be.equal(9);
name = DataTypes.fromName('BLOB');
name.should.be.equal(10);
name = DataTypes.fromName('DATE');
name.should.be.equal(11);
name = DataTypes.fromName('DATETIME');
name.should.be.equal(12);
name = DataTypes.fromName('GEOMETRY');
name.should.be.equal(13);
});
}); |
<html><body>
<h4>Windows 10 x64 (18362.388)</h4><br>
<h2>_MSUBSECTION</h2>
<font face="arial"> +0x000 Core : <a href="./_SUBSECTION.html">_SUBSECTION</a><br>
+0x038 SubsectionNode : <a href="./_RTL_BALANCED_NODE.html">_RTL_BALANCED_NODE</a><br>
+0x050 DereferenceList : <a href="./_LIST_ENTRY.html">_LIST_ENTRY</a><br>
+0x060 NumberOfMappedViews : Uint8B<br>
+0x068 <API key> : Uint4B<br>
+0x06c LargeViews : Uint4B<br>
+0x070 ProtosNode : <a href="./<API key>.html"><API key></a><br>
</font></body></html> |
import Control.Monad
main = print . msum $ do
x <- [ 1 .. 1000 ]
y <- [x + 1 .. div (1000 - x) 2 ]
let z = 1000 - x - y
return $ if x^2 + y^2 == z^2 && x + y + z == 1000
then Just $ x * y * z
else Nothing |
# encoding=utf8
import utils
import pickle
import zipfile
import os
from tqdm import tqdm
from pprint import pprint
# Globals
#[Special, Heavy, Primary]
bucketHashes = [2465295065,953998645,1498876634]
# Load in Manifest
print 'Loading Manifest...'
with open('manifest.pickle','rb') as f:
data = pickle.loads(f.read())
# Convert strings to Unicodie
print 'Converting Manifest...'
data = utils.convert(data)
# Get the Items, Grid, Stats, and Perks tables from the Manifest
items = data['<API key>']
grids = data['<API key>']
stats = data['<API key>']
perks = data['<API key>']
# Get all named items from the database
all_items = {}
print 'Creating items....\n'
for i in tqdm(items, desc='Item Gathering'):
# Get Weapons
if items[i]['bucketTypeHash'] in bucketHashes:
if 'itemName' in items[i].viewkeys():
all_items[items[i]['itemName']] = {'grid':items[i]['talentGridHash'],'hash': i}
# Loop through items and create training data
cur_arch = 0
num_guns = 0
hash_list = []
bad_hashes = []
print '\nLooping through Guns to create training data...\n'
for item in tqdm(all_items, desc='Guns'):
gun = all_items[item]
cur_archive = 'archive_%d.zip' % cur_arch
# First check to see if this archive exists, if not make it
if not os.path.exists(cur_archive):
zf = zipfile.ZipFile(cur_archive, 'a', zipfile.ZIP_DEFLATED, allowZip64=True)
zf.close()
# Make sure this archive can handle another file
if not(os.stat(cur_archive).st_size <= 3900000000):
# Create a contents file for the archive
with open('contents.txt','w') as f:
for i in hash_list:
f.write('%d.txt' % i)
zf = zipfile.ZipFile(cur_archive, 'a', zipfile.ZIP_DEFLATED, allowZip64=True)
zf.write('contents.txt')
zf.close()
os.remove('contents.txt')
cur_arch += 1
hash_list = []
# Open zipfile
zf = zipfile.ZipFile(cur_archive, 'a', zipfile.ZIP_DEFLATED, allowZip64=True)
# Create grid for gun
# If it is no good, just continue onto the next
try:
grid = utils.makeGrid(grids[gun['grid']])
except:
bad_hashes.append(gun['hash'])
continue
# Create the training data!
utils.<API key>(items, stats, perks, utils.makeGrid(grids[gun['grid']]), gun['hash'])
# Add this to the zipfile
zf.write('%d.txt' % gun['hash'])
zf.close()
# Remove the file and add the hash to the list
os.remove('%d.txt' % gun['hash'])
hash_list.append(gun['hash'])
num_guns += 1
# Done! Add contents to the last archive
with open('contents.txt','w') as f:
for i in hash_list:
f.write('%d.txt\n' % i)
zf = zipfile.ZipFile('archive_%d.zip' % cur_arch, 'a', zipfile.ZIP_DEFLATED, allowZip64=True)
zf.write('contents.txt')
zf.close()
os.remove('contents.txt')
# Show completion and print end stats!
print '\nComplete!'
print 'Created training data for %d guns across %d %s!' % (num_guns, cur_arch+1, 'archives' if cur_arch > 0 else 'archive')
print 'Skipped %d hashes!' % len(bad_hashes) |
namespace BullsAndCows.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Notification
{
public int Id { get; set; }
[Required]
[MinLength(3)]
public string Message { get; set; }
[Required]
public DateTime DateCreated { get; set; }
public NotificationType Type { get; set; }
public NotificationState State { get; set; }
public int GameId { get; set; }
[Required]
public string ApplicationUserId { get; set; }
}
} |
import webapp2, logging
from database import <API key>, store_feed_source, \
<API key>, <API key>
class AddHandler(webapp2.RequestHandler):
def post(self):
from database import FeedSource
name = self.request.get('name')
url = self.request.get('url')
frequency_ms = self.request.get('frequency_ms')
should_update = self.request.get('should_update')
should_be_added = True
existing_source = <API key>(url)
if existing_source:
should_be_added = False
self.response.write( \
'The URL (' + url + ') already exists (name - ' + \
existing_source.name + ').<br/>')
self.response.write('Forgot you added it already? :O')
else:
existing_source = <API key>(name)
if existing_source:
if should_update:
should_be_added = False
<API key>(existing_source, url)
self.response.write('Updated.')
else:
should_be_added = False
self.response.write('The name (' + name + ') already exists.<br/>')
self.response.write( \
'Go back and choose a different name, or tick "Update?".<br/>')
if should_be_added and store_feed_source(name, url, int(frequency_ms)):
self.response.write('Added.');
def get(self):
from database import FeedSource
self.response.write("""<!doctype html><title>Add Feed</title>
<form method="post">
Name - <input name="name"/><br/>
URL - <input name="url"/><br/>
Frequency (milliseconds) -
<input type="number" value="1000" name="frequency_ms"/><br/>
<label>Update?<input type="checkbox" name="should_update" value="1"/></label>
<input type="submit"/>
</form>""") |
<API key> = function (containerId) {
var <API key> = [
//Rotate Overlap
{ $Duration: 1200, $Zoom: 11, $Rotate: -1, $Easing: { $Zoom: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 0.5 }, $Brother: { $Duration: 1200, $Zoom: 1, $Rotate: 1, $Easing: $JssorEasing$.$EaseSwing, $Opacity: 2, $Round: { $Rotate: 0.5 }, $Shift: 90 } },
//Switch
{ $Duration: 1400, x: 0.25, $Zoom: 1.5, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Zoom: $JssorEasing$.$EaseInSine }, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1400, x: -0.25, $Zoom: 1.5, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Zoom: $JssorEasing$.$EaseInSine }, $Opacity: 2, $ZIndex: -10 } },
//Rotate Relay
{ $Duration: 1200, $Zoom: 11, $Rotate: 1, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 1 }, $ZIndex: -10, $Brother: { $Duration: 1200, $Zoom: 11, $Rotate: -1, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 1 }, $ZIndex: -10, $Shift: 600 } },
//Doors
{ $Duration: 1500, x: 0.5, $Cols: 2, $ChessMode: { $Column: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutCubic }, $Opacity: 2, $Brother: { $Duration: 1500, $Opacity: 2 } },
//Rotate in+ out-
{ $Duration: 1500, x: -0.3, y: 0.5, $Zoom: 1, $Rotate: 0.1, $During: { $Left: [0.6, 0.4], $Top: [0.6, 0.4], $Rotate: [0.6, 0.4], $Zoom: [0.6, 0.4] }, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Brother: { $Duration: 1000, $Zoom: 11, $Rotate: -0.5, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Shift: 200 } },
//Fly Twins
{ $Duration: 1500, x: 0.3, $During: { $Left: [0.6, 0.4] }, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Outside: true, $Brother: { $Duration: 1000, x: -0.3, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 } },
//Rotate in- out+
{ $Duration: 1500, $Zoom: 11, $Rotate: 0.5, $During: { $Left: [0.4, 0.6], $Top: [0.4, 0.6], $Rotate: [0.4, 0.6], $Zoom: [0.4, 0.6] }, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Brother: { $Duration: 1000, $Zoom: 1, $Rotate: -0.5, $Easing: { $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Shift: 200 } },
//Rotate Axis up overlap
{ $Duration: 1200, x: 0.25, y: 0.5, $Rotate: -0.1, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Brother: { $Duration: 1200, x: -0.1, y: -0.7, $Rotate: 0.1, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2 } },
//Chess Replace TB
{ $Duration: 1600, x: 1, $Rows: 2, $ChessMode: { $Row: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1600, x: -1, $Rows: 2, $ChessMode: { $Row: 3 }, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 } },
//Chess Replace LR
{ $Duration: 1600, y: -1, $Cols: 2, $ChessMode: { $Column: 12 }, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1600, y: 1, $Cols: 2, $ChessMode: { $Column: 12 }, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 } },
//Shift TB
{ $Duration: 1200, y: 1, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1200, y: -1, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 } },
//Shift LR
{ $Duration: 1200, x: 1, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Brother: { $Duration: 1200, x: -1, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 } },
//Return TB
{ $Duration: 1200, y: -1, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1200, y: -1, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Shift: -100 } },
//Return LR
{ $Duration: 1200, x: 1, $Delay: 40, $Cols: 6, $Formation: $<API key>$.$FormationStraight, $Easing: { $Left: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Brother: { $Duration: 1200, x: 1, $Delay: 40, $Cols: 6, $Formation: $<API key>$.$FormationStraight, $Easing: { $Top: $JssorEasing$.$EaseInOutQuart, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2, $ZIndex: -10, $Shift: -100 } },
//Rotate Axis down
{ $Duration: 1500, x: -0.1, y: -0.7, $Rotate: 0.1, $During: { $Left: [0.6, 0.4], $Top: [0.6, 0.4], $Rotate: [0.6, 0.4] }, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Brother: { $Duration: 1000, x: 0.2, y: 0.5, $Rotate: -0.1, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Top: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2 } },
//Extrude Replace
{ $Duration: 1600, x: -0.2, $Delay: 40, $Cols: 12, $During: { $Left: [0.4, 0.6] }, $SlideOut: true, $Formation: $<API key>$.$FormationStraight, $Assembly: 260, $Easing: { $Left: $JssorEasing$.$EaseInOutExpo, $Opacity: $JssorEasing$.$EaseInOutQuad }, $Opacity: 2, $Outside: true, $Round: { $Top: 0.5 }, $Brother: { $Duration: 1000, x: 0.2, $Delay: 40, $Cols: 12, $Formation: $<API key>$.$FormationStraight, $Assembly: 1028, $Easing: { $Left: $JssorEasing$.$EaseInOutExpo, $Opacity: $JssorEasing$.$EaseInOutQuad }, $Opacity: 2, $Round: { $Top: 0.5 } } }
];
var _CaptionTransitions = [
//CLIP|LR
{$Duration: 900, $Clip: 3, $Easing: $JssorEasing$.$EaseInOutCubic },
//CLIP|TB
{$Duration: 900, $Clip: 12, $Easing: $JssorEasing$.$EaseInOutCubic },
//DDGDANCE|LB
{$Duration: 1800, x: 0.3, y: -0.3, $Zoom: 1, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Zoom: $JssorEasing$.$EaseOutQuad }, $Opacity: 2, $During: { $Left: [0, 0.8], $Top: [0, 0.8] }, $Round: { $Left: 0.8, $Top: 2.5} },
//DDGDANCE|RB
{$Duration: 1800, x: -0.3, y: -0.3, $Zoom: 1, $Easing: { $Left: $JssorEasing$.$EaseInJump, $Top: $JssorEasing$.$EaseInJump, $Zoom: $JssorEasing$.$EaseOutQuad }, $Opacity: 2, $During: { $Left: [0, 0.8], $Top: [0, 0.8] }, $Round: { $Left: 0.8, $Top: 2.5} },
//TORTUOUS|HL
{$Duration: 1500, x: 0.2, $Zoom: 1, $Easing: { $Left: $JssorEasing$.$EaseOutWave, $Zoom: $JssorEasing$.$EaseOutCubic }, $Opacity: 2, $During: { $Left: [0, 0.7] }, $Round: { $Left: 1.3} },
//TORTUOUS|VB
{$Duration: 1500, y: -0.2, $Zoom: 1, $Easing: { $Top: $JssorEasing$.$EaseOutWave, $Zoom: $JssorEasing$.$EaseOutCubic }, $Opacity: 2, $During: { $Top: [0, 0.7] }, $Round: { $Top: 1.3} },
//ZMF|10
{$Duration: 600, $Zoom: 11, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 },
//ZML|R
{$Duration: 600, x: -0.6, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2 },
//ZML|B
{$Duration: 600, y: -0.6, $Zoom: 11, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2 },
//ZMS|B
{$Duration: 700, y: -0.6, $Zoom: 1, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2 },
//ZM*JDN|LB
{$Duration: 1200, x: 0.8, y: -0.5, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*JUP|LB
{$Duration: 1200, x: 0.8, y: -0.5, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*JUP|RB
{$Duration: 1200, x: -0.8, y: -0.5, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//ZM*WVR|LT
{$Duration: 1200, x: 0.5, y: 0.3, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInWave }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|RT
{$Duration: 1200, x: -0.5, y: 0.3, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInWave }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|TL
{$Duration: 1200, x: 0.3, y: 0.5, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//ZM*WVR|BL
{$Duration: 1200, x: 0.3, y: -0.5, $Zoom: 11, $Easing: { $Left: $JssorEasing$.$EaseInWave, $Top: $JssorEasing$.$EaseLinear }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTT|10
{$Duration: 700, $Zoom: 11, $Rotate: 1, $Easing: { $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTL|R
{$Duration: 700, x: -0.6, $Zoom: 11, $Rotate: 1, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTL|B
{$Duration: 700, y: -0.6, $Zoom: 11, $Rotate: 1, $Easing: { $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.8} },
//RTTS|R
{$Duration: 700, x: -0.6, $Zoom: 1, $Rotate: 1, $Easing: { $Left: $JssorEasing$.$EaseInQuad, $Zoom: $JssorEasing$.$EaseInQuad, $Rotate: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseOutQuad }, $Opacity: 2, $Round: { $Rotate: 1.2} },
//RTTS|B
{$Duration: 700, y: -0.6, $Zoom: 1, $Rotate: 1, $Easing: { $Top: $JssorEasing$.$EaseInQuad, $Zoom: $JssorEasing$.$EaseInQuad, $Rotate: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseOutQuad }, $Opacity: 2, $Round: { $Rotate: 1.2} },
//RTT*JDN|RT
{$Duration: 1000, x: -0.8, y: 0.5, $Zoom: 11, $Rotate: 0.2, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//RTT*JDN|LB
{$Duration: 1000, x: 0.8, y: -0.5, $Zoom: 11, $Rotate: 0.2, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseOutCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5]} },
//RTT*JUP|RB
{ $Duration: 1000, x: -0.8, y: -0.5, $Zoom: 11, $Rotate: 0.2, $Easing: { $Left: $JssorEasing$.$EaseLinear, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Top: [0, 0.5] } },
{ $Duration: 1000, x: -0.5, y: 0.8, $Zoom: 11, $Rotate: 1, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseLinear, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Left: [0, 0.5] }, $Round: { $Rotate: 0.5 } },
//RTT*JUP|BR
{$Duration: 1000, x: -0.5, y: -0.8, $Zoom: 11, $Rotate: 0.2, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseLinear, $Zoom: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $During: { $Left: [0, 0.5]} },
//R|IB
{$Duration: 900, x: -0.6, $Easing: { $Left: $JssorEasing$.$EaseInOutBack }, $Opacity: 2 },
//B|IB
{$Duration: 900, y: -0.6, $Easing: { $Top: $JssorEasing$.$EaseInOutBack }, $Opacity: 2 },
];
var options = {
$AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
$AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
$PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1
$ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false
$SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$<API key>: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20
//$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container
//$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container
$SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc).
$PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1
$DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$SlideshowOptions: { //[Optional] Options to specify and enable slideshow or not
$Class: $<API key>$, //[Required] Class to create instance of slideshow
$Transitions: <API key>, //[Required] An array of slideshow transitions to play slideshow
$TransitionsOrder: 1, //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random
$ShowLink: true //[Optional] Whether to bring slide link on top of the slider when slideshow is running, default value is false
},
$<API key>: { //[Optional] Options which specifies how to animate caption
$Class: $JssorCaptionSlider$, //[Required] Class to create instance to animate caption
$CaptionTransitions: _CaptionTransitions, //[Required] An array of caption transitions to play caption, see caption transition section at jssor slideshow transition builder
$PlayInMode: 1, //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1
$PlayOutMode: 3 //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1
},
$<API key>: { //[Optional] Options to specify and enable navigator or not
$Class: $<API key>$, //[Required] Class to create navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1
$SpacingX: 10, //[Optional] Horizontal space between each item in pixel, default value is 0
$SpacingY: 10, //[Optional] Vertical space between each item in pixel, default value is 0
$Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
},
$<API key>: {
$Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
$ChanceToShow: 2 //[Required] 0 Never, 1 Mouse Over, 2 Always
}
};
var jssor_slider1 = new $JssorSlider$(containerId, options);
//responsive code begin
//you can remove responsive code if you don't want the slider scales while window resizes
function ScaleSlider() {
var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth;
if (parentWidth)
jssor_slider1.$ScaleWidth(Math.min(parentWidth, 600));
else
$Jssor$.$Delay(ScaleSlider, 30);
}
ScaleSlider();
$Jssor$.$AddEvent(window, "load", ScaleSlider);
$Jssor$.$AddEvent(window, "resize", $Jssor$.$WindowResizeFilter(window, ScaleSlider));
$Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
//responsive code end
}; |
from rest_framework import serializers
import models
class PluginSerializer(serializers.<API key>):
class Meta:
model = models.Plugin
fields = ('id', 'name', )
class <API key>(serializers.<API key>):
class Meta:
model = models.ScoredService
fields = ('id', 'name', 'plugin', 'checks', 'services')
class CheckSerializer(serializers.<API key>):
class Meta:
model = models.Check
fields = ('id', 'key', 'value', 'scored_service')
class TeamSerializer(serializers.<API key>):
class Meta:
model = models.Team
fields = ('id', 'name', 'services')
class ServiceSerializer(serializers.<API key>):
class Meta:
model = models.Service
fields = ('id', 'scored_service', 'address', 'port', 'team', 'credentials', 'results')
read_only_fields = ('results', )
class <API key>(serializers.<API key>):
class Meta:
model = models.Credential
fields = ('id', 'username', 'password', 'service')
class ResultSerializer(serializers.<API key>):
class Meta:
model = models.Result
fields = ('id', 'status', 'service', 'explanation') |
package com.github.mgoeminne.sitar.parser.acm
import com.github.mgoeminne.sitar.parser.{Citation}
import org.scalatest.{FlatSpec, Matchers}
class ACMthesisTest extends FlatSpec with Matchers
{
val p = parser.thesisParser
"Single author phd thesis citation" should "be correctly parsed" in {
val citation = "van der Spek, P. Managing software evolution in embedded systems. PhD thesis, Vrije Universiteit, Belgium, 2010."
p.parseAll(p.citation, citation) match {
case p.Success(matched: Citation,_) => {
matched.title shouldBe "Managing software evolution in embedded systems"
matched.authors shouldEqual Seq("Spek")
matched.year shouldEqual 2010
}
case p.Failure(msg,_) => fail("Parsing failed : " + msg)
case p.Error(msg,_) => fail("Parsing error : " + msg)
}
}
} |
<?php
namespace Dmitrynaum\SAM;
use <API key>;
use <API key>;
use Dmitrynaum\SAM\Component\Manifest;
class AssetBuilder
{
protected $needFreeze;
protected $needCompress;
/**
* Manifest
* @var Manifest
*/
protected $manifest;
protected $manifestFilePath;
public function __construct($manifestFilePath)
{
$this->manifestFilePath = $manifestFilePath;
$this->needCompress = false;
$this->needFreeze = false;
}
public function enableFreezing()
{
$this->needFreeze = true;
}
public function disableFreezing()
{
$this->needFreeze = false;
}
public function isFreezingEnabled()
{
return $this->needFreeze;
}
public function enableCompressor()
{
$this->needCompress = true;
}
public function disableCompressor()
{
$this->needCompress = false;
}
public function isCompressorEnabled()
{
return $this->needCompress;
}
public function build()
{
$this->clearAssetDirectory();
$this->buildCss();
$this->buildJs();
$this->resultMap()->save();
}
protected function clearAssetDirectory()
{
$assetBasePath = $this->manifest()-><API key>();
$dirIterator = new <API key>($assetBasePath, <API key>::SKIP_DOTS);
$files = new <API key>($dirIterator, <API key>::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
}
protected function buildCss()
{
$cssAssets = $this->manifest()->getCssAssets();
$this->buildAssets($cssAssets);
}
protected function buildJs()
{
$jsAssets = $this->manifest()->getJsAssets();
$this->buildAssets($jsAssets);
}
protected function buildAssets($assets)
{
$assetsPaths = $this->getFilesPaths($assets);
foreach ($assetsPaths as $assetName => $assetFiles) {
$assetContent = $this->readFiles($assetFiles);
$assetSavePath = $this->manifest()-><API key>() . '/' . $assetName;
$assetWebPath = $this->manifest()->getAssetBasePath() . '/' . $assetName;
if ($this->isCompressorEnabled()) {
$compressor = $this->getCompressor($assetName);
$compressor->add($assetContent);
$assetContent = $compressor->minify();
}
if ($this->isFreezingEnabled()) {
$assetHash = sha1($assetContent);
$assetSavePath = $this-><API key>($assetName, $assetHash);
}
$this->saveAsset($assetSavePath, $assetContent);
$this->resultMap()->addAsset($assetName, $assetWebPath);
}
}
protected function saveAsset($assetPath, $content)
{
$dirName = dirname($assetPath);
if (!is_dir($dirName)) {
mkdir($dirName, 0777, true);
}
file_put_contents($assetPath, $content);
}
protected function getFilesPaths($assets)
{
$assetFilePaths = [];
foreach ($assets as $assetName => $assetFiles) {
$assetFilePaths[$assetName] = $this-><API key>($assets, $assetFiles);
}
return $assetFilePaths;
}
protected function <API key>($assets, $assetFiles)
{
$assetFilePaths = [];
foreach ($assetFiles as $assetNameOrFile) {
if (isset($assets[$assetNameOrFile])) {
$assetFiles = $assets[$assetNameOrFile];
$assetFilePaths = array_merge($assetFilePaths, $this-><API key>($assets, $assetFiles));
} else {
$assetFilePaths[] = $assetNameOrFile;
}
}
return $assetFilePaths;
}
protected function <API key>($assetName, $assetHash)
{
$fileInfo = pathinfo($assetName);
$fileName = $fileInfo['filename'] . '-' . $assetHash . '.' . $fileInfo['extension'];
return $this->manifest()-><API key>() . '/' . $fileInfo['dirname'] . '/' . $fileName;
}
protected function manifest()
{
if (!$this->manifest) {
$this->manifest = new Manifest($this->manifestFilePath);
}
return $this->manifest;
}
protected function resultMap()
{
return $this->manifest()->resultMap();
}
protected function readFiles($filePaths)
{
$filesContent = [];
foreach ($filePaths as $filePath) {
$filesContent[] = file_get_contents($filePath);
}
return join(PHP_EOL, $filesContent);
}
protected function getCompressor($assetPath)
{
$fileExtension = pathinfo($assetPath, PATHINFO_EXTENSION);
$compressor = null;
switch ($fileExtension) {
case 'js':
$compressor = new \MatthiasMullie\Minify\JS();
break;
case 'css':
$compressor = new \MatthiasMullie\Minify\CSS();
break;
}
return $compressor;
}
} |
package fr.upem.journal.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import fr.upem.journal.newsfeed.NewsFeed;
import fr.upem.journal.adapter.NewsFeedAdapter;
import fr.upem.journal.newsfeed.NewsFeedItem;
import fr.upem.journal.R;
import fr.upem.journal.activity.NewsContentActivity;
import fr.upem.journal.task.FetchRSSFeedTask;
public class NewsFeedFragment extends Fragment implements AdapterView.OnItemClickListener {
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private NewsFeedAdapter newsFeedAdapter;
private ArrayList<NewsFeed> feeds;
public static NewsFeedFragment newInstance(ArrayList<NewsFeed> feeds) {
Bundle args = new Bundle();
args.<API key>("feeds", feeds);
NewsFeedFragment fragment = new NewsFeedFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
feeds = args.<API key>("feeds");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeRefreshLayout);
listView = (ListView) layout.findViewById(R.id.listView);
newsFeedAdapter = new NewsFeedAdapter(layout.getContext(), inflater);
listView.setAdapter(newsFeedAdapter);
listView.<API key>(this);
fetch();
swipeRefreshLayout.<API key>(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
fetch();
}
});
return layout;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsFeedItem item = (NewsFeedItem) newsFeedAdapter.getItem(position);
Intent intent = new Intent(getActivity(), NewsContentActivity.class);
intent.putExtra("item", item);
startActivity(intent);
}
private void fetch() {
new FetchRSSFeedTask() {
@Override
protected void onPostExecute(List<NewsFeedItem> items) {
newsFeedAdapter.updateItems(items);
swipeRefreshLayout.setRefreshing(false);
}
}.execute(feeds.toArray(new NewsFeed[feeds.size()]));
}
} |
using HitboxUnofficialApp.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace HitboxUnofficialApp
{
<summary>
A basic page that provides characteristics common to most applications.
</summary>
public sealed partial class MainPage : Page
{
private NavigationHelper navigationHelper;
<summary>
NavigationHelper is used on each page to aid in navigation and
process lifetime management
</summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public MainPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += <API key>;
this.navigationHelper.SaveState += <API key>;
}
<summary>
Populates the page with content passed during navigation. Any saved state is also
provided when recreating a page from a prior session.
</summary>
<param name="sender">
The source of the event; typically <see cref="Common.NavigationHelper"/>
</param>
<param name="e">Event data that provides both the navigation parameter passed to
<see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
a dictionary of state preserved by this page during an earlier
session. The state will be null the first time a page is visited.</param>
private async void <API key>(object sender, LoadStateEventArgs e)
{
await Locator.ViewModels.MainPageVm.Initialize();
}
<summary>
Preserves state associated with this page in case the application is suspended or the
page is discarded from the navigation cache. Values must conform to the serialization
requirements of <see cref="Common.SuspensionManager.SessionState"/>.
</summary>
<param name="sender">The source of the event; typically <see cref="Common.NavigationHelper"/></param>
<param name="e">Event data that provides an empty dictionary to be populated with
serializable state.</param>
private void <API key>(object sender, SaveStateEventArgs e)
{
}
#region NavigationHelper registration
The methods provided in this section are simply used to allow
NavigationHelper to respond to the page's navigation methods.
Page specific logic should be placed in event handlers for the
<see cref="Common.NavigationHelper.LoadState"/>
and <see cref="Common.NavigationHelper.SaveState"/>.
The navigation parameter is available in the LoadState method
in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
}
} |
exports.category = [
{
name: 'clothes',
created_at: new Date,
updated_at: new Date
},
{
name: 'shoes',
created_at: new Date,
updated_at: new Date
},
{
name: 'food',
created_at: new Date,
updated_at: new Date
},
{
name: 'electronics',
created_at: new Date,
updated_at: new Date
},
{
name: 'sports',
created_at: new Date,
updated_at: new Date
},
] |
package com.imos.pi.utils;
/**
*
* @author Alok
*/
//@Stateless
//public class SentMailEvent {
// private final SMTPMailService mailService;
// public SentMailEvent() {
// this.mailService = new SMTPMailService();
// public void sendMail() {
// mailService.<API key>("./"); |
<?php
namespace DannySuryadi\Http\Controllers\Admin;
use DannySuryadi\Http\Controllers\Controller;
class HomeController extends Controller
{
public function getIndex()
{
return view('admin.index');
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.6.6: deps/v8/include Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.6.6
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">deps</a></li><li class="navelem"><a class="el" href="<API key>.html">v8</a></li><li class="navelem"><a class="el" href="<API key>.html">include</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">include Directory Reference</div> </div>
</div><!--header
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:v8-debug_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8-debug.h</b> <a href="v8-debug_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:v8-preparser_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8-preparser.h</b> <a href="<API key>.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:v8-profiler_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8-profiler.h</b> <a href="<API key>.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:v8-testing_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8-testing.h</b> <a href="<API key>.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:v8_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8.h</b> <a href="v8_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:v8stdint_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>v8stdint.h</b> <a href="v8stdint_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:47:46 for V8 API Reference Guide for node.js v0.6.6 by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html> |
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef DUST_NET_POLLER_H_
#define DUST_NET_POLLER_H_
#include <vector>
namespace dust {
class EventHandler;
class EventLoop;
class Poller {
public:
explicit Poller(EventLoop* eventloop);
virtual ~Poller();
EventLoop* eventloop() const { return eventloop_; }
virtual void AddEventHandler(EventHandler* eventhandler, int events) = 0;
virtual void UpdateEventHandler(EventHandler* eventhandler, int events) = 0;
virtual void RemoveEventHandler(EventHandler* eventhandler) = 0;
// millisecond
// virtual void Poll(int timeout,
// std::vector<EventHandler*>* eventhandlers) = 0;
virtual void Poll(int timeout) = 0;
static Poller* NewDefaultPoller(EventLoop* eventloop);
private:
EventLoop* eventloop_;
private:
Poller(const Poller&);
Poller& operator=(const Poller&);
}; // class Poller
} // namespace dust
#endif // DUST_NET_POLLER_H_ |
#!/usr/bin/env ruby
$:.push File.expand_path("../lib", __FILE__)
require 'readline-ng'
reader = ReadlineNG::Reader.new
loop do
line = reader.get_line
reader.puts_above("Got #{line}")
end |
# PyWal-Spotify-Theme
[`python-pywal`](https: |
const url = require('url');
const path = require('path');
const electron = require('electron');
const <API key> = require('./windows/main/config');
const <API key> = require('./windows/settings/config');
const {BrowserWindow} = electron;
const <API key> = {
center: false,
darkTheme: true,
defaultFontFamily: '"Ubuntu Mono", "Courier New", monospace',
webPreferences: {
devTools: false
}
};
function create(pathToIndex, config) {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize;
const x = (width - config.width) / 2;
const y = (height - config.height) / 2;
const fullConfig = Object.assign({x, y}, <API key>, config);
const wnd = new BrowserWindow(fullConfig);
wnd.loadURL(
url.format({
pathname: pathToIndex,
protocol: 'file:',
slashes: true
})
);
wnd.setMenu(null);
if (fullConfig.webPreferences.devTools) {
wnd.webContents.openDevTools();
}
wnd.setWidth = function setWidth(newWidth) {
wnd.setSize(newWidth, config.height);
wnd.setPosition((width - newWidth) / 2, y);
};
return wnd;
}
function createMainWindow(config) {
const pathToIndex = path.join(__dirname, 'windows/main/index.html');
return create(pathToIndex, Object.assign({}, <API key>, config));
}
function <API key>(config) {
const pathToIndex = path.join(__dirname, 'windows/settings/index.html');
return create(pathToIndex, Object.assign({}, <API key>, config));
}
module.exports = {
create,
createMainWindow,
<API key>
}; |
#ifndef GUIUTIL_H
#define GUIUTIL_H
#include <QString>
#include <QObject>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
class QFont;
class QLineEdit;
class QWidget;
class QDateTime;
class QUrl;
class QAbstractItemView;
QT_END_NAMESPACE
class SendCoinsRecipient;
/** Utility functions used by the PokerCoin-qt UI.
*/
namespace GUIUtil
{
// Create human-readable string from date
QString dateTimeStr(const QDateTime &datetime);
QString dateTimeStr(qint64 nTime);
// Render addresses in monospace font
QFont bitcoinAddressFont();
// Set up widgets for address and amounts
void setupAddressWidget(QLineEdit *widget, QWidget *parent);
void setupAmountWidget(QLineEdit *widget, QWidget *parent);
// Parse "PokerCoin:" URI into recipient object, return true on succesful parsing
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out);
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out);
// HTML escaping for rich text controls
QString HtmlEscape(const QString& str, bool fMultiLine=false);
QString HtmlEscape(const std::string& str, bool fMultiLine=false);
/** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing
is selected.
@param[in] column Data column to extract from the model
@param[in] role Data role to extract from the model
@see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress
*/
void copyEntryData(QAbstractItemView *view, int column, int role=Qt::EditRole);
/** Get save file name, mimics QFileDialog::getSaveFileName, except that it appends a default suffix
when no suffix is provided by the user.
@param[in] parent Parent window (or 0)
@param[in] caption Window caption (or empty, for default)
@param[in] dir Starting directory (or empty, to default to documents directory)
@param[in] filter Filter specification such as "Comma Separated Files (*.csv)"
@param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0).
Can be useful when choosing the save file format based on suffix.
*/
QString getSaveFileName(QWidget *parent=0, const QString &caption=QString(),
const QString &dir=QString(), const QString &filter=QString(),
QString *selectedSuffixOut=0);
/** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking.
@returns If called from the GUI thread, return a Qt::DirectConnection.
If called from another thread, return a Qt::<API key>.
*/
Qt::ConnectionType <API key>();
// Determine whether a widget is hidden behind other windows
bool isObscured(QWidget *w);
// Open debug.log
void openDebugLogfile();
/** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text
representation if needed. This assures that Qt can word-wrap long tooltip messages.
Tooltips longer than the provided size threshold (in characters) are wrapped.
*/
class <API key> : public QObject
{
Q_OBJECT
public:
explicit <API key>(int size_threshold, QObject *parent = 0);
protected:
bool eventFilter(QObject *obj, QEvent *evt);
private:
int size_threshold;
};
bool <API key>();
bool <API key>(bool fAutoStart);
/** Help message, shown with --help. */
class HelpMessageBox : public QMessageBox
{
Q_OBJECT
public:
HelpMessageBox(QWidget *parent = 0);
/** Show message box or print help message to standard output, based on operating system. */
void showOrPrint();
/** Print help message to console */
void printToConsole();
private:
QString header;
QString coreOptions;
QString uiOptions;
};
} // namespace GUIUtil
#endif // GUIUTIL_H |
#include "stdafx.h"
#include "SplashScene.h"
SplashScene::SplashScene(E_GAME_STATE* State)
{
SyncGameState(State);
LoadImageResources();
Setup();
}
SplashScene::~SplashScene()
{
}
void SplashScene::Update()
{
}
void SplashScene::Render(HDC hdc)
{
if (m_startTime + 5.0f > g_pTimerManager->GetWorldTime())
{
if (m_startTime + 4.0f < g_pTimerManager->GetWorldTime())
{
m_dLogoAlpha -= 5.0f;
if (m_dLogoAlpha < 0.0f)
{
m_dLogoAlpha = 0.0f;
}
m_sprLogo->SetAlpha(m_dLogoAlpha);
}
m_sprLogo->GetBodyImg()->AlphaRender(hdc, 0, 0, (BYTE)m_sprLogo->GetAlpha());
}
else
{
m_sprSplash->GetBodyImg()->FastRender(hdc);
}
}
void SplashScene::Setup()
{
m_dLogoAlpha = 255.0f;
m_startTime = g_pTimerManager->GetWorldTime();
m_sprLogo = new SpritesObject;
m_sprLogo->SetBodyImg(g_pImgManager->FindImage("logo-komastar"));
m_sprLogo->SetupForSprites(1, 1);
m_sprSplash = new SpritesObject;
m_sprSplash->SetBodyImg(g_pImgManager->FindImage("splash"));
m_sprSplash->SetupForSprites(1, 1);
}
void SplashScene::LoadImageResources()
{
}
void SplashScene::DeleteScene()
{
} |
require_relative '../../../spec_helper'
describe :numeric_rect, shared: true do
before :each do
@numbers = [
20, # Integer
398.72, # Float
Rational(3, 4), # Rational
99999999**99, # Bignum
infinity_value,
nan_value
]
end
it "returns an Array" do
@numbers.each do |number|
number.send(@method).should be_an_instance_of(Array)
end
end
it "returns a two-element Array" do
@numbers.each do |number|
number.send(@method).size.should == 2
end
end
it "returns self as the first element" do
@numbers.each do |number|
if Float === number and number.nan?
number.send(@method).first.nan?.should be_true
else
number.send(@method).first.should == number
end
end
end
it "returns 0 as the last element" do
@numbers.each do |number|
number.send(@method).last.should == 0
end
end
it "raises an ArgumentError if given any arguments" do
@numbers.each do |number|
lambda { number.send(@method, number) }.should raise_error(ArgumentError)
end
end
end |
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Cloud Code Demo - 1 - Hello World</title>
</head>
<body>
</body>
<script src='https:
<script>
Parse.initialize("<API key>",
"<API key>");
Parse.Cloud.run('hello', {}, {
success: function(result) {
alert(result);
// result is 'Hello world!'
},
error: function(error) {
}
});
</script>
</html> |
import React, { Component } from 'react';
import BookList from '../containers/book-list';
import BookDetail from '../containers/book-detail'
export default class App extends Component {
render() {
return (
<div>
<BookList />
<BookDetail />
</div>
);
}
} |
'use strict';
/**
* Main module of the application.
*/
angular.module('test.app', [
'ngAnimate',
'ngMessages',
'ngTouch',
'pascalprecht.translate',
'ui.router',
'test.config',
'test.login',
'test.main',
'test.model',
'test.photos',
'test.translation',
'test.util'
])
/** Configure whether to output debugging information to console. */
.config(function ($logProvider, config) {
$logProvider.debugEnabled(config.DEBUG);
})
/** Set up our app translations. */
.config(function ($translateProvider) {
$translateProvider
.<API key>('escaped')
.<API key>()
.fallbackLanguage('en');
})
/** Configure application routes. */
.config(function ($urlRouterProvider, $stateProvider) {
// For any unmatched URL redirect to /
$urlRouterProvider.otherwise('/login');
// Set up our application states
$stateProvider
.state('login', {
url: '/login?next¶ms',
templateUrl: 'components/login/login.html',
controller: 'LoginCtrl',
controllerAs: 'loginCtrl',
data: { title: 'LOGIN.TITLE' }
})
.state('main', {
abstract: true,
templateUrl: 'components/main/main.html',
controller: 'MainCtrl',
controllerAs: 'mainCtrl'
})
.state('main.photos', {
url: '/photos',
templateUrl: 'components/photos/photos.html',
controller: 'PhotoCtrl',
controllerAs: 'photoCtrl',
data: { title: 'PHOTOS.TITLE' }
})
.state('main.photos.single', {
url: '/:id',
data: { title: 'PHOTOS.TITLE' }
})
.state('main.about', {
url: '/about',
template: '<p>Hello!</p>',
data: { title: 'About.TITLE' }
})
;
})
/** Log our version information to the console. */
.run(function ($log, build) {
$log.info('Test App Version:', build.version,
'Commit:', build.commit, 'Env:', build.env);
})
.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
})
/** Set up service to check logged in state for route changes. */
.run(function ($rootScope, RouteCheckerService) {
$rootScope.$on('$stateChangeStart', RouteCheckerService);
})
; |
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
Bug Fixes
* **accessibility:** fixes visibility manager not being notified if reduced motion is enabled ([95d9164](https://github.com/element-motion/element-motion/commit/95d9164))
Features
* **accessibility:** skips animation if reduced motion is enabled ([a5e7da0](https://github.com/element-motion/element-motion/commit/a5e7da0))
Features
* **motion:** adds ability to compose keyframe animations in motion components ([e7e971a](https://github.com/element-motion/element-motion/commit/e7e971a))
* **scale:** adds transform origin prop ([dfe9b5c](https://github.com/element-motion/element-motion/commit/dfe9b5c))
**Note:** Version bump only for package element-motion
Features
* **motion:** skips execution if both elements are outside of the viewport ([6f62e22](https://github.com/element-motion/element-motion/commit/6f62e22))
* **translate:** adds new translate motion ([6b97dd1](https://github.com/element-motion/element-motion/commit/6b97dd1))
**Note:** Version bump only for package element-motion
Features
* **motion:** adds dev logging to improve dx ([ed7a332](https://github.com/element-motion/element-motion/commit/ed7a332))
**Note:** Version bump only for package element-motion
Features
* **scale:** adds scale motion with inverse scale helper ([721c34b](https://github.com/element-motion/element-motion/commit/721c34b))
Features
* **reveal:** adds ability to resize via width and height ([84b2818](https://github.com/madou/element-motion/commit/84b2818))
Bug Fixes
* **motion:** fixes motions flickering when animating and images having dimensions of zero ([143a40a](https://github.com/madou/element-motion/commit/143a40a))
* **reveal:** fixes reveal in safari ([ec29c7c](https://github.com/madou/element-motion/commit/ec29c7c))
Features
* **move:** adds new prop to set stacking context on move motion ([68d5b60](https://github.com/madou/element-motion/commit/68d5b60))
Bug Fixes
* **reshaping-container:** fixes children to move with container ([0d3b762](https://github.com/madou/element-motion/commit/0d3b762))
Features
* **fade-move:** adds props to disable scaling ([a3dbf96](https://github.com/madou/element-motion/commit/a3dbf96))
* **move:** adds props to disable scaling ([56141f1](https://github.com/madou/element-motion/commit/56141f1))
**Note:** Version bump only for package element-motion
**Note:** Version bump only for package element-motion
**Note:** Version bump only for package element-motion
**Note:** Version bump only for package yubaba-repo
Features
* **animator:** adds first class self targeted animations api ([6ad648e](https://github.com/madou/yubaba/commit/6ad648e))
Bug Fixes
* **baba:** replaces usage of render subtree with create portal to pass new context through ([cb67a58](https://github.com/madou/yubaba/commit/cb67a58))
Bug Fixes
* **baba:** removes baba controlling opacity and pushes it into appropriate animations ([b7bcc60](https://github.com/madou/yubaba/commit/b7bcc60))
Bug Fixes
* **reshaping-container:** adds triggerKey for triggering animation for composite components ([0f1ec5f](https://github.com/madou/yubaba/commit/0f1ec5f))
* **reshaping-container:** passes down max height to children ([1d31e94](https://github.com/madou/yubaba/commit/1d31e94))
Features
* **baba-manager:** adds ability for baba manager to hide visibility when an animation is about to start ([4a73cf7](https://github.com/madou/yubaba/commit/4a73cf7))
* **focal-conceal-move:** renames to focal conceal move from conceal move ([039ef9a](https://github.com/madou/yubaba/commit/039ef9a))
* **visibility-manager:** renames baba manager to visibility manager ([b283d09](https://github.com/madou/yubaba/commit/b283d09))
Bug Fixes
* **docs:** correct spelling mistakes and pointing to simple reveal ([8a8b4cd](https://github.com/madou/yubaba/commit/8a8b4cd))
* **peer-dependencies:** release peer deps to be greater than or equal to their version ([5fcc5e6](https://github.com/madou/yubaba/commit/5fcc5e6))
Bug Fixes
* fixes ordering of docs, adds extra content to introduction ([2fddeba](https://github.com/madou/yubaba/commit/2fddeba))
Features
* adds reshaping container composite component ([485d259](https://github.com/madou/yubaba/commit/485d259))
* adds reveal reshaping container composite component ([b8d711b](https://github.com/madou/yubaba/commit/b8d711b))
**Note:** Version bump only for package yubaba-repo
<a name="2.1.0"></a>
Features
* adds dynamic duration ([8732a40](https://github.com/madou/yubaba/commit/8732a40))
<a name="2.0.2"></a>
**Note:** Version bump only for package yubaba-repo
<a name="2.0.1"></a>
**Note:** Version bump only for package yubaba-repo
<a name="2.0.0"></a>
Chores
* renames components ([9d9282c](https://github.com/madou/yubaba/commit/9d9282c))
* renames props passed to animation components ([c54740a](https://github.com/madou/yubaba/commit/c54740a))
BREAKING CHANGES
* props passsed to animation components have changed, see the release notes for the migration guide.
* FLIPMove has been renamed to Move. Target has been renamed to FocalTarget.
<a name="1.4.1"></a>
**Note:** Version bump only for package yubaba-repo
<a name="1.4.0"></a>
Features
* adds <API key> prop ([ab441ad](https://github.com/madou/yubaba/commit/ab441ad))
<a name="1.3.0"></a>
Features
* introduces internal composable api ([9aa4945](https://github.com/madou/yubaba/commit/9aa4945))
<a name="1.2.0"></a>
Features
* adds revealmove and concealmove animations ([30579a0](https://github.com/madou/yubaba/commit/30579a0))
<a name="1.1.4"></a>
**Note:** Version bump only for package yubaba-repo
<a name="1.1.3"></a>
Bug Fixes
* fixes baba component not showing its children when using 'in' prop ([5aab9fc](https://github.com/madou/yubaba/commit/5aab9fc))
<a name="1.1.2"></a>
Bug Fixes
* set default curve for move animations to spring like, change default duration from 300ms to 500ms ([f6370a9](https://github.com/madou/yubaba/commit/f6370a9))
<a name="1.1.1"></a>
**Note:** Version bump only for package yubaba-repo
<a name="1.1.0"></a>
Features
* **flip-animations:** refactors internals to support flip animation, adds FLIPMove component ([f90a16a](https://github.com/madou/yubaba/commit/f90a16a))
<a name="1.0.1"></a>
**Note:** Version bump only for package yubaba-repo
<a name="1.0.0"></a>
Chores
* update docs ([5571e97](https://github.com/madou/yubaba/commit/5571e97))
Features
* **move:** adds timing function prop ([d5ed715](https://github.com/madou/yubaba/commit/d5ed715))
BREAKING CHANGES
* version bump
<a name="0.0.1"></a>
**Note:** Version bump only for package yubaba-repo |
package com.selenium.drivers;
import java.net.<API key>;
import org.openqa.selenium.WebDriver;
/**
* Creates SeleniumDriver
*
* @author balnave
*/
public class DriverFactory {
public WebDriver getDriver(Object... args) throws <API key> {
String type = ((String) args[0]).toLowerCase();
if (args.length == 1) {
getLocalDriver(type, null);
} else if (args.length == 2) {
// 2nd arg is options or grid url
if(args[1] instanceof String) {
getRemoteDriver(type, (String) args[1]);
} else {
getLocalDriver(type, args[1]);
}
} else if (args.length == 3) {
// 2nd arg is options
// 3rd is grid url
getRemoteDriver(type, args[1], (String) args[2]);
}
return null;
}
private WebDriver getLocalDriver(String type, Object options) {
if (type.contains("firefox")) {
return new FirefoxDriver().getDriver(options);
} else if (type.contains("ie") || type.contains("explorer")) {
return new <API key>().getDriver(options);
} else if (type.contains("chrome")) {
return new ChromeDriver().getDriver(options);
} else if (type.contains("safari")) {
return new SafariDriver().getDriver(options);
} else if (type.contains("phantom")) {
return new PhantomDriver().getDriver(options);
} else if (type.contains("htmlunit")) {
return new HtmlUnitDriver().getDriver(options);
}
return null;
}
private WebDriver getRemoteDriver(String type, String gridHubUrl) throws <API key> {
return getRemoteDriver(type, gridHubUrl, null);
}
private WebDriver getRemoteDriver(String type, Object options, String gridHubUrl) throws <API key> {
if (type.contains("firefox")) {
return new FirefoxDriver().getRemoteDriver(gridHubUrl, options);
} else if (type.contains("ie") || type.contains("explorer")) {
return new <API key>().getRemoteDriver(gridHubUrl, options);
} else if (type.contains("chrome")) {
return new ChromeDriver().getRemoteDriver(gridHubUrl, options);
} else if (type.contains("safari")) {
return new SafariDriver().getRemoteDriver(gridHubUrl, options);
} else if (type.contains("phantom")) {
return new PhantomDriver().getRemoteDriver(gridHubUrl, options);
} else if (type.contains("htmlunit")) {
return new HtmlUnitDriver().getRemoteDriver(gridHubUrl, options);
}
return null;
}
} |
import {default as process, processAST} from '../../src'
import fs from 'fs'
const inFile = __dirname + '/input.js'
const inSource = fs.readFileSync(inFile).toString()
const options = {
sourceFileName: inFile,
sourceMapName: `${inFile}.map`,
values: {}
}
options.values.PRODUCTION = true
const outProduction = process(inSource, options)
options.values.PRODUCTION = false
const outDevelopment = process(inSource, options)
fs.writeFileSync(__dirname + '/output.production.js', outProduction.code)
fs.writeFileSync(__dirname + '/output.production.js.map', outProduction.map)
fs.writeFileSync(__dirname + '/output.development.js', outDevelopment.code)
fs.writeFileSync(__dirname + '/output.development.js.map', outDevelopment.map) |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace wiquotes
{
public partial class PreferencesForm : Form
{
Dictionary<string,TextBox> textboxes = new Dictionary<string,TextBox>();
SQLiteConnection databaseConnection;
Dictionary<string, string> vals = new Dictionary<string, string>();
public PreferencesForm()
{
InitializeComponent();
databaseConnection = new SQLiteConnection("Data Source=wiquotes.sqlite;Version=3;");
databaseConnection.Open();
createTable("kwoty", "amount", "DOUBLE");
createTable("colors", "color", "VARCHAR (30)");
createTable("favourites", "fav", "VARCHAR (30)");
}
private void <API key>(object sender, EventArgs e)
{
/wartosci spinboxow zle wpisywane
TabPage kwoty = newTab("Kwoty");
newLabel(kwoty,"Kwota 1: ", 100, 50, 50, 20);
NumericUpDown spin1 = newSpinBox(kwoty,50, 200, 200, 20);
vals.Add("kwota1", Convert.ToString(spin1.Value));
newLabel(kwoty, "Kwota 2: ", 100, 50, 50, 120);
NumericUpDown spin2 = newSpinBox(kwoty,50, 200, 200, 120);
vals.Add("kwota2", Convert.ToString(spin2.Value));
newLabel(kwoty,"Odsetki: ", 100, 50, 50, 220);
NumericUpDown spin3 = newSpinBox(kwoty,50, 200, 200, 220);
vals.Add("odsetki", Convert.ToString(spin3.Value));
Button butK = newButton(kwoty, "Accept", 50, 30, 355, 55);
butK.Click += new EventHandler(butKHandler);
TabPage favs = newTab("Favourites");
newLabel(favs,"Enter your favourite websites:", 200, 30, 50, 20);
TextBox txt = newTextBox(favs,300, 30, 50, 60);
Button but = newButton(favs,"Accept", 50, 30, 355, 55);
but.Click += new EventHandler(buttonHandler);
TabPage colors = newTab("Colors");
newLabel(colors,"Graph: ", 100, 50, 50, 20);
Button but1 = newButton(colors,"Change color", 150, 30, 200, 20);
but1.Name = "graph";
newLabel(colors,"Mesh: ", 100, 50, 50, 120);
Button but2 = newButton(colors, "Change color", 150, 30, 200, 120);
but2.Name = "mesh";
newLabel(colors,"Background: ", 100, 50, 50, 220);
Button but3 = newButton(colors,"Change color", 150, 30, 200, 220);
but3.Name = "background";
but1.Click += new EventHandler(colorButClicked);
but2.Click += new EventHandler(colorButClicked);
but3.Click += new EventHandler(colorButClicked);
TabPage analysis = newTab("Analysis");
newLabel(analysis, "Name", 80, 30, 20, 20);
newTextBox(analysis, 150, 30, 20, 50);
newTextBox(analysis, 150, 30, 20, 80);
newTextBox(analysis, 150, 30, 20, 110);
newLabel(analysis, "Code", 80, 30, 220, 20);
newTextBox(analysis, 150, 30, 220, 50);
newTextBox(analysis, 150, 30, 220, 80);
newTextBox(analysis, 150, 30, 220, 110);
//calabazka();
}
//private void calabazka()
// string sql = "select * from kwoty";
// SQLiteCommand command = new SQLiteCommand(sql, databaseConnection);
// SQLiteDataReader reader = command.ExecuteReader();
// while (reader.Read())
// MessageBox.Show("Name: " + reader["name"] + "\tAmount: " + reader["amount"]);
// sql = "select * from colors";
// command = new SQLiteCommand(sql, databaseConnection);
// reader = command.ExecuteReader();
// while (reader.Read())
// MessageBox.Show("Name: " + reader["name"] + "\tColor: " + reader["color"]);
private void createTable(string table, string var2, string type)
{
string sql = "CREATE TABLE " + table + "(name VARCHAR(20), " + var2 + ' ' + type + " )";
try
{
SQLiteCommand command = new SQLiteCommand(sql, databaseConnection);
command.ExecuteNonQuery();
}
catch(SQLiteException ex)
{
MessageBox.Show(Convert.ToString(ex));
}
}
private void insertIntoTable(string table, string type1, string type2, string val1, string val2)
{
string sql = "insert into " + table + " (" + type1 + "," + type2 + ") values ('" + val1 + "'," + val2 + ")";
SQLiteCommand command = new SQLiteCommand(sql, databaseConnection);
command.ExecuteNonQuery();
}
private void insertIntoTableStr(string table, string name1, string name2, string val1, string val2)
{
string sql = "insert into " + table + " (" + name1 + "," + name2 + ") values ('" + val1 + "', '" + val2 + "' )";
MessageBox.Show(sql);
SQLiteCommand command = new SQLiteCommand(sql, databaseConnection);
command.ExecuteNonQuery();
}
private void buttonHandler(object sender, EventArgs e)
{
// string txt = ((Button)sender).Text;
// textboxes.Add("FAV", txt);
}
private void butKHandler(object sender, EventArgs e)
{
foreach (KeyValuePair<string, string> kvp in vals)
insertIntoTableStr("kwoty", "name", "amount",kvp.Key, kvp.Value);
}
private void colorButClicked(object sender, EventArgs e)
{
Button but = (Button)sender;
ColorDialog colorPicker = new ColorDialog();
if (colorPicker.ShowDialog() == DialogResult.OK)
{
if (colorPicker.Color == Color.FromName("Black"))
but.ForeColor = Color.FromName("White");
but.BackColor = colorPicker.Color;
}
if (but != null)
{
string x = but.Name;
insertIntoTableStr("colors", "name", "color", x, Convert.ToString(colorPicker.Color));
}
}
private Button newButton(TabPage tab, string name, int sizex, int sizey, int locationx, int locationy)
{
Button button = new Button();
button.Text = name;
button.Size = new Size(sizex, sizey);
button.Location = new Point(locationx, locationy);
tab.Controls.Add(button);
return button;
}
private TextBox newTextBox(TabPage tab, int sizex, int sizey, int locationx, int locationy)
{
TextBox box = new TextBox();
box.Size = new Size(sizex, sizey);
box.Location = new Point(locationx, locationy);
tab.Controls.Add(box);
return box;
}
private NumericUpDown newSpinBox(TabPage tab,int sizex, int sizey, int locationx, int locationy)
{
NumericUpDown spin = new NumericUpDown();
spin.Size = new Size(sizex, sizey);
spin.Location = new Point(locationx, locationy);
spin.DecimalPlaces = 2;
spin.Increment = 0.1m;
tab.Controls.Add(spin);
return spin;
}
private Label newLabel(TabPage tab, string name, int sizex, int sizey, int locationx, int locationy)
{
Label lab = new Label();
lab.Text = name;
lab.Size = new Size(sizex, sizey);
lab.Font = new Font(lab.Font.FontFamily, lab.Font.Size + 1.0f, lab.Font.Style);
lab.Location = new Point(locationx, locationy);
tab.Controls.Add(lab);
return lab;
}
private TabPage newTab(string name)
{
TabPage page = new TabPage();
page.Text = name;
tabControl1.TabPages.Add(page);
return page;
}
private void <API key>(object sender, EventArgs e)
{
}
}
} |
// LuaReader.cpp
// Grapedit
#include "./LuaReader.h"
using namespace lua;
bool lua::readColor(const Value& colorRef, QColor& color) {
if (colorRef.is<Table>()) {
if (colorRef[1].is<Number>())
if (colorRef[2].is<Number>())
if (colorRef[3].is<Number>())
color.setRgbF(colorRef[1], colorRef[2], colorRef[3]);
if (colorRef[4].is<Number>())
color.setAlphaF(colorRef[4]);
else
color.setAlphaF(1);
return true;
}
else if (colorRef.is<String>()) {
color.setNamedColor(String(colorRef));
return true;
}
else if (colorRef.is<Number>()) {
Number whiteIntensity = colorRef;
color.setRgbF(whiteIntensity, whiteIntensity, whiteIntensity);
return true;
}
return false;
}
bool lua::readInset(const Value& insetRef, RectInset& inset) {
if (insetRef.is<Table>()) {
if (insetRef["top"].is<Number>())
inset.top = Number(insetRef["top"]);
if (insetRef["bottom"].is<Number>())
inset.bottom = Number(insetRef["bottom"]);
if (insetRef["left"].is<Number>())
inset.left = Number(insetRef["left"]);
if (insetRef["right"].is<Number>())
inset.right = Number(insetRef["right"]);
return true;
}
else if (insetRef.is<Number>()) {
Number insetSize = insetRef;
inset.top = insetSize;
inset.bottom = insetSize;
inset.left = insetSize;
inset.right = insetSize;
return true;
}
return false;
}
bool lua::readSize(const lua::Value& sizeRef, QSize& size)
{
if (sizeRef.is<Table>()) {
if (sizeRef["width"].is<Number>())
size.setWidth(sizeRef["width"]);
if (sizeRef["height"].is<Number>())
size.setWidth(sizeRef["height"]);
return true;
}
else if (sizeRef.is<Number>()) {
// Nastavime ako sirku
size.setWidth(sizeRef);
return true;
}
return false;
} |
<!DOCTYPE html>
<html>
<head>
<title>Clocker</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="robots" content="index,follow"/>
<meta name="googlebot" content="index,follow"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
</head>
<body>
<div class="react-root"></div>
</body>
</html> |
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b> </b></th><td class="std2"></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><sup class="subfont">ˋ</sup><sup class="subfont">ˊ</sup><sup class="subfont">ˋ</sup></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><font class="english_word">jiāo zhù tiáo sè</font></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>˙˙<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>˙˙˙<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr>
<tr><th class="std1"><b><font class="fltypefont"></font> </b></th><td class="std2"></td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table> |
use futures::channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use futures::executor;
use futures::future;
use futures::prelude::*;
use notify::*;
use future_ext::{Breaker, FutureWrapExt};
use module::{audio_io::Frame, flow, Module};
use std::path::{Path, PathBuf};
use std::process;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn <API key><F: FnMut(Frame) -> Frame + Send + 'static, Ex: executor::Executor>(
processor: F,
in_port: Arc<flow::Port<Frame, ()>>,
out_port: Arc<flow::Port<(), Frame>>,
breaker: Breaker,
mut exec: Ex,
) {
exec.spawn(Box::new(future::loop_fn(
(processor, in_port, out_port, breaker),
|(processor, in_port, out_port, breaker)| {
in_port
.write1(())
.wrap((processor, out_port, breaker))
.map_err(|((processor, out_port, breaker), (in_port, err))| {
(
processor,
in_port,
out_port,
breaker,
format!("in write1 {:?}", err),
)
})
.and_then(|((processor, out_port, breaker), in_port)| {
in_port.read1().wrap((processor, out_port, breaker)).map_err(
|((processor, out_port, breaker), (in_port, err))| {
(
processor,
in_port,
out_port,
breaker,
format!("in read1 {:?}", err),
)
},
)
})
.and_then(|((processor, out_port, breaker), (in_port, frame))| {
out_port
.read1()
.wrap((processor, in_port, breaker, frame))
.map_err(|((processor, in_port, breaker, frame), (out_port, err))| {
(
processor,
in_port,
out_port,
breaker,
format!("out read1 {:?}", err),
)
})
})
.and_then(move |((mut processor, in_port, breaker, frame), (out_port, _))| {
out_port
.write1(processor(frame))
.wrap((processor, in_port, breaker))
.map_err(|((processor, in_port, breaker), (out_port, err))| {
(
processor,
in_port,
out_port,
breaker,
format!("out write1 {:?}", err),
)
})
})
.recover(|(processor, in_port, out_port, breaker, err)| {
println!("err: {}", err);
((processor, in_port, breaker), out_port)
})
.map(|((processor, in_port, breaker), out_port)| {
if breaker.test() {
future::Loop::Break(())
} else {
future::Loop::Continue((processor, in_port, out_port, breaker))
}
})
},
))).unwrap();
}
#[derive(Debug)]
enum UserCommand {
NewFile(String),
}
pub struct LiveCode {
ifc: Arc<flow::Interface>,
in_port: Arc<flow::Port<Frame, ()>>,
out_port: Arc<flow::Port<(), Frame>>,
breaker: Breaker,
cmd_rx: Option<UnboundedReceiver<UserCommand>>,
cmd_tx: Option<UnboundedSender<UserCommand>>,
watcher: Arc<Mutex<Option<RecommendedWatcher>>>,
child: Arc<Mutex<Option<process::Child>>>,
}
impl Drop for LiveCode {
fn drop(&mut self) {
self.child.lock().unwrap().take().map(|mut child| {
println!("killing leftover child");
child.kill()
});
}
}
impl Module for LiveCode {
fn new(ifc: Arc<flow::Interface>) -> LiveCode {
let in_port = ifc.get_or_create_port("Input".into());
let out_port = ifc.get_or_create_port("Output".into());
let (cmd_tx, cmd_rx) = mpsc::unbounded();
LiveCode {
ifc,
in_port,
out_port,
breaker: Breaker::new(),
cmd_rx: Some(cmd_rx),
cmd_tx: Some(cmd_tx),
watcher: Arc::default(),
child: Arc::default(),
}
}
fn start<Ex: executor::Executor>(&mut self, mut exec: Ex) {
let cmd_rx = self.cmd_rx.take().unwrap();
let watcher_handle = self.watcher.clone();
let child_handle = self.child.clone();
exec.spawn(Box::new(
cmd_rx
.for_each(move |event| {
println!("event {:?}", event);
match event {
UserCommand::NewFile(filename) => {
let (tx, rx) = ::std::sync::mpsc::channel();
let mut watcher: RecommendedWatcher =
Watcher::new(tx, Duration::from_secs(1)).unwrap();
// watch parent dir and filter later, because if we just watch the file and
// it gets removed it will stop watching it
let parent_dir = Path::new(&filename).parent().unwrap();
watcher.watch(parent_dir, RecursiveMode::NonRecursive).unwrap();
// store it globally because otherwise it gets dropped and stops watching
*watcher_handle.lock().unwrap() = Some(watcher);
let child_handle = child_handle.clone();
spawn_child(&child_handle, PathBuf::from(&filename));
// TODO
// This thread gets leaked, as does the thread spawned internally inside
// the watcher... the notify crate is not cleaning up properly.
// Not sure if it's mio that's broken or what.
thread::spawn(move || loop {
match rx.recv() {
Ok(event) => {
println!("{:?}", event);
match event {
DebouncedEvent::Write(path) => {
if path.to_str().unwrap() != filename {
continue;
}
spawn_child(&child_handle, path);
}
_ => {}
}
}
Err(e) => {
println!("Watcher thread done: {:?}", e);
return;
}
}
});
}
}
Ok(())
})
.then(|x| Ok(())),
)).unwrap();
let child_handle = self.child.clone();
<API key>(
move |mut frame: Frame| -> Frame {
let mut guard = child_handle.lock().unwrap();
let child = match *guard {
Some(ref mut child) => child,
None => return frame,
};
let stdin = child.stdin.as_mut().unwrap();
let stdout = child.stdout.as_mut().unwrap();
//temporary hack
//need to use futures for io
use std::io::{Read, Write};
use std::mem;
let mut buffer: Vec<_> = frame.data.iter().cloned().collect();
let bytes: &mut [u8] = unsafe {
::std::slice::from_raw_parts_mut(
buffer.as_ptr() as *mut u8,
buffer.len() * mem::size_of::<f32>(),
)
};
stdin.write(bytes).unwrap();
stdout.read(bytes).unwrap();
for (outs, ins) in frame.data.iter_mut().zip(buffer.drain(..)) {
*outs = ins;
}
frame
},
self.in_port.clone(),
self.out_port.clone(),
self.breaker.clone(),
exec,
);
}
fn name() -> &'static str {
"Livecode"
}
fn stop(&mut self) {
self.breaker.brake();
}
fn ports(&self) -> Vec<Arc<flow::OpaquePort>> {
self.ifc.ports()
}
}
fn spawn_child(child_handle: &Arc<Mutex<Option<process::Child>>>, path: PathBuf) {
let child = match process::Command::new(path)
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(e) => {
println!("err spawning: {:?}", e);
return;
}
};
let mut child_handle = child_handle.lock().unwrap();
child_handle.take().map(|mut child| {
println!("killing previous child");
child.kill().unwrap();
});
*child_handle = Some(child);
}
use gfx_device_gl as gl;
use gui::{button::*, component::*, event::*, geom::*, module_gui::*, render::*};
struct LiveCodeGui {
bounds: Box3,
open_button: Button,
cmd_tx: UnboundedSender<UserCommand>,
}
const PADDING: f32 = 4.0;
impl ModuleGui for LiveCode {
fn new_body(&mut self, ctx: &mut RenderContext, bounds: Box3) -> Box<dyn GuiComponent<BodyUpdate>> {
Box::new(LiveCodeGui {
cmd_tx: self.cmd_tx.take().unwrap(),
bounds,
open_button: Button::new(
ctx.clone(),
"Pick file".into(),
Box3 {
pos: bounds.pos + Pt3::new(PADDING, PADDING, 0.0),
size: Pt3::new(bounds.size.x - PADDING * 2.0, 26.0, 0.0),
},
),
})
}
}
impl GuiComponent<bool> for LiveCodeGui {
fn set_bounds(&mut self, bounds: Box3) {
self.bounds = bounds;
}
fn bounds(&self) -> Box3 {
self.bounds
}
fn render(&mut self, device: &mut gl::Device, ctx: &mut RenderContext) {
self.open_button.render(device, ctx);
}
fn handle(&mut self, event: &Event) -> BodyUpdate {
match self.open_button.handle(event) {
ButtonUpdate::Unchanged => false,
ButtonUpdate::NeedRender => true,
ButtonUpdate::Clicked => {
match nfd::open_file_dialog(None, None).unwrap() {
nfd::Response::Okay(path) => {
self.open_button.set_label(path.clone());
self.cmd_tx.unbounded_send(UserCommand::NewFile(path)).unwrap();
}
nfd::Response::Cancel => println!("selection cancelled"),
_ => panic!(),
}
true
}
}
}
} |
require 'set'
module Trailblazer
class RouteTable
attr_reader :table, :vpc, :gateway
def initialize(config)
@logger = Logging.logger['TABLE']
raise "No route table declared in configuration! See `trailblazer -h`" unless config.route_table?
@ec2 = AWS::EC2.new
logger.debug "Retrieving route table information"
@table = ec2.route_tables[config.route_table]
@vpc = @table.vpc
@gateway = @vpc.internet_gateway
end
def update(new_routes)
logger.debug "Synchronizing with route table"
changes = Hash.new {|h, k| h[k] = 0}
destinations = Set.new
table.routes.each do |route|
dest, old_target = route.<API key>, route.target
destinations.add dest
if new_target = new_routes[dest]
if new_target == old_target
logger.debug "#{dest} -> #{old_target.id} : No change"
changes[:unchanged] += 1
else
logger.warn "#{dest} -> #{old_target.id} : Replacing target with #{new_target.id}"
route.replace target_option(new_target)
changes[:replaced] += 1
end
# Special cases; don't delete the global route or default targets without replacing them
elsif dest == '0.0.0.0/0' || old_target.id == 'local'
logger.debug "#{dest} -> #{old_target.id} : Leaving default route unmodified"
changes[:unchanged] += 1
else
logger.warn "#{dest} -> #{old_target.id} : Deleting unlisted route"
route.delete
changes[:deleted] += 1
end
end
new_routes.each do |dest, target|
unless destinations.include?(dest)
logger.warn "#{dest} -> #{target.id} : Adding new route"
table.create_route dest, target_option(target)
changes[:added] += 1
end
end
changes
end
private
attr_reader :ec2, :logger
def target_option(target)
case target
when AWS::EC2::InternetGateway
{internet_gateway: target}
when AWS::EC2::NetworkInterface
{network_interface: target}
when AWS::EC2::Instance
{instance: target}
end
end
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>src\utils\Common.ts - Kiwi.js</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title="Kiwi.js"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 1.4.0</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/Kiwi.Animations.Animation.html">Kiwi.Animations.Animation</a></li>
<li><a href="../classes/Kiwi.Animations.Sequence.html">Kiwi.Animations.Sequence</a></li>
<li><a href="../classes/Kiwi.Animations.Tween.html">Kiwi.Animations.Tween</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Back.html">Kiwi.Animations.Tweens.Easing.Back</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Bounce.html">Kiwi.Animations.Tweens.Easing.Bounce</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Circular.html">Kiwi.Animations.Tweens.Easing.Circular</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Cubic.html">Kiwi.Animations.Tweens.Easing.Cubic</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Elastic.html">Kiwi.Animations.Tweens.Easing.Elastic</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Exponential.html">Kiwi.Animations.Tweens.Easing.Exponential</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Linear.html">Kiwi.Animations.Tweens.Easing.Linear</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Quadratic.html">Kiwi.Animations.Tweens.Easing.Quadratic</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Quartic.html">Kiwi.Animations.Tweens.Easing.Quartic</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Quintic.html">Kiwi.Animations.Tweens.Easing.Quintic</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.Easing.Sinusoidal.html">Kiwi.Animations.Tweens.Easing.Sinusoidal</a></li>
<li><a href="../classes/Kiwi.Animations.Tweens.TweenManager.html">Kiwi.Animations.Tweens.TweenManager</a></li>
<li><a href="../classes/Kiwi.Camera.html">Kiwi.Camera</a></li>
<li><a href="../classes/Kiwi.CameraManager.html">Kiwi.CameraManager</a></li>
<li><a href="../classes/Kiwi.Component.html">Kiwi.Component</a></li>
<li><a href="../classes/Kiwi.ComponentManager.html">Kiwi.ComponentManager</a></li>
<li><a href="../classes/Kiwi.Components.AnimationManager.html">Kiwi.Components.AnimationManager</a></li>
<li><a href="../classes/Kiwi.Components.ArcadePhysics.html">Kiwi.Components.ArcadePhysics</a></li>
<li><a href="../classes/Kiwi.Components.Box.html">Kiwi.Components.Box</a></li>
<li><a href="../classes/Kiwi.Components.Input.html">Kiwi.Components.Input</a></li>
<li><a href="../classes/Kiwi.Components.Sound.html">Kiwi.Components.Sound</a></li>
<li><a href="../classes/Kiwi.Entity.html">Kiwi.Entity</a></li>
<li><a href="../classes/Kiwi.Files.AudioFile.html">Kiwi.Files.AudioFile</a></li>
<li><a href="../classes/Kiwi.Files.DataFile.html">Kiwi.Files.DataFile</a></li>
<li><a href="../classes/Kiwi.Files.DataLibrary.html">Kiwi.Files.DataLibrary</a></li>
<li><a href="../classes/Kiwi.Files.File.html">Kiwi.Files.File</a></li>
<li><a href="../classes/Kiwi.Files.FileStore.html">Kiwi.Files.FileStore</a></li>
<li><a href="../classes/Kiwi.Files.Loader.html">Kiwi.Files.Loader</a></li>
<li><a href="../classes/Kiwi.Files.TextureFile.html">Kiwi.Files.TextureFile</a></li>
<li><a href="../classes/Kiwi.Game.html">Kiwi.Game</a></li>
<li><a href="../classes/Kiwi.GameManager.html">Kiwi.GameManager</a></li>
<li><a href="../classes/Kiwi.GameObjects.Sprite.html">Kiwi.GameObjects.Sprite</a></li>
<li><a href="../classes/Kiwi.GameObjects.StaticImage.html">Kiwi.GameObjects.StaticImage</a></li>
<li><a href="../classes/Kiwi.GameObjects.TextField.html">Kiwi.GameObjects.TextField</a></li>
<li><a href="../classes/Kiwi.GameObjects.Tilemap.TileMap.html">Kiwi.GameObjects.Tilemap.TileMap</a></li>
<li><a href="../classes/Kiwi.GameObjects.Tilemap.TileMapLayer.html">Kiwi.GameObjects.Tilemap.TileMapLayer</a></li>
<li><a href="../classes/Kiwi.GameObjects.Tilemap.<API key>.html">Kiwi.GameObjects.Tilemap.<API key></a></li>
<li><a href="../classes/Kiwi.GameObjects.Tilemap.<API key>.html">Kiwi.GameObjects.Tilemap.<API key></a></li>
<li><a href="../classes/Kiwi.GameObjects.Tilemap.TileType.html">Kiwi.GameObjects.Tilemap.TileType</a></li>
<li><a href="../classes/Kiwi.Geom.AABB.html">Kiwi.Geom.AABB</a></li>
<li><a href="../classes/Kiwi.Geom.Circle.html">Kiwi.Geom.Circle</a></li>
<li><a href="../classes/Kiwi.Geom.Intersect.html">Kiwi.Geom.Intersect</a></li>
<li><a href="../classes/Kiwi.Geom.IntersectResult.html">Kiwi.Geom.IntersectResult</a></li>
<li><a href="../classes/Kiwi.Geom.Line.html">Kiwi.Geom.Line</a></li>
<li><a href="../classes/Kiwi.Geom.Matrix.html">Kiwi.Geom.Matrix</a></li>
<li><a href="../classes/Kiwi.Geom.Point.html">Kiwi.Geom.Point</a></li>
<li><a href="../classes/Kiwi.Geom.Ray.html">Kiwi.Geom.Ray</a></li>
<li><a href="../classes/Kiwi.Geom.Rectangle.html">Kiwi.Geom.Rectangle</a></li>
<li><a href="../classes/Kiwi.Geom.Transform.html">Kiwi.Geom.Transform</a></li>
<li><a href="../classes/Kiwi.Geom.Vector2.html">Kiwi.Geom.Vector2</a></li>
<li><a href="../classes/Kiwi.Group.html">Kiwi.Group</a></li>
<li><a href="../classes/Kiwi.HUD.HUDComponents.Counter.html">Kiwi.HUD.HUDComponents.Counter</a></li>
<li><a href="../classes/Kiwi.HUD.HUDComponents.Time.html">Kiwi.HUD.HUDComponents.Time</a></li>
<li><a href="../classes/Kiwi.HUD.HUDComponents.WidgetInput.html">Kiwi.HUD.HUDComponents.WidgetInput</a></li>
<li><a href="../classes/Kiwi.HUD.HUDDisplay.html">Kiwi.HUD.HUDDisplay</a></li>
<li><a href="../classes/Kiwi.HUD.HUDManager.html">Kiwi.HUD.HUDManager</a></li>
<li><a href="../classes/Kiwi.HUD.HUDWidget.html">Kiwi.HUD.HUDWidget</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.Bar.html">Kiwi.HUD.Widget.Bar</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.BasicScore.html">Kiwi.HUD.Widget.BasicScore</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.Button.html">Kiwi.HUD.Widget.Button</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.Icon.html">Kiwi.HUD.Widget.Icon</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.IconBar.html">Kiwi.HUD.Widget.IconBar</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.Menu.html">Kiwi.HUD.Widget.Menu</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.MenuItem.html">Kiwi.HUD.Widget.MenuItem</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.TextField.html">Kiwi.HUD.Widget.TextField</a></li>
<li><a href="../classes/Kiwi.HUD.Widget.Time.html">Kiwi.HUD.Widget.Time</a></li>
<li><a href="../classes/Kiwi.IChild.html">Kiwi.IChild</a></li>
<li><a href="../classes/Kiwi.Input.Finger.html">Kiwi.Input.Finger</a></li>
<li><a href="../classes/Kiwi.Input.InputManager.html">Kiwi.Input.InputManager</a></li>
<li><a href="../classes/Kiwi.Input.Key.html">Kiwi.Input.Key</a></li>
<li><a href="../classes/Kiwi.Input.Keyboard.html">Kiwi.Input.Keyboard</a></li>
<li><a href="../classes/Kiwi.Input.Keycodes.html">Kiwi.Input.Keycodes</a></li>
<li><a href="../classes/Kiwi.Input.Mouse.html">Kiwi.Input.Mouse</a></li>
<li><a href="../classes/Kiwi.Input.MouseCursor.html">Kiwi.Input.MouseCursor</a></li>
<li><a href="../classes/Kiwi.Input.Pointer.html">Kiwi.Input.Pointer</a></li>
<li><a href="../classes/Kiwi.Input.Touch.html">Kiwi.Input.Touch</a></li>
<li><a href="../classes/Kiwi.PluginManager.html">Kiwi.PluginManager</a></li>
<li><a href="../classes/Kiwi.Renderers.CanvasRenderer.html">Kiwi.Renderers.CanvasRenderer</a></li>
<li><a href="../classes/Kiwi.Renderers.GLArrayBuffer.html">Kiwi.Renderers.GLArrayBuffer</a></li>
<li><a href="../classes/Kiwi.Renderers.GLBlendMode.html">Kiwi.Renderers.GLBlendMode</a></li>
<li><a href="../classes/Kiwi.Renderers.<API key>.html">Kiwi.Renderers.<API key></a></li>
<li><a href="../classes/Kiwi.Renderers.GLRenderManager.html">Kiwi.Renderers.GLRenderManager</a></li>
<li><a href="../classes/Kiwi.Renderers.GLTextureManager.html">Kiwi.Renderers.GLTextureManager</a></li>
<li><a href="../classes/Kiwi.Renderers.GLTextureWrapper.html">Kiwi.Renderers.GLTextureWrapper</a></li>
<li><a href="../classes/Kiwi.Renderers.Renderer.html">Kiwi.Renderers.Renderer</a></li>
<li><a href="../classes/Kiwi.Renderers.<API key>.html">Kiwi.Renderers.<API key></a></li>
<li><a href="../classes/Kiwi.Shaders.ShaderManager.html">Kiwi.Shaders.ShaderManager</a></li>
<li><a href="../classes/Kiwi.Shaders.ShaderPair.html">Kiwi.Shaders.ShaderPair</a></li>
<li><a href="../classes/Kiwi.Shaders.TextureAtlasShader.html">Kiwi.Shaders.TextureAtlasShader</a></li>
<li><a href="../classes/Kiwi.Signal.html">Kiwi.Signal</a></li>
<li><a href="../classes/Kiwi.SignalBinding.html">Kiwi.SignalBinding</a></li>
<li><a href="../classes/Kiwi.Sound.Audio.html">Kiwi.Sound.Audio</a></li>
<li><a href="../classes/Kiwi.Sound.AudioLibrary.html">Kiwi.Sound.AudioLibrary</a></li>
<li><a href="../classes/Kiwi.Sound.AudioManager.html">Kiwi.Sound.AudioManager</a></li>
<li><a href="../classes/Kiwi.Stage.html">Kiwi.Stage</a></li>
<li><a href="../classes/Kiwi.State.html">Kiwi.State</a></li>
<li><a href="../classes/Kiwi.StateConfig.html">Kiwi.StateConfig</a></li>
<li><a href="../classes/Kiwi.StateManager.html">Kiwi.StateManager</a></li>
<li><a href="../classes/Kiwi.System.Bootstrap.html">Kiwi.System.Bootstrap</a></li>
<li><a href="../classes/Kiwi.System.Device.html">Kiwi.System.Device</a></li>
<li><a href="../classes/Kiwi.Textures.SingleImage.html">Kiwi.Textures.SingleImage</a></li>
<li><a href="../classes/Kiwi.Textures.SpriteSheet.html">Kiwi.Textures.SpriteSheet</a></li>
<li><a href="../classes/Kiwi.Textures.TextureAtlas.html">Kiwi.Textures.TextureAtlas</a></li>
<li><a href="../classes/Kiwi.Textures.TextureLibrary.html">Kiwi.Textures.TextureLibrary</a></li>
<li><a href="../classes/Kiwi.Time.Clock.html">Kiwi.Time.Clock</a></li>
<li><a href="../classes/Kiwi.Time.ClockManager.html">Kiwi.Time.ClockManager</a></li>
<li><a href="../classes/Kiwi.Time.MasterClock.html">Kiwi.Time.MasterClock</a></li>
<li><a href="../classes/Kiwi.Time.Timer.html">Kiwi.Time.Timer</a></li>
<li><a href="../classes/Kiwi.Time.TimerEvent.html">Kiwi.Time.TimerEvent</a></li>
<li><a href="../classes/Kiwi.Utils.Canvas.html">Kiwi.Utils.Canvas</a></li>
<li><a href="../classes/Kiwi.Utils.Color.html">Kiwi.Utils.Color</a></li>
<li><a href="../classes/Kiwi.Utils.Common.html">Kiwi.Utils.Common</a></li>
<li><a href="../classes/Kiwi.Utils.GameMath.html">Kiwi.Utils.GameMath</a></li>
<li><a href="../classes/Kiwi.Utils.Log.html">Kiwi.Utils.Log</a></li>
<li><a href="../classes/Kiwi.Utils.RandomDataGenerator.html">Kiwi.Utils.RandomDataGenerator</a></li>
<li><a href="../classes/Kiwi.Utils.<API key>.html">Kiwi.Utils.<API key></a></li>
<li><a href="../classes/Kiwi.Utils.Version.html">Kiwi.Utils.Version</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/Animations.html">Animations</a></li>
<li><a href="../modules/Components.html">Components</a></li>
<li><a href="../modules/Easing.html">Easing</a></li>
<li><a href="../modules/Files.html">Files</a></li>
<li><a href="../modules/GameObjects.html">GameObjects</a></li>
<li><a href="../modules/Geom.html">Geom</a></li>
<li><a href="../modules/HUD.html">HUD</a></li>
<li><a href="../modules/HUDComponents.html">HUDComponents</a></li>
<li><a href="../modules/Input.html">Input</a></li>
<li><a href="../modules/Kiwi.html">Kiwi</a></li>
<li><a href="../modules/Renderers.html">Renderers</a></li>
<li><a href="../modules/Shaders.html">Shaders</a></li>
<li><a href="../modules/Sound.html">Sound</a></li>
<li><a href="../modules/System.html">System</a></li>
<li><a href="../modules/Textures.html">Textures</a></li>
<li><a href="../modules/Tilemap.html">Tilemap</a></li>
<li><a href="../modules/Time.html">Time</a></li>
<li><a href="../modules/Tweens.html">Tweens</a></li>
<li><a href="../modules/Utils.html">Utils</a></li>
<li><a href="../modules/Utils..html">Utils.</a></li>
<li><a href="../modules/Widget.html">Widget</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: src\utils\Common.ts</h1>
<div class="file">
<pre class="code prettyprint linenums">
/**
* Utils is a space that holds a wide varity of useful methods.
*
* @module Kiwi
* @submodule Utils
* @main Utils
*/
module Kiwi.Utils {
export class Common {
/**
* Default function to compare element order.
* @method defaultCompare
* @param {Any} a.
* @param {Any} b.
* @return {Number}
* @static
*/
public static defaultCompare(a, b) {
if (a < b)
{
return -1;
}
else if (a === b)
{
return 0;
}
else
{
return 1;
}
}
/**
* The type of object that this is.
* @method objType
* @return {String} "Common"
* @public
*/
public objType() {
return "Common";
}
/**
* Default function to test equality.
* @method defaultEquals
* @param {Any} a
* @param {Any} b
* @return {boolean}
* @static
* @public
*/
public static defaultEquals(a, b) {
return a === b;
}
/**
* Default function to convert an object to a string.
* @method defaultToString
* @param item {Any}
* @return {Any}
* @static
* @public
*/
public static defaultToString(item) {
if (item === null)
{
return 'KIWI_NULL';
}
else if (Kiwi.Utils.Common.isUndefined(item))
{
return 'KIWI_UNDEFINED';
}
else if (Kiwi.Utils.Common.isString(item))
{
return item;
}
else
{
return item.toString();
}
}
/**
* Returns a boolean indicating whether x is between two parameters passed.
*
* @method isBetween
* @param x {Number} The values to be checked
* @param min {Number} The minimum value
* @param max {Number} The maximum value
* @return {Boolean}
* @static
* @public
*/
public static isBetween(x, min, max):boolean {
return (x > min && x < max);
}
/**
* Checks if the given argument is a function.
* @method isFunction
* @param {Any} func.
* @return {boolean}
* @static
* @public
*/
public static isFunction(func) {
return (typeof func) === 'function';
}
/**
* Checks if the given value is numeric.
* @method isNumeric
* @param value {Any}
* @return {Boolean}
* @static
* @public
*/
public static isNumeric(value) {
return !isNaN(value);
}
/**
* Checks if the given argument is undefined.
* @method isUndefined
* @param {Any} obj
* @return {boolean}
* @static
* @public
*/
public static isUndefined(obj) {
return (typeof obj) === 'undefined';
}
/**
* Checks if the given argument is a string.
* @method isString
* @param {Any} obj
* @return {boolean}
* @static
* @public
*/
public static isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
/**
* Checks if the given argument is a array.
* @method isArray
* @param {Any} obj
* @return {boolean}
* @static
* @public
*/
public static isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
}
/**
* Checks if the given argument is an object.
* @method isObject
* @param {Any} obj
* @return {boolean}
* @static
* @public
*/
public static isObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
/**
* Reverses a compare function.
* @method <API key>
* @param {Any} compareFunction
* @return {Number}
* @static
* @public
*/
public static <API key>(compareFunction) {
if (!Kiwi.Utils.Common.isFunction(compareFunction))
{
return function (a, b) {
if (a < b)
{
return 1;
}
else if (a === b)
{
return 0;
}
else
{
return -1;
}
};
}
else
{
return function (d, v) {
return compareFunction(d, v) * -1;
};
}
}
/**
* Returns an equal function given a compare function.
* @method compareToEquals
* @param {Any} compareFunction
* @return {boolean}
* @static
* @public
*/
public static compareToEquals(compareFunction) {
return function (a, b) {
return compareFunction(a, b) === 0;
};
}
/**
* Shuffles the contents of an array given into a random order.
* @method shuffleArray
* @param array {Any}
* @return {Any} What you passed but the with the contents in a new order.
* @static
* @public
*/
public static shuffleArray(array) {
for (var i = array.length - 1; i > 0; i
{
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/**
* An array containing all of the base2sizes that are allowed.
* This is used when creating a new TextureAtlas/or resizing a Image to be rendered in WebGL.
* @property base2Sizes
* @type number[]
* @public
* @static
*/
public static base2Sizes: number[] = [2, 4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
public static convertToBase2(image: any): any {
//Get the width/height
var width = image.width;
var height = image.height
//Check to see if the width is base2
if (this.base2Sizes.indexOf(width) == -1) {
var i = 0;
while (width > this.base2Sizes[i]) i++;
width = this.base2Sizes[i];
}
//Check to see if the height is base2
if (this.base2Sizes.indexOf(height) == -1) {
var i = 0;
while (height > this.base2Sizes[i]) i++;
height = this.base2Sizes[i];
}
//If either of them did not have a base2 size then create a canvas and create a new canvas.
if (image.width !== width || image.height !== height) {
//Is it already a canvas?
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
return image;
}
}
}
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html> |
# <API key>
This project was created to streamline tasks test by using Microsoft Test Manager, the idea was taken from a discontinued project (thanks to Dipak Sarma for sharing your code) of some aspects were improved but lack of time I I have given him the right track . I hope you find it useful.
To use this tool needs the VS SDK for 2010-2012 versions of Visual Studio , in the higher versions need install the Nuget Microsoft.<API key>.ExtendedClient instead. |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mod.hrs.view;
import erp.mod.SModConsts;
import java.util.ArrayList;
import sa.lib.SLibConsts;
import sa.lib.db.SDbConsts;
import sa.lib.grid.SGridColumnView;
import sa.lib.grid.SGridConsts;
import sa.lib.grid.SGridPaneSettings;
import sa.lib.grid.SGridPaneView;
import sa.lib.gui.SGuiClient;
/**
*
* @author Juan Barajas
*/
public class SViewMwzTypeWage extends SGridPaneView {
public SViewMwzTypeWage(SGuiClient client, String title) {
super(client, SGridConsts.GRID_PANE_VIEW, SModConsts.HRS_MWZ_WAGE, SLibConsts.UNDEFINED, title);
<API key>(true, true, true, false, true);
}
@Override
public void prepareSqlQuery() {
String sql = "";
Object filter = null;
moPaneSettings = new SGridPaneSettings(2);
moPaneSettings.<API key>(true);
moPaneSettings.<API key>(true);
filter = (Boolean) moFiltersMap.get(SGridConsts.FILTER_DELETED).getValue();
if ((Boolean) filter) {
sql += (sql.isEmpty() ? "" : "AND ") + "v.b_del = 0 ";
}
msSql = "SELECT "
+ "v.id_tp_mwz AS " + SDbConsts.FIELD_ID + "1, "
+ "v.id_wage AS " + SDbConsts.FIELD_ID + "2, "
+ "'' AS " + SDbConsts.FIELD_CODE + ", "
+ "'' AS " + SDbConsts.FIELD_NAME + ", "
+ "v.dt_sta, "
+ "v.wage, "
+ "tmwz.code, "
+ "tmwz.name, "
+ "v.b_del AS " + SDbConsts.FIELD_IS_DEL + ", "
+ "v.fk_usr_ins AS " + SDbConsts.FIELD_USER_INS_ID + ", "
+ "v.fk_usr_upd AS " + SDbConsts.FIELD_USER_UPD_ID + ", "
+ "v.ts_usr_ins AS " + SDbConsts.FIELD_USER_INS_TS + ", "
+ "v.ts_usr_upd AS " + SDbConsts.FIELD_USER_UPD_TS + ", "
+ "ui.usr AS " + SDbConsts.FIELD_USER_INS_NAME + ", "
+ "uu.usr AS " + SDbConsts.FIELD_USER_UPD_NAME + " "
+ "FROM " + SModConsts.TablesMap.get(SModConsts.HRS_MWZ_WAGE) + " AS v "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRSU_TP_MWZ) + " AS tmwz ON "
+ "v.id_tp_mwz = tmwz.id_tp_mwz "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.USRU_USR) + " AS ui ON "
+ "v.fk_usr_ins = ui.id_usr "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.USRU_USR) + " AS uu ON "
+ "v.fk_usr_upd = uu.id_usr "
+ (sql.isEmpty() ? "" : "WHERE " + sql)
+ "ORDER BY v.dt_sta, tmwz.name, v.id_tp_mwz, v.id_wage ";
}
@Override
public ArrayList<SGridColumnView> createGridColumns() {
ArrayList<SGridColumnView> gridColumnsViews = new ArrayList<>();
gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "v.dt_sta", "Inicio vigencia"));
gridColumnsViews.add(new SGridColumnView(SGridConsts.<API key>, "tmwz.name", "Área geográfica"));
gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "v.wage", "Salario mínimo"));
gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_S, SDbConsts.FIELD_IS_DEL, SGridConsts.COL_TITLE_IS_DEL));
gridColumnsViews.add(new SGridColumnView(SGridConsts.<API key>, SDbConsts.FIELD_USER_INS_NAME, SGridConsts.<API key>));
gridColumnsViews.add(new SGridColumnView(SGridConsts.<API key>, SDbConsts.FIELD_USER_INS_TS, SGridConsts.<API key>));
gridColumnsViews.add(new SGridColumnView(SGridConsts.<API key>, SDbConsts.FIELD_USER_UPD_NAME, SGridConsts.<API key>));
gridColumnsViews.add(new SGridColumnView(SGridConsts.<API key>, SDbConsts.FIELD_USER_UPD_TS, SGridConsts.<API key>));
return gridColumnsViews;
}
@Override
public void defineSuscriptions() {
moSuscriptionsSet.add(mnGridType);
moSuscriptionsSet.add(SModConsts.HRSU_TP_WRK);
moSuscriptionsSet.add(SModConsts.USRU_USR);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Documentation - Scope of Work</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<!-- 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="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">Documentation</a></li>
<li><a href="#">Scope of Work</a></li>
<li><a href="persona.html">Persona</a></li>
<li><a href="flowchart.html">Scenario</a></li>
<li><a href="wireframe.html">Wireframe</a></li>
<li><a href="graphics.html">Graphics</a></li>
<li><a href="mockup.html">Mock Up</a></li>
<li><a href="https://marisade.github.io/AmandaSite/">Final Project</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="<API key>">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<h1>Scope of Work</h1>
<p>This is the documentation site for the final project.</p>
<p><strong>Project Title</strong>: Animation Portfolio</p>
<p><strong>Brief Description</strong>: My client needs a website that will showcase her animation and artwork in an innovative and perhaps interactive way so that it stands out from her peers. It will include minimal text.</p>
<p><strong>Target Audience</strong> - The audience is a producer or creative art director of a company looking to hire a storyboard artist. This person has experience managing people and has been in the art industry for a while. They think they've seen everything so they really need something innovative to grab their attention and even devote time to look at an applicant's portfolio. They have been in the field for a least a few years so they know what they want and what they don't want.</p>
<p><strong>Client</strong>: Amanda DePasquale</p>
<p> </p>
<center><h2>Business Card</h2></center>
<center><img src="bcard.png"><br><br><br></center>
<p> </p>
<a href="#menu-toggle" class="btn btn-default" id="menu-toggle">Toggle Menu</a>
</div>
</div>
</div>
</div>
<!-- /#<API key> -->
</div>
<p><!-- /#wrapper -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Menu Toggle Script --></p>
<script>
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
</script>
</body>
</html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.