repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
doasync/eslint-config-airbnb-standard | example.js | 1250 | import {Component} from 'react'
export class Greeter {
constructor (message) {
this.greeting = message;
}
greetFrom (...names) {
let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase());
return "Hello, " + this.greeting + " from " + suffix;
}
greetNTimes ({name, times}) {
let greeting = this.greetFrom(name);
for (let i = 0; i < times; i++) {
console.log(greeting)
}
}
}
new Greeter("foo").greetNTimes({name: "Webstorm", times: 3})
function foo (x, y, z) {
var i = 0;
var x = {0: "zero", 1: "one"};
var a = [0, 1, 2];
var foo = function () {
}
var asyncFoo = async (x, y, z) => {
}
var v = x.map(s => s.length);
if (!i > 10) {
for (var j = 0; j < 10; j++) {
switch (j) {
case 0:
value = "zero";
break;
case 1:
value = "one";
break;
}
var c = j > 5 ? "GT 5" : "LE 5";
}
} else {
var j = 0;
try {
while (j < 10) {
if (i == j || j > 5) {
a[j] = i + j * 12;
}
i = (j << 2) & 4;
j++;
}
do {
j--;
} while (j > 0)
} catch (e) {
alert("Failure: " + e.message);
} finally {
reset(a, i);
}
}
}
| mit |
afzalbk/Dynamic_Table | demos/data-manipulation.html | 5917 | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>jsGrid - Data Manipulation</title>
<link rel="stylesheet" type="text/css" href="demos.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="../css/jsgrid.css" />
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="db.js"></script>
<script src="../src/jsgrid.core.js"></script>
<script src="../src/jsgrid.load-indicator.js"></script>
<script src="../src/jsgrid.load-strategies.js"></script>
<script src="../src/jsgrid.sort-strategies.js"></script>
<script src="../src/jsgrid.field.js"></script>
<script src="../src/jsgrid.field.text.js"></script>
<script src="../src/jsgrid.field.number.js"></script>
<script src="../src/jsgrid.field.select.js"></script>
<script src="../src/jsgrid.field.checkbox.js"></script>
<script src="../src/jsgrid.field.control.js"></script>
<style>
.details-form-field input,
.details-form-field select {
width: 250px;
float: right;
}
.details-form-field {
margin: 15px 0;
}
.ui-widget *, .ui-widget input, .ui-widget select, .ui-widget button {
font-family: 'Helvetica Neue Light', 'Open Sans', Helvetica;
font-size: 14px;
font-weight: 300 !important;
}
</style>
</head>
<body>
<h1>Data Manipulation</h1>
<div id="jsGrid"></div>
<div id="detailsForm">
<div class="details-form-field">
<label>Name: <input id="name" type="text" /></label>
</div>
<div class="details-form-field">
<label>Age: <input id="age" type="number" /></label>
</div>
<div class="details-form-field">
<label>Address: <input id="address" type="text" /></label>
</div>
<div class="details-form-field">
<label>Country:
<select id="country">
<option value="0">(Select)</option>
<option value="1">United States</option>
<option value="2">Canada</option>
<option value="3">United Kingdom</option>
<option value="4">France</option>
<option value="5">Brazil</option>
<option value="6">China</option>
<option value="7">Russia</option>
</select>
</label>
</div>
<div class="details-form-field">
<label>Is Married: <input id="married" type="checkbox" /></label>
</div>
<div class="details-form-field">
<button type="button" id="save">Save</button>
</div>
</div>
<script>
$(function() {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
editing: true,
autoload: true,
paging: true,
deleteConfirm: function(item) {
return "The client \"" + item.Name + "\" will be removed. Are you sure?";
},
rowClick: function(args) {
showDetailsDialog("Edit", args.item);
},
controller: db,
fields: [
{ name: "Name", type: "text", width: 150 },
{ name: "Age", type: "number", width: 50 },
{ name: "Address", type: "text", width: 200 },
{ name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{
type: "control",
modeSwitchButton: false,
editButton: false,
headerTemplate: function() {
return $("<button>").attr("type", "button").text("Add")
.on("click", function () {
showDetailsDialog("Add", {});
});
}
}
]
});
$("#detailsForm").dialog({
autoOpen: false,
width: 400
});
var showDetailsDialog = function(dialogType, client) {
$("#name").val(client.Name);
$("#age").val(client.Age);
$("#address").val(client.Address);
$("#country").val(client.Country);
$("#married").prop("checked", client.Married);
$("#save").off("click").on("click", function() {
saveClient(client, dialogType === "Add");
});
$("#detailsForm").dialog("option", "title", dialogType + " Client")
.dialog("open");
};
var saveClient = function(client, isNew) {
$.extend(client, {
Name: $("#name").val(),
Age: parseInt($("#age").val(), 10),
Address: $("#address").val(),
Country: parseInt($("#country").val(), 10),
Married: $("#married").is(":checked")
});
$("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client);
$("#detailsForm").dialog("close");
};
});
</script>
</body>
</html>
| mit |
stealthylabs/teatime | teatime.c | 19398 | /*
* COPYRIGHT: Stealthy Labs LLC
* DATE: 29th May 2015
* AUTHOR: Stealthy Labs
* SOFTWARE: Tea Time
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <teatime.h>
static int teatime_check_gl_version(uint32_t *major, uint32_t *minor);
static int teatime_check_program_errors(GLuint program);
static int teatime_check_shader_errors(GLuint shader);
#define TEATIME_BREAKONERROR(FN,RC) if ((RC = teatime_check_gl_errors(__LINE__, #FN )) < 0) break
#define TEATIME_BREAKONERROR_FB(FN,RC) if ((RC = teatime_check_gl_fb_errors(__LINE__, #FN )) < 0) break
teatime_t *teatime_setup()
{
int rc = 0;
teatime_t *obj = calloc(1, sizeof(teatime_t));
if (!obj) {
fprintf(stderr, "Out of memory allocating %zu bytes\n",
sizeof(teatime_t));
return NULL;
}
do {
uint32_t version[2] = { 0, 0};
if (teatime_check_gl_version(&version[0], &version[1]) < 0) {
fprintf(stderr, "Unable to verify OpenGL version\n");
rc = -1;
break;
}
if (version[0] < 3) {
fprintf(stderr, "Minimum Required OpenGL version 3.0. You have %u.%u\n",
version[0], version[1]);
rc = -1;
break;
}
/* initialize off-screen framebuffer */
/*
* This is the EXT_framebuffer_object OpenGL extension that allows us to
* use an offscreen buffer as a target for rendering operations such as
* vector calculations, providing full precision and removing unwanted
* clamping issues.
* we are turning off the traditional framebuffer here apparently.
*/
glGenFramebuffersEXT(1, &(obj->ofb));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, obj->ofb);
TEATIME_BREAKONERROR(glBindFramebufferEXT, rc);
fprintf(stderr, "Successfully created off-screen framebuffer with id: %d\n",
obj->ofb);
/* get the texture size */
obj->maxtexsz = -1;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &(obj->maxtexsz));
fprintf(stderr, "Maximum Texture size for the GPU: %d\n", obj->maxtexsz);
obj->itexid = obj->otexid = 0;
obj->shader = obj->program = 0;
} while (0);
if (rc < 0) {
teatime_cleanup(obj);
obj = NULL;
}
return obj;
}
void teatime_cleanup(teatime_t *obj)
{
if (obj) {
teatime_delete_program(obj);
teatime_delete_textures(obj);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glDeleteFramebuffersEXT(1, &(obj->ofb));
glFlush();
free(obj);
obj = NULL;
}
}
int teatime_set_viewport(teatime_t *obj, uint32_t ilen)
{
uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0)));
if (obj && texsz > 0 && texsz < (GLuint)obj->maxtexsz) {
/* viewport mapping 1:1 pixel = texel = data mapping */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, texsz, 0.0, texsz);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, texsz, texsz);
obj->tex_size = texsz;
fprintf(stderr, "Texture size: %u x %u\n", texsz, texsz);
return 0;
} else if (obj) {
fprintf(stderr, "Max. texture size is %d. Calculated: %u from input length: %u\n",
obj->maxtexsz, texsz, ilen);
}
return -EINVAL;
}
int teatime_create_textures(teatime_t *obj, const uint32_t *input, uint32_t ilen)
{
if (obj && input && ilen > 0) {
int rc = 0;
do {
uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0)));
if (texsz != obj->tex_size) {
fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n",
obj->tex_size, texsz);
rc = -EINVAL;
break;
}
glGenTextures(1, &(obj->itexid));
glGenTextures(1, &(obj->otexid));
fprintf(stderr, "Created input texture with ID: %u\n", obj->itexid);
fprintf(stderr, "Created output texture with ID: %u\n", obj->otexid);
/** BIND ONE TEXTURE AT A TIME **/
/* the texture target can vary depending on GPU */
glBindTexture(GL_TEXTURE_2D, obj->itexid);
TEATIME_BREAKONERROR(glBindTexture, rc);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
/* turn off filtering and set proper wrap mode - this is obligatory for
* floating point textures */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
TEATIME_BREAKONERROR(glTexParameteri, rc);
/* create a 2D texture of the same size as the data
* internal format: GL_RGBA32UI_EXT
* texture format: GL_RGBA_INTEGER
* texture type: GL_UNSIGNED_INT
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT,
texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL);
TEATIME_BREAKONERROR(glTexImage2D, rc);
/* transfer data to texture */
#ifdef WIN32
glTexSubImage2D
#else
glTexSubImage2DEXT
#endif
(GL_TEXTURE_2D, 0, 0, 0, obj->tex_size,
obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, input);
#ifdef WIN32
TEATIME_BREAKONERROR(glTexSubImage2D, rc);
#else
TEATIME_BREAKONERROR(glTexSubImage2DEXT, rc);
#endif
fprintf(stderr, "Successfully transferred input data to texture ID: %u\n", obj->itexid);
/* BIND the OUTPUT texture and work on it */
/* the texture target can vary depending on GPU */
glBindTexture(GL_TEXTURE_2D, obj->otexid);
TEATIME_BREAKONERROR(glBindTexture, rc);
/* turn off filtering and set proper wrap mode - this is obligatory for
* floating point textures */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
TEATIME_BREAKONERROR(glTexParameteri, rc);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
TEATIME_BREAKONERROR(glTexParameteri, rc);
/* create a 2D texture of the same size as the data
* internal format: GL_RGBA32UI_EXT
* texture format: GL_RGBA_INTEGER
* texture type: GL_UNSIGNED_INT
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT,
texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL);
TEATIME_BREAKONERROR(glTexImage2D, rc);
/* change tex-env to replace instead of the default modulate */
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
TEATIME_BREAKONERROR(glTexEnvi, rc);
/* attach texture */
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D, obj->otexid, 0);
TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc);
TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc);
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
TEATIME_BREAKONERROR(glDrawBuffer, rc);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT,
GL_TEXTURE_2D, obj->otexid, 0);
TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc);
TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc);
rc = 0;
} while (0);
return rc;
}
return -EINVAL;
}
int teatime_read_textures(teatime_t *obj, uint32_t *output, uint32_t olen)
{
if (obj && output && olen > 0 && obj->otexid > 0) {
int rc = 0;
do {
uint32_t texsz = (uint32_t)((long)(sqrt(olen / 4.0)));
if (texsz != obj->tex_size) {
fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n",
obj->tex_size, texsz);
rc = -EINVAL;
break;
}
/* read the texture back */
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
TEATIME_BREAKONERROR(glReadBuffer, rc);
glReadPixels(0, 0, obj->tex_size, obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, output);
TEATIME_BREAKONERROR(glReadPixels, rc);
fprintf(stderr, "Successfully read data from the texture\n");
} while (0);
return rc;
}
return -EINVAL;
}
int teatime_create_program(teatime_t *obj, const char *source)
{
if (obj && source) {
int rc = 0;
do {
obj->program = glCreateProgram();
TEATIME_BREAKONERROR(glCreateProgram, rc);
obj->shader = glCreateShader(GL_FRAGMENT_SHADER_ARB);
TEATIME_BREAKONERROR(glCreateShader, rc);
glShaderSource(obj->shader, 1, &source, NULL);
TEATIME_BREAKONERROR(glShaderSource, rc);
glCompileShader(obj->shader);
rc = teatime_check_shader_errors(obj->shader);
if (rc < 0) break;
TEATIME_BREAKONERROR(glCompileShader, rc);
glAttachShader(obj->program, obj->shader);
TEATIME_BREAKONERROR(glAttachShader, rc);
glLinkProgram(obj->program);
rc = teatime_check_program_errors(obj->program);
if (rc < 0) break;
TEATIME_BREAKONERROR(glLinkProgram, rc);
obj->locn_input = glGetUniformLocation(obj->program, "idata");
TEATIME_BREAKONERROR(glGetUniformLocation, rc);
obj->locn_output = glGetUniformLocation(obj->program, "odata");
TEATIME_BREAKONERROR(glGetUniformLocation, rc);
obj->locn_key = glGetUniformLocation(obj->program, "ikey");
TEATIME_BREAKONERROR(glGetUniformLocation, rc);
obj->locn_rounds = glGetUniformLocation(obj->program, "rounds");
TEATIME_BREAKONERROR(glGetUniformLocation, rc);
rc = 0;
} while (0);
return rc;
}
return -EINVAL;
}
int teatime_run_program(teatime_t *obj, const uint32_t ikey[4], uint32_t rounds)
{
if (obj && obj->program > 0) {
int rc = 0;
do {
glUseProgram(obj->program);
TEATIME_BREAKONERROR(glUseProgram, rc);
glActiveTexture(GL_TEXTURE0);
TEATIME_BREAKONERROR(glActiveTexture, rc);
glBindTexture(GL_TEXTURE_2D, obj->itexid);
TEATIME_BREAKONERROR(glBindTexture, rc);
glUniform1i(obj->locn_input, 0);
TEATIME_BREAKONERROR(glUniform1i, rc);
glActiveTexture(GL_TEXTURE1);
TEATIME_BREAKONERROR(glActiveTexture, rc);
glBindTexture(GL_TEXTURE_2D, obj->otexid);
TEATIME_BREAKONERROR(glBindTexture, rc);
glUniform1i(obj->locn_output, 1);
TEATIME_BREAKONERROR(glUniform1i, rc);
glUniform4uiv(obj->locn_key, 1, ikey);
TEATIME_BREAKONERROR(glUniform1uiv, rc);
glUniform1ui(obj->locn_rounds, rounds);
TEATIME_BREAKONERROR(glUniform1ui, rc);
glFinish();
glPolygonMode(GL_FRONT, GL_FILL);
/* render */
glBegin(GL_QUADS);
glTexCoord2i(0, 0);
glVertex2i(0, 0);
//glTexCoord2i(obj->tex_size, 0);
glTexCoord2i(1, 0);
glVertex2i(obj->tex_size, 0);
//glTexCoord2i(obj->tex_size, obj->tex_size);
glTexCoord2i(1, 1);
glVertex2i(obj->tex_size, obj->tex_size);
glTexCoord2i(0, 1);
//glTexCoord2i(0, obj->tex_size);
glVertex2i(0, obj->tex_size);
glEnd();
glFinish();
TEATIME_BREAKONERROR_FB(Rendering, rc);
TEATIME_BREAKONERROR(Rendering, rc);
rc = 0;
} while (0);
return rc;
}
return -EINVAL;
}
void teatime_delete_textures(teatime_t *obj)
{
if (obj) {
if (obj->itexid != 0) {
glDeleteTextures(1, &(obj->itexid));
obj->itexid = 0;
}
if (obj->otexid != 0) {
glDeleteTextures(1, &(obj->otexid));
obj->otexid = 0;
}
}
}
void teatime_delete_program(teatime_t *obj)
{
if (obj) {
if (obj->shader > 0 && obj->program > 0) {
glDetachShader(obj->program, obj->shader);
}
if (obj->shader > 0)
glDeleteShader(obj->shader);
if (obj->program > 0)
glDeleteProgram(obj->program);
obj->shader = 0;
obj->program = 0;
}
}
void teatime_print_version(FILE *fp)
{
const GLubyte *version = NULL;
version = glGetString(GL_VERSION);
fprintf(fp, "GL Version: %s\n", (const char *)version);
version = glGetString(GL_SHADING_LANGUAGE_VERSION);
fprintf(fp, "GLSL Version: %s\n", (const char *)version);
version = glGetString(GL_VENDOR);
fprintf(fp, "GL Vendor: %s\n", (const char *)version);
}
int teatime_check_gl_version(uint32_t *major, uint32_t *minor)
{
const GLubyte *version = NULL;
version = glGetString(GL_VERSION);
if (version) {
uint32_t ver[2] = { 0, 0 };
char *endp = NULL;
char *endp2 = NULL;
errno = 0;
ver[0] = strtol((const char *)version, &endp, 10);
if (errno == ERANGE || (const void *)endp == (const void *)version) {
fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version);
return -1;
}
/* endp[0] = '.' and endp[1] points to minor */
errno = 0;
ver[1] = strtol((const char *)&endp[1], &endp2, 10);
if (errno == ERANGE || endp2 == &endp[1]) {
fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version);
return -1;
}
if (major)
*major = ver[0];
if (minor)
*minor = ver[1];
return 0;
}
return -1;
}
int teatime_check_gl_errors(int line, const char *fn_name)
{
GLenum err = glGetError();
if (err != GL_NO_ERROR) {
const GLubyte *estr = gluErrorString(err);
fprintf(stderr, "%s(): GL Error(%d) on line %d: %s\n", fn_name,
err, line, (const char *)estr);
return -1;
}
return 0;
}
int teatime_check_gl_fb_errors(int line, const char *fn_name)
{
GLenum st = (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch (st) {
case GL_FRAMEBUFFER_COMPLETE_EXT:
return 0;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete attachment\n", fn_name, line);
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: unsupported\n", fn_name, line);
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete missing attachment\n", fn_name, line);
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete dimensions\n", fn_name, line);
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete formats\n", fn_name, line);
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete draw buffer\n", fn_name, line);
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
fprintf(stderr, "%s(): GL FB error on line %d: incomplete read buffer\n", fn_name, line);
break;
default:
fprintf(stderr, "%s(): GL FB error on line %d: Unknown. Error Value: %d\n", fn_name, line, st);
break;
}
return -1;
}
int teatime_check_program_errors(GLuint program)
{
GLint ilen = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &ilen);
if (ilen > 1) {
GLsizei wb = 0;
GLchar *buf = calloc(ilen, sizeof(GLchar));
if (!buf) {
fprintf(stderr, "Out of memory allocating %d bytes\n", ilen);
return -ENOMEM;
}
glGetProgramInfoLog(program, ilen, &wb, buf);
buf[wb] = '\0';
fprintf(stderr, "Program Errors:\n%s\n",
(const char *)buf);
free(buf);
}
return 0;
}
int teatime_check_shader_errors(GLuint shader)
{
GLint ilen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &ilen);
if (ilen > 1) {
GLsizei wb = 0;
GLchar *buf = calloc(ilen, sizeof(GLchar));
if (!buf) {
fprintf(stderr, "Out of memory allocating %d bytes\n", ilen);
return -ENOMEM;
}
glGetShaderInfoLog(shader, ilen, &wb, buf);
buf[wb] = '\0';
fprintf(stderr, "Shader Errors:\n%s\n",
(const char *)buf);
free(buf);
}
return 0;
}
#define TEA_ENCRYPT_SOURCE \
"#version 130\n" \
"#extension GL_EXT_gpu_shader4 : enable\n" \
"uniform usampler2D idata;\n" \
"uniform uvec4 ikey; \n" \
"uniform uint rounds; \n" \
"out uvec4 odata; \n" \
"void main(void) {\n" \
" uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \
" uint delta = uint(0x9e3779b9); \n" \
" uint sum = uint(0); \n" \
" for (uint i = uint(0); i < rounds; ++i) {\n" \
" sum += delta; \n" \
" x[0] += (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \
" x[1] += (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \
" x[2] += (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \
" x[3] += (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \
" }\n" \
" odata = x; \n" \
"}\n"
#define TEA_DECRYPT_SOURCE \
"#version 130\n" \
"#extension GL_EXT_gpu_shader4 : enable\n" \
"uniform usampler2D idata;\n" \
"uniform uvec4 ikey; \n" \
"uniform uint rounds; \n" \
"out uvec4 odata; \n" \
"void main(void) {\n" \
" uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \
" uint delta = uint(0x9e3779b9); \n" \
" uint sum = delta * rounds; \n" \
" for (uint i = uint(0); i < rounds; ++i) {\n" \
" x[1] -= (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \
" x[0] -= (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \
" x[3] -= (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \
" x[2] -= (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \
" sum -= delta; \n" \
" }\n" \
" odata = x; \n" \
"}\n"
const char *teatime_encrypt_source()
{
return TEA_ENCRYPT_SOURCE;
}
const char *teatime_decrypt_source()
{
return TEA_DECRYPT_SOURCE;
}
| mit |
vts-group/sat-lista-negra | db/migrate/20170506210330_create_lists.rb | 234 | class CreateLists < ActiveRecord::Migration[5.1]
def change
create_table :lists do |t|
t.string :letter
t.string :tax_reference
t.string :list_type
t.date :date_list
t.timestamps
end
end
end
| mit |
dwrensha/groovebasin | lib/player.js | 88399 | var groove = require('groove');
var semver = require('semver');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var mkdirp = require('mkdirp');
var fs = require('fs');
var uuid = require('./uuid');
var path = require('path');
var Pend = require('pend');
var DedupedQueue = require('./deduped_queue');
var findit = require('findit2');
var shuffle = require('mess');
var mv = require('mv');
var MusicLibraryIndex = require('music-library-index');
var keese = require('keese');
var safePath = require('./safe_path');
var PassThrough = require('stream').PassThrough;
var url = require('url');
var dbIterate = require('./db_iterate');
var log = require('./log');
var importUrlFilters = require('./import_url_filters');
var youtubeSearch = require('./youtube_search');
var yauzl = require('yauzl');
var importFileFilters = [
{
name: 'zip',
fn: importFileAsZip,
},
{
name: 'song',
fn: importFileAsSong,
},
];
module.exports = Player;
ensureGrooveVersionIsOk();
var cpuCount = 1;
var PLAYER_KEY_PREFIX = "Player.";
var LIBRARY_KEY_PREFIX = "Library.";
var LIBRARY_DIR_PREFIX = "LibraryDir.";
var QUEUE_KEY_PREFIX = "Playlist.";
var PLAYLIST_KEY_PREFIX = "StoredPlaylist.";
var LABEL_KEY_PREFIX = "Label.";
var PLAYLIST_META_KEY_PREFIX = "StoredPlaylistMeta.";
// db: store in the DB
var DB_PROPS = {
key: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'string',
},
name: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
artistName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
albumArtistName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
albumName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
compilation: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'boolean',
},
track: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
trackCount: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
disc: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
discCount: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
duration: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'float',
},
year: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
genre: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
file: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'string',
},
mtime: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'integer',
},
replayGainAlbumGain: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainAlbumPeak: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainTrackGain: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainTrackPeak: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
composerName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
performerName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
lastQueueDate: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'date',
},
fingerprint: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'array_of_integer',
},
playCount: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'integer',
},
labels: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'set',
},
};
var PROP_TYPE_PARSERS = {
'string': function(value) {
return value ? String(value) : "";
},
'date': function(value) {
if (!value) return null;
var date = new Date(value);
if (isNaN(date.getTime())) return null;
return date;
},
'integer': parseIntOrNull,
'float': parseFloatOrNull,
'boolean': function(value) {
return value == null ? null : !!value;
},
'array_of_integer': function(value) {
if (!Array.isArray(value)) return null;
value = value.map(parseIntOrNull);
for (var i = 0; i < value.length; i++) {
if (value[i] == null) return null;
}
return value;
},
'set': function(value) {
var result = {};
for (var key in value) {
result[key] = 1;
}
return result;
},
};
var labelColors = [
"#e11d21", "#eb6420", "#fbca04", "#009800",
"#006b75", "#207de5", "#0052cc", "#5319e7",
"#f7c6c7", "#fad8c7", "#fef2c0", "#bfe5bf",
"#bfdadc", "#bfd4f2", "#c7def8", "#d4c5f9",
];
// how many GrooveFiles to keep open, ready to be decoded
var OPEN_FILE_COUNT = 8;
var PREV_FILE_COUNT = Math.floor(OPEN_FILE_COUNT / 2);
var NEXT_FILE_COUNT = OPEN_FILE_COUNT - PREV_FILE_COUNT;
var DB_SCALE = Math.log(10.0) * 0.05;
var REPLAYGAIN_PREAMP = 0.75;
var REPLAYGAIN_DEFAULT = 0.25;
Player.REPEAT_OFF = 0;
Player.REPEAT_ALL = 1;
Player.REPEAT_ONE = 2;
Player.trackWithoutIndex = trackWithoutIndex;
Player.setGrooveLoggingLevel = setGrooveLoggingLevel;
util.inherits(Player, EventEmitter);
function Player(db, config) {
EventEmitter.call(this);
this.setMaxListeners(0);
this.db = db;
this.musicDirectory = config.musicDirectory;
this.dbFilesByPath = {};
this.dbFilesByLabel = {};
this.libraryIndex = new MusicLibraryIndex({
searchFields: MusicLibraryIndex.defaultSearchFields.concat('file'),
});
this.addQueue = new DedupedQueue({
processOne: this.addToLibrary.bind(this),
// limit to 1 async operation because we're blocking on the hard drive,
// it's faster to read one file at a time.
maxAsync: 1,
});
this.dirs = {};
this.dirScanQueue = new DedupedQueue({
processOne: this.refreshFilesIndex.bind(this),
// only 1 dir scanning can happen at a time
// we'll pass the dir to scan as the ID so that not more than 1 of the
// same dir can queue up
maxAsync: 1,
});
this.dirScanQueue.on('error', function(err) {
log.error("library scanning error:", err.stack);
});
this.disableFsRefCount = 0;
this.playlist = {};
this.playlists = {};
this.currentTrack = null;
this.tracksInOrder = []; // another way to look at playlist
this.grooveItems = {}; // maps groove item id to track
this.seekRequestPos = -1; // set to >= 0 when we want to seek
this.invalidPaths = {}; // files that could not be opened
this.playlistItemDeleteQueue = [];
this.dontBelieveTheEndOfPlaylistSentinelItsATrap = false;
this.queueClearEncodedBuffers = false;
this.repeat = Player.REPEAT_OFF;
this.desiredPlayerHardwareState = null; // true: normal hardware playback. false: dummy
this.pendingPlayerAttachDetach = null;
this.isPlaying = false;
this.trackStartDate = null;
this.pausedTime = 0;
this.autoDjOn = false;
this.autoDjHistorySize = 10;
this.autoDjFutureSize = 10;
this.ongoingScans = {};
this.scanQueue = new DedupedQueue({
processOne: this.performScan.bind(this),
maxAsync: cpuCount,
});
this.headerBuffers = [];
this.recentBuffers = [];
this.newHeaderBuffers = [];
this.openStreamers = [];
this.expectHeaders = true;
// when a streaming client connects we send them many buffers quickly
// in order to get the stream started, then we slow down.
this.encodeQueueDuration = config.encodeQueueDuration;
this.groovePlaylist = groove.createPlaylist();
this.groovePlayer = null;
this.grooveEncoder = groove.createEncoder();
this.grooveEncoder.encodedBufferSize = 128 * 1024;
this.detachEncoderTimeout = null;
this.pendingEncoderAttachDetach = false;
this.desiredEncoderAttachState = false;
this.flushEncodedInterval = null;
this.groovePlaylist.pause();
this.volume = this.groovePlaylist.gain;
this.grooveEncoder.formatShortName = "mp3";
this.grooveEncoder.codecShortName = "mp3";
this.grooveEncoder.bitRate = config.encodeBitRate * 1000;
this.importProgress = {};
this.lastImportProgressEvent = new Date();
// tracking playCount
this.previousIsPlaying = false;
this.playingStart = new Date();
this.playingTime = 0;
this.lastPlayingItem = null;
this.googleApiKey = config.googleApiKey;
this.ignoreExtensions = config.ignoreExtensions.map(makeLower);
}
Player.prototype.initialize = function(cb) {
var self = this;
var startupTrackInfo = null;
initLibrary(function(err) {
if (err) return cb(err);
cacheTracksArray(self);
self.requestUpdateDb();
cacheAllOptions(function(err) {
if (err) return cb(err);
setInterval(doPersistCurrentTrack, 10000);
if (startupTrackInfo) {
self.seek(startupTrackInfo.id, startupTrackInfo.pos);
} else {
playlistChanged(self);
}
lazyReplayGainScanPlaylist(self);
cb();
});
});
function initLibrary(cb) {
var pend = new Pend();
pend.go(cacheAllDb);
pend.go(cacheAllDirs);
pend.go(cacheAllQueue);
pend.go(cacheAllPlaylists);
pend.go(cacheAllLabels);
pend.wait(cb);
}
function cacheAllPlaylists(cb) {
cacheAllPlaylistMeta(function(err) {
if (err) return cb(err);
cacheAllPlaylistItems(cb);
});
function cacheAllPlaylistMeta(cb) {
dbIterate(self.db, PLAYLIST_META_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var playlist = deserializePlaylist(value);
self.playlists[playlist.id] = playlist;
}
}
function cacheAllPlaylistItems(cb) {
dbIterate(self.db, PLAYLIST_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var playlistIdEnd = key.indexOf('.', PLAYLIST_KEY_PREFIX.length);
var playlistId = key.substring(PLAYLIST_KEY_PREFIX.length, playlistIdEnd);
var playlistItem = JSON.parse(value);
self.playlists[playlistId].items[playlistItem.id] = playlistItem;
}
}
}
function cacheAllLabels(cb) {
dbIterate(self.db, LABEL_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var labelId = key.substring(LABEL_KEY_PREFIX.length);
var labelEntry = JSON.parse(value);
self.libraryIndex.addLabel(labelEntry);
}
}
function cacheAllQueue(cb) {
dbIterate(self.db, QUEUE_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var plEntry = JSON.parse(value);
self.playlist[plEntry.id] = plEntry;
}
}
function cacheAllOptions(cb) {
var options = {
repeat: null,
autoDjOn: null,
autoDjHistorySize: null,
autoDjFutureSize: null,
hardwarePlayback: null,
volume: null,
currentTrackInfo: null,
};
var pend = new Pend();
for (var name in options) {
pend.go(makeGetFn(name));
}
pend.wait(function(err) {
if (err) return cb(err);
if (options.repeat != null) {
self.setRepeat(options.repeat);
}
if (options.autoDjOn != null) {
self.setAutoDjOn(options.autoDjOn);
}
if (options.autoDjHistorySize != null) {
self.setAutoDjHistorySize(options.autoDjHistorySize);
}
if (options.autoDjFutureSize != null) {
self.setAutoDjFutureSize(options.autoDjFutureSize);
}
if (options.volume != null) {
self.setVolume(options.volume);
}
startupTrackInfo = options.currentTrackInfo;
var hardwarePlaybackValue = options.hardwarePlayback == null ? true : options.hardwarePlayback;
// start the hardware player first
// fall back to dummy
self.setHardwarePlayback(hardwarePlaybackValue, function(err) {
if (err) {
log.error("Unable to attach hardware player, falling back to dummy.", err.stack);
self.setHardwarePlayback(false);
}
cb();
});
});
function makeGetFn(name) {
return function(cb) {
self.db.get(PLAYER_KEY_PREFIX + name, function(err, value) {
if (!err && value != null) {
try {
options[name] = JSON.parse(value);
} catch (err) {
cb(err);
return;
}
}
cb();
});
};
}
}
function cacheAllDirs(cb) {
dbIterate(self.db, LIBRARY_DIR_PREFIX, processOne, cb);
function processOne(key, value) {
var dirEntry = JSON.parse(value);
self.dirs[dirEntry.dirName] = dirEntry;
}
}
function cacheAllDb(cb) {
var scrubCmds = [];
dbIterate(self.db, LIBRARY_KEY_PREFIX, processOne, scrubAndCb);
function processOne(key, value) {
var dbFile = deserializeFileData(value);
// scrub duplicates
if (self.dbFilesByPath[dbFile.file]) {
scrubCmds.push({type: 'del', key: key});
} else {
self.libraryIndex.addTrack(dbFile);
self.dbFilesByPath[dbFile.file] = dbFile;
for (var labelId in dbFile.labels) {
var files = self.dbFilesByLabel[labelId];
if (files == null) files = self.dbFilesByLabel[labelId] = {};
files[dbFile.key] = dbFile;
}
}
}
function scrubAndCb() {
if (scrubCmds.length === 0) return cb();
log.warn("Scrubbing " + scrubCmds.length + " duplicate db entries");
self.db.batch(scrubCmds, function(err) {
if (err) log.error("Unable to scrub duplicate tracks from db:", err.stack);
cb();
});
}
}
function doPersistCurrentTrack() {
if (self.isPlaying) {
self.persistCurrentTrack();
}
}
};
function startEncoderAttach(self, cb) {
if (self.desiredEncoderAttachState) return;
self.desiredEncoderAttachState = true;
if (self.pendingEncoderAttachDetach) return;
self.pendingEncoderAttachDetach = true;
self.grooveEncoder.attach(self.groovePlaylist, function(err) {
self.pendingEncoderAttachDetach = false;
if (err) {
self.desiredEncoderAttachState = false;
cb(err);
} else if (!self.desiredEncoderAttachState) {
startEncoderDetach(self, cb);
}
});
}
function startEncoderDetach(self, cb) {
if (!self.desiredEncoderAttachState) return;
self.desiredEncoderAttachState = false;
if (self.pendingEncoderAttachDetach) return;
self.pendingEncoderAttachDetach = true;
self.grooveEncoder.detach(function(err) {
self.pendingEncoderAttachDetach = false;
if (err) {
self.desiredEncoderAttachState = true;
cb(err);
} else if (self.desiredEncoderAttachState) {
startEncoderAttach(self, cb);
}
});
}
Player.prototype.getBufferedSeconds = function() {
if (this.recentBuffers.length < 2) return 0;
var firstPts = this.recentBuffers[0].pts;
var lastPts = this.recentBuffers[this.recentBuffers.length - 1].pts;
var frameCount = lastPts - firstPts;
var sampleRate = this.grooveEncoder.actualAudioFormat.sampleRate;
return frameCount / sampleRate;
};
Player.prototype.attachEncoder = function(cb) {
var self = this;
cb = cb || logIfError;
if (self.flushEncodedInterval) return cb();
log.debug("first streamer connected - attaching encoder");
self.flushEncodedInterval = setInterval(flushEncoded, 100);
startEncoderAttach(self, cb);
function flushEncoded() {
if (!self.desiredEncoderAttachState || self.pendingEncoderAttachDetach) return;
var playHead = self.groovePlayer.position();
if (!playHead.item) return;
var plItems = self.groovePlaylist.items();
// get rid of old items
var buf;
while (buf = self.recentBuffers[0]) {
/*
log.debug(" buf.item " + buf.item.file.filename + "\n" +
"playHead.item " + playHead.item.file.filename + "\n" +
" playHead.pos " + playHead.pos + "\n" +
" buf.pos " + buf.pos);
*/
if (isBufOld(buf)) {
self.recentBuffers.shift();
} else {
break;
}
}
// poll the encoder for more buffers until either there are no buffers
// available or we get enough buffered
while (self.getBufferedSeconds() < self.encodeQueueDuration) {
buf = self.grooveEncoder.getBuffer();
if (!buf) break;
if (buf.buffer) {
if (buf.item) {
if (self.expectHeaders) {
log.debug("encoder: got first non-header");
self.headerBuffers = self.newHeaderBuffers;
self.newHeaderBuffers = [];
self.expectHeaders = false;
}
self.recentBuffers.push(buf);
for (var i = 0; i < self.openStreamers.length; i += 1) {
self.openStreamers[i].write(buf.buffer);
}
} else if (self.expectHeaders) {
// this is a header
log.debug("encoder: got header");
self.newHeaderBuffers.push(buf.buffer);
} else {
// it's a footer, ignore the fuck out of it
log.debug("ignoring encoded audio footer");
}
} else {
// end of playlist sentinel
log.debug("encoder: end of playlist sentinel");
if (self.queueClearEncodedBuffers) {
self.queueClearEncodedBuffers = false;
self.clearEncodedBuffer();
self.emit('seek');
}
self.expectHeaders = true;
}
}
function isBufOld(buf) {
// typical case
if (buf.item.id === playHead.item.id) {
return playHead.pos > buf.pos;
}
// edge case
var playHeadIndex = -1;
var bufItemIndex = -1;
for (var i = 0; i < plItems.length; i += 1) {
var plItem = plItems[i];
if (plItem.id === playHead.item.id) {
playHeadIndex = i;
} else if (plItem.id === buf.item.id) {
bufItemIndex = i;
}
}
return playHeadIndex > bufItemIndex;
}
}
function logIfError(err) {
if (err) {
log.error("Unable to attach encoder:", err.stack);
}
}
};
Player.prototype.detachEncoder = function(cb) {
cb = cb || logIfError;
this.clearEncodedBuffer();
this.queueClearEncodedBuffers = false;
clearInterval(this.flushEncodedInterval);
this.flushEncodedInterval = null;
startEncoderDetach(this, cb);
this.grooveEncoder.removeAllListeners();
function logIfError(err) {
if (err) {
log.error("Unable to detach encoder:", err.stack);
}
}
};
Player.prototype.deleteDbMtimes = function(cb) {
cb = cb || logIfDbError;
var updateCmds = [];
for (var key in this.libraryIndex.trackTable) {
var dbFile = this.libraryIndex.trackTable[key];
delete dbFile.mtime;
persistDbFile(dbFile, updateCmds);
}
this.db.batch(updateCmds, cb);
};
Player.prototype.requestUpdateDb = function(dirName, cb) {
var fullPath = path.resolve(this.musicDirectory, dirName || "");
this.dirScanQueue.add(fullPath, {
dir: fullPath,
}, cb);
};
Player.prototype.refreshFilesIndex = function(args, cb) {
var self = this;
var dir = args.dir;
var dirWithSlash = ensureSep(dir);
var walker = findit(dirWithSlash, {followSymlinks: true});
var thisScanId = uuid();
var delCmds = [];
walker.on('directory', function(fullDirPath, stat, stop, linkPath) {
var usePath = linkPath || fullDirPath;
var dirName = path.relative(self.musicDirectory, usePath);
var baseName = path.basename(dirName);
if (isFileIgnored(baseName)) {
stop();
return;
}
var dirEntry = self.getOrCreateDir(dirName, stat);
if (usePath === dirWithSlash) return; // ignore root search path
var parentDirName = path.dirname(dirName);
if (parentDirName === '.') parentDirName = '';
var parentDirEntry = self.getOrCreateDir(parentDirName);
parentDirEntry.dirEntries[baseName] = thisScanId;
});
walker.on('file', function(fullPath, stat, linkPath) {
var usePath = linkPath || fullPath;
var relPath = path.relative(self.musicDirectory, usePath);
var dirName = path.dirname(relPath);
if (dirName === '.') dirName = '';
var baseName = path.basename(relPath);
if (isFileIgnored(baseName)) return;
var extName = path.extname(relPath);
if (isExtensionIgnored(self, extName)) return;
var dirEntry = self.getOrCreateDir(dirName);
dirEntry.entries[baseName] = thisScanId;
var fileMtime = stat.mtime.getTime();
onAddOrChange(self, relPath, fileMtime);
});
walker.on('error', function(err) {
walker.stop();
cleanupAndCb(err);
});
walker.on('end', function() {
var dirName = path.relative(self.musicDirectory, dir);
checkDirEntry(self.dirs[dirName]);
cleanupAndCb();
function checkDirEntry(dirEntry) {
if (!dirEntry) return;
var id;
var baseName;
var i;
var deletedFiles = [];
var deletedDirs = [];
for (baseName in dirEntry.entries) {
id = dirEntry.entries[baseName];
if (id !== thisScanId) deletedFiles.push(baseName);
}
for (i = 0; i < deletedFiles.length; i += 1) {
baseName = deletedFiles[i];
delete dirEntry.entries[baseName];
onFileMissing(dirEntry, baseName);
}
for (baseName in dirEntry.dirEntries) {
id = dirEntry.dirEntries[baseName];
var childEntry = self.dirs[path.join(dirEntry.dirName, baseName)];
checkDirEntry(childEntry);
if (id !== thisScanId) deletedDirs.push(baseName);
}
for (i = 0; i < deletedDirs.length; i += 1) {
baseName = deletedDirs[i];
delete dirEntry.dirEntries[baseName];
onDirMissing(dirEntry, baseName);
}
self.persistDirEntry(dirEntry);
}
});
function cleanupAndCb(err) {
if (delCmds.length > 0) {
self.db.batch(delCmds, logIfDbError);
self.emit('deleteDbTrack');
}
cb(err);
}
function onDirMissing(parentDirEntry, baseName) {
var dirName = path.join(parentDirEntry.dirName, baseName);
log.debug("directory deleted:", dirName);
var dirEntry = self.dirs[dirName];
var watcher = dirEntry.watcher;
if (watcher) watcher.close();
delete self.dirs[dirName];
delete parentDirEntry.dirEntries[baseName];
}
function onFileMissing(parentDirEntry, baseName) {
var relPath = path.join(parentDirEntry.dirName, baseName);
log.debug("file deleted:", relPath);
delete parentDirEntry.entries[baseName];
var dbFile = self.dbFilesByPath[relPath];
if (dbFile) {
// batch up some db delete commands to run after walking the file system
delDbEntryCmds(self, dbFile, delCmds);
}
}
};
Player.prototype.watchDirEntry = function(dirEntry) {
var self = this;
var changeTriggered = null;
var fullDirPath = path.join(self.musicDirectory, dirEntry.dirName);
var watcher;
try {
watcher = fs.watch(fullDirPath, onChange);
watcher.on('error', onWatchError);
} catch (err) {
log.warn("Unable to fs.watch:", err.stack);
watcher = null;
}
dirEntry.watcher = watcher;
function onChange(eventName) {
if (changeTriggered) clearTimeout(changeTriggered);
changeTriggered = setTimeout(function() {
changeTriggered = null;
log.debug("dir updated:", dirEntry.dirName);
self.dirScanQueue.add(fullDirPath, { dir: fullDirPath });
}, 100);
}
function onWatchError(err) {
log.error("watch error:", err.stack);
}
};
Player.prototype.getOrCreateDir = function (dirName, stat) {
var dirEntry = this.dirs[dirName];
if (!dirEntry) {
dirEntry = this.dirs[dirName] = {
dirName: dirName,
entries: {},
dirEntries: {},
watcher: null, // will be set just below
mtime: stat && stat.mtime,
};
} else if (stat && dirEntry.mtime !== stat.mtime) {
dirEntry.mtime = stat.mtime;
}
if (!dirEntry.watcher) this.watchDirEntry(dirEntry);
return dirEntry;
};
Player.prototype.getCurPos = function() {
return this.isPlaying ?
((new Date() - this.trackStartDate) / 1000.0) : this.pausedTime;
};
function startPlayerSwitchDevice(self, wantHardware, cb) {
self.desiredPlayerHardwareState = wantHardware;
if (self.pendingPlayerAttachDetach) return;
self.pendingPlayerAttachDetach = true;
if (self.groovePlayer) {
self.groovePlayer.removeAllListeners();
self.groovePlayer.detach(onDetachComplete);
} else {
onDetachComplete();
}
function onDetachComplete(err) {
if (err) return cb(err);
self.groovePlayer = groove.createPlayer();
self.groovePlayer.deviceIndex = wantHardware ? null : groove.DUMMY_DEVICE;
self.groovePlayer.attach(self.groovePlaylist, function(err) {
self.pendingPlayerAttachDetach = false;
if (err) return cb(err);
if (self.desiredPlayerHardwareState !== wantHardware) {
startPlayerSwitchDevice(self, self.desiredPlayerHardwareState, cb);
} else {
cb();
}
});
}
}
Player.prototype.setHardwarePlayback = function(value, cb) {
var self = this;
cb = cb || logIfError;
value = !!value;
if (value === self.desiredPlayerHardwareState) return cb();
startPlayerSwitchDevice(self, value, function(err) {
if (err) return cb(err);
self.clearEncodedBuffer();
self.emit('seek');
self.groovePlayer.on('nowplaying', onNowPlaying);
self.persistOption('hardwarePlayback', self.desiredPlayerHardwareState);
self.emit('hardwarePlayback', self.desiredPlayerHardwareState);
cb();
});
function onNowPlaying() {
var playHead = self.groovePlayer.position();
var decodeHead = self.groovePlaylist.position();
if (playHead.item) {
var nowMs = (new Date()).getTime();
var posMs = playHead.pos * 1000;
self.trackStartDate = new Date(nowMs - posMs);
self.currentTrack = self.grooveItems[playHead.item.id];
playlistChanged(self);
self.currentTrackChanged();
} else if (!decodeHead.item) {
if (!self.dontBelieveTheEndOfPlaylistSentinelItsATrap) {
// both play head and decode head are null. end of playlist.
log.debug("end of playlist");
self.currentTrack = null;
playlistChanged(self);
self.currentTrackChanged();
}
}
}
function logIfError(err) {
if (err) {
log.error("Unable to set hardware playback mode:", err.stack);
}
}
};
Player.prototype.startStreaming = function(resp) {
this.headerBuffers.forEach(function(headerBuffer) {
resp.write(headerBuffer);
});
this.recentBuffers.forEach(function(recentBuffer) {
resp.write(recentBuffer.buffer);
});
this.cancelDetachEncoderTimeout();
this.attachEncoder();
this.openStreamers.push(resp);
this.emit('streamerConnect', resp.client);
};
Player.prototype.stopStreaming = function(resp) {
for (var i = 0; i < this.openStreamers.length; i += 1) {
if (this.openStreamers[i] === resp) {
this.openStreamers.splice(i, 1);
this.emit('streamerDisconnect', resp.client);
break;
}
}
};
Player.prototype.lastStreamerDisconnected = function() {
log.debug("last streamer disconnected");
this.startDetachEncoderTimeout();
if (!this.desiredPlayerHardwareState && this.isPlaying) {
this.emit("autoPause");
this.pause();
}
};
Player.prototype.cancelDetachEncoderTimeout = function() {
if (this.detachEncoderTimeout) {
clearTimeout(this.detachEncoderTimeout);
this.detachEncoderTimeout = null;
}
};
Player.prototype.startDetachEncoderTimeout = function() {
var self = this;
self.cancelDetachEncoderTimeout();
// we use encodeQueueDuration for the encoder timeout so that we are
// guaranteed to have audio available for the encoder in the case of
// detaching and reattaching the encoder.
self.detachEncoderTimeout = setTimeout(timeout, self.encodeQueueDuration * 1000);
function timeout() {
if (self.openStreamers.length === 0 && self.isPlaying) {
log.debug("detaching encoder");
self.detachEncoder();
}
}
};
Player.prototype.deleteFiles = function(keys) {
var self = this;
var delCmds = [];
for (var i = 0; i < keys.length; i += 1) {
var key = keys[i];
var dbFile = self.libraryIndex.trackTable[key];
if (!dbFile) continue;
var fullPath = path.join(self.musicDirectory, dbFile.file);
delDbEntryCmds(self, dbFile, delCmds);
fs.unlink(fullPath, logIfError);
}
if (delCmds.length > 0) {
self.emit('deleteDbTrack');
self.db.batch(delCmds, logIfError);
}
function logIfError(err) {
if (err) {
log.error("Error deleting files:", err.stack);
}
}
};
function delDbEntryCmds(self, dbFile, dbCmds) {
// delete items from the queue that are being deleted from the library
var deleteQueueItems = [];
for (var queueId in self.playlist) {
var queueItem = self.playlist[queueId];
if (queueItem.key === dbFile.key) {
deleteQueueItems.push(queueId);
}
}
self.removeQueueItems(deleteQueueItems);
// delete items from playlists that are being deleted from the library
var playlistRemovals = {};
for (var playlistId in self.playlists) {
var playlist = self.playlists[playlistId];
var removals = [];
playlistRemovals[playlistId] = removals;
for (var playlistItemId in playlist.items) {
var playlistItem = playlist.items[playlistItemId];
if (playlistItem.key === dbFile.key) {
removals.push(playlistItemId);
}
}
}
self.playlistRemoveItems(playlistRemovals);
self.libraryIndex.removeTrack(dbFile.key);
delete self.dbFilesByPath[dbFile.file];
var baseName = path.basename(dbFile.file);
var parentDirName = path.dirname(dbFile.file);
if (parentDirName === '.') parentDirName = '';
var parentDirEntry = self.dirs[parentDirName];
if (parentDirEntry) delete parentDirEntry[baseName];
dbCmds.push({type: 'del', key: LIBRARY_KEY_PREFIX + dbFile.key});
}
Player.prototype.setVolume = function(value) {
value = Math.min(2.0, value);
value = Math.max(0.0, value);
this.volume = value;
this.groovePlaylist.setGain(value);
this.persistOption('volume', this.volume);
this.emit("volumeUpdate");
};
Player.prototype.importUrl = function(urlString, cb) {
var self = this;
cb = cb || logIfError;
var filterIndex = 0;
tryImportFilter();
function tryImportFilter() {
var importFilter = importUrlFilters[filterIndex];
if (!importFilter) return cb();
importFilter.fn(urlString, callNextFilter);
function callNextFilter(err, dlStream, filenameHintWithoutPath, size) {
if (err || !dlStream) {
if (err) {
log.error(importFilter.name + " import filter error, skipping:", err.stack);
}
filterIndex += 1;
tryImportFilter();
return;
}
self.importStream(dlStream, filenameHintWithoutPath, size, cb);
}
}
function logIfError(err) {
if (err) {
log.error("Unable to import by URL.", err.stack, "URL:", urlString);
}
}
};
Player.prototype.importNames = function(names, cb) {
var self = this;
var pend = new Pend();
var allDbFiles = [];
names.forEach(function(name) {
pend.go(function(cb) {
youtubeSearch(name, self.googleApiKey, function(err, videoUrl) {
if (err) {
log.error("YouTube search error, skipping " + name + ": " + err.stack);
cb();
return;
}
self.importUrl(videoUrl, function(err, dbFiles) {
if (err) {
log.error("Unable to import from YouTube: " + err.stack);
} else if (!dbFiles) {
log.error("Unrecognized YouTube URL: " + videoUrl);
} else if (dbFiles.length > 0) {
allDbFiles = allDbFiles.concat(dbFiles);
}
cb();
});
});
});
});
pend.wait(function() {
cb(null, allDbFiles);
});
};
Player.prototype.importStream = function(readStream, filenameHintWithoutPath, size, cb) {
var self = this;
var ext = path.extname(filenameHintWithoutPath);
var tmpDir = path.join(self.musicDirectory, '.tmp');
var id = uuid();
var destPath = path.join(tmpDir, id + ext);
var calledCallback = false;
var writeStream = null;
var progressTimer = null;
var importEvent = {
id: id,
filenameHintWithoutPath: filenameHintWithoutPath,
bytesWritten: 0,
size: size,
date: new Date(),
};
readStream.on('error', cleanAndCb);
self.importProgress[importEvent.id] = importEvent;
self.emit('importStart', importEvent);
mkdirp(tmpDir, function(err) {
if (calledCallback) return;
if (err) return cleanAndCb(err);
writeStream = fs.createWriteStream(destPath);
readStream.pipe(writeStream);
progressTimer = setInterval(checkProgress, 100);
writeStream.on('close', onClose);
writeStream.on('error', cleanAndCb);
function checkProgress() {
importEvent.bytesWritten = writeStream.bytesWritten;
self.maybeEmitImportProgress();
}
function onClose(){
if (calledCallback) return;
checkProgress();
self.importFile(destPath, filenameHintWithoutPath, function(err, dbFiles) {
if (calledCallback) return;
if (err) {
cleanAndCb(err);
} else {
calledCallback = true;
cleanTimer();
delete self.importProgress[importEvent.id];
self.emit('importEnd', importEvent);
cb(null, dbFiles);
}
});
}
});
function cleanTimer() {
if (progressTimer) {
clearInterval(progressTimer);
progressTimer = null;
}
}
function cleanAndCb(err) {
if (writeStream) {
fs.unlink(destPath, onUnlinkDone);
writeStream = null;
}
cleanTimer();
if (calledCallback) return;
calledCallback = true;
delete self.importProgress[importEvent.id];
self.emit('importAbort', importEvent);
cb(err);
function onUnlinkDone(err) {
if (err) {
log.warn("Unable to clean up temp file:", err.stack);
}
}
}
};
Player.prototype.importFile = function(srcFullPath, filenameHintWithoutPath, cb) {
var self = this;
cb = cb || logIfError;
var filterIndex = 0;
log.debug("importFile open file:", srcFullPath);
disableFsListenRef(self, tryImportFilter);
function tryImportFilter() {
var importFilter = importFileFilters[filterIndex];
if (!importFilter) return cleanAndCb();
importFilter.fn(self, srcFullPath, filenameHintWithoutPath, callNextFilter);
function callNextFilter(err, dbFiles) {
if (err || !dbFiles) {
if (err) {
log.debug(importFilter.name + " import filter error, skipping:", err.message);
}
filterIndex += 1;
tryImportFilter();
return;
}
cleanAndCb(null, dbFiles);
}
}
function cleanAndCb(err, dbFiles) {
if (!dbFiles) {
fs.unlink(srcFullPath, logIfUnlinkError);
}
disableFsListenUnref(self);
cb(err, dbFiles);
}
function logIfUnlinkError(err) {
if (err) {
log.error("unable to unlink file:", err.stack);
}
}
function logIfError(err) {
if (err) {
log.error("unable to import file:", err.stack);
}
}
};
Player.prototype.maybeEmitImportProgress = function() {
var now = new Date();
var passedTime = now - this.lastImportProgressEvent;
if (passedTime > 500) {
this.lastImportProgressEvent = now;
this.emit("importProgress");
}
};
Player.prototype.persistDirEntry = function(dirEntry, cb) {
cb = cb || logIfError;
this.db.put(LIBRARY_DIR_PREFIX + dirEntry.dirName, serializeDirEntry(dirEntry), cb);
function logIfError(err) {
if (err) {
log.error("unable to persist db entry:", dirEntry, err.stack);
}
}
};
Player.prototype.persistDbFile = function(dbFile, updateCmds) {
this.libraryIndex.addTrack(dbFile);
this.dbFilesByPath[dbFile.file] = dbFile;
persistDbFile(dbFile, updateCmds);
};
Player.prototype.persistOneDbFile = function(dbFile, cb) {
cb = cb || logIfDbError;
var updateCmds = [];
this.persistDbFile(dbFile, updateCmds);
this.db.batch(updateCmds, cb);
};
Player.prototype.persistOption = function(name, value, cb) {
this.db.put(PLAYER_KEY_PREFIX + name, JSON.stringify(value), cb || logIfError);
function logIfError(err) {
if (err) {
log.error("unable to persist player option:", err.stack);
}
}
};
Player.prototype.addToLibrary = function(args, cb) {
var self = this;
var relPath = args.relPath;
var mtime = args.mtime;
var fullPath = path.join(self.musicDirectory, relPath);
log.debug("addToLibrary open file:", fullPath);
groove.open(fullPath, function(err, file) {
if (err) {
self.invalidPaths[relPath] = err.message;
cb();
return;
}
var dbFile = self.dbFilesByPath[relPath];
var filenameHintWithoutPath = path.basename(relPath);
var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath, dbFile);
newDbFile.file = relPath;
newDbFile.mtime = mtime;
var pend = new Pend();
pend.go(function(cb) {
log.debug("addToLibrary close file:", file.filename);
file.close(cb);
});
pend.go(function(cb) {
self.persistOneDbFile(newDbFile, function(err) {
if (err) log.error("Error saving", relPath, "to db:", err.stack);
cb();
});
});
self.emit('updateDb');
pend.wait(cb);
});
};
Player.prototype.updateTags = function(obj) {
var updateCmds = [];
for (var key in obj) {
var dbFile = this.libraryIndex.trackTable[key];
if (!dbFile) continue;
var props = obj[key];
for (var propName in DB_PROPS) {
var prop = DB_PROPS[propName];
if (! prop.clientCanModify) continue;
if (! (propName in props)) continue;
var parser = PROP_TYPE_PARSERS[prop.type];
dbFile[propName] = parser(props[propName]);
}
this.persistDbFile(dbFile, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('updateDb');
}
};
Player.prototype.insertTracks = function(index, keys, tagAsRandom) {
if (keys.length === 0) return [];
if (index < 0) index = 0;
if (index > this.tracksInOrder.length) index = this.tracksInOrder.length;
var trackBeforeIndex = this.tracksInOrder[index - 1];
var trackAtIndex = this.tracksInOrder[index];
var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null;
var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null;
var items = {};
var ids = [];
var sortKeys = keese(prevSortKey, nextSortKey, keys.length);
keys.forEach(function(key, i) {
var id = uuid();
var sortKey = sortKeys[i];
items[id] = {
key: key,
sortKey: sortKey,
};
ids.push(id);
});
this.addItems(items, tagAsRandom);
return ids;
};
Player.prototype.appendTracks = function(keys, tagAsRandom) {
return this.insertTracks(this.tracksInOrder.length, keys, tagAsRandom);
};
// items looks like {id: {key, sortKey}}
Player.prototype.addItems = function(items, tagAsRandom) {
var self = this;
tagAsRandom = !!tagAsRandom;
var updateCmds = [];
for (var id in items) {
var item = items[id];
var dbFile = self.libraryIndex.trackTable[item.key];
if (!dbFile) continue;
dbFile.lastQueueDate = new Date();
self.persistDbFile(dbFile, updateCmds);
var queueItem = {
id: id,
key: item.key,
sortKey: item.sortKey,
isRandom: tagAsRandom,
grooveFile: null,
pendingGrooveFile: false,
deleted: false,
};
self.playlist[id] = queueItem;
persistQueueItem(queueItem, updateCmds);
}
if (updateCmds.length > 0) {
self.db.batch(updateCmds, logIfDbError);
playlistChanged(self);
lazyReplayGainScanPlaylist(self);
}
};
Player.prototype.playlistCreate = function(id, name) {
if (this.playlists[id]) {
log.warn("tried to create playlist with same id as existing");
return;
}
var playlist = {
id: id,
name: name,
mtime: new Date().getTime(),
items: {},
};
this.playlists[playlist.id] = playlist;
this.persistPlaylist(playlist);
this.emit('playlistCreate', playlist);
return playlist;
};
Player.prototype.playlistRename = function(playlistId, newName) {
var playlist = this.playlists[playlistId];
if (!playlist) return;
playlist.name = newName;
playlist.mtime = new Date().getTime();
this.persistPlaylist(playlist);
this.emit('playlistUpdate', playlist);
};
Player.prototype.playlistDelete = function(playlistIds) {
var delCmds = [];
for (var i = 0; i < playlistIds.length; i += 1) {
var playlistId = playlistIds[i];
var playlist = this.playlists[playlistId];
if (!playlist) continue;
for (var id in playlist.items) {
var item = playlist.items[id];
if (!item) continue;
delCmds.push({type: 'del', key: playlistItemKey(playlist, item)});
delete playlist.items[id];
}
delCmds.push({type: 'del', key: playlistKey(playlist)});
delete this.playlists[playlistId];
}
if (delCmds.length > 0) {
this.db.batch(delCmds, logIfDbError);
this.emit('playlistDelete');
}
};
Player.prototype.playlistAddItems = function(playlistId, items) {
var playlist = this.playlists[playlistId];
if (!playlist) return;
var updateCmds = [];
for (var id in items) {
var item = items[id];
var dbFile = this.libraryIndex.trackTable[item.key];
if (!dbFile) continue;
var playlistItem = {
id: id,
key: item.key,
sortKey: item.sortKey,
};
playlist.items[id] = playlistItem;
updateCmds.push({
type: 'put',
key: playlistItemKey(playlist, playlistItem),
value: serializePlaylistItem(playlistItem),
});
}
if (updateCmds.length > 0) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate', playlist);
}
};
Player.prototype.playlistRemoveItems = function(removals) {
var updateCmds = [];
for (var playlistId in removals) {
var playlist = this.playlists[playlistId];
if (!playlist) continue;
var ids = removals[playlistId];
var dirty = false;
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var item = playlist.items[id];
if (!item) continue;
dirty = true;
updateCmds.push({type: 'del', key: playlistItemKey(playlist, item)});
delete playlist.items[id];
}
if (dirty) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
}
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate');
}
};
// items looks like {playlistId: {id: {sortKey}}}
Player.prototype.playlistMoveItems = function(updates) {
var updateCmds = [];
for (var playlistId in updates) {
var playlist = this.playlists[playlistId];
if (!playlist) continue;
var playlistDirty = false;
var update = updates[playlistId];
for (var id in update) {
var playlistItem = playlist.items[id];
if (!playlistItem) continue;
var updateItem = update[id];
playlistItem.sortKey = updateItem.sortKey;
playlistDirty = true;
updateCmds.push({
type: 'put',
key: playlistItemKey(playlist, playlistItem),
value: serializePlaylistItem(playlistItem),
});
}
if (playlistDirty) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
}
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate');
}
};
Player.prototype.persistPlaylist = function(playlist, cb) {
cb = cb || logIfDbError;
var key = playlistKey(playlist);
var payload = serializePlaylist(playlist);
this.db.put(key, payload, cb);
};
Player.prototype.labelCreate = function(id, name) {
if (id in this.libraryIndex.labelTable) {
log.warn("tried to create label that already exists");
return;
}
var color = labelColors[Math.floor(Math.random() * labelColors.length)];
var labelEntry = {id: id, name: name, color: color};
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelCreate');
};
Player.prototype.labelRename = function(id, name) {
var labelEntry = this.libraryIndex.labelTable[id];
if (!labelEntry) return;
labelEntry.name = name;
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelRename');
};
Player.prototype.labelColorUpdate = function(id, color) {
var labelEntry = this.libraryIndex.labelTable[id];
if (!labelEntry) return;
labelEntry.color = color;
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelColorUpdate');
};
Player.prototype.labelDelete = function(ids) {
var updateCmds = [];
var libraryChanged = false;
for (var i = 0; i < ids.length; i++) {
var labelId = ids[i];
if (!(labelId in this.libraryIndex.labelTable)) continue;
this.libraryIndex.removeLabel(labelId);
var key = LABEL_KEY_PREFIX + labelId;
updateCmds.push({type: 'del', key: key});
// clean out references from the library
var files = this.dbFilesByLabel[labelId];
for (var fileId in files) {
var dbFile = files[fileId];
delete dbFile.labels[labelId];
persistDbFile(dbFile, updateCmds);
libraryChanged = true;
}
delete this.dbFilesByLabel[labelId];
}
if (updateCmds.length === 0) return;
this.db.batch(updateCmds, logIfDbError);
if (libraryChanged) {
this.emit('updateDb');
}
this.emit('labelDelete');
};
Player.prototype.labelAdd = function(additions) {
this.changeLabels(additions, true);
};
Player.prototype.labelRemove = function(removals) {
this.changeLabels(removals, false);
};
Player.prototype.changeLabels = function(changes, isAdd) {
var self = this;
var updateCmds = [];
for (var id in changes) {
var labelIds = changes[id];
var dbFile = this.libraryIndex.trackTable[id];
if (!dbFile) continue;
if (labelIds.length === 0) continue;
var changedTrack = false;
for (var i = 0; i < labelIds.length; i++) {
var labelId = labelIds[i];
var filesByThisLabel = self.dbFilesByLabel[labelId];
if (isAdd) {
if (labelId in dbFile.labels) continue; // already got it
dbFile.labels[labelId] = 1;
if (filesByThisLabel == null) filesByThisLabel = self.dbFilesByLabel[labelId] = {};
filesByThisLabel[dbFile.key] = dbFile;
} else {
if (!(labelId in dbFile.labels)) continue; // already gone
delete dbFile.labels[labelId];
delete filesByThisLabel[dbFile.key];
}
changedTrack = true;
}
if (changedTrack) {
this.persistDbFile(dbFile, updateCmds);
}
}
if (updateCmds.length === 0) return;
this.db.batch(updateCmds, logIfDbError);
this.emit('updateDb');
};
Player.prototype.clearQueue = function() {
this.removeQueueItems(Object.keys(this.playlist));
};
Player.prototype.removeAllRandomQueueItems = function() {
var idsToRemove = [];
for (var i = 0; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
if (track.isRandom && track !== this.currentTrack) {
idsToRemove.push(track.id);
}
}
return this.removeQueueItems(idsToRemove);
};
Player.prototype.shufflePlaylist = function() {
if (this.tracksInOrder.length === 0) return;
if (this.autoDjOn) return this.removeAllRandomQueueItems();
var sortKeys = this.tracksInOrder.map(function(track) {
return track.sortKey;
});
shuffle(sortKeys);
// fix sortKey and index properties
var updateCmds = [];
for (var i = 0; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
track.index = i;
track.sortKey = sortKeys[i];
persistQueueItem(track, updateCmds);
}
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
};
Player.prototype.removeQueueItems = function(ids) {
if (ids.length === 0) return;
var delCmds = [];
var currentTrackChanged = false;
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var item = this.playlist[id];
if (!item) continue;
delCmds.push({type: 'del', key: QUEUE_KEY_PREFIX + id});
if (item.grooveFile) this.playlistItemDeleteQueue.push(item);
if (item === this.currentTrack) {
var nextPos = this.currentTrack.index + 1;
for (;;) {
var nextTrack = this.tracksInOrder[nextPos];
var nextTrackId = nextTrack && nextTrack.id;
this.currentTrack = nextTrackId && this.playlist[nextTrack.id];
if (!this.currentTrack && nextPos < this.tracksInOrder.length) {
nextPos += 1;
continue;
}
break;
}
if (this.currentTrack) {
this.seekRequestPos = 0;
}
currentTrackChanged = true;
}
delete this.playlist[id];
}
if (delCmds.length > 0) this.db.batch(delCmds, logIfDbError);
playlistChanged(this);
if (currentTrackChanged) {
this.currentTrackChanged();
}
};
// items looks like {id: {sortKey}}
Player.prototype.moveQueueItems = function(items) {
var updateCmds = [];
for (var id in items) {
var track = this.playlist[id];
if (!track) continue; // race conditions, etc.
track.sortKey = items[id].sortKey;
persistQueueItem(track, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
}
};
Player.prototype.moveRangeToPos = function(startPos, endPos, toPos) {
var ids = [];
for (var i = startPos; i < endPos; i += 1) {
var track = this.tracksInOrder[i];
if (!track) continue;
ids.push(track.id);
}
this.moveIdsToPos(ids, toPos);
};
Player.prototype.moveIdsToPos = function(ids, toPos) {
var trackBeforeIndex = this.tracksInOrder[toPos - 1];
var trackAtIndex = this.tracksInOrder[toPos];
var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null;
var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null;
var sortKeys = keese(prevSortKey, nextSortKey, ids.length);
var updateCmds = [];
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var queueItem = this.playlist[id];
if (!queueItem) continue;
queueItem.sortKey = sortKeys[i];
persistQueueItem(queueItem, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
}
};
Player.prototype.pause = function() {
if (!this.isPlaying) return;
this.isPlaying = false;
this.pausedTime = (new Date() - this.trackStartDate) / 1000;
this.groovePlaylist.pause();
this.cancelDetachEncoderTimeout();
playlistChanged(this);
this.currentTrackChanged();
};
Player.prototype.play = function() {
if (!this.currentTrack) {
this.currentTrack = this.tracksInOrder[0];
} else if (!this.isPlaying) {
this.trackStartDate = new Date(new Date() - this.pausedTime * 1000);
}
this.groovePlaylist.play();
this.startDetachEncoderTimeout();
this.isPlaying = true;
playlistChanged(this);
this.currentTrackChanged();
};
// This function should be avoided in favor of seek. Note that it is called by
// some MPD protocol commands, because the MPD protocol is stupid.
Player.prototype.seekToIndex = function(index, pos) {
var track = this.tracksInOrder[index];
if (!track) return null;
this.currentTrack = track;
this.seekRequestPos = pos;
playlistChanged(this);
this.currentTrackChanged();
return track;
};
Player.prototype.seek = function(id, pos) {
var track = this.playlist[id];
if (!track) return null;
this.currentTrack = this.playlist[id];
this.seekRequestPos = pos;
playlistChanged(this);
this.currentTrackChanged();
return track;
};
Player.prototype.next = function() {
return this.skipBy(1);
};
Player.prototype.prev = function() {
return this.skipBy(-1);
};
Player.prototype.skipBy = function(amt) {
var defaultIndex = amt > 0 ? -1 : this.tracksInOrder.length;
var currentIndex = this.currentTrack ? this.currentTrack.index : defaultIndex;
var newIndex = currentIndex + amt;
return this.seekToIndex(newIndex, 0);
};
Player.prototype.setRepeat = function(value) {
value = Math.floor(value);
if (value !== Player.REPEAT_ONE &&
value !== Player.REPEAT_ALL &&
value !== Player.REPEAT_OFF)
{
return;
}
if (value === this.repeat) return;
this.repeat = value;
this.persistOption('repeat', this.repeat);
playlistChanged(this);
this.emit('repeatUpdate');
};
Player.prototype.setAutoDjOn = function(value) {
value = !!value;
if (value === this.autoDjOn) return;
this.autoDjOn = value;
this.persistOption('autoDjOn', this.autoDjOn);
this.emit('autoDjOn');
this.checkAutoDj();
};
Player.prototype.setAutoDjHistorySize = function(value) {
value = Math.floor(value);
if (value === this.autoDjHistorySize) return;
this.autoDjHistorySize = value;
this.persistOption('autoDjHistorySize', this.autoDjHistorySize);
this.emit('autoDjHistorySize');
this.checkAutoDj();
};
Player.prototype.setAutoDjFutureSize = function(value) {
value = Math.floor(value);
if (value === this.autoDjFutureSize) return;
this.autoDjFutureSize = value;
this.persistOption('autoDjFutureSize', this.autoDjFutureSize);
this.emit('autoDjFutureSize');
this.checkAutoDj();
};
Player.prototype.stop = function() {
this.isPlaying = false;
this.cancelDetachEncoderTimeout();
this.groovePlaylist.pause();
this.seekRequestPos = 0;
this.pausedTime = 0;
playlistChanged(this);
};
Player.prototype.clearEncodedBuffer = function() {
while (this.recentBuffers.length > 0) {
this.recentBuffers.shift();
}
};
Player.prototype.getSuggestedPath = function(track, filenameHint) {
var p = "";
if (track.albumArtistName) {
p = path.join(p, safePath(track.albumArtistName));
} else if (track.compilation) {
p = path.join(p, safePath(this.libraryIndex.variousArtistsName));
} else if (track.artistName) {
p = path.join(p, safePath(track.artistName));
}
if (track.albumName) {
p = path.join(p, safePath(track.albumName));
}
var t = "";
if (track.track != null) {
t += safePath(zfill(track.track, 2)) + " ";
}
t += safePath(track.name + path.extname(filenameHint));
return path.join(p, t);
};
Player.prototype.queueScan = function(dbFile) {
var self = this;
var scanKey, scanType;
if (dbFile.albumName) {
scanType = 'album';
scanKey = self.libraryIndex.getAlbumKey(dbFile);
} else {
scanType = 'track';
scanKey = dbFile.key;
}
if (self.scanQueue.idInQueue(scanKey)) {
return;
}
self.scanQueue.add(scanKey, {
type: scanType,
key: scanKey,
});
};
Player.prototype.performScan = function(args, cb) {
var self = this;
var scanType = args.type;
var scanKey = args.key;
// build list of files we want to open
var dbFilesToOpen;
if (scanType === 'album') {
var albumKey = scanKey;
self.libraryIndex.rebuildTracks();
var album = self.libraryIndex.albumTable[albumKey];
if (!album) {
log.warn("wanted to scan album with key", JSON.stringify(albumKey), "but no longer exists.");
cb();
return;
}
log.debug("Scanning album for loudness:", JSON.stringify(albumKey));
dbFilesToOpen = album.trackList;
} else if (scanType === 'track') {
var trackKey = scanKey;
var dbFile = self.libraryIndex.trackTable[trackKey];
if (!dbFile) {
log.warn("wanted to scan track with key", JSON.stringify(trackKey), "but no longer exists.");
cb();
return;
}
log.debug("Scanning track for loudness:", JSON.stringify(trackKey));
dbFilesToOpen = [dbFile];
} else {
throw new Error("unexpected scan type: " + scanType);
}
// open all the files in the list
var pend = new Pend();
// we're already doing multiple parallel scans. within each scan let's
// read one thing at a time to avoid slamming the system.
pend.max = 1;
var grooveFileList = [];
var files = {};
dbFilesToOpen.forEach(function(dbFile) {
pend.go(function(cb) {
var fullPath = path.join(self.musicDirectory, dbFile.file);
log.debug("performScan open file:", fullPath);
groove.open(fullPath, function(err, file) {
if (err) {
log.error("Error opening", fullPath, "in order to scan:", err.stack);
} else {
var fileInfo;
files[file.id] = fileInfo = {
dbFile: dbFile,
loudnessDone: false,
fingerprintDone: false,
};
self.ongoingScans[dbFile.key] = fileInfo;
grooveFileList.push(file);
}
cb();
});
});
});
var scanPlaylist;
var endOfPlaylistPend = new Pend();
var scanDetector;
var scanDetectorAttached = false;
var endOfDetectorCb;
var scanFingerprinter;
var scanFingerprinterAttached = false;
var endOfFingerprinterCb;
pend.wait(function() {
// emit this because we updated ongoingScans
self.emit('scanProgress');
scanPlaylist = groove.createPlaylist();
scanPlaylist.setFillMode(groove.ANY_SINK_FULL);
scanDetector = groove.createLoudnessDetector();
scanFingerprinter = groove.createFingerprinter();
scanDetector.on('info', onLoudnessInfo);
scanFingerprinter.on('info', onFingerprinterInfo);
var pend = new Pend();
pend.go(attachLoudnessDetector);
pend.go(attachFingerprinter);
pend.wait(onEverythingAttached);
});
function onEverythingAttached(err) {
if (err) {
log.error("Error attaching:", err.stack);
cleanupAndCb();
return;
}
grooveFileList.forEach(function(file) {
scanPlaylist.insert(file);
});
endOfPlaylistPend.wait(function() {
for (var fileId in files) {
var fileInfo = files[fileId];
var dbFile = fileInfo.dbFile;
self.persistOneDbFile(dbFile);
self.emit('scanComplete', dbFile);
}
cleanupAndCb();
});
}
function attachLoudnessDetector(cb) {
scanDetector.attach(scanPlaylist, function(err) {
if (err) return cb(err);
scanDetectorAttached = true;
endOfPlaylistPend.go(function(cb) {
endOfDetectorCb = cb;
});
cb();
});
}
function attachFingerprinter(cb) {
scanFingerprinter.attach(scanPlaylist, function(err) {
if (err) return cb(err);
scanFingerprinterAttached = true;
endOfPlaylistPend.go(function(cb) {
endOfFingerprinterCb = cb;
});
cb();
});
}
function onLoudnessInfo() {
var info;
while (info = scanDetector.getInfo()) {
var gain = groove.loudnessToReplayGain(info.loudness);
var dbFile;
var fileInfo;
if (info.item) {
fileInfo = files[info.item.file.id];
fileInfo.loudnessDone = true;
dbFile = fileInfo.dbFile;
log.info("loudness scan file complete:", dbFile.name,
"gain", gain, "duration", info.duration);
dbFile.replayGainTrackGain = gain;
dbFile.replayGainTrackPeak = info.peak;
dbFile.duration = info.duration;
checkUpdateGroovePlaylist(self);
self.emit('scanProgress');
} else {
log.debug("loudness scan complete:", JSON.stringify(scanKey), "gain", gain);
for (var fileId in files) {
fileInfo = files[fileId];
dbFile = fileInfo.dbFile;
dbFile.replayGainAlbumGain = gain;
dbFile.replayGainAlbumPeak = info.peak;
}
checkUpdateGroovePlaylist(self);
if (endOfDetectorCb) {
endOfDetectorCb();
endOfDetectorCb = null;
}
return;
}
}
}
function onFingerprinterInfo() {
var info;
while (info = scanFingerprinter.getInfo()) {
if (info.item) {
var fileInfo = files[info.item.file.id];
fileInfo.fingerprintDone = true;
var dbFile = fileInfo.dbFile;
log.info("fingerprint scan file complete:", dbFile.name);
dbFile.fingerprint = info.fingerprint;
self.emit('scanProgress');
} else {
log.debug("fingerprint scan complete:", JSON.stringify(scanKey));
if (endOfFingerprinterCb) {
endOfFingerprinterCb();
endOfFingerprinterCb = null;
}
return;
}
}
}
function cleanupAndCb() {
grooveFileList.forEach(function(file) {
pend.go(function(cb) {
var fileInfo = files[file.id];
var dbFile = fileInfo.dbFile;
delete self.ongoingScans[dbFile.key];
log.debug("performScan close file:", file.filename);
file.close(cb);
});
});
if (scanDetectorAttached) pend.go(detachLoudnessScanner);
if (scanFingerprinterAttached) pend.go(detachFingerprinter);
pend.wait(function(err) {
// emit this because we changed ongoingScans above
self.emit('scanProgress');
cb(err);
});
}
function detachLoudnessScanner(cb) {
scanDetector.detach(cb);
}
function detachFingerprinter(cb) {
scanFingerprinter.detach(cb);
}
};
Player.prototype.checkAutoDj = function() {
var self = this;
if (!self.autoDjOn) return;
// if no track is playing, assume the first track is about to be
var currentIndex = self.currentTrack ? self.currentTrack.index : 0;
var deleteCount = Math.max(currentIndex - self.autoDjHistorySize, 0);
if (self.autoDjHistorySize < 0) deleteCount = 0;
var addCount = Math.max(self.autoDjFutureSize + 1 - (self.tracksInOrder.length - currentIndex), 0);
var idsToDelete = [];
for (var i = 0; i < deleteCount; i += 1) {
idsToDelete.push(self.tracksInOrder[i].id);
}
var keys = getRandomSongKeys(addCount);
self.removeQueueItems(idsToDelete);
self.appendTracks(keys, true);
function getRandomSongKeys(count) {
if (count === 0) return [];
var neverQueued = [];
var sometimesQueued = [];
for (var key in self.libraryIndex.trackTable) {
var dbFile = self.libraryIndex.trackTable[key];
if (dbFile.lastQueueDate == null) {
neverQueued.push(dbFile);
} else {
sometimesQueued.push(dbFile);
}
}
// backwards by time
sometimesQueued.sort(function(a, b) {
return b.lastQueueDate - a.lastQueueDate;
});
// distribution is a triangle for ever queued, and a rectangle for never queued
// ___
// /| |
// / | |
// /__|_|
var maxWeight = sometimesQueued.length;
var triangleArea = Math.floor(maxWeight * maxWeight / 2);
if (maxWeight === 0) maxWeight = 1;
var rectangleArea = maxWeight * neverQueued.length;
var totalSize = triangleArea + rectangleArea;
if (totalSize === 0) return [];
// decode indexes through the distribution shape
var keys = [];
for (var i = 0; i < count; i += 1) {
var index = Math.random() * totalSize;
if (index < triangleArea) {
// triangle
keys.push(sometimesQueued[Math.floor(Math.sqrt(index))].key);
} else {
keys.push(neverQueued[Math.floor((index - triangleArea) / maxWeight)].key);
}
}
return keys;
}
};
Player.prototype.currentTrackChanged = function() {
this.persistCurrentTrack();
this.emit('currentTrack');
};
Player.prototype.persistCurrentTrack = function(cb) {
// save the current track and time to db
var currentTrackInfo = {
id: this.currentTrack && this.currentTrack.id,
pos: this.getCurPos(),
};
this.persistOption('currentTrackInfo', currentTrackInfo, cb);
};
Player.prototype.sortAndQueueTracks = function(tracks) {
// given an array of tracks, sort them according to the library sorting
// and then queue them in the best place
if (!tracks.length) return;
var sortedTracks = sortTracks(tracks);
this.queueTracks(sortedTracks);
};
Player.prototype.sortAndQueueTracksInPlaylist = function(playlist, tracks, previousKey, nextKey) {
if (!tracks.length) return;
var sortedTracks = sortTracks(tracks);
var items = {};
var sortKeys = keese(previousKey, nextKey, tracks.length);
for (var i = 0; i < tracks.length; i += 1) {
var track = tracks[i];
var sortKey = sortKeys[i];
var id = uuid();
items[id] = {
key: track.key,
sortKey: sortKey,
};
}
this.playlistAddItems(playlist.id, items);
};
Player.prototype.queueTrackKeys = function(trackKeys, previousKey, nextKey) {
if (!trackKeys.length) return;
if (previousKey == null && nextKey == null) {
var defaultPos = this.getDefaultQueuePosition();
previousKey = defaultPos.previousKey;
nextKey = defaultPos.nextKey;
}
var items = {};
var sortKeys = keese(previousKey, nextKey, trackKeys.length);
for (var i = 0; i < trackKeys.length; i += 1) {
var trackKey = trackKeys[i];
var sortKey = sortKeys[i];
var id = uuid();
items[id] = {
key: trackKey,
sortKey: sortKey,
};
}
this.addItems(items, false);
};
Player.prototype.queueTracks = function(tracks, previousKey, nextKey) {
// given an array of tracks, and a previous sort key and a next sort key,
// call addItems correctly
var trackKeys = tracks.map(function(track) {
return track.key;
}).filter(function(key) {
return !!key;
});
return this.queueTrackKeys(trackKeys, previousKey, nextKey);
};
Player.prototype.getDefaultQueuePosition = function() {
var previousKey = this.currentTrack && this.currentTrack.sortKey;
var nextKey = null;
var startPos = this.currentTrack ? this.currentTrack.index + 1 : 0;
for (var i = startPos; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
var sortKey = track.sortKey;
if (track.isRandom) {
nextKey = sortKey;
break;
}
previousKey = sortKey;
}
return {
previousKey: previousKey,
nextKey: nextKey
};
};
function persistDbFile(dbFile, updateCmds) {
updateCmds.push({
type: 'put',
key: LIBRARY_KEY_PREFIX + dbFile.key,
value: serializeFileData(dbFile),
});
}
function persistQueueItem(item, updateCmds) {
updateCmds.push({
type: 'put',
key: QUEUE_KEY_PREFIX + item.id,
value: serializeQueueItem(item),
});
}
function onAddOrChange(self, relPath, fileMtime, cb) {
cb = cb || logIfError;
// check the mtime against the mtime of the same file in the db
var dbFile = self.dbFilesByPath[relPath];
if (dbFile) {
var dbMtime = dbFile.mtime;
if (dbMtime >= fileMtime) {
// the info we have in our db for this file is fresh
cb(null, dbFile);
return;
}
}
self.addQueue.add(relPath, {
relPath: relPath,
mtime: fileMtime,
});
self.addQueue.waitForId(relPath, function(err) {
var dbFile = self.dbFilesByPath[relPath];
cb(err, dbFile);
});
function logIfError(err) {
if (err) {
log.error("Unable to add to queue:", err.stack);
}
}
}
function checkPlayCount(self) {
if (self.isPlaying && !self.previousIsPlaying) {
self.playingStart = new Date(new Date() - self.playingTime);
self.previousIsPlaying = true;
}
self.playingTime = new Date() - self.playingStart;
if (self.currentTrack === self.lastPlayingItem) return;
if (self.lastPlayingItem) {
var dbFile = self.libraryIndex.trackTable[self.lastPlayingItem.key];
if (dbFile) {
var minAmt = 15 * 1000;
var maxAmt = 4 * 60 * 1000;
var halfAmt = dbFile.duration / 2 * 1000;
if (self.playingTime >= minAmt && (self.playingTime >= maxAmt || self.playingTime >= halfAmt)) {
dbFile.playCount += 1;
self.persistOneDbFile(dbFile);
self.emit('play', self.lastPlayingItem, dbFile, self.playingStart);
self.emit('updateDb');
}
}
}
self.lastPlayingItem = self.currentTrack;
self.previousIsPlaying = self.isPlaying;
self.playingStart = new Date();
self.playingTime = 0;
}
function disableFsListenRef(self, fn) {
self.disableFsRefCount += 1;
if (self.disableFsRefCount === 1) {
log.debug("pause dirScanQueue");
self.dirScanQueue.setPause(true);
self.dirScanQueue.waitForProcessing(fn);
} else {
fn();
}
}
function disableFsListenUnref(self) {
self.disableFsRefCount -= 1;
if (self.disableFsRefCount === 0) {
log.debug("unpause dirScanQueue");
self.dirScanQueue.setPause(false);
} else if (self.disableFsRefCount < 0) {
throw new Error("disableFsListenUnref called too many times");
}
}
function operatorCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
function disambiguateSortKeys(self) {
var previousUniqueKey = null;
var previousKey = null;
self.tracksInOrder.forEach(function(track, i) {
if (track.sortKey === previousKey) {
// move the repeat back
track.sortKey = keese(previousUniqueKey, track.sortKey);
previousUniqueKey = track.sortKey;
} else {
previousUniqueKey = previousKey;
previousKey = track.sortKey;
}
});
}
// generate self.tracksInOrder from self.playlist
function cacheTracksArray(self) {
self.tracksInOrder = Object.keys(self.playlist).map(trackById);
self.tracksInOrder.sort(asc);
self.tracksInOrder.forEach(function(track, index) {
track.index = index;
});
function asc(a, b) {
return operatorCompare(a.sortKey, b.sortKey);
}
function trackById(id) {
return self.playlist[id];
}
}
function lazyReplayGainScanPlaylist(self) {
// clear the queue since we're going to completely rebuild it anyway
// this allows the following priority code to work.
self.scanQueue.clear();
// prioritize the currently playing track, followed by the next tracks,
// followed by the previous tracks
var albumGain = {};
var start1 = self.currentTrack ? self.currentTrack.index : 0;
var i;
for (i = start1; i < self.tracksInOrder.length; i += 1) {
checkScan(self.tracksInOrder[i]);
}
for (i = 0; i < start1; i += 1) {
checkScan(self.tracksInOrder[i]);
}
function checkScan(track) {
var dbFile = self.libraryIndex.trackTable[track.key];
if (!dbFile) return;
var albumKey = self.libraryIndex.getAlbumKey(dbFile);
var needScan =
dbFile.fingerprint == null ||
dbFile.replayGainAlbumGain == null ||
dbFile.replayGainTrackGain == null ||
(dbFile.albumName && albumGain[albumKey] && albumGain[albumKey] !== dbFile.replayGainAlbumGain);
if (needScan) {
self.queueScan(dbFile);
} else {
albumGain[albumKey] = dbFile.replayGainAlbumGain;
}
}
}
function playlistChanged(self) {
cacheTracksArray(self);
disambiguateSortKeys(self);
if (self.currentTrack) {
self.tracksInOrder.forEach(function(track, index) {
var prevDiff = self.currentTrack.index - index;
var nextDiff = index - self.currentTrack.index;
var withinPrev = prevDiff <= PREV_FILE_COUNT && prevDiff >= 0;
var withinNext = nextDiff <= NEXT_FILE_COUNT && nextDiff >= 0;
var shouldHaveGrooveFile = withinPrev || withinNext;
var hasGrooveFile = track.grooveFile != null || track.pendingGrooveFile;
if (hasGrooveFile && !shouldHaveGrooveFile) {
self.playlistItemDeleteQueue.push(track);
} else if (!hasGrooveFile && shouldHaveGrooveFile) {
preloadFile(self, track);
}
});
} else {
self.isPlaying = false;
self.cancelDetachEncoderTimeout();
self.trackStartDate = null;
self.pausedTime = 0;
}
checkUpdateGroovePlaylist(self);
performGrooveFileDeletes(self);
self.checkAutoDj();
checkPlayCount(self);
self.emit('queueUpdate');
}
function performGrooveFileDeletes(self) {
while (self.playlistItemDeleteQueue.length) {
var item = self.playlistItemDeleteQueue.shift();
// we set this so that any callbacks that return which were trying to
// set the grooveItem can check if the item got deleted
item.deleted = true;
if (!item.grooveFile) continue;
log.debug("performGrooveFileDeletes close file:", item.grooveFile.filename);
var grooveFile = item.grooveFile;
item.grooveFile = null;
closeFile(grooveFile);
}
}
function preloadFile(self, track) {
var relPath = self.libraryIndex.trackTable[track.key].file;
var fullPath = path.join(self.musicDirectory, relPath);
track.pendingGrooveFile = true;
log.debug("preloadFile open file:", fullPath);
// set this so that we know we want the file preloaded
track.deleted = false;
groove.open(fullPath, function(err, file) {
track.pendingGrooveFile = false;
if (err) {
log.error("Error opening", relPath, err.stack);
return;
}
if (track.deleted) {
log.debug("preloadFile close file (already deleted):", file.filename);
closeFile(file);
return;
}
track.grooveFile = file;
checkUpdateGroovePlaylist(self);
});
}
function checkUpdateGroovePlaylist(self) {
if (!self.currentTrack) {
self.groovePlaylist.clear();
self.grooveItems = {};
return;
}
var groovePlaylist = self.groovePlaylist.items();
var playHead = self.groovePlayer.position();
var playHeadItemId = playHead.item && playHead.item.id;
var groovePlIndex = 0;
var grooveItem;
if (playHeadItemId) {
while (groovePlIndex < groovePlaylist.length) {
grooveItem = groovePlaylist[groovePlIndex];
if (grooveItem.id === playHeadItemId) break;
// this groove playlist item is before the current playhead. delete it!
self.groovePlaylist.remove(grooveItem);
delete self.grooveItems[grooveItem.id];
groovePlIndex += 1;
}
}
var plItemIndex = self.currentTrack.index;
var plTrack;
var currentGrooveItem = null; // might be different than playHead.item
var groovePlItemCount = 0;
var gainAndPeak;
while (groovePlIndex < groovePlaylist.length) {
grooveItem = groovePlaylist[groovePlIndex];
var grooveTrack = self.grooveItems[grooveItem.id];
// now we have deleted all items before the current track. we are now
// comparing the libgroove playlist and the groovebasin playlist
// side by side.
plTrack = self.tracksInOrder[plItemIndex];
if (grooveTrack === plTrack) {
// if they're the same, we advance
// but we might have to correct the gain
gainAndPeak = calcGainAndPeak(plTrack);
self.groovePlaylist.setItemGain(grooveItem, gainAndPeak.gain);
self.groovePlaylist.setItemPeak(grooveItem, gainAndPeak.peak);
currentGrooveItem = currentGrooveItem || grooveItem;
groovePlIndex += 1;
incrementPlIndex();
continue;
}
// this groove track is wrong. delete it.
self.groovePlaylist.remove(grooveItem);
delete self.grooveItems[grooveItem.id];
groovePlIndex += 1;
}
// we still need to add more libgroove playlist items, but this one has
// not yet finished loading from disk. We must take note of this so that
// if we receive the end of playlist sentinel, we start playback again
// once this track has finished loading.
self.dontBelieveTheEndOfPlaylistSentinelItsATrap = true;
while (groovePlItemCount < NEXT_FILE_COUNT) {
plTrack = self.tracksInOrder[plItemIndex];
if (!plTrack) {
// we hit the end of the groove basin playlist. we're done adding tracks
// to the libgroove playlist.
self.dontBelieveTheEndOfPlaylistSentinelItsATrap = false;
break;
}
if (!plTrack.grooveFile) {
break;
}
// compute the gain adjustment
gainAndPeak = calcGainAndPeak(plTrack);
grooveItem = self.groovePlaylist.insert(plTrack.grooveFile, gainAndPeak.gain, gainAndPeak.peak);
self.grooveItems[grooveItem.id] = plTrack;
currentGrooveItem = currentGrooveItem || grooveItem;
incrementPlIndex();
}
if (currentGrooveItem && self.seekRequestPos >= 0) {
var seekPos = self.seekRequestPos;
// we want to clear encoded buffers after the seek completes, e.g. after
// we get the end of playlist sentinel
self.clearEncodedBuffer();
self.queueClearEncodedBuffers = true;
self.groovePlaylist.seek(currentGrooveItem, seekPos);
self.seekRequestPos = -1;
if (self.isPlaying) {
var nowMs = (new Date()).getTime();
var posMs = seekPos * 1000;
self.trackStartDate = new Date(nowMs - posMs);
} else {
self.pausedTime = seekPos;
}
self.currentTrackChanged();
}
function calcGainAndPeak(plTrack) {
// if the previous item is the previous item from the album, or the
// next item is the next item from the album, use album replaygain.
// else, use track replaygain.
var dbFile = self.libraryIndex.trackTable[plTrack.key];
var albumMode = albumInfoMatch(-1) || albumInfoMatch(1);
var gain = REPLAYGAIN_PREAMP;
var peak;
if (dbFile.replayGainAlbumGain != null && albumMode) {
gain *= dBToFloat(dbFile.replayGainAlbumGain);
peak = dbFile.replayGainAlbumPeak || 1.0;
} else if (dbFile.replayGainTrackGain != null) {
gain *= dBToFloat(dbFile.replayGainTrackGain);
peak = dbFile.replayGainTrackPeak || 1.0;
} else {
gain *= REPLAYGAIN_DEFAULT;
peak = 1.0;
}
return {gain: gain, peak: peak};
function albumInfoMatch(dir) {
var otherPlTrack = self.tracksInOrder[plTrack.index + dir];
if (!otherPlTrack) return false;
var otherDbFile = self.libraryIndex.trackTable[otherPlTrack.key];
if (!otherDbFile) return false;
var albumMatch = self.libraryIndex.getAlbumKey(dbFile) === self.libraryIndex.getAlbumKey(otherDbFile);
if (!albumMatch) return false;
// if there are no track numbers then it's hardly an album, is it?
if (dbFile.track == null || otherDbFile.track == null) {
return false;
}
var trackMatch = dbFile.track + dir === otherDbFile.track;
if (!trackMatch) return false;
return true;
}
}
function incrementPlIndex() {
groovePlItemCount += 1;
if (self.repeat !== Player.REPEAT_ONE) {
plItemIndex += 1;
if (self.repeat === Player.REPEAT_ALL && plItemIndex >= self.tracksInOrder.length) {
plItemIndex = 0;
}
}
}
}
function isFileIgnored(basename) {
return (/^\./).test(basename) || (/~$/).test(basename);
}
function isExtensionIgnored(self, extName) {
var extNameLower = extName.toLowerCase();
for (var i = 0; i < self.ignoreExtensions.length; i += 1) {
if (self.ignoreExtensions[i] === extNameLower) {
return true;
}
}
return false;
}
function deserializeFileData(dataStr) {
var dbFile = JSON.parse(dataStr);
for (var propName in DB_PROPS) {
var propInfo = DB_PROPS[propName];
if (!propInfo) continue;
var parser = PROP_TYPE_PARSERS[propInfo.type];
dbFile[propName] = parser(dbFile[propName]);
}
return dbFile;
}
function serializeQueueItem(item) {
return JSON.stringify({
id: item.id,
key: item.key,
sortKey: item.sortKey,
isRandom: item.isRandom,
});
}
function serializePlaylistItem(item) {
return JSON.stringify({
id: item.id,
key: item.key,
sortKey: item.sortKey,
});
}
function trackWithoutIndex(category, dbFile) {
var out = {};
for (var propName in DB_PROPS) {
var prop = DB_PROPS[propName];
if (!prop[category]) continue;
// save space by leaving out null and undefined values
var value = dbFile[propName];
if (value == null) continue;
if (prop.type === 'set') {
out[propName] = copySet(value);
} else {
out[propName] = value;
}
}
return out;
}
function serializeFileData(dbFile) {
return JSON.stringify(trackWithoutIndex('db', dbFile));
}
function serializeDirEntry(dirEntry) {
return JSON.stringify({
dirName: dirEntry.dirName,
entries: dirEntry.entries,
dirEntries: dirEntry.dirEntries,
mtime: dirEntry.mtime,
});
}
function filenameWithoutExt(filename) {
var ext = path.extname(filename);
return filename.substring(0, filename.length - ext.length);
}
function closeFile(file) {
file.close(function(err) {
if (err) {
log.error("Error closing", file, err.stack);
}
});
}
function parseTrackString(trackStr) {
if (!trackStr) return {};
var parts = trackStr.split('/');
if (parts.length > 1) {
return {
value: parseIntOrNull(parts[0]),
total: parseIntOrNull(parts[1]),
};
}
return {
value: parseIntOrNull(parts[0]),
};
}
function parseIntOrNull(n) {
n = parseInt(n, 10);
if (isNaN(n)) return null;
return n;
}
function parseFloatOrNull(n) {
n = parseFloat(n);
if (isNaN(n)) return null;
return n;
}
function grooveFileToDbFile(file, filenameHintWithoutPath, object) {
object = object || {key: uuid()};
var parsedTrack = parseTrackString(file.getMetadata("track"));
var parsedDisc = parseTrackString(
file.getMetadata("disc") ||
file.getMetadata("TPA") ||
file.getMetadata("TPOS"));
object.name = (file.getMetadata("title") || filenameWithoutExt(filenameHintWithoutPath) || "").trim();
object.artistName = (file.getMetadata("artist") || "").trim();
object.composerName = (file.getMetadata("composer") ||
file.getMetadata("TCM") || "").trim();
object.performerName = (file.getMetadata("performer") || "").trim();
object.albumArtistName = (file.getMetadata("album_artist") || "").trim();
object.albumName = (file.getMetadata("album") || "").trim();
object.compilation = !!(parseInt(file.getMetadata("TCP"), 10) ||
parseInt(file.getMetadata("TCMP"), 10) ||
file.getMetadata("COMPILATION") ||
file.getMetadata("Compilation") ||
file.getMetadata("cpil") ||
file.getMetadata("WM/IsCompilation"));
object.track = parsedTrack.value;
object.trackCount = parsedTrack.total;
object.disc = parsedDisc.value;
object.discCount = parsedDisc.total;
object.duration = file.duration();
object.year = parseIntOrNull(file.getMetadata("date"));
object.genre = file.getMetadata("genre");
object.replayGainTrackGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_GAIN"));
object.replayGainTrackPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_PEAK"));
object.replayGainAlbumGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_GAIN"));
object.replayGainAlbumPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_PEAK"));
object.labels = {};
return object;
}
function uniqueFilename(filename) {
// break into parts
var dirname = path.dirname(filename);
var basename = path.basename(filename);
var extname = path.extname(filename);
var withoutExt = basename.substring(0, basename.length - extname.length);
var match = withoutExt.match(/_(\d+)$/);
var withoutMatch;
var number;
if (match) {
number = parseInt(match[1], 10);
if (!number) number = 0;
withoutMatch = withoutExt.substring(0, match.index);
} else {
number = 0;
withoutMatch = withoutExt;
}
number += 1;
// put it back together
var newBasename = withoutMatch + "_" + number + extname;
return path.join(dirname, newBasename);
}
function dBToFloat(dB) {
return Math.exp(dB * DB_SCALE);
}
function ensureSep(dir) {
return (dir[dir.length - 1] === path.sep) ? dir : (dir + path.sep);
}
function ensureGrooveVersionIsOk() {
var ver = groove.getVersion();
var verStr = ver.major + '.' + ver.minor + '.' + ver.patch;
var reqVer = '>=4.1.1';
if (semver.satisfies(verStr, reqVer)) return;
log.fatal("Found libgroove", verStr, "need", reqVer);
process.exit(1);
}
function playlistItemKey(playlist, item) {
return PLAYLIST_KEY_PREFIX + playlist.id + '.' + item.id;
}
function playlistKey(playlist) {
return PLAYLIST_META_KEY_PREFIX + playlist.id;
}
function serializePlaylist(playlist) {
return JSON.stringify({
id: playlist.id,
name: playlist.name,
mtime: playlist.mtime,
});
}
function deserializePlaylist(str) {
var playlist = JSON.parse(str);
playlist.items = {};
return playlist;
}
function zfill(number, size) {
number = String(number);
while (number.length < size) number = "0" + number;
return number;
}
function setGrooveLoggingLevel() {
switch (log.level) {
case log.levels.Fatal:
case log.levels.Error:
case log.levels.Info:
case log.levels.Warn:
groove.setLogging(groove.LOG_QUIET);
break;
case log.levels.Debug:
groove.setLogging(groove.LOG_INFO);
break;
}
}
function importFileAsSong(self, srcFullPath, filenameHintWithoutPath, cb) {
groove.open(srcFullPath, function(err, file) {
if (err) return cb(err);
var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath);
var suggestedPath = self.getSuggestedPath(newDbFile, filenameHintWithoutPath);
var pend = new Pend();
pend.go(function(cb) {
log.debug("importFileAsSong close file:", file.filename);
file.close(cb);
});
pend.go(function(cb) {
tryMv(suggestedPath, cb);
});
pend.wait(function(err) {
if (err) return cb(err);
cb(null, [newDbFile]);
});
function tryMv(destRelPath, cb) {
var destFullPath = path.join(self.musicDirectory, destRelPath);
// before importFileAsSong is called, file system watching is disabled.
// So we can safely move files into the library without triggering an
// update db.
mv(srcFullPath, destFullPath, {mkdirp: true, clobber: false}, function(err) {
if (err) {
if (err.code === 'EEXIST') {
tryMv(uniqueFilename(destRelPath), cb);
} else {
cb(err);
}
return;
}
onAddOrChange(self, destRelPath, (new Date()).getTime(), function(err, dbFile) {
if (err) return cb(err);
newDbFile = dbFile;
cb();
});
});
}
});
}
function importFileAsZip(self, srcFullPath, filenameHintWithoutPath, cb) {
yauzl.open(srcFullPath, function(err, zipfile) {
if (err) return cb(err);
var allDbFiles = [];
var pend = new Pend();
zipfile.on('error', handleError);
zipfile.on('entry', onEntry);
zipfile.on('end', onEnd);
function onEntry(entry) {
if (/\/$/.test(entry.fileName)) {
// ignore directories
return;
}
pend.go(function(cb) {
zipfile.openReadStream(entry, function(err, readStream) {
if (err) {
log.warn("Error reading zip file:", err.stack);
cb();
return;
}
var entryBaseName = path.basename(entry.fileName);
self.importStream(readStream, entryBaseName, entry.uncompressedSize, function(err, dbFiles) {
if (err) {
log.warn("unable to import entry from zip file:", err.stack);
} else if (dbFiles) {
allDbFiles = allDbFiles.concat(dbFiles);
}
cb();
});
});
});
}
function onEnd() {
pend.wait(function() {
unlinkZipFile();
cb(null, allDbFiles);
});
}
function handleError(err) {
unlinkZipFile();
cb(err);
}
function unlinkZipFile() {
fs.unlink(srcFullPath, function(err) {
if (err) {
log.error("Unable to remove zip file after importing:", err.stack);
}
});
}
});
}
// sort keys according to how they appear in the library
function sortTracks(tracks) {
var lib = new MusicLibraryIndex();
tracks.forEach(function(track) {
lib.addTrack(track);
});
lib.rebuildTracks();
var results = [];
lib.artistList.forEach(function(artist) {
artist.albumList.forEach(function(album) {
album.trackList.forEach(function(track) {
results.push(track);
});
});
});
return results;
}
function logIfDbError(err) {
if (err) {
log.error("Unable to update DB:", err.stack);
}
}
function makeLower(str) {
return str.toLowerCase();
}
function copySet(set) {
var out = {};
for (var key in set) {
out[key] = 1;
}
return out;
}
| mit |
hanguofeng/gocaptcha | README.md | 1242 | ***
View in [[English](README-en.md)][[中文](README.md)]
***
# gocaptcha
go语言验证码服务器
Feature
-------
* 支持中文验证码
* 支持自定义词库、字库
* 支持自定义滤镜机制,通过滤镜来增加干扰,加大识别难度
* 当前的滤镜包括:
* 支持干扰点
* 支持干扰线
* 支持其他模式的干扰
* 更多模式,可实现imagefilter接口来扩展
* 支持自定义存储引擎,存储引擎可扩展
* 目前支持的存储引擎包括:
* 内置(buildin)
* memcache
* redis (from https://github.com/dtynn/gocaptcha)
* 如需扩展存储引擎,可实现StoreInterface接口
Useage
------
**安装**
go get github.com/hanguofeng/gocaptcha
**Quick Start**
参考 [captcha_test.go](captcha_test.go)
参考 [samples/gocaptcha-server](samples/gocaptcha-server)
[Demo](http://hanguofeng-gocaptcha.daoapp.io/)
**文档**
[[captcha.go Wiki](https://github.com/hanguofeng/gocaptcha/wiki)]
TODO
----
* 运维管理工具
LICENCE
-------
gocaptcha使用[[MIT许可协议](LICENSE)]
使用的开源软件列表,表示感谢
* https://github.com/dchest/captcha
* https://github.com/golang/freetype
* https://github.com/bradfitz/gomemcache
* https://code.google.com/p/zpix/
| mit |
poligen/Tealeaf | prep_course/variables/age.rb | 291 |
def add_age
puts "How old are you?"
age = gets.chomp
puts "In 10 years you will be:"
puts age.to_i + 10
puts "In 20 years you will be:"
puts age.to_i + 20
puts "In 30 years you will be:"
puts age.to_i + 30
puts "In 40 years you will be:"
puts age.to_i + 40
end
add_age
| mit |
SummerBuger/summerbuger.github.io | archives/2016/index.html | 17538 | <!DOCTYPE html>
<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="Hexo, NexT" />
<meta name="description" content="About technology and about life.">
<meta property="og:type" content="website">
<meta property="og:title" content="Ice summer bug's notes">
<meta property="og:url" content="https://summerbuger.github.io/archives/2016/index.html">
<meta property="og:site_name" content="Ice summer bug's notes">
<meta property="og:description" content="About technology and about life.">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Ice summer bug's notes">
<meta name="twitter:description" content="About technology and about life.">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Mist',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="https://summerbuger.github.io/archives/2016/"/>
<title>归档 | Ice summer bug's notes</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left page-archive">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Ice summer bug's notes</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div class="post-block archive">
<div id="posts" class="posts-collapse">
<span class="archive-move-on"></span>
<span class="archive-page-counter">
好! 目前共计 55 篇日志。 继续努力。
</span>
<div class="collection-title">
<h1 class="archive-year" id="archive-year-2016">2016</h1>
</div>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/12/10/技术/spring/2016-12-10-SpringMvc-@ControllerAdvice/" itemprop="url">
<span itemprop="name">SpringMVC 中的 @ControllerAdvice</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-12-10T21:00:00+08:00"
content="2016-12-10" >
12-10
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/12/01/技术/spring/2016-12-01-SpringMVC源码学习-mvc加载过程/" itemprop="url">
<span itemprop="name">SpringMVC源码学习 —— MVC 配置加载过程</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-12-01T21:00:00+08:00"
content="2016-12-01" >
12-01
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/26/技术/java/2016-10-26-分布式锁/" itemprop="url">
<span itemprop="name">几种分布式锁的实现方式</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-26T21:00:00+08:00"
content="2016-10-26" >
10-26
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-XMLMapperBuilder/" itemprop="url">
<span itemprop="name">mybatis 中的 Configuration</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-16T21:00:00+08:00"
content="2016-10-16" >
10-16
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperBuilderAssistant/" itemprop="url">
<span itemprop="name">mybatis 中的 MapperBuilderAssistant</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-16T21:00:00+08:00"
content="2016-10-16" >
10-16
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-Configuration/" itemprop="url">
<span itemprop="name">mybatis 中的 Configuration</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-16T21:00:00+08:00"
content="2016-10-16" >
10-16
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperAnnotationBuilder/" itemprop="url">
<span itemprop="name">mybatis 中的 MapperAnnotationBuilder</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-16T21:00:00+08:00"
content="2016-10-16" >
10-16
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperMethod/" itemprop="url">
<span itemprop="name">mybatis 中的 MapperMethod</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-10-16T21:00:00+08:00"
content="2016-10-16" >
10-16
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/09/20/技术/mybatis/2016-09-20-mybatis源码阅读/" itemprop="url">
<span itemprop="name">mybatis 源码阅读(一)</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-09-20T21:00:00+08:00"
content="2016-09-20" >
09-20
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/09/13/技术/java/2016-09-13-CPU占用过高处理过程/" itemprop="url">
<span itemprop="name">线上应用故障排查</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-09-13T21:00:00+08:00"
content="2016-09-13" >
09-13
</time>
</div>
</header>
</article>
</div>
</div>
<nav class="pagination">
<span class="page-number current">1</span><a class="page-number" href="/archives/2016/page/2/">2</a><a class="extend next" rel="next" href="/archives/2016/page/2/"><i class="fa fa-angle-right"></i></a>
</nav>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview-wrap sidebar-panel sidebar-panel-active">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="/images/headPicture.png"
alt="Liam Chen" />
<p class="site-author-name" itemprop="name">Liam Chen</p>
<p class="site-description motion-element" itemprop="description">About technology and about life.</p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">55</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">21</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">41</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© <span itemprop="copyrightYear">2019</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">Liam Chen</span>
</div>
<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
<span class="post-meta-divider">|</span>
<div class="theme-info">主题 — <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>
</body>
</html>
| mit |
jskit/kit-start | src/config/api.js | 6364 | import { stringify } from 'qs'
import _request from '@/utils/request'
import mini from '@/utils/mini'
import env from '@/config/env'
// import { modelApis, commonParams } from './model'
// import { version } from '../package.json'
let apiBaseUrl
apiBaseUrl = `${env.apiBaseUrl}`
const regHttp = /^https?/i
const isMock = true;
// const regMock = /^mock?/i
function compact(obj) {
for (const key in obj) {
if (!obj[key]) {
delete obj[key]
}
}
return obj
}
function request(url, options, success, fail) {
const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}`
return _request(originUrl, compact(options), success, fail)
}
/**
* API 命名规则
* - 使用 camelCase 命名格式(小驼峰命名)
* - 命名尽量对应 RESTful 风格,`${动作}${资源}`
* - 假数据增加 fake 前缀
* - 便捷易用大于规则,程序是给人看的
*/
// api 列表
const modelApis = {
// 初始化配置
test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/',
getConfig: '/common/initconfig',
getWxSign: '/common/getwxsign',
// 积分兑换
getPointIndex: '/point/index',
getPointList: '/point/skulist',
getPointDetail: '/point/iteminfo',
getPointDetaiMore: '/product/productdetail',
getRList: '/point/recommenditems',
// 专题
getPointTopicInfo: '/point/topicinfo',
getPointTopicList: '/point/topicbuskulist',
// 主站专题
getTopicInfo: '/product/topicskusinfo',
getTopicList: '/product/topicskulist',
// 个人中心
getProfile: '/user/usercenter',
// 拼团相关
getCoupleList: '/product/coupleskulist',
getCoupleDetail: '/product/coupleskudetail',
getMerchantList: '/merchant/coupleskulist',
coupleOrderInit: 'POST /order/coupleorderinit',
coupleOrderList: '/user/usercouplelist',
coupleOrderDetail: '/user/usercoupleorderdetail',
coupleUserList: '/market/pinactivitiesuserlist', // 分享页拼团头像列表
coupleShareDetail: '/user/coupleactivitiedetail', // 分享详情
// 首页
getIndex: '/common/index',
getIndexNew: '/common/index_v1',
getHotSearch: '/common/hotsearchsug',
// 主流程
orderInit: 'POST /order/orderinit',
orderSubmit: 'POST /order/submitorder',
orderPay: 'POST /order/orderpay',
orderPayConfirm: '/order/orderpayconfirm', // 确认支付状态
getUserOrders: '/order/getuserorders', // 订单列表
getNeedCommentOrders: '/order/waitcommentlist', // 待评论
getUserRefundorders: '/order/userrefundorder', // 退款
getUserServiceOrders: '/order/userserviceorders', // 售后
orderCancel: 'POST /order/cancelorder', // 取消订单
orderDetail: '/order/orderdetail',
confirmReceived: 'POST /order/userorderconfirm', // 确认收货
orderComplaint: 'POST /refund/complaint', // 订单申诉
// 积分订单相关
pointOrderInit: 'POST /tradecenter/pointorderpreview',
pointOrderSubmit: 'POST /tradecenter/pointordersubmit',
pointOrderCancel: 'POST /tradecenter/ordercancel',
pointOrderList: '/tradecenter/orderlist',
pointOrderDetail: '/tradecenter/orderinfo',
pointOrderSuccess: '/tradecenter/ordersuccess',
// 退款相关
refundInit: '/refund/init',
refundDetail: '/refund/detail',
refundApply: 'POST /refund/apply',
// 登录注销
login: 'POST /user/login',
logout: 'POST /user/logout',
// 地址管理
addressList: '/user/addresslist',
addAddress: 'POST /user/addaddress',
updateAddress: 'POST /user/updateaddress',
setDefaultAddress: 'POST /user/setdefaultaddress',
deleteAddress: 'POST /user/deleteaddress',
provinceList: '/nation/provincelist',
cityList: '/nation/citylist',
districtList: '/nation/districtlist',
// 查看物流
getDelivery: '/order/deliverymessage',
// 获取七牛 token
getQiniuToken: '/common/qiniutoken',
}
// 仅限本地调试支持
// if (__DEV__ && env.mock) {
if (__DEV__ && isMock) {
apiBaseUrl = `${env.apiMockUrl}`
// Object.assign(modelApis, require('../mock'))
}
// 线上代理
if (__DEV__ && env.proxy) {
const proxyUrl = '/proxy'
apiBaseUrl = `${env.origin}${proxyUrl}`
}
const {
width,
height,
} = window.screen
// 公共参数
const commonParams = {
uuid: '', // 用户唯一标志
udid: '', // 设备唯一标志
device: '', // 设备
net: '', // 网络
uid: '',
token: '',
timestamp: '', // 时间
channel: 'h5', // 渠道
spm: 'h5',
v: env.version, // 系统版本
terminal: env.terminal, // 终端
swidth: width, // 屏幕宽度 分辨率
sheight: height, // 屏幕高度
location: '', // 地理位置
zoneId: 857, // 必须
}
// console.log(Object.keys(modelApis))
const apiList = Object.keys(modelApis).reduce((api, key) => {
const val = modelApis[key]
const [url, methodType = 'GET'] = val.split(/\s+/).reverse()
const method = methodType.toUpperCase()
// let originUrl = regHttp.test(url) ? url : `${env.apiBaseUrl}${url}`;
// NOTE: headers 在此处设置?
// if (__DEV__ && regLocalMock.test(url)) {
// api[key] = function postRequest(params, success, fail) {
// const res = require(`../${url}.json`)
// mini.hideLoading()
// res.errno === 0 ? success(res) : fail(res)
// }
// return api
// }
switch (method) {
case 'POST':
// originUrl = `${originUrl}`;
api[key] = function postRequest(params, success, fail) {
return request(url, {
headers: {
// Accept: 'application/json',
// 我们的 post 请求,使用的这个,不是 application/json
// 'Content-Type': 'application/x-www-form-urlencoded',
},
method,
data: compact(Object.assign({}, getCommonParams(), params)),
}, success, fail)
}
break
case 'GET':
default:
api[key] = function getRequest(params, success, fail) {
params = compact(Object.assign({}, getCommonParams(), params))
let query = stringify(params)
if (query) query = `?${query}`
return request(`${url}${query}`, {}, success, fail)
}
break
}
return api
}, {})
function setCommonParams(params) {
return Object.assign(commonParams, params)
}
function getCommonParams(key) {
return key ? commonParams[key] : {
// ...commonParams,
}
}
apiList.getCommonParams = getCommonParams
apiList.setCommonParams = setCommonParams
// console.log(apiList)
export default apiList
| mit |
thiagocatarse/catarse.js | src/root/projects-contribution-report.js | 8807 | import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import models from '../models';
import h from '../h';
import projectDashboardMenu from '../c/project-dashboard-menu';
import projectContributionReportHeader from '../c/project-contribution-report-header';
import projectContributionReportContent from '../c/project-contribution-report-content';
import projectsContributionReportVM from '../vms/projects-contribution-report-vm';
import FilterMain from '../c/filter-main';
import FilterDropdown from '../c/filter-dropdown';
import InfoProjectContributionLegend from '../c/info-project-contribution-legend';
import ProjectContributionStateLegendModal from '../c/project-contribution-state-legend-modal';
import ProjectContributionDeliveryLegendModal from '../c/project-contribution-delivery-legend-modal';
const projectContributionReport = {
controller(args) {
const listVM = postgrest.paginationVM(models.projectContribution, 'id.desc', {
Prefer: 'count=exact'
}),
filterVM = projectsContributionReportVM,
project = m.prop([{}]),
rewards = m.prop([]),
contributionStateOptions = m.prop([]),
reloadSelectOptions = (projectState) => {
let opts = [{
value: '',
option: 'Todos'
}];
const optionsMap = {
online: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'pending',
option: 'Iniciado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
],
waiting_funds: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'pending',
option: 'Iniciado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
],
failed: [{
value: 'pending_refund',
option: 'Reembolso em andamento'
},
{
value: 'refunded',
option: 'Reembolsado'
},
{
value: 'paid',
option: 'Reembolso não iniciado'
},
],
successful: [{
value: 'paid',
option: 'Confirmado'
},
{
value: 'refunded,chargeback,deleted,pending_refund',
option: 'Contestado'
},
]
};
opts = opts.concat(optionsMap[projectState] || []);
contributionStateOptions(opts);
},
submit = () => {
if (filterVM.reward_id() === 'null') {
listVM.firstPage(filterVM.withNullParameters()).then(null);
} else {
listVM.firstPage(filterVM.parameters()).then(null);
}
return false;
},
filterBuilder = [{
component: FilterMain,
data: {
inputWrapperClass: '.w-input.text-field',
btnClass: '.btn.btn-medium',
vm: filterVM.full_text_index,
placeholder: 'Busque por nome ou email do apoiador'
}
},
{
label: 'reward_filter',
component: FilterDropdown,
data: {
label: 'Recompensa selecionada',
onchange: submit,
name: 'reward_id',
vm: filterVM.reward_id,
wrapper_class: '.w-sub-col.w-col.w-col-4',
options: []
}
},
{
label: 'delivery_filter',
component: FilterDropdown,
data: {
custom_label: [InfoProjectContributionLegend, {
content: [ProjectContributionDeliveryLegendModal],
text: 'Status da entrega'
}],
onchange: submit,
name: 'delivery_status',
vm: filterVM.delivery_status,
wrapper_class: '.w-col.w-col-4',
options: [{
value: '',
option: 'Todos'
},
{
value: 'undelivered',
option: 'Não enviada'
},
{
value: 'delivered',
option: 'Enviada'
},
{
value: 'error',
option: 'Erro no envio'
},
{
value: 'received',
option: 'Recebida'
}
]
}
},
{
label: 'payment_state',
component: FilterDropdown,
data: {
custom_label: [InfoProjectContributionLegend, {
text: 'Status do apoio',
content: [ProjectContributionStateLegendModal, {
project
}]
}],
name: 'state',
onchange: submit,
vm: filterVM.state,
wrapper_class: '.w-sub-col.w-col.w-col-4',
options: contributionStateOptions
}
}
];
filterVM.project_id(args.root.getAttribute('data-id'));
const lReward = postgrest.loaderWithToken(models.rewardDetail.getPageOptions({
project_id: `eq.${filterVM.project_id()}`
}));
const lProject = postgrest.loaderWithToken(models.projectDetail.getPageOptions({
project_id: `eq.${filterVM.project_id()}`
}));
lReward.load().then(rewards);
lProject.load().then((data) => {
project(data);
reloadSelectOptions(_.first(data).state);
});
const mapRewardsToOptions = () => {
let options = [];
if (!lReward()) {
options = _.map(rewards(), r => ({
value: r.id,
option: `R$ ${h.formatNumber(r.minimum_value, 2, 3)} - ${r.description.substring(0, 20)}`
}));
}
options.unshift({
value: null,
option: 'Sem recompensa'
});
options.unshift({
value: '',
option: 'Todas'
});
return options;
};
if (!listVM.collection().length) {
listVM.firstPage(filterVM.parameters());
}
return {
listVM,
filterVM,
filterBuilder,
submit,
lReward,
lProject,
rewards,
project,
mapRewardsToOptions
};
},
view(ctrl) {
const list = ctrl.listVM;
if (!ctrl.lProject()) {
return [
m.component(projectDashboardMenu, {
project: m.prop(_.first(ctrl.project()))
}),
m.component(projectContributionReportHeader, {
submit: ctrl.submit,
filterBuilder: ctrl.filterBuilder,
form: ctrl.filterVM.formDescriber,
mapRewardsToOptions: ctrl.mapRewardsToOptions,
filterVM: ctrl.filterVM
}),
m('.divider.u-margintop-30'),
m.component(projectContributionReportContent, {
submit: ctrl.submit,
list,
filterVM: ctrl.filterVM,
project: m.prop(_.first(ctrl.project()))
})
];
}
return h.loader();
}
};
export default projectContributionReport;
| mit |
localheinz/Faker | src/Faker/Provider/fa_IR/PhoneNumber.php | 2348 | <?php
namespace Faker\Provider\fa_IR;
class PhoneNumber extends \Faker\Provider\PhoneNumber
{
/**
* @link https://fa.wikipedia.org/wiki/%D8%B4%D9%85%D8%A7%D8%B1%D9%87%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%AA%D9%84%D9%81%D9%86_%D8%AF%D8%B1_%D8%A7%DB%8C%D8%B1%D8%A7%D9%86#.D8.AA.D9.84.D9.81.D9.86.E2.80.8C.D9.87.D8.A7.DB.8C_.D9.87.D9.85.D8.B1.D8.A7.D9.87
*/
protected static $formats = array( // land line formts seprated by province
"011########", //Mazandaran
"013########", //Gilan
"017########", //Golestan
"021########", //Tehran
"023########", //Semnan
"024########", //Zanjan
"025########", //Qom
"026########", //Alborz
"028########", //Qazvin
"031########", //Isfahan
"034########", //Kerman
"035########", //Yazd
"038########", //Chaharmahal and Bakhtiari
"041########", //East Azerbaijan
"044########", //West Azerbaijan
"045########", //Ardabil
"051########", //Razavi Khorasan
"054########", //Sistan and Baluchestan
"056########", //South Khorasan
"058########", //North Khorasan
"061########", //Khuzestan
"066########", //Lorestan
"071########", //Fars
"074########", //Kohgiluyeh and Boyer-Ahmad
"076########", //Hormozgan
"077########", //Bushehr
"081########", //Hamadan
"083########", //Kermanshah
"084########", //Ilam
"086########", //Markazi
"087########", //Kurdistan
);
protected static $mobileNumberPrefixes = array(
'0910#######',//mci
'0911#######',
'0912#######',
'0913#######',
'0914#######',
'0915#######',
'0916#######',
'0917#######',
'0918#######',
'0919#######',
'0901#######',
'0901#######',
'0902#######',
'0903#######',
'0930#######',
'0933#######',
'0935#######',
'0936#######',
'0937#######',
'0938#######',
'0939#######',
'0920#######',
'0921#######',
'0937#######',
'0990#######', // MCI
);
public static function mobileNumber()
{
return static::numerify(static::randomElement(static::$mobileNumberPrefixes));
}
}
| mit |
bsmr-x-script/vscode | src/vs/workbench/services/request/node/requestService.ts | 5651 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise, Promise } from 'vs/base/common/winjs.base';
import { xhr } from 'vs/base/common/network';
import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry';
import strings = require('vs/base/common/strings');
import nls = require('vs/nls');
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import platform = require('vs/platform/platform');
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { BaseRequestService } from 'vs/platform/request/common/baseRequestService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { assign } from 'vs/base/common/objects';
import { IXHROptions, IXHRResponse } from 'vs/base/common/http';
import { request } from 'vs/base/node/request';
import { getProxyAgent } from 'vs/base/node/proxy';
import { createGunzip } from 'zlib';
import { Stream } from 'stream';
interface IHTTPConfiguration {
http?: {
proxy?: string;
proxyStrictSSL?: boolean;
};
}
export class RequestService extends BaseRequestService {
private disposables: IDisposable[];
private proxyUrl: string = null;
private strictSSL: boolean = true;
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IConfigurationService configurationService: IConfigurationService,
@ITelemetryService telemetryService?: ITelemetryService
) {
super(contextService, telemetryService);
this.disposables = [];
const config = configurationService.getConfiguration<IHTTPConfiguration>();
this.configure(config);
const disposable = configurationService.onDidUpdateConfiguration(e => this.configure(e.config));
this.disposables.push(disposable);
}
private configure(config: IHTTPConfiguration) {
this.proxyUrl = config.http && config.http.proxy;
this.strictSSL = config.http && config.http.proxyStrictSSL;
}
makeRequest(options: IXHROptions): TPromise<IXHRResponse> {
let url = options.url;
if (!url) {
throw new Error('IRequestService.makeRequest: Url is required.');
}
// Support file:// in native environment through XHR
if (strings.startsWith(url, 'file://')) {
return xhr(options).then(null, (xhr: XMLHttpRequest) => {
if (xhr.status === 0 && xhr.responseText) {
return xhr; // loading resources locally returns a status of 0 which in WinJS is an error so we need to handle it here
}
return <any>Promise.wrapError({ status: 404, responseText: nls.localize('localFileNotFound', "File not found.")});
});
}
return super.makeRequest(options);
}
protected makeCrossOriginRequest(options: IXHROptions): TPromise<IXHRResponse> {
const { proxyUrl, strictSSL } = this;
const agent = getProxyAgent(options.url, { proxyUrl, strictSSL });
options = assign({}, options);
options = assign(options, { agent, strictSSL });
return request(options).then(result => new TPromise<IXHRResponse>((c, e, p) => {
const res = result.res;
let stream: Stream = res;
if (res.headers['content-encoding'] === 'gzip') {
stream = stream.pipe(createGunzip());
}
const data: string[] = [];
stream.on('data', c => data.push(c));
stream.on('end', () => {
const status = res.statusCode;
if (options.followRedirects > 0 && (status >= 300 && status <= 303 || status === 307)) {
let location = res.headers['location'];
if (location) {
let newOptions = {
type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers,
timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
};
xhr(newOptions).done(c, e, p);
return;
}
}
const response: IXHRResponse = {
responseText: data.join(''),
status,
getResponseHeader: header => res.headers[header],
readyState: 4
};
if ((status >= 200 && status < 300) || status === 1223) {
c(response);
} else {
e(response);
}
});
}, err => {
let message: string;
if (agent) {
message = 'Unable to to connect to ' + options.url + ' through a proxy . Error: ' + err.message;
} else {
message = 'Unable to to connect to ' + options.url + '. Error: ' + err.message;
}
return TPromise.wrapError<IXHRResponse>({
responseText: message,
status: 404
});
}));
}
dispose(): void {
this.disposables = dispose(this.disposables);
}
}
// Configuration
let confRegistry = <IConfigurationRegistry>platform.Registry.as(Extensions.Configuration);
confRegistry.registerConfiguration({
id: 'http',
order: 15,
title: nls.localize('httpConfigurationTitle', "HTTP configuration"),
type: 'object',
properties: {
'http.proxy': {
type: 'string',
pattern: '^https?://[^:]+(:\\d+)?$|^$',
description: nls.localize('proxy', "The proxy setting to use. If not set will be taken from the http_proxy and https_proxy environment variables")
},
'http.proxyStrictSSL': {
type: 'boolean',
default: true,
description: nls.localize('strictSSL', "Whether the proxy server certificate should be verified against the list of supplied CAs.")
}
}
}); | mit |
siuying/KaifKit | Example/KaifKit/IGViewController.h | 226 | //
// IGViewController.h
// KaifKit
//
// Created by Francis Chong on 04/15/2015.
// Copyright (c) 2014 Francis Chong. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface IGViewController : UIViewController
@end
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/globalize/0.1.1/cultures/globalize.culture.da.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:f5c198d5eef0ca0f41f87746ef8fefe819a727fcd59a6477c76b94b55d27128d
size 1730
| mit |
tonimedina/crobo | app/widgets/featured_news.php | 4331 | <?php
$news = array(
array(
'created_at' => '2015-04-29 00:00:00',
'image' => 'http://fakeimg.pl/768x370/3c3c3c/',
'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/',
'title' => 'Blimps to Defend Washington, D.C. Airspace',
'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in pulvinar neque. Duis in pharetra purus. Mauris varius porttitor augue in iaculis. Phasellus tincidunt justo magna, eget porta est sagittis quis. Quisque at ante nec dolor euismod elementum sit amet hendrerit nibh. Etiam ut odio tortor. Mauris blandit purus et mauris gravida, eget gravida nulla convallis.</p><p>Vivamus vehicula dignissim malesuada. Donec cursus luctus mi, ac sagittis arcu scelerisque a. Nullam et metus quis sem mollis accumsan. Aenean in sapien pretium, pretium leo eu, ullamcorper sapien. Nulla tempus, metus eu iaculis posuere, ipsum ex faucibus velit, cursus condimentum ligula ex non enim. Aliquam iaculis pellentesque erat molestie feugiat. Morbi ornare maximus rutrum. Pellentesque id euismod erat, eget aliquam massa.</p>'
),
array(
'created_at' => '2015-04-26 00:00:00',
'image' => 'http://fakeimg.pl/768x370/3c3c3c/',
'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/',
'title' => 'Eye Receptor Transplants May Restore Eyesight to the Blind',
'content' => '<p>Praesent cursus lobortis dui eu congue. Phasellus pellentesque posuere commodo. Curabitur dignissim placerat sapien, nec egestas ante. Mauris nec commodo est, ac faucibus massa. Nam et dolor at est dignissim condimentum. Quisque consequat tempus aliquam. Mauris consectetur rutrum efficitur.</p><p>Quisque vulputate massa velit, at facilisis turpis euismod id. Pellentesque molestie lectus ut nisl dignissim sagittis. Sed vitae rutrum turpis. Aenean ex est, sagittis vel lectus nec, suscipit condimentum ligula. Ut vitae vehicula lectus. Morbi sit amet cursus arcu. Curabitur quis nunc ultrices, suscipit erat vel, faucibus diam. Sed odio turpis, consequat eu feugiat a, porttitor eget nisl.</p>'
),
array(
'created_at' => '2015-04-27 00:00:00',
'image' => 'http://fakeimg.pl/768x370/3c3c3c/',
'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/',
'title' => 'Researchers Look to Tattoos to Monitor Your Sweat',
'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultricies malesuada risus, at pretium elit scelerisque in. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vel risus sed leo suscipit tempus vel vel eros. Suspendisse augue elit, tempor a leo tempus, egestas hendrerit leo. Fusce mattis quam magna, ut mattis nulla ultrices at. Etiam sollicitudin tempus placerat. Nulla facilisi. Praesent non porttitor diam, imperdiet volutpat dolor. Pellentesque viverra consectetur auctor. Etiam metus purus, accumsan ac efficitur et, laoreet ut orci. Phasellus rutrum rhoncus lacus a imperdiet. Nam ac scelerisque quam. Donec vitae est pharetra, consequat risus et, maximus odio.</p>'
),
);
?>
<?php if ( isset( $news ) ) : ?>
<div class="widget widget-featured-news">
<div class="widget-header">
<h3 class="widget-title">
<i class="glyphicon glyphicon-star"></i>
Featured News
</h3>
<!-- /.widget-title -->
</div>
<!-- /.widget-header -->
<div class="widget-content">
<ul class="list-unstyled">
<?php foreach ( $news as $new ) : ?>
<li data-title="<?php echo $new['title']; ?>">
<a href="#">
<img alt="<?php echo $new['title']; ?>" class="img-responsive" height="370" src="<?php echo $new['image']; ?>" width="768">
</a>
<h2><a href="#"><?php echo $new['title']; ?></a></h2>
<div class="article hidden">
<button class="btn btn-close" type="button"><i class="glyphicon glyphicon-remove"></i></button>
<p class="h2"><?php echo $new['title']; ?></p>
<!-- /.h2 -->
<?php echo $new['content']; ?>
</div>
<!-- /.article hidden -->
</li>
<?php endforeach; ?>
</ul>
<!-- /.list-unstyled -->
</div>
<!-- /.widget-content -->
</div>
<!-- /.widget widget-featured-news -->
<?php endif; ?>
| mit |
Dreedi/Dreedi | README.md | 296 | # Dreedi
To start your this app:
1. Install dependencies with `mix deps.get`
2. Create and migrate your database with `mix ecto.create && mix ecto.migrate`
3. Start Phoenix endpoint with `mix phoenix.server`
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
| mit |
pratheep1231kumar/mpps | README.md | 22 | # mpps
web repository
| mit |
g33kidd/bracket | database/migrations/2016_05_25_043614_create_platforms_table.php | 703 | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePlatformsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('platforms', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('short_name');
$table->string('slug')->unique();
$table->string('logo');
$table->string('banner');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('platforms');
}
}
| mit |
sferik/rails_admin | spec/helpers/rails_admin/application_helper_spec.rb | 17723 | require 'spec_helper'
RSpec.describe RailsAdmin::ApplicationHelper, type: :helper do
describe '#authorized?' do
let(:abstract_model) { RailsAdmin.config(FieldTest).abstract_model }
it 'doesn\'t use unpersisted objects' do
expect(helper).to receive(:action).with(:edit, abstract_model, nil).and_call_original
helper.authorized?(:edit, abstract_model, FactoryBot.build(:field_test))
end
end
describe 'with #authorized? stubbed' do
before do
allow(controller).to receive(:authorized?).and_return(true)
end
describe '#current_action?' do
it 'returns true if current_action, false otherwise' do
@action = RailsAdmin::Config::Actions.find(:index)
expect(helper.current_action?(RailsAdmin::Config::Actions.find(:index))).to be_truthy
expect(helper.current_action?(RailsAdmin::Config::Actions.find(:show))).not_to be_truthy
end
end
describe '#action' do
it 'returns action by :custom_key' do
RailsAdmin.config do |config|
config.actions do
dashboard do
custom_key :my_custom_dashboard_key
end
end
end
expect(helper.action(:my_custom_dashboard_key)).to be
end
it 'returns only visible actions' do
RailsAdmin.config do |config|
config.actions do
dashboard do
visible false
end
end
end
expect(helper.action(:dashboard)).to be_nil
end
it 'returns only visible actions, passing all bindings' do
RailsAdmin.config do |config|
config.actions do
member :test_bindings do
visible do
bindings[:controller].is_a?(ActionView::TestCase::TestController) &&
bindings[:abstract_model].model == Team &&
bindings[:object].is_a?(Team)
end
end
end
end
expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Team.new)).to be
expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Player.new)).to be_nil
expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Player), Team.new)).to be_nil
end
end
describe '#actions' do
it 'returns actions by type' do
abstract_model = RailsAdmin::AbstractModel.new(Player)
object = FactoryBot.create :player
expect(helper.actions(:all, abstract_model, object).collect(&:custom_key)).to eq([:dashboard, :index, :show, :new, :edit, :export, :delete, :bulk_delete, :history_show, :history_index, :show_in_app])
expect(helper.actions(:root, abstract_model, object).collect(&:custom_key)).to eq([:dashboard])
expect(helper.actions(:collection, abstract_model, object).collect(&:custom_key)).to eq([:index, :new, :export, :bulk_delete, :history_index])
expect(helper.actions(:member, abstract_model, object).collect(&:custom_key)).to eq([:show, :edit, :delete, :history_show, :show_in_app])
end
it 'only returns visible actions, passing bindings correctly' do
RailsAdmin.config do |config|
config.actions do
member :test_bindings do
visible do
bindings[:controller].is_a?(ActionView::TestCase::TestController) &&
bindings[:abstract_model].model == Team &&
bindings[:object].is_a?(Team)
end
end
end
end
expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Team.new).collect(&:custom_key)).to eq([:test_bindings])
expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Player.new).collect(&:custom_key)).to eq([])
expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Player), Team.new).collect(&:custom_key)).to eq([])
end
end
describe '#logout_method' do
it 'defaults to :delete when Devise is not defined' do
allow(Object).to receive(:defined?).with(Devise).and_return(false)
expect(helper.logout_method).to eq(:delete)
end
it 'uses first sign out method from Devise when it is defined' do
allow(Object).to receive(:defined?).with(Devise).and_return(true)
expect(Devise).to receive(:sign_out_via).and_return([:whatever_defined_on_devise, :something_ignored])
expect(helper.logout_method).to eq(:whatever_defined_on_devise)
end
end
describe '#wording_for' do
it 'gives correct wording even if action is not visible' do
RailsAdmin.config do |config|
config.actions do
index do
visible false
end
end
end
expect(helper.wording_for(:menu, :index)).to eq('List')
end
it 'passes correct bindings' do
expect(helper.wording_for(:title, :edit, RailsAdmin::AbstractModel.new(Team), Team.new(name: 'the avengers'))).to eq("Edit Team 'the avengers'")
end
it 'defaults correct bindings' do
@action = RailsAdmin::Config::Actions.find :edit
@abstract_model = RailsAdmin::AbstractModel.new(Team)
@object = Team.new(name: 'the avengers')
expect(helper.wording_for(:title)).to eq("Edit Team 'the avengers'")
end
it 'does not try to use the wrong :label_metod' do
@abstract_model = RailsAdmin::AbstractModel.new(Draft)
@object = Draft.new
expect(helper.wording_for(:link, :new, RailsAdmin::AbstractModel.new(Team))).to eq('Add a new Team')
end
end
describe '#breadcrumb' do
it 'gives us a breadcrumb' do
@action = RailsAdmin::Config::Actions.find(:edit, abstract_model: RailsAdmin::AbstractModel.new(Team), object: FactoryBot.create(:team, name: 'the avengers'))
bc = helper.breadcrumb
expect(bc).to match(/Dashboard/) # dashboard
expect(bc).to match(/Teams/) # list
expect(bc).to match(/the avengers/) # show
expect(bc).to match(/Edit/) # current (edit)
end
end
describe '#menu_for' do
it 'passes model and object as bindings and generates a menu, excluding non-get actions' do
RailsAdmin.config do |config|
config.actions do
dashboard
index do
visible do
bindings[:abstract_model].model == Team
end
end
show do
visible do
bindings[:object].class == Team
end
end
delete do
http_methods [:post, :put, :delete]
end
end
end
@action = RailsAdmin::Config::Actions.find :show
@abstract_model = RailsAdmin::AbstractModel.new(Team)
@object = FactoryBot.create(:team, name: 'the avengers')
expect(helper.menu_for(:root)).to match(/Dashboard/)
expect(helper.menu_for(:collection, @abstract_model)).to match(/List/)
expect(helper.menu_for(:member, @abstract_model, @object)).to match(/Show/)
@abstract_model = RailsAdmin::AbstractModel.new(Player)
@object = Player.new
expect(helper.menu_for(:collection, @abstract_model)).not_to match(/List/)
expect(helper.menu_for(:member, @abstract_model, @object)).not_to match(/Show/)
end
it 'excludes non-get actions' do
RailsAdmin.config do |config|
config.actions do
dashboard do
http_methods [:post, :put, :delete]
end
end
end
@action = RailsAdmin::Config::Actions.find :dashboard
expect(helper.menu_for(:root)).not_to match(/Dashboard/)
end
it 'shows actions which are marked as show_in_menu' do
I18n.backend.store_translations(
:en, admin: {actions: {
shown_in_menu: {menu: 'Look this'},
}}
)
RailsAdmin.config do |config|
config.actions do
dashboard do
show_in_menu false
end
root :shown_in_menu, :dashboard do
action_name :dashboard
show_in_menu true
end
end
end
@action = RailsAdmin::Config::Actions.find :dashboard
expect(helper.menu_for(:root)).not_to match(/Dashboard/)
expect(helper.menu_for(:root)).to match(/Look this/)
end
end
describe '#main_navigation' do
it 'shows included models' do
RailsAdmin.config do |config|
config.included_models = [Ball, Comment]
end
expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Comments)/m)
end
it 'does not draw empty navigation labels' do
RailsAdmin.config do |config|
config.included_models = [Ball, Comment, Comment::Confirmed]
config.model Comment do
navigation_label 'Commentz'
end
config.model Comment::Confirmed do
label_plural 'Confirmed'
end
end
expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed)/m)
expect(helper.main_navigation).not_to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed).*(Comment)/m)
end
it 'does not show unvisible models' do
RailsAdmin.config do |config|
config.included_models = [Ball, Comment]
config.model Comment do
hide
end
end
result = helper.main_navigation
expect(result).to match(/(dropdown-header).*(Navigation).*(Balls)/m)
expect(result).not_to match('Comments')
end
it 'shows children of hidden models' do # https://github.com/sferik/rails_admin/issues/978
RailsAdmin.config do |config|
config.included_models = [Ball, Hardball]
config.model Ball do
hide
end
end
expect(helper.main_navigation).to match(/(dropdown\-header).*(Navigation).*(Hardballs)/m)
end
it 'shows children of excluded models' do
RailsAdmin.config do |config|
config.included_models = [Hardball]
end
expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Hardballs)/m)
end
it 'nests in navigation label' do
RailsAdmin.config do |config|
config.included_models = [Comment]
config.model Comment do
navigation_label 'commentable'
end
end
expect(helper.main_navigation).to match(/(dropdown\-header).*(commentable).*(Comments)/m)
end
it 'nests in parent model' do
RailsAdmin.config do |config|
config.included_models = [Player, Comment]
config.model Comment do
parent Player
end
end
expect(helper.main_navigation).to match(/(Players).* (nav\-level\-1).*(Comments)/m)
end
it 'orders' do
RailsAdmin.config do |config|
config.included_models = [Player, Comment]
end
expect(helper.main_navigation).to match(/(Comments).*(Players)/m)
RailsAdmin.config(Comment) do
weight 1
end
expect(helper.main_navigation).to match(/(Players).*(Comments)/m)
end
end
describe '#root_navigation' do
it 'shows actions which are marked as show_in_sidebar' do
I18n.backend.store_translations(
:en, admin: {actions: {
shown_in_sidebar: {menu: 'Look this'},
}}
)
RailsAdmin.config do |config|
config.actions do
dashboard do
show_in_sidebar false
end
root :shown_in_sidebar, :dashboard do
action_name :dashboard
show_in_sidebar true
end
end
end
expect(helper.root_navigation).not_to match(/Dashboard/)
expect(helper.root_navigation).to match(/Look this/)
end
it 'allows grouping by sidebar_label' do
I18n.backend.store_translations(
:en, admin: {
actions: {
foo: {menu: 'Foo'},
bar: {menu: 'Bar'},
},
}
)
RailsAdmin.config do |config|
config.actions do
dashboard do
show_in_sidebar true
sidebar_label 'One'
end
root :foo, :dashboard do
action_name :dashboard
show_in_sidebar true
sidebar_label 'Two'
end
root :bar, :dashboard do
action_name :dashboard
show_in_sidebar true
sidebar_label 'Two'
end
end
end
expect(helper.strip_tags(helper.root_navigation).delete(' ')).to eq 'OneDashboardTwoFooBar'
end
end
describe '#static_navigation' do
it 'shows not show static nav if no static links defined' do
RailsAdmin.config do |config|
config.navigation_static_links = {}
end
expect(helper.static_navigation).to be_empty
end
it 'shows links if defined' do
RailsAdmin.config do |config|
config.navigation_static_links = {
'Test Link' => 'http://www.google.com',
}
end
expect(helper.static_navigation).to match(/Test Link/)
end
it 'shows default header if navigation_static_label not defined in config' do
RailsAdmin.config do |config|
config.navigation_static_links = {
'Test Link' => 'http://www.google.com',
}
end
expect(helper.static_navigation).to match(I18n.t('admin.misc.navigation_static_label'))
end
it 'shows custom header if defined' do
RailsAdmin.config do |config|
config.navigation_static_label = 'Test Header'
config.navigation_static_links = {
'Test Link' => 'http://www.google.com',
}
end
expect(helper.static_navigation).to match(/Test Header/)
end
end
describe '#bulk_menu' do
it 'includes all visible bulkable actions' do
RailsAdmin.config do |config|
config.actions do
index
collection :zorg do
bulkable true
action_name :zorg_action
end
collection :blub do
bulkable true
visible do
bindings[:abstract_model].model == Team
end
end
end
end
# Preload all models to prevent I18n being cleared in Mongoid builds
RailsAdmin::AbstractModel.all
en = {admin: {actions: {
zorg: {bulk_link: 'Zorg all these %{model_label_plural}'},
blub: {bulk_link: 'Blub all these %{model_label_plural}'},
}}}
I18n.backend.store_translations(:en, en)
@abstract_model = RailsAdmin::AbstractModel.new(Team)
result = helper.bulk_menu
expect(result).to match('zorg_action')
expect(result).to match('Zorg all these Teams')
expect(result).to match('blub')
expect(result).to match('Blub all these Teams')
result_2 = helper.bulk_menu(RailsAdmin::AbstractModel.new(Player))
expect(result_2).to match('zorg_action')
expect(result_2).to match('Zorg all these Players')
expect(result_2).not_to match('blub')
expect(result_2).not_to match('Blub all these Players')
end
end
describe '#edit_user_link' do
it "don't include email column" do
allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:player))
result = helper.edit_user_link
expect(result).to eq nil
end
it 'include email column' do
allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user))
result = helper.edit_user_link
expect(result).to match('href')
end
it 'show gravatar' do
allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user))
result = helper.edit_user_link
expect(result).to include('gravatar')
end
it "don't show gravatar" do
RailsAdmin.config do |config|
config.show_gravatar = false
end
allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user))
result = helper.edit_user_link
expect(result).not_to include('gravatar')
end
context 'when the user is not authorized to perform edit' do
let(:user) { FactoryBot.create(:user) }
before do
allow_any_instance_of(RailsAdmin::Config::Actions::Edit).to receive(:authorized?).and_return(false)
allow(helper).to receive(:_current_user).and_return(user)
end
it 'show gravatar and email without a link' do
result = helper.edit_user_link
expect(result).to include('gravatar')
expect(result).to include(user.email)
expect(result).not_to match('href')
end
end
end
end
describe '#flash_alert_class' do
it 'makes errors red with alert-danger' do
expect(helper.flash_alert_class('error')).to eq('alert-danger')
end
it 'makes alerts yellow with alert-warning' do
expect(helper.flash_alert_class('alert')).to eq('alert-warning')
end
it 'makes notices blue with alert-info' do
expect(helper.flash_alert_class('notice')).to eq('alert-info')
end
it 'prefixes others with "alert-"' do
expect(helper.flash_alert_class('foo')).to eq('alert-foo')
end
end
end
| mit |
voostindie/sprox-json | src/test/java/nl/ulso/sprox/json/spotify/AlbumFactory.java | 972 | package nl.ulso.sprox.json.spotify;
import nl.ulso.sprox.Node;
import java.time.LocalDate;
import java.util.List;
/**
* Sprox processor for Spotify API album data. This is a very simple processor that ignores most data.
* <p>
* This implementation creates an Artist object for each and every artist in the response. But only the first one on
* album level is kept in the end.
* </p>
*/
public class AlbumFactory {
@Node("album")
public Album createAlbum(@Node("name") String name, @Node("release_date") LocalDate releaseDate, Artist artist,
List<Track> tracks) {
return new Album(name, releaseDate, artist, tracks);
}
@Node("artists")
public Artist createArtist(@Node("name") String name) {
return new Artist(name);
}
@Node("items")
public Track createTrack(@Node("track_number") Integer trackNumber, @Node("name") String name) {
return new Track(trackNumber, name);
}
}
| mit |
DanceCats/CoreCat | corecat/models/project.py | 1533 | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def __init__(self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None)
| mit |
hankaibo/myangular | src/app/app.component.ts | 1649 | /**
* Angular 2 decorators and services
*/
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { environment } from 'environments/environment';
import { AppState } from './app.service';
/**
* App Component
* Top Level Component
*/
@Component({
selector: 'my-app',
encapsulation: ViewEncapsulation.None,
template: `
<nav>
<a [routerLink]=" ['./'] "
routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}">
Index
</a>
</nav>
<main>
<router-outlet></router-outlet>
</main>
<pre class="app-state">this.appState.state = {{ appState.state | json }}</pre>
<footer>
<span>Angular Starter by <a [href]="twitter">@gdi2290</a></span>
<div>
<a [href]="url">
<img [src]="tipe" width="25%">
</a>
</div>
</footer>
`
})
export class AppComponent implements OnInit {
public name = 'Angular Starter';
public tipe = 'assets/img/tipe.png';
public twitter = 'https://twitter.com/gdi2290';
public url = 'https://tipe.io';
public showDevModule: boolean = environment.showDevModule;
constructor(
public appState: AppState
) {}
public ngOnInit() {
console.log('Initial App State', this.appState.state);
}
}
/**
* Please review the https://github.com/AngularClass/angular2-examples/ repo for
* more angular app examples that you may copy/paste
* (The examples may not be updated as quickly. Please open an issue on github for us to update it)
* For help or questions please contact us at @AngularClass on twitter
* or our chat on Slack at https://AngularClass.com/slack-join
*/
| mit |
Darknet-Crypto/Darknet | src/sapling/noteencryption.h | 2843 | // Copyright (c) 2016-2020 The ZCash developers
// Copyright (c) 2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/*
See the Zcash protocol specification for more information.
https://github.com/zcash/zips/blob/master/protocol/protocol.pdf
*/
#ifndef ZC_NOTE_ENCRYPTION_H_
#define ZC_NOTE_ENCRYPTION_H_
#include "uint256.h"
#include "sapling/address.h"
#include "sapling/sapling.h"
#include <array>
namespace libzcash {
// Ciphertext for the recipient to decrypt
typedef std::array<unsigned char, ZC_SAPLING_ENCCIPHERTEXT_SIZE> SaplingEncCiphertext;
typedef std::array<unsigned char, ZC_SAPLING_ENCPLAINTEXT_SIZE> SaplingEncPlaintext;
// Ciphertext for outgoing viewing key to decrypt
typedef std::array<unsigned char, ZC_SAPLING_OUTCIPHERTEXT_SIZE> SaplingOutCiphertext;
typedef std::array<unsigned char, ZC_SAPLING_OUTPLAINTEXT_SIZE> SaplingOutPlaintext;
//! This is not a thread-safe API.
class SaplingNoteEncryption {
protected:
// Ephemeral public key
uint256 epk;
// Ephemeral secret key
uint256 esk;
bool already_encrypted_enc;
bool already_encrypted_out;
SaplingNoteEncryption(uint256 epk, uint256 esk) : epk(epk), esk(esk), already_encrypted_enc(false), already_encrypted_out(false) {
}
public:
static boost::optional<SaplingNoteEncryption> FromDiversifier(diversifier_t d);
boost::optional<SaplingEncCiphertext> encrypt_to_recipient(
const uint256 &pk_d,
const SaplingEncPlaintext &message
);
SaplingOutCiphertext encrypt_to_ourselves(
const uint256 &ovk,
const uint256 &cv,
const uint256 &cm,
const SaplingOutPlaintext &message
);
uint256 get_epk() const {
return epk;
}
uint256 get_esk() const {
return esk;
}
};
// Attempts to decrypt a Sapling note. This will not check that the contents
// of the ciphertext are correct.
boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk
);
// Attempts to decrypt a Sapling note using outgoing plaintext.
// This will not check that the contents of the ciphertext are correct.
boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption (
const SaplingEncCiphertext &ciphertext,
const uint256 &epk,
const uint256 &esk,
const uint256 &pk_d
);
// Attempts to decrypt a Sapling note. This will not check that the contents
// of the ciphertext are correct.
boost::optional<SaplingOutPlaintext> AttemptSaplingOutDecryption(
const SaplingOutCiphertext &ciphertext,
const uint256 &ovk,
const uint256 &cv,
const uint256 &cm,
const uint256 &epk
);
}
#endif /* ZC_NOTE_ENCRYPTION_H_ */
| mit |
kevyu/ctp_demo | app/components/Chart/index.js | 516 | import React from 'react';
import { TypeChooser } from 'react-stockcharts/lib/helper'
import Chart from './Chart'
import { getData } from './util';
class ChartComponent extends React.Component {
componentDidMount () {
getData().then(data => {
this.setState({ data})
})
}
render () {
if (this.state == null) {
return <div>
Loading...
</div>
}
return (
<Chart type='hybrid' data={this.state.data} />
)
}
}
export default ChartComponent;
| mit |
stevenhaddox/cookbook-stow | spec/recipes/default_spec.rb | 4049 | #
# Cookbook Name:: stow
# Spec:: default
#
# Copyright (c) 2015 Steven Haddox
require 'spec_helper'
describe 'stow::default' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
it 'converges successfully' do
chef_run # This should not raise an error
end
it 'creates stow src directory' do
expect(chef_run).to run_execute('create_stow_source_dir')
end
it 'adds stow bin to $PATH' do
expect(chef_run).to create_template('/etc/profile.d/stow.sh')
end
end
context 'When running on CentOS 6' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '6.5')
runner.converge(described_recipe)
end
it 'installs stow' do
expect(chef_run).to install_package 'stow'
end
end
context 'When running on Fedora 20' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'fedora', version: '20')
runner.converge(described_recipe)
end
it 'installs stow' do
expect(chef_run).to install_package 'stow'
end
end
context 'When running on Ubuntu 14' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '14.04')
runner.converge(described_recipe)
end
it 'installs stow' do
expect(chef_run).to install_package 'stow'
end
end
context 'When running on Debian 7' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'debian', version: '7.0')
runner.converge(described_recipe)
end
it 'installs stow' do
expect(chef_run).to install_package 'stow'
end
end
context 'When installing from source' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new(platform: 'opensuse', version: '12.3')
runner.converge(described_recipe)
end
it 'gets the latest stow' do
expect(chef_run).to create_remote_file("/usr/local/stow/src/stow-2.2.0.tar.gz")
end
it 'installs stow from source' do
expect(chef_run).to install_tar_package("file:////usr/local/stow/src/stow-2.2.0.tar.gz")
end
describe '.stow_stow' do
it 'runs on a clean install' do
expect(chef_run).to run_execute('stow_stow')
end
it 'is skipped if stow is up to date' do
# Stub package_stowed? to return true
allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true)
expect(chef_run).to_not run_execute('stow_stow')
end
end
describe '.destow_stow' do
it 'is skipped if stow is up to date' do
# Stub package_stowed? to return true
allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true)
expect(chef_run).to_not run_execute('destow_stow')
end
it 'is skipped if old_stow_packages is blank' do
# Stub package_stowed? to return false
allow_any_instance_of(Chef::Resource::Execute).to receive(:package_stowed?).and_return(true)
# Stub the directory glob to return no package matches
allow_any_instance_of(Chef::Resource::Execute).to receive(:old_stow_packages).and_return([])
expect(chef_run).to_not run_execute('destow_stow')
end
it 'should destow existing stow packages' do
# Return array of stow packages that exist in stow's path
allow_any_instance_of(Chef::Resource::Execute).to receive(:old_stow_packages).and_return(['/usr/local/stow/stow-+-2.1.3'])
# Ensure the directory glob returns the proper package
allow(::File).to receive(:exist?).and_call_original
allow(::File).to receive(:exist?).with('/usr/local/stow/stow-+-2.1.3').and_return(true)
# Ensure the correct files are present
# Ensure the symlink is detected
expect(chef_run).to run_execute('destow_stow')
expect(chef_run).to run_execute('stow_stow')
end
end
end
end
| mit |
dan-42/turbo-broccoli | src/turbo_broccoli/database.hpp | 6563 | /*
* database.hpp
*
* Created on: Sep 22, 2016
* Author: dan
*/
#ifndef SRC_TURBO_BROCCOLI_DATABASE_HPP_
#define SRC_TURBO_BROCCOLI_DATABASE_HPP_
#include <boost/filesystem.hpp>
#include <turbo_broccoli/type/key.hpp>
#include <turbo_broccoli/type/value.hpp>
#include <turbo_broccoli/type/blob.hpp>
#include <turbo_broccoli/type/tags.hpp>
#include <turbo_broccoli/type/tagged_records.hpp>
#include <turbo_broccoli/type/result_find.hpp>
#include <turbo_broccoli/type/result_key.hpp>
#include <turbo_broccoli/detail/utils.hpp>
namespace turbo_broccoli {
using types::blob;
using types::db_key;
using types::result_key;
using types::result_find;
struct database {
database(const std::string& path) : path_(path) {
namespace fs = boost::filesystem;
if(!fs::exists(path_) ) {
if(!fs::create_directories(path_)) {
throw std::runtime_error("cannot open db, cannot create directory: " + path_.generic_string());
}
}
else {
if(!fs::is_directory(path_)) {
throw std::runtime_error("cannot open db, is not a directory: " + path_.generic_string());
}
}
}
result_find find(const std::string& key) {
return find(detail::calculate_key(key));
}
result_find find(const db_key& key) {
result_find result{};
result.success = false;
if(!record_exists(key)) {
std::cout << "no record with key" << types::to_string(key) << std::endl;
return result;
}
auto record = read_record(key);
if( is_blob(record)) {
result.success = true;
result.results.push_back(detail::deserialize<blob>(record.data));
}
if(is_tag_list(record)) {
auto records = detail::deserialize<types::tagged_records>(record.data);
for(auto& t : records.keys) {
auto k = types::string_to_key(t);
if(record_exists(k)) {
auto r = read_record(k);
if( is_blob(r)) {
result.success = true;
result.results.push_back(detail::deserialize<blob>(r.data));
}
else {
std::cout << "inconsistent: record is not blob " << t << std::endl;
}
}
else {
std::cout << "inconsistent no record from tag list " << t << std::endl;
}
}
}
return result;
}
result_key store(const blob& new_blob) {
static const result_key failed_result{false, turbo_broccoli::types::nil_key() };
if(record_exists(new_blob)) {
/*
* read all tags and update them!
*/
auto r = read_record(new_blob.key_hash());
auto old_blob = detail::deserialize<blob>(r.data);
types::tag_list::list_type to_delete = diff( old_blob.tags().tags, new_blob.tags().tags);
types::tag_list::list_type to_add = diff( new_blob.tags().tags, old_blob.tags().tags);
for(auto& t : to_add ) {
update_tag_add(t, types::to_string(new_blob.key_hash()));
}
for(auto& t : to_delete ) {
update_tag_remove(t, types::to_string(new_blob.key_hash()));
}
}
else {
detail::create_folder(path_, new_blob.key_hash());
for(auto& t : new_blob.tags().tags ) {
update_tag_add(t, types::to_string(new_blob.key_hash()));
}
}
write_blob(new_blob);
return {true, new_blob.key_hash()};
return failed_result;
}
private:
inline bool record_exists(const blob& b) {
namespace fs = boost::filesystem;
return fs::exists(detail::to_filename(path_, b.key_hash()));
}
inline bool record_exists(const db_key& k) {
namespace fs = boost::filesystem;
return fs::exists(detail::to_filename(path_, k));
}
inline void write_blob(const blob& b) {
namespace fs = boost::filesystem;
types::value_t v;
v.data = detail::serialize(b);
v.reccord_type = types::value_type::blob;
v.key = b.key();
detail::create_folder(path_, b.key_hash());
detail::write_file(detail::to_filename(path_, b.key_hash()).generic_string(), detail::serialize(v));
}
inline types::value_t read_record(const db_key& k) {
namespace fs = boost::filesystem;
auto tmp = detail::read_file(detail::to_filename(path_, k).generic_string() );
return detail::deserialize<types::value_t>(tmp);
}
inline void update_tag_add(const std::string& tag_name, const std::string& record_key) {
auto tag_key = detail::calculate_key(tag_name);
types::value_t v;
types::tagged_records records;
if(record_exists(tag_key)) {
v = read_record(tag_key);
if(types::is_tag_list(v)) {
records = detail::deserialize<types::tagged_records>(v.data);
for(auto& r : records.keys) {
if(record_key.compare(r) == 0) {
return;
}
}
records.keys.push_back(record_key);
}
else {
throw std::runtime_error("record exissts and is not a tagged_list: " + tag_name);
}
}
else {
records.keys.push_back(record_key);
v.key = tag_name;
v.reccord_type = types::value_type::tag_list;
v.data = detail::serialize(records);
detail::create_folder(path_, tag_key);
}
v.data = detail::serialize(records);
detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v));
}
inline void update_tag_remove(const std::string& tag_name, const std::string& record_key) {
auto tag_key = detail::calculate_key(tag_name);
types::value_t v = read_record(tag_key);
if(types::is_tag_list(v)) {
types::tagged_records records = detail::deserialize<types::tagged_records>(v.data);
records.keys.erase(std::remove(records.keys.begin(), records.keys.end(), record_key), records.keys.end());
v.data = detail::serialize(records);
detail::write_file(detail::to_filename(path_, tag_key).generic_string(), detail::serialize(v));
}
}
/*
* \brief return list of all elements that are only in a
* a{0, 1, 2, 3, 4}
* b{3, 4, 5, 6, 7}
* d{0, 1, 2}
*/
inline std::vector<std::string> diff(const std::vector<std::string>& a, const std::vector<std::string>& b) {
std::vector<std::string> d;
for(auto& a_i : a) {
bool contains_b_i{false};
for(auto& b_i : b) {
if(a_i.compare(b_i) == 0) {
contains_b_i = true;
break;
}
}
if(!contains_b_i) {
d.push_back(a_i);
}
}
return d;
}
using path_t = boost::filesystem::path;
path_t path_;
};
}
#endif /* SRC_TURBO_BROCCOLI_DATABASE_HPP_ */
| mit |
TerryHowe/ansible-modules-hashivault | ansible/modules/hashivault/hashivault_approle_role_get.py | 1659 | #!/usr/bin/env python
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'}
DOCUMENTATION = '''
---
module: hashivault_approle_role_get
version_added: "3.8.0"
short_description: Hashicorp Vault approle role get module
description:
- Module to get a approle role from Hashicorp Vault.
options:
name:
description:
- role name.
mount_point:
description:
- mount point for role
default: approle
extends_documentation_fragment: hashivault
'''
EXAMPLES = '''
---
- hosts: localhost
tasks:
- hashivault_approle_role_get:
name: 'ashley'
register: 'vault_approle_role_get'
- debug: msg="Role is {{vault_approle_role_get.role}}"
'''
def main():
argspec = hashivault_argspec()
argspec['name'] = dict(required=True, type='str')
argspec['mount_point'] = dict(required=False, type='str', default='approle')
module = hashivault_init(argspec)
result = hashivault_approle_role_get(module.params)
if result.get('failed'):
module.fail_json(**result)
else:
module.exit_json(**result)
@hashiwrapper
def hashivault_approle_role_get(params):
name = params.get('name')
client = hashivault_auth_client(params)
result = client.get_role(name, mount_point=params.get('mount_point'))
return {'role': result}
if __name__ == '__main__':
main()
| mit |
DankBots/GN4R | src/main/java/com/gmail/hexragon/gn4rBot/command/ai/PrivateCleverbotCommand.java | 1619 | package com.gmail.hexragon.gn4rBot.command.ai;
import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor;
import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command;
import com.gmail.hexragon.gn4rBot.util.GnarMessage;
import com.google.code.chatterbotapi.ChatterBot;
import com.google.code.chatterbotapi.ChatterBotFactory;
import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import net.dv8tion.jda.entities.User;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.WeakHashMap;
@Command(
aliases = {"cbot", "cleverbot"},
usage = "(query)",
description = "Talk to Clever-Bot."
)
public class PrivateCleverbotCommand extends CommandExecutor
{
private ChatterBotFactory factory = new ChatterBotFactory();
private ChatterBotSession session = null;
private Map<User, ChatterBotSession> sessionMap = new WeakHashMap<>();
@Override
public void execute(GnarMessage message, String[] args)
{
try
{
if (!sessionMap.containsKey(message.getAuthor()))
{
ChatterBot bot = factory.create(ChatterBotType.CLEVERBOT);
sessionMap.put(message.getAuthor(), bot.createSession());
}
message.replyRaw(sessionMap.get(message.getAuthor()).think(StringUtils.join(args, " ")));
}
catch (Exception e)
{
message.reply("Chat Bot encountered an exception. Restarting. `:[`");
sessionMap.remove(message.getAuthor());
}
}
}
| mit |
sushrutb/website | source/_posts/2007-06-17-bhaas.markdown | 699 | ---
layout: post
title: Bhaas
date: '2007-06-17 21:32:00'
tags: ["poetry"]
---
<p><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://bp2.blogger.com/_cWdd7TsTIWo/RnWon-oIleI/AAAAAAAAAAk/PCXo2q26GsQ/s1600-h/bhas.JPG"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;" src="http://bp2.blogger.com/_cWdd7TsTIWo/RnWon-oIleI/AAAAAAAAAAk/PCXo2q26GsQ/s320/bhas.JPG" border="0" alt="" id="BLOGGER_PHOTO_ID_5077149559709799906"/></a></p><div class="blogger-post-footer"><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/5416117946427095362-1632748105544492475?l=soranthou.blogspot.com" alt=""/></div>
| mit |
SvenFrankson/SvenFrankson.github.io | scripts/pages/Projects.ts | 1442 | class Projects {
public static filters: string[] = [];
public static open(): void {
$.ajax(
{
url: "./projects.html",
success: (data) => {
$("#page").fadeOut(
"fast",
() => {
document.getElementById("page").innerHTML = data;
NavTree.Update([
{
name: "home",
url: "#"
},
{
name: "projects",
url: "#projects"
}
]);
$("#page").show(0);
$(".menu-item").hide();
$(".menu-item").each(
(i, e) => {
setTimeout(
() => {
$(e).fadeIn(500);
},
i * 100
)
}
)
}
);
}
}
)
}
} | mit |
teiler/web.teiler.io | src/test/spy-factory/index.ts | 171 | /**
* Created by Keerthikan on 29-Apr-17.
*/
export {expenseSpyFactory} from './expense-spy-factory';
export {compensationSpyFactory} from './compensation-spy-factory';
| mit |
sanaehirotaka/logbook | main/logbook/data/ScriptLoader.java | 3288 | package logbook.data;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import logbook.config.AppConfig;
import org.apache.commons.io.FilenameUtils;
/**
* スクリプトを読み込みEventListenerの実装を取得する
*
*/
public final class ScriptLoader implements Closeable {
/** ClassLoader */
private final URLClassLoader classLoader;
/** ScriptEngineManager */
private final ScriptEngineManager manager;
/**
* コンストラクター
*/
public ScriptLoader() {
this.classLoader = URLClassLoader.newInstance(this.getLibraries());
this.manager = new ScriptEngineManager(this.classLoader);
}
/**
* スクリプトを読み込みEventListenerの実装を取得する<br>
*
* @param script スクリプト
* @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null
* @throws IOException
* @throws ScriptException
*/
@CheckForNull
public EventListener getEventListener(Path script) throws IOException, ScriptException {
try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
// 拡張子からScriptEngineを取得
String ext = FilenameUtils.getExtension(script.toString());
ScriptEngine engine = this.manager.getEngineByExtension(ext);
if (engine != null) {
// eval
engine.eval(reader);
// 実装を取得
EventListener listener = ((Invocable) engine).getInterface(EventListener.class);
if (listener != null) {
return new ScriptEventAdapter(listener, script);
}
}
return null;
}
}
/**
* ScriptEngineManagerで使用する追加のライブラリ
*
* @return ライブラリ
*/
public URL[] getLibraries() {
String[] engines = AppConfig.get().getScriptEngines();
List<URL> libs = new ArrayList<>();
for (String engine : engines) {
Path path = Paths.get(engine);
if (Files.isReadable(path)) {
try {
libs.add(path.toUri().toURL());
} catch (MalformedURLException e) {
// ここに入るパターンはないはず
e.printStackTrace();
}
}
}
return libs.toArray(new URL[libs.size()]);
}
@Override
public void close() throws IOException {
this.classLoader.close();
}
}
| mit |
eirTony/INDI1 | to/lang/OpenCV-2.2.0/dbg-w32/modules/haartraining/CMakeFiles/CMakeDirectoryInformation.cmake | 1186 | # CMAKE generated file: DO NOT EDIT!
# Generated by "MinGW Makefiles" Generator, CMake Version 2.8
# Relative path conversion top directories.
SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "D:/lang/OpenCV-2.2.0")
SET(CMAKE_RELATIVE_PATH_TOP_BINARY "D:/lang/OpenCV-2.2.0/dbg-w32")
# Force unix paths in dependencies.
SET(CMAKE_FORCE_UNIX_PATHS 1)
# The C and CXX include file search paths:
SET(CMAKE_C_INCLUDE_PATH
"../."
"."
"../include"
"../include/opencv"
"../modules/haartraining"
"../modules/core/include"
"../modules/imgproc/include"
"../modules/objdetect/include"
"../modules/ml/include"
"../modules/highgui/include"
"../modules/video/include"
"../modules/features2d/include"
"../modules/flann/include"
"../modules/calib3d/include"
"../modules/legacy/include"
)
SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
# The C and CXX include file regular expressions for this directory.
SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
| mit |
Mr-Polite/Mr-Polite.github.io | styles-fa6c583b3cd626e54a0e.js | 248 | (window.webpackJsonp=window.webpackJsonp||[]).push([[1],{107:function(n,o,c){},108:function(n,o,c){},109:function(n,o,c){},110:function(n,o,c){},150:function(n,o,c){},151:function(n,o,c){}}]);
//# sourceMappingURL=styles-fa6c583b3cd626e54a0e.js.map | mit |
rjspencer/projectmogo_server | app/controllers/user.rb | 348 | get '/user' do
if logged_in?
redirect '/'
end
erb :create_account
end
post '/user' do
user = User.create(params[:user])
redirect '/'
end
post '/login' do
if user = User.login(params[:user])
session[:permissions] = '3'
end
redirect '/'
end
get '/logout' do
session.clear
session[:permissions] = '0'
redirect '/'
end
| mit |
Quantisan/WholeCell | knowledgebase/lib/geshi/filter/geshi/geshi/pascal.php | 4352 | <?php
/*************************************************************************************
* pascal.php
* ----------
* Author: Tux ([email protected])
* Copyright: (c) 2004 Tux (http://tux.a4.cz/), Nigel McNie (http://qbnz.com/highlighter)
* Release Version: 1.0.6
* CVS Revision Version: $Revision: 1.1 $
* Date Started: 2004/07/26
* Last Modified: $Date: 2005/06/02 04:57:18 $
*
* Pascal language file for GeSHi.
*
* CHANGES
* -------
* 2004/11/27 (1.0.2)
* - Added support for multiple object splitters
* 2004/10/27 (1.0.1)
* - Added support for URLs
* 2004/08/05 (1.0.0)
* - Added support for symbols
* 2004/07/27 (0.9.1)
* - Pascal is OO language. Some new words.
* 2004/07/26 (0.9.0)
* - First Release
*
* TODO (updated 2004/11/27)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GeSHi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'Pascal',
'COMMENT_SINGLE' => array(1 => '//'),
'COMMENT_MULTI' => array('{' => '}','(*' => '*)'),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
'if', 'while', 'until', 'repeat', 'default',
'do', 'else', 'for', 'switch', 'goto','label','asm','begin','end',
'assembler','case', 'downto', 'to','div','mod','far','forward','in','inherited',
'inline','interrupt','label','library','not','var','of','then','stdcall',
'cdecl','end.','raise','try','except','name','finally','resourcestring','override','overload',
'default','public','protected','private','property','published','stored','catch'
),
2 => array(
'nil', 'false', 'break', 'true', 'function', 'procedure','implementation','interface',
'unit','program','initialization','finalization','uses'
),
3 => array(
'abs', 'absolute','and','arc','arctan','chr','constructor','destructor',
'dispose','cos','eof','eoln','exp','get','index','ln','new','xor','write','writeln',
'shr','sin','sqrt','succ','pred','odd','read','readln','ord','ordinal','blockread','blockwrite'
),
4 => array(
'array', 'char', 'const', 'boolean', 'real', 'integer', 'longint',
'word', 'shortint', 'record','byte','bytebool','string',
'type','object','export','exports','external','file','longbool','pointer','set',
'packed','ansistring','union'
),
),
'SYMBOLS' => array(
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => false,
2 => false,
3 => false,
4 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #b1b100;',
2 => 'color: #000000; font-weight: bold;',
3 => '',
4 => 'color: #993333;'
),
'COMMENTS' => array(
1 => 'color: #808080; font-style: italic;',
2 => 'color: #339933;',
'MULTI' => 'color: #808080; font-style: italic;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #66cc66;'
),
'STRINGS' => array(
0 => 'color: #ff0000;'
),
'NUMBERS' => array(
0 => 'color: #cc66cc;'
),
'METHODS' => array(
1 => 'color: #202020;'
),
'SYMBOLS' => array(
0 => 'color: #66cc66;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => '',
4 => ''
),
'OOLANG' => true,
'OBJECT_SPLITTERS' => array(
1 => '.'
),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?>
| mit |
infinitydevphp/infinity-gii | src/migration/Generator.php | 4539 | <?php
namespace infinitydevphp\gii\migration;
use infinitydevphp\MultipleModelValidator\MultipleModelValidator;
use infinitydevphp\tableBuilder\TableBuilder;
use infinitydevphp\tableBuilder\TableBuilderTemplateMigration;
use infinitydevphp\gii\models\Field;
use yii\db\ColumnSchema;
use yii\db\Schema;
use yii\db\TableSchema;
use yii\gii\CodeFile;
use yii\helpers\ArrayHelper;
use yii\gii\Generator as GeneratorBase;
use Yii;
use yii\validators\RangeValidator;
class Generator extends GeneratorBase
{
public $db = 'db';
public $fields = [];
public $tableName;
public $migrationPath = '@common/migrations/db';
public $fileName = '';
public $migrationName = '';
public $useTablePrefix = true;
public function init()
{
parent::init();
}
public function attributeHints()
{
return ArrayHelper::merge(parent::attributeHints(), [
'tableName' => 'Origin table name',
'fieldsOrigin' => 'Origin table fields for DB table creation',
'autoCreateTable' => 'Options for run create table query',
'migrationPath' => 'Migration path',
'fields' => 'Table fields'
]);
}
public function rules()
{
$rules = ArrayHelper::merge(parent::rules(), [
// [['tableName'], RangeValidator::className(), 'not' => true, 'range' => $this->tablesList, 'message' => 'Table name exists'],
[['tableName'], 'required'],
[['tableName'], 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'],
[['fields'], MultipleModelValidator::className(), 'baseModel' => Field::className()],
[['useTablePrefix'], 'boolean'],
[['migrationPath', 'migrationName'], 'safe'],
]);
return $rules;
}
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'fields' => 'Table fields'
]);
}
protected function getTableFields() {
if (sizeof($this->fields) > 1)
return;
$pks = [];
$table = Yii::$app->db->schema->getTableSchema($this->tableName);
if ($table && $columns = $table->columns) {
$pks = $table->primaryKey;
/** @var ColumnSchema[] $columns */
$this->fields = [];
foreach ($columns as $name => $column) {
$this->fields[] = new Field([
'name' => $name,
'length' => $column->size,
'type' => $column->phpType,
'precision' => $column->precision,
'scale' => $column->scale,
'comment' => $column->comment,
'is_not_null' => !$column->allowNull,
'isCompositeKey' => in_array($name, $pks),
]);
}
}
return $pks;
}
public function generate()
{
$this->tableName = preg_replace('/({{%)(\w+)(}})?/', "$2", $this->tableName);
$tableName = $this->tableName;
if ($this->useTablePrefix) {
$tableName = "{{%{$tableName}}}";
}
$primary = $this->getTableFields();
$files = [];
$this->migrationName = Yii::$app->session->get($this->tableName) ?: false;
$mCreate = new TableBuilderTemplateMigration([
'tableName' => $tableName,
'fields' => $this->fields,
'useTablePrefix' => $this->useTablePrefix,
]);
if (!$this->migrationName) {
Yii::$app->session->set($this->tableName, $mCreate->migrationName);
}
$this->migrationName = $this->migrationName ?: Yii::$app->session->get($this->tableName);
$mCreate->migrationName = $this->migrationName ?: $mCreate->migrationName;
$files[] = new CodeFile(
Yii::getAlias($this->migrationPath) . '/' . $mCreate->migrationName . '.php',
$mCreate->runQuery()
);
return $files;
}
public function getName()
{
return 'Migration Generator';
}
public function defaultTemplate()
{
return parent::defaultTemplate();
}
public function getDescription()
{
return 'This generator helps you create migration from existing table';
}
public function stickyAttributes()
{
return ArrayHelper::merge(parent::stickyAttributes(), ['db', 'migrationPath']);
}
} | mit |
rayjun/awesome-algorithm | leetcode/sql/Leetcode196.sql | 86 | delete p1 from person as p1, person as p2 where p1.email = p2.email and p1.id > p2.id; | mit |
iotdesignshop/FizViz-Arduino | FizVizSketch/HotNeedleLightControl.cpp | 2285 | #include "HotNeedleLightControl.h"
HotNeedleLightControlClass::HotNeedleLightControlClass(uint8_t background[NEOPIXEL_COUNT][COLOR_BYTES], uint8_t hotNeedleColor[COLOR_BYTES], float highlightMultiplier, bool useHighlight, uint16_t fadeTime, uint8_t framePeriod, Adafruit_NeoPixel *strip) : LightControlClass(framePeriod, strip)
{
memcpy(this->backgroundColors, background, COLOR_BYTES*NEOPIXEL_COUNT);
memcpy(this->hotNeedleColor, hotNeedleColor, COLOR_BYTES);
fadeFrames = fadeTime / framePeriod;
this->useHighlight = useHighlight;
this->highlightMultiplier = highlightMultiplier;
this->maximumLedPosition = 0;
this->minimumLedPosition = NEOPIXEL_COUNT;
}
// Rendering code
void HotNeedleLightControlClass::renderFrame(uint16_t pos, NEEDLE_DIRECTION dir)
{
// Increment existing counters
decrementCounters(ledCounters);
uint16_t needlePosition = pixelFromInputPosition(pos);
// Set current position hot pixel counter to max
ledCounters[needlePosition] = fadeFrames;
draw(needlePosition);
}
void HotNeedleLightControlClass::draw(uint16_t needlePosition)
{
// Calculate display values for each pixel
for (uint16_t p = 0; p < NEOPIXEL_COUNT; p++)
{
float backgroundRatio = (float)(fadeFrames - ledCounters[p]) / fadeFrames;
float foregroundRatio = 1.0 - backgroundRatio;
for (uint8_t c = 0; c < COLOR_BYTES; c++)
{
if (useHighlight)
{
// Foreground color is background color * highlight multiplier
// Make sure we don't wrap past 255
int bg = backgroundColors[p][c] * highlightMultiplier;
if (bg > 255)
{
bg = 255;
}
ledCurrentColors[p][c] = gammaCorrect((foregroundRatio * bg) + (backgroundRatio * backgroundColors[p][c]));
}
else
{
ledCurrentColors[p][c] = gammaCorrect((foregroundRatio * hotNeedleColor[c]) + (backgroundRatio * backgroundColors[p][c]));
}
}
strip->setPixelColor(p, ledCurrentColors[p][RED],
ledCurrentColors[p][GREEN],
ledCurrentColors[p][BLUE]);
}
if(useMaximum){
updateMaximum(needlePosition);
drawMaximum();
}
if(useMinimum){
updateMinimum(needlePosition);
drawMinimum();
}
strip->show();
}
| mit |
bkorobeinikov/movieapp-ionic | src/store/reducers/movie.ts | 3346 | import { createSelector } from 'reselect';
import * as movie from './../actions/movie';
import { Movie } from './../models';
import * as _ from 'lodash';
import { AsyncOperation, AsyncStatus, makeAsyncOp } from "./../utils";
export interface State {
entities: { [movieId: string]: Movie };
mapMovieToCinema: {
[cinemaId: string]: {
releasedIds: string[]
otherIds: string[],
loadingOp: AsyncOperation,
}
};
selectedId: string;
}
export const initialState: State = {
entities: {},
mapMovieToCinema: {},
selectedId: null,
};
export function reducer(state: State = initialState, actionRaw: movie.Actions): State {
switch (actionRaw.type) {
case movie.ActionTypes.LOAD: {
let action = <movie.LoadAction>actionRaw;
let cinemaId = action.payload.cinemaId;
return {
...state,
mapMovieToCinema: {
...state.mapMovieToCinema,
[cinemaId]: {
...state.mapMovieToCinema[cinemaId],
releasedIds: [],
otherIds: [],
loadingOp: makeAsyncOp(AsyncStatus.Pending),
},
},
};
}
case movie.ActionTypes.LOAD_SUCCESS: {
let action = <movie.LoadSuccessAction>actionRaw;
let entities = _.flatten([action.payload.released, action.payload.other])
.reduce((entities, movie) => {
return {
...entities,
[movie.id]: movie,
};
}, state.entities);
let map = {
releasedIds: action.payload.released.map(m => m.id),
otherIds: action.payload.other.map(m => m.id),
loadingOp: makeAsyncOp(AsyncStatus.Success),
};
return {
...state,
entities: entities,
mapMovieToCinema: {
...state.mapMovieToCinema,
[action.payload.cinemaId]: map
},
};
}
case movie.ActionTypes.LOAD_FAIL: {
let action = <movie.LoadFailAction>actionRaw;
let cinemaId = action.payload.cinemaId;
return {
...state,
mapMovieToCinema: {
...state.mapMovieToCinema,
[cinemaId]: {
...state.mapMovieToCinema[cinemaId],
loadingOp: makeAsyncOp(AsyncStatus.Fail, action.payload.errorMessage),
},
},
};
}
case movie.ActionTypes.SELECT: {
var action = <movie.SelectAction>actionRaw;
return {
...state,
selectedId: action.payload,
};
}
default:
return state;
}
}
export const getEntities = (state: State) => state.entities;
export const getMapToCinema = (state: State) => state.mapMovieToCinema;
export const getSelectedId = (state: State) => state.selectedId;
export const getSelected = createSelector(getEntities, getSelectedId, (entities, id) => {
return entities[id];
}); | mit |
iMartinezMateu/gamecraft | gamecraft-ui/src/main/resources/templates/dashboard.html | 1885 | <!DOCTYPE HTML>
<html>
<head>
<title>Gamecraft CI</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/dashboard.css"/>
<script src="/webjars/jquery/1.11.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
<script src="/js/account_operations.js"></script>
<script src="/js/ui_operations.js"></script>
<script src="/js/validator.min.js"></script>
<script src="/js/lang_operations.js"></script>
<script>
checkAuthState();
setDefaultLanguage();
loadNavbar();
</script>
</head>
<body>
<div class="navbar-frame"></div>
<div class="container">
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h1>Welcome to Gamecraft!</h1>
<div class="alert alert-success" role="alert">You are logged in as user "<script> document.write(getUsername())</script>".</div>
<p>If you have any question on Gamecraft:</p>
<ul>
<li><a href="https://github.com/iMartinezMateu/gamecraft/issues?state=open" target="_blank" rel="noopener" >Gamecraft bug tracker</a></li>
<li><a href="https://github.com/iMartinezMateu/gamecraft/wiki" target="_blank" rel="noopener" >Gamecraft wiki</a></li>
</ul>
<p>
<span jhiTranslate="home.like">If you like Gamecraft, don't forget to give us a star on</span> <a href="https://github.com/iMartinezMateu/gamecraft" target="_blank" rel="noopener" >GitHub</a>!
</p>
<img src="/img/gamecraft.png" alt="Gamecraft" class="center-block" />
</div>
</div> <!-- /container -->
</body>
</html> | mit |
HashirZahir/FIFA-Player-Ratings | FIFAscrape/spiders/fifa_spider.py | 3458 | from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from FIFAscrape.items import PlayerItem
from urlparse import urlparse, urljoin
from scrapy.http.request import Request
from scrapy.conf import settings
import random
import time
class fifaSpider(Spider):
name = "fifa"
allowed_domains = ["futhead.com"]
start_urls = [
"http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps"
]
def parse(self, response):
#obtains links from page to page and passes links to parse_playerURL
sel = Selector(response) #define selector based on response object (points to urls in start_urls by default)
url_list = sel.xpath('//a[@class="display-block padding-0"]/@href') #obtain a list of href links that contain relative links of players
for i in url_list:
relative_url = self.clean_str(i.extract()) #i is a selector and hence need to extract it to obtain unicode object
print urljoin(response.url, relative_url) #urljoin is able to merge absolute and relative paths to form 1 coherent link
req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL
req.headers["User-Agent"] = self.random_ua()
yield req
next_url=sel.xpath('//div[@class="right-nav pull-right"]/a[@rel="next"]/@href').extract_first()
if(next_url): #checks if next page exists
clean_next_url = self.clean_str(next_url)
reqNext = Request(urljoin(response.url, clean_next_url),callback=self.parse) #calls back this function to repeat process on new list of links
yield reqNext
def parse_playerURL(self, response):
#parses player specific data into items list
site = Selector(response)
items = []
item = PlayerItem()
item['1name'] = (response.url).rsplit("/")[-2].replace("-"," ")
title = self.clean_str(site.xpath('/html/head/title/text()').extract_first())
item['OVR'] = title.partition("FIFA 16 -")[1].split("-")[0]
item['POS'] = self.clean_str(site.xpath('//div[@class="playercard-position"]/text()').extract_first())
#stats = site.xpath('//div[@class="row player-center-container"]/div/a')
stat_names = site.xpath('//span[@class="player-stat-title"]')
stat_values = site.xpath('//span[contains(@class, "player-stat-value")]')
for index in range(len(stat_names)):
attr_name = stat_names[index].xpath('.//text()').extract_first()
item[attr_name] = stat_values[index].xpath('.//text()').extract_first()
items.append(item)
return items
def clean_str(self,ustring):
#removes wierd unicode chars (/u102 bla), whitespaces, tabspaces, etc to form clean string
return str(ustring.encode('ascii', 'replace')).strip()
def random_ua(self):
#randomise user-agent from list to reduce chance of being banned
ua = random.choice(settings.get('USER_AGENT_LIST'))
if ua:
ua='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
return ua
| mit |
tejasbadadare/Arbiter | single.html | 3326 | <!DOCTYPE HTML>
<html>
<head>
<title>Arbiter - Decisions Simplified</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="app.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
</head>
<body ng-app="decisionPage" ng-controller="decisionController" class="single">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<h1><a href="#">Arbiter</a></h1>
<nav class="links">
<ul>
<li><a href="#">My Posts</a></li>
</ul>
</nav>
<nav class="main">
<ul>
<li class="search">
<a class="fa-search" href="#search">Search</a>
<form id="search" method="get" action="#">
<input type="text" name="query" placeholder="Search" />
</form>
</li>
<li class="menu">
<a class="fa-bars" href="#menu">Menu</a>
</li>
</ul>
</nav>
</header>
<!-- Menu -->
<section id="menu">
<!-- Search -->
<section>
<form class="search" method="get" action="#">
<input type="text" name="query" placeholder="Search" />
</form>
</section>
<!-- Actions -->
<section>
<ul class="actions vertical">
<li><a href="#" class="button big fit">Log In</a></li>
</ul>
</section>
</section>
<!-- Main -->
<div id="main">
<!-- Post -->
<article class="post">
<header>
<div class="title">
<h2>{{test}}</h2>
</div>
<div class="meta">
<time class="published" datetime="2015-11-01">November 1, 2015</time>
<a href="#" class="author"><span class="name">Jane Doe</span><img src="images/avatar.jpg" alt="" /></a>
</div>
</header>
<footer>
<ul class="actions">
<li><a href="#" class="button big">Apple</a></li>
<li><a href="#" class="button big">Orange</a></li>
</ul>
</footer>
</article>
</div>
<!-- Footer -->
<section id="footer">
<ul class="icons">
<li><a href="#" class="fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="#" class="fa-facebook"><span class="label">Facebook</span></a></li>
<li><a href="#" class="fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="#" class="fa-rss"><span class="label">RSS</span></a></li>
<li><a href="#" class="fa-envelope"><span class="label">Email</span></a></li>
</ul>
<p class="copyright">Made by love @ UCSD</p>
</section>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>
</html>
| mit |
JulesMarcil/colocall | web/js/base.js | 1815 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
var div = document.getElementById('content');
var div1 = document.getElementById('leftbox');
div.style.height = document.body.clientHeight + 'px';
div1.style.height = div.style.height;
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
var oritop = -100;
$(window).scroll(function() {
var scrollt = window.scrollY;
var elm = $("#leftbox");
if(oritop < 0) {
oritop= elm.offset().top;
}
if(scrollt >= oritop) {
elm.css({"position": "fixed", "top": 0, "left": 0});
}
else {
elm.css("position", "static");
}
});
/*$(window).resize(function() {
var wi = $(window).width();
$("p.testp").text('Screen width is currently: ' + wi + 'px.');
});
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 767){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).hide();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).show();
$("#leftbox").css("width","30px");
$("#content").css("width","90%");
}else if (wi > 800){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).show();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
$("#leftbox").css("width","15%");
$("#content").css("width","85%");
}
});*/
}); | mit |
goldenio/webpack-rails | spec/webpack/rails_spec.rb | 141 | require 'spec_helper'
describe Webpack::Rails do
it 'has a version number' do
expect(Webpack::Rails::VERSION).not_to be nil
end
end
| mit |
Sioweb/Sioweb-MVC | app/assets/Test/sql/comment.sql | 96 | CREATE TABLE IF NOT EXISTS `comment` (
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
; | mit |
glasdam/edifact_converter | lib/edifact_converter/command_line_parser.rb | 2042 | require 'optparse'
require 'pathname'
module EdifactConverter
class CommandLineParser
class << self
attr_writer :options
def options
@options ||= {}
end
def parser
@parser ||= begin
OptionParser.new do|opts|
opts.banner = "Usage: #{$COMMAND_NAME} [options] file"
opts.on( '-x', '--xml', 'Convert from Edifact to XML' ) do
options[:source] = :edifact
end
opts.on( '-e', '--edi', 'Convert from XML to Edifact' ) do
options[:source] = :xml
end
opts.on( '-1', '--xml11', 'Only convert to XML 1-1') do
options[:xml11] = true
end
opts.on( '-f', '--format', 'Format edifact output with newlines') do
options[:format] = true
end
opts.on( '--html', 'Only convert to XML 1-1') do
options[:html] = true
end
opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do |file|
options[:logfile] = file
end
opts.on( '-o', '--output FILE', 'Write output to FILE' ) do |file|
options[:to_file] = file
end
opts.on( '-v', '--version', "Prints version of #{$COMMAND_NAME}") do
puts "#{$COMMAND_NAME} version #{VERSION}"
exit
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
end
end
def parse
parser.parse!
if ARGV.size != 1
puts "Wrong number of arguments, run #{$COMMAND_NAME} -h for a list of possible arguments."
exit
end
options[:input] = Pathname.new ARGV.first
unless options[:source]
if options[:input].extname =~ /xml/
options[:source] = :xml
else
options[:source] = :edifact
end
end
options
end
end
end
end
| mit |
Microsoft/vso-intellij | plugin/src/com/microsoft/alm/plugin/idea/tfvc/ui/ServerPathCellEditor.java | 4047 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.alm.plugin.idea.tfvc.ui;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.util.ui.AbstractTableCellEditor;
import com.intellij.util.ui.CellEditorComponentWithBrowseButton;
import com.microsoft.alm.plugin.context.ServerContext;
import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle;
import com.microsoft.alm.plugin.idea.common.utils.VcsHelper;
import com.microsoft.alm.plugin.idea.tfvc.ui.servertree.ServerBrowserDialog;
import org.apache.commons.lang.StringUtils;
import javax.swing.JTable;
import javax.swing.JTextField;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ServerPathCellEditor extends AbstractTableCellEditor {
private final String title;
private final Project project;
private final ServerContext serverContext;
private CellEditorComponentWithBrowseButton<JTextField> component;
public ServerPathCellEditor(final String title, final Project project, final ServerContext serverContext) {
this.title = title;
this.project = project;
this.serverContext = serverContext;
}
public Object getCellEditorValue() {
return component.getChildComponent().getText();
}
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
final ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
createBrowserDialog();
}
};
component = new CellEditorComponentWithBrowseButton<JTextField>(new TextFieldWithBrowseButton(listener), this);
component.getChildComponent().setText((String) value);
return component;
}
/**
* Creates the browser dialog for file selection
*/
@VisibleForTesting
protected void createBrowserDialog() {
final String serverPath = getServerPath();
if (StringUtils.isNotEmpty(serverPath)) {
final ServerBrowserDialog dialog = new ServerBrowserDialog(title, project, serverContext, serverPath, true, false);
if (dialog.showAndGet()) {
component.getChildComponent().setText(dialog.getSelectedPath());
}
} else {
Messages.showErrorDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG),
TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE));
}
}
/**
* Get a server path to pass into the dialog
*
* @return
*/
@VisibleForTesting
protected String getServerPath() {
String serverPath = (String) getCellEditorValue();
// if there is no entry in the cell to find the root server path with then find it from the server context
if (StringUtils.isEmpty(serverPath) && serverContext != null && serverContext.getTeamProjectReference() != null) {
serverPath = VcsHelper.TFVC_ROOT.concat(serverContext.getTeamProjectReference().getName());
}
return serverPath;
}
} | mit |
PeerWasp/PeerWasp | peerbox/src/main/java/org/peerbox/presenter/MainController.java | 467 | package org.peerbox.presenter;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class MainController implements INavigatable {
@FXML
private Pane mainPane;
/*
* (non-Javadoc)
*
* @see org.peerbox.presenter.INavigatable#setContent(javafx.scene.Node)
*/
@Override
public void setContent(Node content) {
mainPane.getChildren().clear();
mainPane.getChildren().add(content);
mainPane.requestLayout();
}
}
| mit |
LifengDuan/gitCaoLian | TNTLoveFreshBee 2/TNTLoveFreshBee/Classes/ShopingCar/Views/LightningSendDownView.h | 410 | //
// LightningSendDownView.h
// TNTLoveFreshBee
//
// Created by apple on 16/10/14.
// Copyright © 2016年 LiDan. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol didLightningSendDownViewCommitDelegate <NSObject>
@optional
- (void)didLightningSendDownViewCommit;
@end
@interface LightningSendDownView : UIView
@property(weak,nonatomic) id<didLightningSendDownViewCommitDelegate>delegate;
@end
| mit |
PathwayToRecovery-IndyGiveCamp/give-camp-theme-2013 | page-full.php | 200 | <?php
/*
Template Name: Full Page Width Template
*/
get_header();
while ( have_posts() ) {
the_post();
get_template_part( 'content', 'page-full' );
} // end of the loop
get_footer(); | mit |
coolralf/KaggleTraining | HELP.py | 18 | print("hello!!!!") | mit |
monsterhunteronline/monsterhunteronline.github.io | monsters/basarios/data.js | 348 | var monsterArray =
{
"name": "岩龙",
"other": [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
""
],
"weakness": [
{
"data": [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
]
}
]
}; | mit |
kkdawkins/vsts-tasks | Tests/L0.ts | 23620 | /// <reference path="../definitions/mocha.d.ts"/>
/// <reference path="../definitions/node.d.ts"/>
/// <reference path="../definitions/Q.d.ts"/>
import Q = require('q');
import assert = require('assert');
import path = require('path');
import fs = require('fs');
describe('General Suite', function () {
this.timeout(20000);
before((done) => {
// init here
done();
});
after(function () {
});
it('Find invalid task.json', (done) => {
this.timeout(20000);
// get a list of all _build/task folders
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var taskFolders: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(folderName => {
if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) {
taskFolders.push(path.join(tasksRootFolder, folderName));
}
})
// verify no BOM
for (var i = 0; i < taskFolders.length; i++) {
var taskFolder = taskFolders[i];
var taskjson = path.join(taskFolder, 'task.json');
var jsonString = fs.readFileSync(taskjson).toString();
if (jsonString.indexOf('\uFEFF') >= 0) {
console.warn('The task.json starts with a byte-order mark. This may cause JSON.parse to fail.');
console.warn('The byte-order mark has been removed from the task.json file under the _build directory.');
console.warn('Copy the file over the source file in the task folder and commit it.');
var fixedJsonString = jsonString.replace(/[\uFEFF]/g, '');
fs.writeFileSync(taskjson, fixedJsonString);
assert(false, 'Offending file (byte-order mark removed): ' + taskjson);
}
try {
var task = JSON.parse(fs.readFileSync(taskjson).toString());
}
catch (err) {
assert(false, err.message + '\n\tUnable to parse JSON from: ' + taskjson);
}
}
done();
})
it('Find nested task.json', (done) => {
this.timeout(20000);
// Path to the _build/Tasks folder.
var tasksFolder = path.resolve(__dirname, '../Tasks');
// Recursively find all task.json files.
var folders: string[] = [tasksFolder];
while (folders.length > 0) {
// Pop the next folder.
var folder: string = folders.pop();
// Read the directory.
fs.readdirSync(folder).forEach(item => {
var itemPath: string = path.join(folder, item);
if (fs.statSync(itemPath).isDirectory() && itemPath != path.join(tasksFolder, 'Tests')) {
// Push the child directory.
folders.push(itemPath);
} else if (item.toUpperCase() == "TASK.JSON" &&
path.resolve(folder, '..').toUpperCase() != tasksFolder.toUpperCase()) {
// A task.json file was found nested recursively within the task folder.
assert(false, 'A task.json file was found nested recursively within the task folder. This will break the servicing step. Offending file: ' + itemPath);
}
});
}
done();
})
it('Find .js with uppercase', (done) => {
this.timeout(20000);
// Path to the _build/Tasks folder.
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var taskFolders: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(folderName => {
if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) {
taskFolders.push(path.join(tasksRootFolder, folderName));
}
})
for (var i = 0; i < taskFolders.length; i++) {
var taskFolder = taskFolders[i];
var taskjson = path.join(taskFolder, 'task.json');
var task = JSON.parse(fs.readFileSync(taskjson).toString());
if (task.execution && task.execution['Node']) {
var jsFiles = fs.readdirSync(taskFolder).filter(file => {
return file.search(/\.js$/) > 0;
})
jsFiles.forEach(jsFile => {
if (jsFile.search(/[A-Z]/g) >= 0) {
console.error('Has uppercase in .js file name for tasks: ' + path.relative(tasksRootFolder, taskjson));
assert(false, 'Has uppercase is dangerous for xplat tasks.' + taskjson);
}
})
var targetJs = task.execution['Node'].target;
if (targetJs.search(/[A-Z]/g) >= 0) {
console.error('Has uppercase in task.json\'s execution.node.target for tasks: ' + path.relative(tasksRootFolder, taskjson));
assert(false, 'Has uppercase is dangerous for xplat tasks.' + taskjson);
}
}
}
done();
})
it('Find unsupported demands', (done) => {
this.timeout(20000);
var supportedDemands: string[] = ['AndroidSDK',
'ant',
'AzurePS',
'Chef',
'DotNetFramework',
'java',
'JDK',
'maven',
'MSBuild',
'MSBuild_x64',
'npm',
'node.js',
'PowerShell',
'SqlPackage',
'VisualStudio',
'VisualStudio_IDE',
'VSTest',
'WindowsKit',
'WindowsSdk',
'cmake',
'cocoapods',
'curl',
'Cmd',
'SCVMMAdminConsole',
'sh',
'KnifeReporting',
'Xamarin.Android',
'Xamarin.iOS',
'xcode'];
supportedDemands.forEach(demand => {
if (supportedDemands.indexOf(demand.toLocaleLowerCase()) < 0) {
supportedDemands.push(demand.toLocaleLowerCase());
}
});
// Path to the _build/Tasks folder.
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var taskFolders: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(folderName => {
if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) {
taskFolders.push(path.join(tasksRootFolder, folderName));
}
})
var unsupportedDemands: string[] = [];
for (var i = 0; i < taskFolders.length; i++) {
var taskFolder = taskFolders[i];
var taskjson = path.join(taskFolder, 'task.json');
var task = JSON.parse(fs.readFileSync(taskjson).toString());
if (task.hasOwnProperty('demands')) {
task['demands'].forEach(demand => {
if (supportedDemands.indexOf(demand.toLocaleLowerCase()) < 0) {
console.warn('find unsupported demand: ' + demand + ' in ' + taskjson);
console.warn('fix the unit test if the new demand is added on purpose.');
unsupportedDemands.push(demand);
}
});
}
}
if (unsupportedDemands.length > 0) {
assert(false, 'find unsupported demands, please take necessary operation to fix this. unsupported demands count: ' + unsupportedDemands.length);
}
done();
})
it('Find unsupported runsOn', (done) => {
this.timeout(20000);
var supportedRunsOn: string[] = ['Agent', 'DeploymentGroup', 'Server'];
supportedRunsOn.forEach(runsOn => {
if (supportedRunsOn.indexOf(runsOn.toLocaleLowerCase()) < 0) {
supportedRunsOn.push(runsOn.toLocaleLowerCase());
}
});
// Path to the _build/Tasks folder.
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var taskFolders: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(folderName => {
if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) {
taskFolders.push(path.join(tasksRootFolder, folderName));
}
})
var unsupportedRunsOnCount = 0;
for (var i = 0; i < taskFolders.length; i++) {
var taskFolder = taskFolders[i];
var taskjson = path.join(taskFolder, 'task.json');
var task = JSON.parse(fs.readFileSync(taskjson).toString());
if (task.hasOwnProperty('runsOn')) {
task['runsOn'].forEach(runsOn => {
if (supportedRunsOn.indexOf(runsOn.toLocaleLowerCase()) < 0) {
++unsupportedRunsOnCount;
console.warn('found unsupported runsOn: ' + runsOn + ' in ' + taskjson);
}
});
}
}
if (unsupportedRunsOnCount > 0){
assert(false, 'found unsupported runsOn. please make necessary action to fix this. unsupported runsOn count: ' + unsupportedRunsOnCount);
}
done();
})
it('Find invalid server Task', (done) => {
this.timeout(20000);
// Path to the _build/Tasks folder.
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var taskFolders: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(folderName => {
if (folderName != 'Common' && fs.statSync(path.join(tasksRootFolder, folderName)).isDirectory()) {
taskFolders.push(path.join(tasksRootFolder, folderName));
}
})
var supportedServerExecutionHandlers: string[] = [
'RM:ManualIntervention',
'ServiceBus',
'HttpRequest'];
var supportedTaskEvents: string[] = [
'TaskAssigned',
'TaskStarted',
'TaskCompleted'];
var invalidTaskFound: boolean = false;
for (var i = 0; i < taskFolders.length; i++) {
var taskFolder = taskFolders[i];
var taskjson = path.join(taskFolder, 'task.json');
var task = JSON.parse(fs.readFileSync(taskjson).toString());
if (task.hasOwnProperty('runsOn') && task['runsOn'].some(x => x.toLowerCase() == 'server')) {
if (task['runsOn'].length > 1) {
assert(false, 'Found invalid value of runsOn in ' + taskjson + '. RunsOn should only be server for server task.');
}
if (task.hasOwnProperty('demands') && task['demands'].length > 0) {
assert(false, 'Found invalid value for demands in ' + taskjson + '. Demands should be either empty or absent for server task.');
}
if (task.hasOwnProperty('minimumAgentVersion')){
assert(false, 'Found minimumAgentVersion in ' + taskjson + '. This should not be present for server task.');
}
if (!task.hasOwnProperty('execution')) {
assert(false, 'No execution section found for server task in ' + taskjson + '.');
}
var handlers = Object.keys(task['execution']);
if (handlers.length != 1) {
assert(false, 'Number of execution handlers should be 1. Invalid section found in ' + taskjson + '.');
}
var handlerName : string = handlers[0];
if (!supportedServerExecutionHandlers.some(x => x.toLowerCase() == handlerName.toLowerCase())){
assert(false, 'Found Invalid task handler name : ' + handlerName + ' in ' + taskjson + '.');
}
var execution = task['execution'][handlerName];
if (execution.hasOwnProperty('events')) {
var taskEvents = execution['events'];
Object.keys(taskEvents).forEach( eventName => {
if (!supportedTaskEvents.some(x => x.toLowerCase() == eventName.toLowerCase())) {
assert(false, 'Found Invalid task event name ' + eventName + 'in ' + taskjson + '.')
}
});
}
}
}
done();
})
it('Find invalid message key in task.json', (done) => {
this.timeout(20000);
// get all task.json and module.json paths under _build/Tasks.
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
var jsons: string[] = [];
fs.readdirSync(tasksRootFolder).forEach(name => {
let itemPath = path.join(tasksRootFolder, name);
if (name == 'Common') {
fs.readdirSync(itemPath).forEach(name => {
let nestedItemPath = path.join(itemPath, name);
if (fs.statSync(nestedItemPath).isDirectory()) {
let moduleJsonPath = path.join(nestedItemPath, 'module.json');
try {
fs.statSync(moduleJsonPath);
}
catch (err) {
return;
}
jsons.push(moduleJsonPath);
}
});
}
else if (fs.statSync(itemPath).isDirectory()) {
jsons.push(path.join(itemPath, 'task.json'));
}
});
for (var i = 0; i < jsons.length; i++) {
var json = jsons[i];
var obj = JSON.parse(fs.readFileSync(json).toString());
if (obj.hasOwnProperty('messages')) {
for (var key in obj.messages) {
var jsonName = path.relative(tasksRootFolder, json);
assert(key.search(/\W+/gi) < 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' contain non-word characters, only allows [a-zA-Z0-9_].'));
if (typeof (obj.messages[key]) === 'object') {
assert(obj.messages[key].loc, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.'));
assert(obj.messages[key].loc.toString().length >= 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.'));
assert(obj.messages[key].fallback, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a fallback string.'));
assert(obj.messages[key].fallback.toString().length > 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a fallback string.'));
}
else if (typeof (obj.messages[key]) === 'string') {
assert(obj.messages[key].toString().length > 0, ('(' + jsonName + ')' + 'messages key: \'' + key + '\' should have a loc string.'));
}
}
}
}
done();
})
it('Find missing string in .ts', (done: MochaDone) => {
this.timeout(20000);
// search the source dir for all _build/Tasks and module folders.
let tasksPath = path.resolve(__dirname, '../Tasks');
let taskPaths: string[] = [];
fs.readdirSync(tasksPath).forEach((itemName: string) => {
let itemPath = path.join(tasksPath, itemName);
if (itemName != 'Common' && fs.statSync(itemPath).isDirectory()) {
taskPaths.push(itemPath);
}
});
let commonPath = path.join(tasksPath, 'Common');
var commonItems = [];
try {
commonItems = fs.readdirSync(commonPath);
}
catch (err) {
if (err.code != 'ENOENT') {
assert('Unexpected error reading dir: ' + commonPath);
}
}
commonItems.forEach((itemName: string) => {
let itemPath = path.join(commonPath, itemName);
if (fs.statSync(itemPath).isDirectory()) {
taskPaths.push(itemPath);
}
});
var testFailed: boolean = false;
taskPaths.forEach((taskPath: string) => {
var locStringMismatch: boolean = false;
// load the task.json or module.json if exists
let taskJson;
for (let jsonName of ['task.json', 'module.json']) {
let jsonPath = path.join(taskPath, jsonName);
try {
fs.statSync(jsonPath);
}
catch (err) {
return;
}
taskJson = JSON.parse(fs.readFileSync(jsonPath).toString());
break;
}
// recursively find all .ts files
let tsFiles: string[] = [];
let dirs: string[] = [taskPath];
while (dirs.length) {
let dir: string = dirs.pop();
fs.readdirSync(dir).forEach((itemName: string) => {
let itemPath: string = path.join(dir, itemName);
if (fs.statSync(itemPath).isDirectory() && itemName != 'node_modules' && itemPath != path.join(taskPath, 'Tests')) {
dirs.push(itemPath);
}
else if (itemName.search(/\.ts$/) > 0) {
tsFiles.push(itemPath);
}
});
}
// search for all loc string keys
let locStringKeys: string[] = [];
tsFiles.forEach((tsFile: string) => {
let content = fs.readFileSync(tsFile).toString().replace(/\r\n/g, '\n').replace(/\r/g, '\n');
let lines: string[] = content.split('\n');
lines.forEach(line => {
// remove all spaces.
line = line.replace(/ /g, '');
let regx = /tl\.loc\(('(\w+)'|"(\w+)")/i;
let res = regx.exec(line);
if (res) {
let key;
if (res[2]) {
key = res[2];
}
else if (res[3]) {
key = res[3];
}
locStringKeys.push(key);
}
});
});
// load the keys from the task.json/module.json
let locStringKeysFromJson: string[] = [];
if (taskJson && taskJson.hasOwnProperty('messages')) {
Object.keys(taskJson.messages).forEach((key: string) => {
locStringKeysFromJson.push(key);
});
}
// find missing keys
var missingLocStringKeys: string[] = [];
locStringKeys.forEach((locKey: string) => {
if (locStringKeysFromJson.indexOf(locKey) === -1 &&
!locKey.match(/^LIB_/)) { // some tasks refernce lib strings
locStringMismatch = true;
missingLocStringKeys.push(locKey);
}
})
if (locStringMismatch) {
testFailed = true;
console.error('add missing loc string keys to messages section for task.json/module.json: ' + path.relative(tasksPath, taskPath));
console.error(JSON.stringify(missingLocStringKeys));
}
});
assert(!testFailed, 'there are missing loc string keys in task.json/module.json.');
done();
})
it('Find missing string in .ps1/.psm1', (done) => {
this.timeout(20000);
// Push all _build/Tasks folders onto the stack.
var folders: string[] = [];
var tasksRootFolder = path.resolve(__dirname, '../Tasks');
fs.readdirSync(tasksRootFolder).forEach(folderName => {
var folder = path.join(tasksRootFolder, folderName);
if (folderName != 'Common' && fs.statSync(folder).isDirectory()) {
folders.push(folder);
}
})
// Push each Common module folder onto the stack. The Common folder does not
// get copied under _build so scan the source copy instead.
var commonFolder = path.resolve(__dirname, "../Tasks/Common");
var commonItems = [];
try {
commonItems = fs.readdirSync(commonFolder);
}
catch (err) {
if (err.code != 'ENOENT') {
assert('Unexpected error reading dir: ' + commonFolder);
}
}
commonItems.forEach(folderName => {
var folder = path.join(commonFolder, folderName);
if (fs.statSync(folder).isDirectory()) {
folders.push(folder);
}
})
folders.forEach(taskFolder => {
// Load the task.json or module.json if one exists.
var jsonFile = path.join(taskFolder, 'task.json');
var obj = { "messages": {} }
if (fs.existsSync(jsonFile) || fs.existsSync(jsonFile = path.join(taskFolder, "module.json"))) {
obj = JSON.parse(fs.readFileSync(jsonFile).toString());
} else {
jsonFile = ''
}
// Recursively find all PS files.
var psFiles: string[] = [];
var folderStack: string[] = [taskFolder];
while (folderStack.length > 0) {
var folder = folderStack.pop();
if (path.basename(folder).toLowerCase() == "node_modules" || // Skip nested node_modules folder.
path.basename(folder).toLowerCase() == "ps_modules") { // Skip nested ps_modules folder.
continue;
}
if (folder == path.join(taskFolder, 'Tests')) { // Skip [...]/Task/Tests and [...]/Common/Tests folders.
continue;
}
fs.readdirSync(folder).forEach(itemName => {
var itemPath = path.join(folder, itemName);
if (fs.statSync(itemPath).isDirectory()) {
folderStack.push(itemPath);
} else if (itemPath.toLowerCase().search(/\.ps1$/) > 0
|| itemPath.toLowerCase().search(/\.psm1$/) > 0) {
psFiles.push(itemPath);
}
})
}
psFiles.forEach(psFile => {
var ps = fs.readFileSync(psFile).toString().replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var lines: string[] = ps.split('\n');
lines.forEach(line => {
if (line.search(/Get-VstsLocString/i) > 0) {
var result = /Get-VstsLocString +-Key +('[^']+'|"[^"]+"|[^ )]+)/i.exec(line);
if (!result) {
assert(false, 'Bad format string in file ' + psFile + ' on line: ' + line);
}
var key = result[1].replace(/['"]/g, "");
assert(
obj.hasOwnProperty('messages') && obj.messages.hasOwnProperty(key),
"Loc resource key not found in task.json/module.json. Resource key: '" + key + "', PS file: '" + psFile + "', JSON file: '" + jsonFile + "'.");
}
});
})
})
done();
})
});
| mit |
manuelhuber/LostColonies | src/data/services/crew.service.ts | 1407 | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Gang } from '../models/gang';
import { Session } from '../models/session';
import { CREW_2_ROUTE } from '../../app/app.routes.model';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class CrewService {
private crewOne: Observable<Gang>;
private crewTwo: Observable<Gang>;
constructor(private http: HttpClient) {
}
public getCrewDataForPath(path: string): Observable<Gang> {
if (path === CREW_2_ROUTE) {
return this.getCrewTwoData();
} else {
return this.getCrewOneData();
}
}
public getCrewOneData(): Observable<Gang> {
if (!this.crewOne) {
this.crewOne = this.getCrew('assassins');
}
return this.crewOne;
}
public getCrewTwoData(): Observable<Gang> {
if (!this.crewTwo) {
this.crewTwo = this.getCrew('assassins2');
}
return this.crewTwo;
}
private getCrew(filename: string): Observable<Gang> {
return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => {
gang.sessions = this.sortSessions(gang.sessions);
return gang;
});
}
private sortSessions(sessions: Session[]): Session[] {
return sessions.map((session: Session) => {
session.date = Date.parse(<any> session.date);
return session;
}).sort((a, b) => a.date - b.date);
}
}
| mit |
gazzlab/LSL-gazzlab-branch | liblsl/external/lslboost/spirit/include/support_standard.hpp | 651 | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
http://spirit.sourceforge.net/
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD
#define BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD
#if defined(_MSC_VER)
#pragma once
#endif
#include <lslboost/spirit/home/support/char_encoding/standard.hpp>
#endif
| mit |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sqlvirtualmachine/azure/mgmt/sqlvirtualmachine/aio/_sql_virtual_machine_management_client.py | 5342 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| mit |
msk610/VoterMLA | kmeans.h | 1892 | //
// kmeans.h
// VoterMLA
//
// Created by MD Shihabul Kabir on 12/5/16.
// Copyright © 2016 MD Shihabul Kabir. All rights reserved.
//
#ifndef kmeans_h
#define kmeans_h
#include "county.h"
#include <vector>
//K-Means Clustering Namespace
namespace KmeansCluster {
//Data Structure to help K-Means Clustering
class KMeans{
private:
//setup three clusters for the clustering and two for last centroids and current centroids
std::vector<CountyStruct::County>cluster1,cluster2,cluster3,last,current,all;
public:
//method find the closest cluster to add
void addToClosest(CountyStruct::County&acounty);
//method to initialize rand centroids and clusters
void initialize(std::vector<CountyStruct::County> counties);
//method to get the mean of a cluster
std::vector<float> mean(std::vector<CountyStruct::County>&cluster);
//method to get centroid closest to mean of cluster
CountyStruct::County getCentroid(std::vector<CountyStruct::County>&cluster,std::vector<float> mean);
//method to get the centroid of a cluster
CountyStruct::County centroid(std::vector<CountyStruct::County>&counties);
//method to setup centroids
bool setupCentroids();
//method to make the clusters
void cluster();
//method to get the distance from a point to rest of cluster
float avgDistance(std::vector<CountyStruct::County>&cluster,int index);
//method to find distance from cluster from a point
float distanceFromCluster(CountyStruct::County&c,std::vector<CountyStruct::County>&cluster);
//method to return silhoute value
float silh(std::vector<CountyStruct::County>&a,std::vector<CountyStruct::County>&b,int index);
//method to print the silhoute for each cluster
void printSil();
};
}
#endif /* kmeans_h */
| mit |
curtclifton/curtclifton.github.io | _site/2017/03/02/t837185195841212416.html | 1623 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>T837185195841212416</title>
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/custom.css">
<link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://curt.micro.blog/feed.xml" />
<link rel="alternate" type="application/json" title="Curt Clifton" href="http://curt.micro.blog/feed.json" />
<link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />
<link rel="me" href="https://micro.blog/curt" />
<link rel="me" href="https://twitter.com/curtclifton" />
<link rel="authorization_endpoint" href="https://indieauth.com/auth" />
<link rel="token_endpoint" href="https://tokens.indieauth.com/token" />
<link rel="micropub" href="https://micro.blog/micropub" />
<link rel="webmention" href="https://micro.blog/webmention" />
</head>
<body>
<div class="container">
<header class="masthead">
<h1 class="masthead-title--small">
<a href="/">Curt Clifton</a>
</h1>
</header>
<div class="content post h-entry">
<div class="post-date">
<time class="dt-published" datetime="2017-03-02 06:17:00 +0000">02 Mar 2017</time>
</div>
<div class="e-content">
<p>Whoever, owing allegiance to [U.S.],… adheres to their enemies… is guilty of treason and shall suffer death… #fb <a href="https://t.co/Uid0RAMMs1">https://t.co/Uid0RAMMs1</a></p>
</div>
</div>
</div>
</body>
</html>
| mit |
AlexandrSachkov/NonLinearEngine | NLE/NL_ImguiD3D11Renderer.cpp | 17834 | #include "NL_ImguiD3D11Renderer.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <imgui.h>
namespace NLE
{
namespace GRAPHICS
{
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
};
ImguiD3D11Renderer::ImguiD3D11Renderer() :
_vertexBuffer(nullptr),
_indexBuffer(nullptr),
_vertexShaderBlob(nullptr),
_vertexShader(nullptr),
_inputLayout(nullptr),
_vertexConstantBuffer(nullptr),
_pixelShaderBlob(nullptr),
_pixelShader(nullptr),
_fontSampler(nullptr),
_fontTextureView(nullptr),
_rasterizerState(nullptr),
_blendState(nullptr),
_depthStencilState(nullptr),
_vertexBufferSize(5000),
_indexBufferSize(10000)
{
}
ImguiD3D11Renderer::~ImguiD3D11Renderer()
{
}
bool ImguiD3D11Renderer::initialize(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
if (!createDeviceObjects(device, devCon))
return false;
if (!createFontAndTextures(device, devCon))
return false;
return true;
}
bool ImguiD3D11Renderer::createDeviceObjects(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
// If you would like to use this DX11 sample code but remove this dependency you can:
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [prefered solution]
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
// Create the vertex shader
{
static const char* vertexShader =
"cbuffer vertexBuffer : register(b0) \
{\
float4x4 ProjectionMatrix; \
};\
struct VS_INPUT\
{\
float2 pos : POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
PS_INPUT main(VS_INPUT input)\
{\
PS_INPUT output;\
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
output.col = input.col;\
output.uv = input.uv;\
return output;\
}";
D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &_vertexShaderBlob, nullptr);
if (!_vertexShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return false;
if (device->CreateVertexShader((DWORD*)_vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), nullptr, &_vertexShader) != S_OK)
return false;
// Create the input layout
D3D11_INPUT_ELEMENT_DESC local_layout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
if (device->CreateInputLayout(local_layout, 3, _vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), &_inputLayout) != S_OK)
return false;
// Create the constant buffer
{
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
device->CreateBuffer(&desc, nullptr, &_vertexConstantBuffer);
}
}
// Create the pixel shader
{
static const char* pixelShader =
"struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
sampler sampler0;\
Texture2D texture0;\
\
float4 main(PS_INPUT input) : SV_Target\
{\
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
return out_col; \
}";
D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &_pixelShaderBlob, nullptr);
if (!_pixelShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return false;
if (device->CreatePixelShader((DWORD*)_pixelShaderBlob->GetBufferPointer(), _pixelShaderBlob->GetBufferSize(), nullptr, &_pixelShader) != S_OK)
return false;
}
// Create the blending setup
{
D3D11_BLEND_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.AlphaToCoverageEnable = false;
desc.RenderTarget[0].BlendEnable = true;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
device->CreateBlendState(&desc, &_blendState);
}
// Create the rasterizer state
{
D3D11_RASTERIZER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.FillMode = D3D11_FILL_SOLID;
desc.CullMode = D3D11_CULL_NONE;
desc.ScissorEnable = true;
desc.DepthClipEnable = true;
device->CreateRasterizerState(&desc, &_rasterizerState);
}
// Create depth-stencil State
{
D3D11_DEPTH_STENCIL_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.DepthEnable = false;
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
desc.StencilEnable = false;
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc.BackFace = desc.FrontFace;
device->CreateDepthStencilState(&desc, &_depthStencilState);
}
return true;
}
bool ImguiD3D11Renderer::createFontAndTextures(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// Upload texture to graphics system
{
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D *pTexture = NULL;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = pixels;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
device->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
device->CreateShaderResourceView(pTexture, &srvDesc, &_fontTextureView);
pTexture->Release();
}
// Store our identifier
io.Fonts->TexID = (void *)_fontTextureView;
// Create texture sampler
{
D3D11_SAMPLER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
desc.MipLODBias = 0.f;
desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
desc.MinLOD = 0.f;
desc.MaxLOD = 0.f;
device->CreateSamplerState(&desc, &_fontSampler);
}
return true;
}
void ImguiD3D11Renderer::render(ID3D11Device* device, ID3D11DeviceContext* devCon, ImDrawData* drawData)
{
// Create and grow vertex/index buffers if needed
if (!_vertexBuffer || _vertexBufferSize < drawData->TotalVtxCount)
{
if (_vertexBuffer) { _vertexBuffer->Release(); _vertexBuffer = nullptr; }
_vertexBufferSize = drawData->TotalVtxCount + 5000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = _vertexBufferSize * sizeof(ImDrawVert);
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
if (device->CreateBuffer(&desc, nullptr, &_vertexBuffer) < 0)
return;
}
if (!_indexBuffer || _indexBufferSize < drawData->TotalIdxCount)
{
if (_indexBuffer) { _indexBuffer->Release(); _indexBuffer = nullptr; }
_indexBufferSize = drawData->TotalIdxCount + 10000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = _indexBufferSize * sizeof(ImDrawIdx);
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (device->CreateBuffer(&desc, nullptr, &_indexBuffer) < 0)
return;
}
// Copy and convert all vertices into a single contiguous buffer
D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
if (devCon->Map(_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
return;
if (devCon->Map(_indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
return;
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
vtx_dst += cmd_list->VtxBuffer.size();
idx_dst += cmd_list->IdxBuffer.size();
}
devCon->Unmap(_vertexBuffer, 0);
devCon->Unmap(_indexBuffer, 0);
// Setup orthographic projection matrix into our constant buffer
{
D3D11_MAPPED_SUBRESOURCE mapped_resource;
if (devCon->Map(_vertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
return;
VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
float L = 0.0f;
float R = ImGui::GetIO().DisplaySize.x;
float B = ImGui::GetIO().DisplaySize.y;
float T = 0.0f;
float mvp[4][4] =
{
{ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f },
};
memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
devCon->Unmap(_vertexConstantBuffer, 0);
}
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
struct BACKUP_DX11_STATE
{
UINT ScissorRectsCount, ViewportsCount;
D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
ID3D11RasterizerState* RS;
ID3D11BlendState* BlendState;
FLOAT BlendFactor[4];
UINT SampleMask;
UINT StencilRef;
ID3D11DepthStencilState* DepthStencilState;
ID3D11ShaderResourceView* PSShaderResource;
ID3D11SamplerState* PSSampler;
ID3D11PixelShader* PS;
ID3D11VertexShader* VS;
UINT PSInstancesCount, VSInstancesCount;
ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
DXGI_FORMAT IndexBufferFormat;
ID3D11InputLayout* InputLayout;
};
BACKUP_DX11_STATE old;
old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
devCon->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
devCon->RSGetViewports(&old.ViewportsCount, old.Viewports);
devCon->RSGetState(&old.RS);
devCon->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
devCon->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
devCon->PSGetShaderResources(0, 1, &old.PSShaderResource);
devCon->PSGetSamplers(0, 1, &old.PSSampler);
old.PSInstancesCount = old.VSInstancesCount = 256;
devCon->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
devCon->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
devCon->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
devCon->IAGetPrimitiveTopology(&old.PrimitiveTopology);
devCon->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
devCon->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
devCon->IAGetInputLayout(&old.InputLayout);
// Setup viewport
D3D11_VIEWPORT vp;
memset(&vp, 0, sizeof(D3D11_VIEWPORT));
vp.Width = ImGui::GetIO().DisplaySize.x;
vp.Height = ImGui::GetIO().DisplaySize.y;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = vp.TopLeftY = 0.0f;
devCon->RSSetViewports(1, &vp);
// Bind shader and vertex buffers
unsigned int stride = sizeof(ImDrawVert);
unsigned int offset = 0;
devCon->IASetInputLayout(_inputLayout);
devCon->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
devCon->IASetIndexBuffer(_indexBuffer, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
devCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
devCon->VSSetShader(_vertexShader, NULL, 0);
devCon->VSSetConstantBuffers(0, 1, &_vertexConstantBuffer);
devCon->PSSetShader(_pixelShader, NULL, 0);
devCon->PSSetSamplers(0, 1, &_fontSampler);
// Setup render state
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
devCon->OMSetBlendState(_blendState, blend_factor, 0xffffffff);
devCon->OMSetDepthStencilState(_depthStencilState, 0);
devCon->RSSetState(_rasterizerState);
// Render command lists
int vtx_offset = 0;
int idx_offset = 0;
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
devCon->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
devCon->RSSetScissorRects(1, &r);
devCon->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
}
idx_offset += pcmd->ElemCount;
}
vtx_offset += cmd_list->VtxBuffer.size();
}
// Restore modified DX state
devCon->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
devCon->RSSetViewports(old.ViewportsCount, old.Viewports);
devCon->RSSetState(old.RS); if (old.RS) old.RS->Release();
devCon->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
devCon->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
devCon->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
devCon->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
devCon->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
devCon->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
devCon->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
devCon->IASetPrimitiveTopology(old.PrimitiveTopology);
devCon->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
devCon->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
devCon->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
}
} | mit |
levfurtado/scoops | vendor/bombayworks/zendframework1/library/Zend/Pdf/Annotation/FileAttachment.php | 3689 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Pdf
* @subpackage Annotation
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: FileAttachment.php 24594 2012-01-05 21:27:01Z matthew $
*/
/** Internally used classes */
// require_once 'Zend/Pdf/Element.php';
// require_once 'Zend/Pdf/Element/Array.php';
// require_once 'Zend/Pdf/Element/Dictionary.php';
// require_once 'Zend/Pdf/Element/Name.php';
// require_once 'Zend/Pdf/Element/Numeric.php';
// require_once 'Zend/Pdf/Element/String.php';
/** Zend_Pdf_Annotation */
// require_once 'Zend/Pdf/Annotation.php';
/**
* A file attachment annotation contains a reference to a file,
* which typically is embedded in the PDF file.
*
* @package Zend_Pdf
* @subpackage Annotation
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Pdf_Annotation_FileAttachment extends Zend_Pdf_Annotation
{
/**
* Annotation object constructor
*
* @throws Zend_Pdf_Exception
*/
public function __construct(Zend_Pdf_Element $annotationDictionary)
{
if ($annotationDictionary->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
// require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Annotation dictionary resource has to be a dictionary.');
}
if ($annotationDictionary->Subtype === null ||
$annotationDictionary->Subtype->getType() != Zend_Pdf_Element::TYPE_NAME ||
$annotationDictionary->Subtype->value != 'FileAttachment') {
// require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('Subtype => FileAttachment entry is requires');
}
parent::__construct($annotationDictionary);
}
/**
* Create link annotation object
*
* @param float $x1
* @param float $y1
* @param float $x2
* @param float $y2
* @param string $fileSpecification
* @return Zend_Pdf_Annotation_FileAttachment
*/
public static function create($x1, $y1, $x2, $y2, $fileSpecification)
{
$annotationDictionary = new Zend_Pdf_Element_Dictionary();
$annotationDictionary->Type = new Zend_Pdf_Element_Name('Annot');
$annotationDictionary->Subtype = new Zend_Pdf_Element_Name('FileAttachment');
$rectangle = new Zend_Pdf_Element_Array();
$rectangle->items[] = new Zend_Pdf_Element_Numeric($x1);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($y1);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($x2);
$rectangle->items[] = new Zend_Pdf_Element_Numeric($y2);
$annotationDictionary->Rect = $rectangle;
$fsDictionary = new Zend_Pdf_Element_Dictionary();
$fsDictionary->Type = new Zend_Pdf_Element_Name('Filespec');
$fsDictionary->F = new Zend_Pdf_Element_String($fileSpecification);
$annotationDictionary->FS = $fsDictionary;
return new Zend_Pdf_Annotation_FileAttachment($annotationDictionary);
}
}
| mit |
developedbyme/dbm | javascripts/dbm/classes/dbm/thirdparty/facebook/constants/EventTypes.js | 1089 | /* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
dbm.registerClass("dbm.thirdparty.facebook.constants.EventTypes", null, function(objectFunctions, staticFunctions, ClassReference) {
//console.log("dbm.thirdparty.facebook.constants.EventTypes");
//REFERENCE: http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
var EventTypes = dbm.importClass("dbm.thirdparty.facebook.constants.EventTypes");
staticFunctions.AUTH_LOGIN = "auth.login";
staticFunctions.AUTH_RESPONSE_CHANGE = "auth.authResponseChange";
staticFunctions.AUTH_STATUS_CHANGE = "auth.statusChange";
staticFunctions.AUTH_LOGOUT = "auth.logout";
staticFunctions.AUTH_PROMPT = "auth.prompt";
staticFunctions.XFBML_RENDER = "xfbml.render";
staticFunctions.EDGE_CREATE = "edge.create";
staticFunctions.EDGE_REMOVE = "edge.remove";
staticFunctions.COMMENT_CREATE = "comment.create";
staticFunctions.COMMENT_REMOVE = "comment.remove";
staticFunctions.MESSAGE_SEND = "message.send";
}); | mit |
eerwitt/tweetstream | lib/tweetstream/error.rb | 506 | module TweetStream
class Terminated < ::StandardError; end
class Error < ::StandardError; end
class ConnectionError < TweetStream::Error; end
# A ReconnectError is raised when the maximum number of retries has
# failed to re-establish a connection.
class ReconnectError < StandardError
attr_accessor :timeout, :retries
def initialize(timeout, retries)
self.timeout = timeout
self.retries = retries
super("Failed to reconnect after #{retries} tries.")
end
end
end | mit |
dotnet/roslyn-analyzers | src/TestReferenceAssembly/OtherDllClass.cs | 3861 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
#pragma warning disable CA1801 // Remove unused parameter
#pragma warning disable IDE0060 // Remove unused parameter
using System;
using System.Linq;
using System.Text;
namespace OtherDll
{
/// <summary>
/// Aids with testing dataflow analysis _not_ doing interprocedural DFA.
/// </summary>
/// <remarks>
/// Since Roslyn doesn't support cross-binary DFA, and this class is
/// defined in a different binary, using this class from test source code
/// is a way to test handling of non-interprocedural results in dataflow
/// analysis implementations.
/// </remarks>
public class OtherDllClass<T>
where T : class
{
public OtherDllClass(T? constructedInput)
{
this.ConstructedInput = constructedInput;
}
public T? ConstructedInput { get; set; }
public T? Default
{
get => default;
set { }
}
public string RandomString
{
get
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
return Encoding.ASCII.GetString(bytes);
}
set { }
}
public T? ReturnsConstructedInput()
{
return this.ConstructedInput;
}
public T? ReturnsDefault()
{
return default;
}
public T? ReturnsInput(T? input)
{
return input;
}
public T? ReturnsDefault(T? input)
{
return default;
}
public string ReturnsRandom(string input)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
return Encoding.ASCII.GetString(bytes);
}
public void SetsOutputToConstructedInput(out T? output)
{
output = this.ConstructedInput;
}
public void SetsOutputToDefault(out T? output)
{
output = default;
}
public void SetsOutputToInput(T? input, out T? output)
{
output = input;
}
public void SetsOutputToDefault(T? input, out T? output)
{
output = default;
}
public void SetsOutputToRandom(string input, out string output)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
output = Encoding.ASCII.GetString(bytes);
}
public void SetsReferenceToConstructedInput(ref T? output)
{
output = this.ConstructedInput;
}
public void SetsReferenceToDefault(ref T? output)
{
output = default;
}
public void SetsReferenceToInput(T? input, ref T? output)
{
output = input;
}
public void SetsReferenceToDefault(T? input, ref T? output)
{
output = default;
}
public void SetsReferenceToRandom(string input, ref string output)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
output = Encoding.ASCII.GetString(bytes);
}
}
}
| mit |
flash662/fashionguide | src/Exceptions/AppException.php | 91 | <?php
namespace FashionGuide\Oauth2\Exceptions;
class AppException extends \Exception
{
} | mit |
daveenguyen/propitious-melting-pot | certs/script.sh | 1712 | #!/bin/bash
# Set up your StartSSL certificates/keys for nginx-proxy
# This script expects your certificate and key files in this folder following
# the nginx-proxy naming convention.
# For example: foo.example.com.crt foo.example.com.key
# are the .crt and .key file for the domain foo.example.com
# Make sure script is ran from correct directory
if [[ ! -e script.sh ]]; then
if [[ -d certs ]]; then
cd certs || { echo >&2 "Bundle directory exists but I can't cd there."; exit 1; }
else
echo >&2 "Please cd into the bundle before running this script."; exit 1;
fi
fi
CERT_CLASS="class1"
CERT_CA_FILE="sub.${CERT_CLASS}.server.ca.pem"
DHPARAM_FILE="dhparam.pem"
# Get the StartSSL Root CA and Class 1 Intermediate Server CA certificates
if [ ! -f ${CERT_CA_FILE} ]; then
wget https://www.startssl.com/certs/${CERT_CA_FILE}
fi
# Generate dhparam.pem if needed.
if [ ! -f ${DHPARAM_FILE} ]; then
echo "${DHPARAM_FILE} not found."
echo "Generating ${DHPARAM_FILE} with openssl"
openssl dhparam -out ${DHPARAM_FILE} 2048
fi
# Create a private key and certificate and transfer them to your server.
for file in *.key; do
DOMAIN=${file%.*}
if [ ! -f ./unified/${DOMAIN}.crt ]; then
echo "DHPARAM: Copying ${DOMAIN}.${DHPARAM_FILE}"
cp ./${DHPARAM_FILE} ./unified/${DOMAIN}.${DHPARAM_FILE}
echo "CRT: Creating unified ${DOMAIN}.crt"
cat ./${DOMAIN}.crt ${CERT_CA_FILE} > ./unified/${DOMAIN}.crt
# Keys should already be decrypted
echo "KEY: Copying ${DOMAIN}.key"
cp ./${DOMAIN}.key ./unified/${DOMAIN}.key
echo ""
fi
# Protect your key files from prying eyes
chmod 600 ./${DOMAIN}.key
chmod 600 ./unified/${DOMAIN}.key
done
| mit |
xmmedia/starter_perch | webpack.test.config.js | 1518 | 'use strict';
// This is the webpack config used for JS unit tests
const Encore = require('@symfony/webpack-encore');
const encoreConfigure = require('./webpack.base.config');
const webpackCustomize = require('./webpack.customize');
// Initialize Encore before requiring the .config file
Encore.configureRuntimeEnvironment('dev-server');
encoreConfigure(Encore);
const webpack = require('webpack');
const merge = require('webpack-merge');
const ManifestPlugin = require('@symfony/webpack-encore/lib/webpack/webpack-manifest-plugin');
const baseWebpackConfig = Encore.getWebpackConfig();
webpackCustomize(baseWebpackConfig);
const webpackConfig = merge(baseWebpackConfig, {
// use inline sourcemap for karma-sourcemap-loader
devtool: '#inline-source-map',
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"testing"'
}
})
]
});
// no need for app entry during tests
delete webpackConfig.entry;
// Set writeToFileEmit option of the ManifestPlugin to false
for (const plugin of webpackConfig.plugins) {
if ((plugin instanceof ManifestPlugin) && plugin.opts) {
plugin.opts.writeToFileEmit = false;
}
}
module.exports = webpackConfig; | mit |
pharpend/dotfiles | .themes/Libra-Dark/gtk-3.0/gnome-applications.css | 13545 | /***********************
* fallback mode panel *
***********************/
PanelWidget,
PanelApplet,
PanelToplevel {
padding: 0;
background-color: @osd_bg;
background-image: none;
color: #222222;
}
PanelApplet {
border-width: 0;
}
PanelSeparator {
border-width: 0;
background-color: @osd_bg;
background-image: none;
color: @osd_fg;
}
.gnome-panel-menu-bar,
PanelApplet > GtkMenuBar.menubar,
PanelApplet > GtkMenuBar.menubar.menuitem,
PanelMenuBar.menubar,
PanelMenuBar.menubar.menuitem {
-Panelpanel-icon-visible: true;
border-width: 0;
background-color: @osd_bg;
background-image: none;
}
PanelAppletFrame {
border-width: 0;
background-color: @osd_bg;
background-image: none;
}
PanelApplet .button {
-GtkButton-inner-border: 2;
border-width: 0;
border-radius: 5px;
border-color: transparent;
background-color: @osd_bg;
background-image: none;
color: #222222;
}
PanelApplet .button:active,
PanelApplet .button:active:prelight {
border-width: 0 ;
border-radius: 5px;
background-color: shade(@button_normal_color, 0.925);
background-image: none;
color: shade(@theme_selected_fg_color, 0.95);
}
PanelApplet .button:prelight {
background-color: shade(@button_normal_color, 1.06);
background-image: none;
color: #222222;
}
WnckPager, WnckTasklist {
background-color: @osd_bg;
}
/************
* nautilus *
************/
.nautilus-canvas-item {
border-radius: 2px;
}
.nautilus-desktop.nautilus-canvas-item {
color: white;
text-shadow: 1px 1px black;
}
.nautilus-desktop.nautilus-canvas-item:active {
}
.nautilus-desktop.nautilus-canvas-item:selected {
}
.nautilus-desktop.nautilus-canvas-item:active,
.nautilus-desktop.nautilus-canvas-item:prelight,
.nautilus-desktop.nautilus-canvas-item:selected {
}
NautilusWindow .toolbar {
border-width: 0;
border-style: none;
}
NautilusWindow .primary-toolbar .button.raised.linked.text-button,
NautilusWindow .primary-toolbar .raised.linked .button.text-button,
NautilusWindow .toolbar .button.raised.linked.text-button,
NautilusWindow .toolbar .raised.linked .button.text-button,
NautilusWindow .toolbar .linked .button.text-button,
NautilusWindow .header-bar .button.raised.linked.text-button,
NautilusWindow .header-bar .raised.linked .button.text-button,
NautilusWindow .header-bar .linked .button.text-button,
NautilusWindow .header-bar .button.text-button,
NautilusWindow .toolbar .button.text-button {
}
NautilusWindow .sidebar .frame {
border-style: none;
}
NautilusWindow > GtkGrid > .pane-separator,
NautilusWindow > GtkGrid > .pane-separator:hover {
border-width: 0;
border-style: none;
}
NautilusNotebook.notebook tab {
padding: 0;
}
NautilusNotebook .frame,
NautilusWindow .sidebar .frame {
border-width: 0;
}
NautilusQueryEditor .primary-toolbar.toolbar {
border-width: 0;
}
NautilusQueryEditor .toolbar {
border-width: 0;
}
NautilusQueryEditor .toolbar:nth-child(2) {
}
NautilusQueryEditor .toolbar:last-child,
NautilusQueryEditor .primary-toolbar.toolbar:only-child {
border-width: 0;
}
/*
NautilusWindow .sidebar,
NautilusWindow .sidebar.view,
NautilusWindow .sidebar .view,
NautilusWindow .sidebar.view:prelight,
NautilusWindow .sidebar .view:prelight {
background-color: @bg_color;
}
*/
/******************
* gnome terminal *
******************/
VteTerminal {
background-color: @base_color;
color: @text_color;
}
TerminalWindow,
TerminalWindow GtkNotebook,
TerminalWindow GtkNotebook.notebook {
background-color: @base_color;
color: @text_color;
border-width: 0;
}
TerminalWindow .scrollbars-junction,
TerminalWindow .scrollbar.trough,
TerminalWindow .scrollbar.trough.vertical {
background-color: @base_color;
}
TerminalWindow .scrollbar.button,
TerminalWindow .scrollbar.button:active,
TerminalWindow .scrollbar.button:active:hover {
}
TerminalWindow .scrollbar.slider {
background-color: shade(@bg_color,1.0);
}
TerminalWindow .scrollbar.slider:hover,
TerminalWindow .scrollbar.slider.vertical:hover {
background-color: shade(@bg_color, 1.1);
}
TerminalWindow .scrollbar.slider:active,
TerminalWindow .scrollbar.slider.vertical:active {
background-color: shade(@bg_color, 1.1);
}
/*********
* gedit *
*********/
GeditWindow .pane-separator,
GeditWindow .pane-separator:hover {
border-width: 0;
border-style: none;
background-color: @theme_bg_color;
}
GeditPanel.title GtkLabel {
padding: 4px 0;
}
GeditPanel.vertical .title {
padding: 4px 0 4px 3px;
border-style: none;
}
GeditPanel .toolbar {
border-style: none;
background-color: transparent;
}
GeditDocumentsPanel .view {
background-color: @theme_base_color;
}
GeditPanel.vertical .notebook {
padding: 0;
border-width: 0;
}
GeditPanel.horizontal .notebook {
padding: 0;
border-width: 0;
}
GeditWindow .notebook {
border-width: 0;
}
GeditPanel .notebook tab,
GeditWindow .notebook tab {
border-width: 0;
}
GeditStatusMenuButton {
color: @theme_fg_color;
text-shadow: none;
}
GeditStatusMenuButton.button,
GeditStatusMenuButton.button:hover,
GeditStatusMenuButton.button:active,
GeditStatusMenuButton.button:active:hover {
text-shadow: none;
font-weight: normal;
border-image: none;
border-style: none;
border-width: 0;
border-radius: 5px;
color: @theme_fg_color;
}
GeditStatusMenuButton.button:hover,
GeditStatusMenuButton.button:active,
GeditStatusMenuButton.button:active:hover {
color: @theme_selected_fg_color;
}
GeditStatusMenuButton.button:active {
}
GeditViewFrame .gedit-search-slider {
padding: 4px;
border-radius: 0 0 5px 5px;
border-width: 0 1px 1px 1px;
border-style: solid;
border-color: @entry_border_color;
background-color: @theme_base_color;
}
GeditViewFrame .gedit-search-slider .not-found {
background-color: @error_bg_color;
background-image: none;
color: @error_fg_color;
}
GeditViewFrame .gedit-search-slider .entry {
padding: 5px 5px 6px 5px;
}
GeditViewFrame .gedit-search-slider .not-found:selected {
background-color: shade(@theme_selected_bg_color, 1.2);
color: @theme_selected_fg_color;
}
GeditFileBrowserWidget .primary-toolbar.toolbar {
padding: 2px;
border: none;
background-color: @theme_bg_color;
background-image: none;
}
GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox *{
color: @theme_fg_color;
}
GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox *:hover,
GeditFileBrowserWidget .primary-toolbar.toolbar GtkComboBox .menu * {
color: @theme_selected_fg_color;
}
.gedit-search-entry-occurrences-tag {
color: @theme_text_color;
margin: 2px;
padding: 2px;
}
/***************
* font-viewer *
***************/
SushiFontWidget {
padding: 6px 12px;
}
/*************
* gucharmap *
*************/
GucharmapChartable {
background-color: @theme_base_color;
}
GucharmapChartable:active,
GucharmapChartable:focus,
GucharmapChartable:selected {
background-color: @theme_selected_bg_color;
color: @theme_selected_fg_color;
}
/* gnome-documents */
.documents-dropdown,
.documents-dropdown .view {
background-color: @theme_bg_color;
}
.documents-dropdown.frame {
padding: 6px;
border-width: 0 1px 1px 1px;
border-style: solid;
border-radius: 0 0 5px 5px;
border-color: @entry_border_color;
}
.documents-dropdown .view.radio,
.documents-dropdown .view.radio:focus {
background-image: url("assets/blank.png");;
background-color: transparent;
}
.documents-dropdown .view.radio:active,
.documents-dropdown .view.radio:active:focus,
.documents-dropdown .view.radio:active:hover,
.documents-dropdown .view.radio:hover {
background-color: transparent;
background-image: url("assets/radio-checked.png");
}
.documents-entry-tag {
background-color: transparent;
color: @theme_text_color;
border-radius: 5px;
border-width: 0;
margin: 2px;
padding: 4px;
}
.documents-entry-tag:hover {
}
.documents-entry-tag.button,
.documents-entry-tag.button:focus,
.documents-entry-tag.button:hover,
.documents-entry-tag.button:hover:focus,
.documents-entry-tag.button:active,
.documents-entry-tag.button:active:focus {
color: @theme_selected_fg_color;
}
/* epiphany */
EphyToolbar .entry:first-child,
EphyToolbar .entry:focus:first-child {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
EphyToolbar .entry:last-child,
EphyToolbar .entry:focus:last-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
EphyToolbar .location-entry .button:last-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
EphyToolbar .location-entry .button:first-child {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
EphyOverview GtkScrolledWindow {
border-style: none;
background-color: @theme_base_color;
}
EphyWindow.background EphyEmbed.vertical GtkScrolledWindow.frame {
border-style: none;
}
EphyWindow.background EphyEmbed.vertical EphyOverview .documents-scrolledwin {
border-style: none;
}
EphyWindow.background EphyNotebook.notebook EphyEmbed.vertical GtkScrolledWindow {
border-style: none;
}
/* Gnome Contacts */
ContactsContactSheet .button,
ContactsContactSheet .button:focus {
color: @theme_text_color;
text-shadow: none;
}
ContactsContactSheet .button:active,
ContactsContactSheet .button:hover,
ContactsContactSheet .button:active:focus,
ContactsContactSheet .button:hover:focus {
color: @theme_selected_fg_color;
text-shadow: none;
}
/* evince */
EvWindow.background > GtkBox.vertical > GtkPaned.horizontal > GtkBox.vertical > GtkOverlay > GtkScrolledWindow.frame {
border-width: 0;
border-radius: 0;
}
EvWindow.background EvSidebar.vertical .frame {
border-width: 0;
border-radius: 0;
}
EvWindow.background EvSidebar.vertical .notebook .frame {
border-width: 0;
}
EvSidebar .button,
EvSidebar .button:focus {
color: @theme_text_color;
text-shadow: none;
}
EvSidebar .button:active,
EvSidebar .button:hover,
EvSidebar .button:active:focus,
EvSidebar .button:hover:focus {
color: @theme_selected_fg_color;
text-shadow: none;
}
/* file-roller */
RBSource .toolbar .button,
FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel {
text-shadow: none;
icon-shadow: none;
color: shade(@theme_text_color, 1.1);
}
CcWindow CcUserPanel CcEditableEntry .button,
CcWindow CcUserPanel UmEditableCombo .button,
CcWindow CcUserPanel UmEditableButton .button,
CcWindow CcUserPanel CcEditableEntry .button:focus,
CcWindow CcUserPanel UmEditableCombo .button:focus,
CcWindow CcUserPanel UmEditableButton .button:focus,
RBSource .toolbar .button,
FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button {
text-shadow: none;
icon-shadow: none;
color: shade(@theme_text_color, 1.1);
}
CcWindow CcUserPanel CcEditableEntry .button:hover,
CcWindow CcUserPanel UmEditableCombo .button:hover,
CcWindow CcUserPanel UmEditableButton .button:hover,
CcWindow CcUserPanel CcEditableEntry .button:active,
CcWindow CcUserPanel UmEditableCombo .button:active,
CcWindow CcUserPanel UmEditableButton .button:active,
RBSource .toolbar .button:hover,
RBSource .toolbar .button:active,
FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:hover,
FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:active {
color: @theme_selected_fg_color;
}
CcWindow CcUserPanel CcEditableEntry .button:insensitive,
CcWindow CcUserPanel UmEditableCombo .button:insensitive,
CcWindow CcUserPanel UmEditableButton .button:insensitive,
RBSource .toolbar .button:insensitive,
FrWindow > GtkGrid > GtkToolbar > GtkToolButton > GtkButton.button GtkLabel:insensitive {
color: shade(@entry_border_color, 0.8);
}
/*********************
* NEMO File manager *
*********************/
/* for breadcrumbs path bar */
.nemo-pathbar-button,
NemoPathbarButton {
border-radius: 5px;
border-width: 1px;
border-style: solid;
border-color: transparent;
text-shadow: none;
icon-shadow: none;
box-shadow: none;
background-color: @button_normal_color;
background-image: none;
color: @theme_selected_fg_color;
}
NemoPathbarButton:active,
NemoPathbarButton:active:hover {
box-shadow: none;
background-color: @theme_selected_bg_color;
background-image: none;
color: shade(@theme_selected_fg_color, 0.95);
}
NemoPathbarButton:hover {
box-shadow: none;
text-shadow: none;
icon-shadow: none;
background-color: shade(@button_normal_color, 1.06);
background-image: none;
color: @theme_selected_fg_color;
}
NemoPathbarButton:insensitive {
box-shadow: none;
background-color: shade(@button_normal_color, 1.17);
background-image: none;
color: shade(@entry_border_color, 1.05);
}
NemoPathbarButton *:insensitive {
color: shade(@entry_border_color, 1.05);
}
/* For Places Sidebar diskfull indicators */
NemoPlacesTreeView {
}
NemoPlacesTreeView:selected {
-NemoPlacesTreeView-disk-full-bg-color: @entry_border_color;
-NemoPlacesTreeView-disk-full-fg-color: @button_normal_color;
}
NemoPlacesTreeView:hover {
}
NemoPlacesTreeView:selected:hover {
}
NemoWindow * {
}
NemoWindow .view {
background-color: @theme_base_color;
}
NemoWindow .rubberband,
NemoWindow .view.rubberband {
background-color: alpha (@theme_selected_bg_color, 0.3);
}
/* inactive pane */
.nemo-inactive-pane .view {
background-color: shade(@theme_bg_color, 1.03);
}
| mit |
Leeway213/BSP-aw1689 | loong/pctools/windows/buildscripts/iot-adk-addonkit/Templates/installupdates.cmd | 393 | @echo off
REM Script to install the updates
net user Administrator p@ssw0rd /active:yes
SET install_dir=%~dp0
REM Getting rid of the \ at the end
SET install_dir=%install_dir:~0,-1%
cd %install_dir%
dir /b %install_dir%\*.cab > updatelist.txt
for /f "delims=" %%i in (updatelist.txt) do (
echo Processing %%i
call applyupdate -stage %%i
)
echo.
echo Commit updates
applyupdate -commit
| mit |
apurvis/petitioneer | config/initializers/session_store.rb | 143 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_petitioneer_session'
| mit |
taylordaug/phase-0 | week-9/review.js | 3848 | // Release 1: User Stories
// As a user, I want to be able to create a new grocery list. After that, I need to be able to add an item with a quantity to the list, remove an item, and update the quantities if they change. I need a way to print out the list in a format that is very readable.
// Release 2: Pseudocode
// input: string of items separated by spaces
// output: object
// create a new object as new variable
// convert string to array (split)
// take each item in array and add to object as a property with a default quantity/value of 1
//
// Release 3: Initial Solution
// function to create list
// var foodList = ("salmon iceCream macAndCheese")
// var groceryList = {};
// var createList = function(foodList) {
// var foodArray = foodList.split(" ");
// for (var i = 0; i < foodArray.length; i++){
// groceryList[(foodArray[i])] = 1;
// }
// console.log(groceryList);
// }
// createList(foodList)
// // function to add item to list
// var addItem = function(newItem) {
// groceryList[newItem] = 1;
// console.log(groceryList);
// }
// addItem("peas")
// // function to remove item from list
// var removeItem = function(itemToLose) {
// delete groceryList[itemToLose];
// console.log(groceryList);
// }
// removeItem("peas")
// // function to update quantity
// var updateList = function(updateItem, newQuantity) {
// groceryList[updateItem] = newQuantity;
// console.log(groceryList);
// }
// updateList("macAndCheese", 5)
// // function to display list
// var displayList = function(groceryList) {
// for (food in groceryList) {
// console.log(food + ": " + groceryList[food]);
// }
// }
// displayList(groceryList)
// Release 4: Refactor
// function to create list
var groceryList = {};
var displayList = function(groceryList) {
console.log("Your Grocery List:")
for (food in groceryList) {
console.log(food + ": " + groceryList[food]);
}
console.log("----------")
}
var createList = function(foodList) {
var foodArray = foodList.split(" ");
for (var i = 0; i < foodArray.length; i++){
groceryList[(foodArray[i])] = 1;
}
displayList(groceryList);
}
var addItem = function(newItem) {
groceryList[newItem] = 1;
displayList(groceryList);
}
var removeItem = function(itemToLose) {
delete groceryList[itemToLose];
displayList(groceryList);
}
var updateList = function(updateItem, newQuantity) {
groceryList[updateItem] = newQuantity;
displayList(groceryList);
}
var foodList = ("funfettiMix bananas chocolateCoveredAlmonds")
createList(foodList)
addItem("peaches")
updateList("peaches", 20)
removeItem("bananas")
// Release 5: Reflect
// What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.)
// I solidified accessing different properties in an object. I was able to add strings from an array into an empty object and set their default value. To change those values I knew I needed to access the property using bracket notation, and change the value it was = to.
// What was the most difficult part of this challenge?
// I forgot I needed to convert the string to an array, but once I did that with the .split(" ") method, all of the strings were easily accessible to add to the new object.
// Did an array or object make more sense to use and why?
// This was weirdly WAY easier with JavaScript than it was initially with Ruby (probably because we were on our second week of Ruby at this point!). It was so easy to add each string from an array into the object as a property and set it's default. Accessing these properties to update or delete was made easier by using bracket notation. Instead of complicated hash methods and having to convert strings to arrays to hashes, all I had to do was split the string and add each string to the object with a default value. | mit |
jdashg/misc | colors/from-coeffs.html | 8409 | <!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<script src='matrices.js'></script>
<style>
.indent {
padding-left: 2em;
}
</style>
</head>
<body>
<h3>Color space:</h3>
Spec: <select id='e_color_space'>
<option value='rec601' selected>Rec601</option>
<option value='rec709'>Rec709</option>
<option value='rec2020'>Rec2020/Rec2100</option>
</select>
<div class='indent'>
Kr: <input id='e_kr'>
<br>
Kg: <input id='e_kg'>
<br>
Kb: <input id='e_kb'>
</div>
<br>Array order:
<select id='e_array_major'>
<option value='row' selected>Row-major (common)</option>
<option value='column'>Column-major (for OpenGL)</option>
</select>
<br>Precision: <input id='e_precision' value='5'>
<pre id='e_color_space_output'>-</pre>
<hr>
<h3>Quantization</h3>
Bits: <input id='e_bits'>
<br>Range:
<select id='e_range_type'>
<option value='narrow' selected>Narrow</option>
<option value='full'>Full</option>
</select>
<div class='indent'>
Yquant: [ <input id='e_yq_min'> , <input id='e_yq_max'> ]
<br>
Cb, Cr: [ <input id='e_uvq_min'> , <input id='e_uvq_max'> ] (<span id='e_uvq_info'></span>)
</div>
<pre id='e_quant_output'>-</pre>
<hr>
<h3>Conversion:</h3>
<pre id='e_matrix_output'>-</pre>
YCbCr: <input id='e_y' value=100> <input id='e_cb' value=100> <input id='e_cr' value=100>
<br>
RGB: <input id='e_r'> <input id='e_g'> <input id='e_b'>
<script>
'use strict';
function round(x) {
const precision = parseInt(e_precision.value);
const pointsPow = Math.pow(10, precision);
return Math.round(x * pointsPow) / pointsPow;
}
function matToOutputVar(var_name, x) {
const precision = parseInt(e_precision.value);
if (e_array_major.value === 'column') {
x = matTrans(x);
}
return var_name + ' =\n' + matString(x, precision);
};
// -
function getRangeInfo() {
const bits = parseInt(e_bits.value);
const normalizer = (1 << bits) - 1;
const cbcr_neg_1 = parseFloat(e_uvq_min.value);
const cbcr_pos_1 = parseFloat(e_uvq_max.value);
const cbcr0 = (cbcr_neg_1 + cbcr_pos_1) / 2;
return {
y0: parseFloat(e_yq_min.value) / normalizer,
y1: parseFloat(e_yq_max.value) / normalizer,
cbcr0: cbcr0 / normalizer,
cbcr1: cbcr_pos_1 / normalizer,
};
}
// -
// Make these easy to use in console:
let yuvFromRgb, rgbFromYuv;
let ycbcrFromYuv;
let ycbcrFromRgb, rgbFromYcbcr;
function refreshQuant() {
const r = getRangeInfo();
ycbcrFromYuv = [ [r.y1-r.y0, 0, 0, r.y0],
[0, r.cbcr1-r.cbcr0, 0, r.cbcr0],
[0, 0, r.cbcr1-r.cbcr0, r.cbcr0] ];
const yuvFromRgb_4x4 = matResized(yuvFromRgb, 4, 4);
ycbcrFromRgb = matMul(ycbcrFromYuv, yuvFromRgb_4x4);
rgbFromYcbcr = matInv(ycbcrFromRgb);
//const back = matInv(rgbFromYcbcr);
//console.log('ycbcrFromRgb-1-1', fnMatToString(back));
const bits = parseInt(e_bits.value);
const normalizer = (1 << bits) - 1;
const cbcrDiff = r.cbcr1 - r.cbcr0;
function roundNorm(x) {
return round(x*normalizer);
}
e_quant_output.textContent = [
`Yq: [${roundNorm(r.y0)}, ${roundNorm(r.y1)}]`,
`Cb, Cr: ${roundNorm(r.cbcr0)} +/- ${roundNorm(cbcrDiff)}` +
` => [${roundNorm(r.cbcr0-cbcrDiff)}, ${roundNorm(r.cbcr0+cbcrDiff)}]`,
'',
`Y: [${round(r.y0)}, ${round(r.y1)}]`,
`U, V: ${round(r.cbcr0)} +/- ${round(cbcrDiff)}` +
` => [${round(r.cbcr0-cbcrDiff)}, ${round(r.cbcr0+cbcrDiff)}]`,
'',
matToOutputVar('ycbcrFromYuv', ycbcrFromYuv)
].join('\n');
e_matrix_output.textContent = [
matToOutputVar('ycbcrFromRgb', ycbcrFromRgb),
'',
matToOutputVar('rgbFromYcbcr', rgbFromYcbcr),
].join('\n');
lastConvertFunc();
}
[
e_yq_min, e_yq_max, e_uvq_min, e_uvq_max,
].forEach(e => {
e.addEventListener('change', refreshQuant);
});
// -
function refreshUvqInfo() {
const r = getRangeInfo();
const bits = parseInt(e_bits.value);
const normalizer = (1 << bits) - 1;
const cbcr0 = r.cbcr0 * normalizer;
const cbcrDiff = (r.cbcr1 - r.cbcr0) * normalizer;
e_uvq_info.textContent = `${round(cbcr0)} +/- ${round(cbcrDiff)}`;
}
e_uvq_min.addEventListener('change', refreshUvqInfo);
e_uvq_max.addEventListener('change', refreshUvqInfo);
// -
function refreshRangeInfo() {
const bits = parseInt(e_bits.value);
const normalizer = (1 << bits) - 1;
if (e_range_type.value == 'full') {
// rec2020 defines these:
// Y: D = Round((2^n-1) * E) | E = [0.0, 1.0]
// AKA Dy = 255*Ey + 0
// Cb,Cr: D = Round((2^n-1) * E + 2^(n-1)) | E = [-0.5, 0.5]
// AKA Dcb,Dcr = 255*Ey + 128, or 128 +/- 127.5. (512 +/- 511.5)
// Next, it then specifies peak/achrome/peak as 1/512/1023,
// but by its formulas, +0.5 => round(1023*0.5+512) = round(512+511.5)
// = round(1023.5) = *1024*. Uhh, oops!
// It seems to me what they wanted instead was 512 +/- 511, or:
// Cb,Cr: D = Round((2^n-2) * E + 2^(n-1))
e_yq_min.value = 0;
e_yq_max.value = normalizer;
e_uvq_min.value = 1;
e_uvq_max.value = normalizer;
} else {
let y0 = 16;
let y1 = 235; // 16+219
let cbcr0 = 128;
let cbcr1 = 240; // 128+224/2
// 10- and 12-bit narrow are just scaled 8-bit narrow.
y0 <<= bits - 8;
y1 <<= bits - 8;
cbcr0 <<= bits - 8;
cbcr1 <<= bits - 8;
e_yq_min.value = y0;
e_yq_max.value = y1;
e_uvq_min.value = cbcr0 - (cbcr1 - cbcr0);
e_uvq_max.value = cbcr1;
}
refreshUvqInfo();
refreshQuant();
}
e_bits.addEventListener('change', refreshRangeInfo);
e_range_type.addEventListener('change', refreshRangeInfo);
// -
function refreshColorSpace() {
const kr = parseFloat(e_kr.value);
const kg = parseFloat(e_kg.value);
const kb = parseFloat(e_kb.value);
const uRange = 1-kb;
const vRange = 1-kr;
yuvFromRgb = [ [kr, kg, kb],
[-kr/uRange, -kg/uRange, (1-kb)/uRange],
[(1-kr)/vRange, -kg/vRange, -kb/vRange] ];
rgbFromYuv = matInv(yuvFromRgb);
e_color_space_output.textContent = [
matToOutputVar('yuvFromRgb', yuvFromRgb),
'',
matToOutputVar('rgbFromYuv', rgbFromYuv),
].join('\n');
refreshRangeInfo();
}
e_kr.addEventListener('change', refreshColorSpace);
e_kg.addEventListener('change', refreshColorSpace);
e_kb.addEventListener('change', refreshColorSpace);
// -
function presetColorSpace() {
const colorSpace = e_color_space.value;
if (colorSpace === 'rec601') {
e_kr.value = 0.299;
e_kg.value = 0.587;
e_kb.value = 0.114;
e_bits.value = 8;
} else if (colorSpace === 'rec709') {
e_kr.value = 0.2126;
e_kg.value = 0.7152;
e_kb.value = 0.0722;
e_bits.value = 8;
} else if (colorSpace === 'rec2020') {
e_kr.value = 0.2627;
e_kg.value = '0.6780'; // String to preserve the trailing zero.
e_kb.value = 0.0593;
e_bits.value = 10;
}
refreshColorSpace();
}
e_color_space.addEventListener('change', presetColorSpace);
// -
[e_array_major, e_precision].forEach(e => {
e.addEventListener('change', () => {
refreshColorSpace();
refreshQuant();
});
});
// -
function convert(srcElems, destFromSrc, destElems) {
const bits = parseInt(e_bits.value);
const normalizer = (1 << bits) - 1;
const src = srcElems.map(e => parseFloat(e.value) / normalizer);
src.push(1);
const dest = matMulVec(destFromSrc, src);
for (let i = 0; i < 3; i++) {
let val = dest[i];
//val = Math.max(0, Math.min(val, 1)); // clamp to [0,1]
destElems[i].value = round(val*normalizer);
}
}
// -
const RGB_ELEMS = [e_r, e_g, e_b];
const YCBCR_ELEMS = [e_y, e_cb, e_cr];
function fromRgb() {
convert(RGB_ELEMS, ycbcrFromRgb, YCBCR_ELEMS);
lastConvertFunc = fromRgb;
}
function fromYcbcr() {
convert(YCBCR_ELEMS, rgbFromYcbcr, RGB_ELEMS);
lastConvertFunc = fromYcbcr;
}
let lastConvertFunc = fromYcbcr;
RGB_ELEMS.forEach(e => e.addEventListener('change', fromRgb));
YCBCR_ELEMS.forEach(e => e.addEventListener('change', fromYcbcr));
// -
presetColorSpace();
refreshQuant();
</script>
</body>
</html>
| mit |
GlukKazan/GlukKazan.github.io | checkmate/scripts/visavis-chess.js | 18337 | Dagaz.Controller.persistense = "setup";
Dagaz.Model.WIDTH = 8;
Dagaz.Model.HEIGHT = 8;
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("animate-captures", "false");
design.checkVersion("smart-moves", "false");
design.checkVersion("show-blink", "false");
design.checkVersion("show-hints", "false");
design.addDirection("w"); // 0
design.addDirection("e"); // 1
design.addDirection("s"); // 2
design.addDirection("ne"); // 3
design.addDirection("n"); // 4
design.addDirection("se"); // 5
design.addDirection("sw"); // 6
design.addDirection("nw"); // 7
design.addPlayer("White", [1, 0, 4, 6, 2, 7, 3, 5]);
design.addPlayer("Black", [0, 1, 4, 5, 2, 3, 7, 6]);
design.addPosition("a8", [0, 1, 8, 0, 0, 9, 0, 0]);
design.addPosition("b8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("c8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("d8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("e8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("f8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("g8", [-1, 1, 8, 0, 0, 9, 7, 0]);
design.addPosition("h8", [-1, 0, 8, 0, 0, 0, 7, 0]);
design.addPosition("a7", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g7", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h7", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a6", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g6", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h6", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a5", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g5", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h5", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a4", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g4", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h4", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a3", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g3", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h3", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a2", [0, 1, 8, -7, -8, 9, 0, 0]);
design.addPosition("b2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("c2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("d2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("e2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("f2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("g2", [-1, 1, 8, -7, -8, 9, 7, -9]);
design.addPosition("h2", [-1, 0, 8, 0, -8, 0, 7, -9]);
design.addPosition("a1", [0, 1, 0, -7, -8, 0, 0, 0]);
design.addPosition("b1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("c1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("d1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("e1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("f1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("g1", [-1, 1, 0, -7, -8, 0, 0, -9]);
design.addPosition("h1", [-1, 0, 0, 0, -8, 0, 0, -9]);
design.addPosition("X1", [0, 0, 0, 0, 0, 0, 0, 0]);
design.addPosition("X2", [0, 0, 0, 0, 0, 0, 0, 0]);
design.addPosition("X3", [0, 0, 0, 0, 0, 0, 0, 0]);
design.addPosition("X4", [0, 0, 0, 0, 0, 0, 0, 0]);
design.addZone("last-rank", 1, [0, 1, 2, 3, 4, 5, 6, 7]);
design.addZone("last-rank", 2, [56, 57, 58, 59, 60, 61, 62, 63]);
design.addZone("third-rank", 1, [40, 41, 42, 43, 44, 45, 46, 47]);
design.addZone("third-rank", 2, [16, 17, 18, 19, 20, 21, 22, 23]);
design.addZone("black", 1, [56, 58, 60, 62, 49, 51, 53, 55, 40, 42, 44, 46, 33, 35, 37, 39, 24, 26, 28, 30, 17, 19, 21, 23, 8, 10, 12, 14, 1, 3, 5, 7]);
design.addZone("black", 2, [56, 58, 60, 62, 49, 51, 53, 55, 40, 42, 44, 46, 33, 35, 37, 39, 24, 26, 28, 30, 17, 19, 21, 23, 8, 10, 12, 14, 1, 3, 5, 7]);
design.addZone("home", 1, [56, 57, 58, 59, 60, 61, 62, 63, 48, 49, 50, 51, 52, 53, 54, 55]);
design.addZone("home", 2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.IN_ZONE, 0); // last-rank
design.addCommand(0, ZRF.FUNCTION, 0); // not
design.addCommand(0, ZRF.IF, 4);
design.addCommand(0, ZRF.PROMOTE, 4); // Queen
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.JUMP, 2);
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addCommand(1, ZRF.FUNCTION, 24); // from
design.addCommand(1, ZRF.PARAM, 0); // $1
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.FUNCTION, 1); // empty?
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.IN_ZONE, 1); // third-rank
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.PARAM, 1); // $2
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.FUNCTION, 1); // empty?
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.FUNCTION, 25); // to
design.addCommand(1, ZRF.FUNCTION, 28); // end
design.addCommand(2, ZRF.FUNCTION, 24); // from
design.addCommand(2, ZRF.PARAM, 0); // $1
design.addCommand(2, ZRF.FUNCTION, 22); // navigate
design.addCommand(2, ZRF.FUNCTION, 2); // enemy?
design.addCommand(2, ZRF.FUNCTION, 20); // verify
design.addCommand(2, ZRF.IN_ZONE, 0); // last-rank
design.addCommand(2, ZRF.FUNCTION, 0); // not
design.addCommand(2, ZRF.IF, 4);
design.addCommand(2, ZRF.PROMOTE, 4); // Queen
design.addCommand(2, ZRF.FUNCTION, 25); // to
design.addCommand(2, ZRF.JUMP, 2);
design.addCommand(2, ZRF.FUNCTION, 25); // to
design.addCommand(2, ZRF.FUNCTION, 28); // end
design.addCommand(3, ZRF.FUNCTION, 24); // from
design.addCommand(3, ZRF.PARAM, 0); // $1
design.addCommand(3, ZRF.FUNCTION, 22); // navigate
design.addCommand(3, ZRF.FUNCTION, 2); // enemy?
design.addCommand(3, ZRF.FUNCTION, 20); // verify
design.addCommand(3, ZRF.FUNCTION, 5); // last-to?
design.addCommand(3, ZRF.FUNCTION, 20); // verify
design.addCommand(3, ZRF.LITERAL, 0); // Pawn
design.addCommand(3, ZRF.FUNCTION, 10); // piece?
design.addCommand(3, ZRF.FUNCTION, 20); // verify
design.addCommand(3, ZRF.FUNCTION, 26); // capture
design.addCommand(3, ZRF.PARAM, 1); // $2
design.addCommand(3, ZRF.FUNCTION, 22); // navigate
design.addCommand(3, ZRF.FUNCTION, 6); // mark
design.addCommand(3, ZRF.PARAM, 2); // $3
design.addCommand(3, ZRF.FUNCTION, 22); // navigate
design.addCommand(3, ZRF.FUNCTION, 4); // last-from?
design.addCommand(3, ZRF.FUNCTION, 20); // verify
design.addCommand(3, ZRF.FUNCTION, 7); // back
design.addCommand(3, ZRF.FUNCTION, 25); // to
design.addCommand(3, ZRF.FUNCTION, 28); // end
design.addCommand(4, ZRF.FUNCTION, 24); // from
design.addCommand(4, ZRF.PARAM, 0); // $1
design.addCommand(4, ZRF.FUNCTION, 22); // navigate
design.addCommand(4, ZRF.FUNCTION, 1); // empty?
design.addCommand(4, ZRF.FUNCTION, 0); // not
design.addCommand(4, ZRF.IF, 7);
design.addCommand(4, ZRF.FORK, 3);
design.addCommand(4, ZRF.FUNCTION, 25); // to
design.addCommand(4, ZRF.FUNCTION, 28); // end
design.addCommand(4, ZRF.PARAM, 1); // $2
design.addCommand(4, ZRF.FUNCTION, 22); // navigate
design.addCommand(4, ZRF.JUMP, -8);
design.addCommand(4, ZRF.FUNCTION, 3); // friend?
design.addCommand(4, ZRF.FUNCTION, 0); // not
design.addCommand(4, ZRF.FUNCTION, 20); // verify
design.addCommand(4, ZRF.FUNCTION, 25); // to
design.addCommand(4, ZRF.FUNCTION, 28); // end
design.addCommand(5, ZRF.FUNCTION, 24); // from
design.addCommand(5, ZRF.PARAM, 0); // $1
design.addCommand(5, ZRF.FUNCTION, 22); // navigate
design.addCommand(5, ZRF.PARAM, 1); // $2
design.addCommand(5, ZRF.FUNCTION, 22); // navigate
design.addCommand(5, ZRF.FUNCTION, 3); // friend?
design.addCommand(5, ZRF.FUNCTION, 0); // not
design.addCommand(5, ZRF.FUNCTION, 20); // verify
design.addCommand(5, ZRF.FUNCTION, 25); // to
design.addCommand(5, ZRF.FUNCTION, 28); // end
design.addCommand(6, ZRF.FUNCTION, 24); // from
design.addCommand(6, ZRF.PARAM, 0); // $1
design.addCommand(6, ZRF.FUNCTION, 22); // navigate
design.addCommand(6, ZRF.FUNCTION, 3); // friend?
design.addCommand(6, ZRF.FUNCTION, 0); // not
design.addCommand(6, ZRF.FUNCTION, 20); // verify
design.addCommand(6, ZRF.FUNCTION, 25); // to
design.addCommand(6, ZRF.FUNCTION, 28); // end
design.addCommand(7, ZRF.IN_ZONE, 3); // home
design.addCommand(7, ZRF.FUNCTION, 20); // verify
design.addCommand(7, ZRF.FUNCTION, 1); // empty?
design.addCommand(7, ZRF.FUNCTION, 20); // verify
design.addCommand(7, ZRF.FUNCTION, 25); // to
design.addCommand(7, ZRF.FUNCTION, 28); // end
design.addPriority(0); // drop-type
design.addPriority(1); // normal-type
design.addPiece("Pawn", 0, 800);
design.addMove(0, 0, [4], 1);
design.addMove(0, 1, [4, 4], 1);
design.addMove(0, 2, [7], 1);
design.addMove(0, 2, [3], 1);
design.addMove(0, 3, [1, 4, 4], 1);
design.addMove(0, 3, [0, 4, 4], 1);
design.addPiece("Rook", 1, 5000);
design.addMove(1, 4, [4, 4], 1);
design.addMove(1, 4, [2, 2], 1);
design.addMove(1, 4, [0, 0], 1);
design.addMove(1, 4, [1, 1], 1);
design.addDrop(1, 7, [], 0);
design.addPiece("Knight", 2, 3350);
design.addMove(2, 5, [4, 7], 1);
design.addMove(2, 5, [4, 3], 1);
design.addMove(2, 5, [2, 6], 1);
design.addMove(2, 5, [2, 5], 1);
design.addMove(2, 5, [0, 7], 1);
design.addMove(2, 5, [0, 6], 1);
design.addMove(2, 5, [1, 3], 1);
design.addMove(2, 5, [1, 5], 1);
design.addDrop(2, 7, [], 0);
design.addPiece("Bishop", 3, 3450);
design.addMove(3, 4, [7, 7], 1);
design.addMove(3, 4, [6, 6], 1);
design.addMove(3, 4, [3, 3], 1);
design.addMove(3, 4, [5, 5], 1);
design.addDrop(3, 7, [], 0);
design.addPiece("Queen", 4, 9750);
design.addMove(4, 4, [4, 4], 1);
design.addMove(4, 4, [2, 2], 1);
design.addMove(4, 4, [0, 0], 1);
design.addMove(4, 4, [1, 1], 1);
design.addMove(4, 4, [7, 7], 1);
design.addMove(4, 4, [6, 6], 1);
design.addMove(4, 4, [3, 3], 1);
design.addMove(4, 4, [5, 5], 1);
design.addDrop(4, 7, [], 0);
design.addPiece("King", 5, 600000);
design.addMove(5, 6, [4], 1);
design.addMove(5, 6, [2], 1);
design.addMove(5, 6, [0], 1);
design.addMove(5, 6, [1], 1);
design.addMove(5, 6, [7], 1);
design.addMove(5, 6, [6], 1);
design.addMove(5, 6, [3], 1);
design.addMove(5, 6, [5], 1);
design.addDrop(5, 7, [], 0);
design.setup("White", "Pawn", 48);
design.setup("White", "Pawn", 49);
design.setup("White", "Pawn", 50);
design.setup("White", "Pawn", 51);
design.setup("White", "Pawn", 52);
design.setup("White", "Pawn", 53);
design.setup("White", "Pawn", 54);
design.setup("White", "Pawn", 55);
design.reserve("White", "Pawn", 0);
design.reserve("White", "Knight", 2);
design.reserve("White", "Bishop", 2);
design.reserve("White", "Rook", 2);
design.reserve("White", "Queen", 1);
design.reserve("White", "King", 1);
design.setup("Black", "Pawn", 8);
design.setup("Black", "Pawn", 9);
design.setup("Black", "Pawn", 10);
design.setup("Black", "Pawn", 11);
design.setup("Black", "Pawn", 12);
design.setup("Black", "Pawn", 13);
design.setup("Black", "Pawn", 14);
design.setup("Black", "Pawn", 15);
design.reserve("Black", "Pawn", 0);
design.reserve("Black", "Knight", 2);
design.reserve("Black", "Bishop", 2);
design.reserve("Black", "Rook", 2);
design.reserve("Black", "Queen", 1);
design.reserve("Black", "King", 1);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("WhitePawn", "White Pawn");
view.defPiece("BlackPawn", "Black Pawn");
view.defPiece("WhiteRook", "White Rook");
view.defPiece("BlackRook", "Black Rook");
view.defPiece("WhiteKnight", "White Knight");
view.defPiece("BlackKnight", "Black Knight");
view.defPiece("WhiteBishop", "White Bishop");
view.defPiece("BlackBishop", "Black Bishop");
view.defPiece("WhiteQueen", "White Queen");
view.defPiece("BlackQueen", "Black Queen");
view.defPiece("WhiteKing", "White King");
view.defPiece("BlackKing", "Black King");
view.defPiece("Ko", "Ko");
view.defPosition("a8", 2, 2, 68, 68);
view.defPosition("b8", 70, 2, 68, 68);
view.defPosition("c8", 138, 2, 68, 68);
view.defPosition("d8", 206, 2, 68, 68);
view.defPosition("e8", 274, 2, 68, 68);
view.defPosition("f8", 342, 2, 68, 68);
view.defPosition("g8", 410, 2, 68, 68);
view.defPosition("h8", 478, 2, 68, 68);
view.defPosition("a7", 2, 70, 68, 68);
view.defPosition("b7", 70, 70, 68, 68);
view.defPosition("c7", 138, 70, 68, 68);
view.defPosition("d7", 206, 70, 68, 68);
view.defPosition("e7", 274, 70, 68, 68);
view.defPosition("f7", 342, 70, 68, 68);
view.defPosition("g7", 410, 70, 68, 68);
view.defPosition("h7", 478, 70, 68, 68);
view.defPosition("a6", 2, 138, 68, 68);
view.defPosition("b6", 70, 138, 68, 68);
view.defPosition("c6", 138, 138, 68, 68);
view.defPosition("d6", 206, 138, 68, 68);
view.defPosition("e6", 274, 138, 68, 68);
view.defPosition("f6", 342, 138, 68, 68);
view.defPosition("g6", 410, 138, 68, 68);
view.defPosition("h6", 478, 138, 68, 68);
view.defPosition("a5", 2, 206, 68, 68);
view.defPosition("b5", 70, 206, 68, 68);
view.defPosition("c5", 138, 206, 68, 68);
view.defPosition("d5", 206, 206, 68, 68);
view.defPosition("e5", 274, 206, 68, 68);
view.defPosition("f5", 342, 206, 68, 68);
view.defPosition("g5", 410, 206, 68, 68);
view.defPosition("h5", 478, 206, 68, 68);
view.defPosition("a4", 2, 274, 68, 68);
view.defPosition("b4", 70, 274, 68, 68);
view.defPosition("c4", 138, 274, 68, 68);
view.defPosition("d4", 206, 274, 68, 68);
view.defPosition("e4", 274, 274, 68, 68);
view.defPosition("f4", 342, 274, 68, 68);
view.defPosition("g4", 410, 274, 68, 68);
view.defPosition("h4", 478, 274, 68, 68);
view.defPosition("a3", 2, 342, 68, 68);
view.defPosition("b3", 70, 342, 68, 68);
view.defPosition("c3", 138, 342, 68, 68);
view.defPosition("d3", 206, 342, 68, 68);
view.defPosition("e3", 274, 342, 68, 68);
view.defPosition("f3", 342, 342, 68, 68);
view.defPosition("g3", 410, 342, 68, 68);
view.defPosition("h3", 478, 342, 68, 68);
view.defPosition("a2", 2, 410, 68, 68);
view.defPosition("b2", 70, 410, 68, 68);
view.defPosition("c2", 138, 410, 68, 68);
view.defPosition("d2", 206, 410, 68, 68);
view.defPosition("e2", 274, 410, 68, 68);
view.defPosition("f2", 342, 410, 68, 68);
view.defPosition("g2", 410, 410, 68, 68);
view.defPosition("h2", 478, 410, 68, 68);
view.defPosition("a1", 2, 478, 68, 68);
view.defPosition("b1", 70, 478, 68, 68);
view.defPosition("c1", 138, 478, 68, 68);
view.defPosition("d1", 206, 478, 68, 68);
view.defPosition("e1", 274, 478, 68, 68);
view.defPosition("f1", 342, 478, 68, 68);
view.defPosition("g1", 410, 478, 68, 68);
view.defPosition("h1", 478, 478, 68, 68);
view.defPopup("Promote", 127, 100);
view.defPopupPosition("X1", 10, 7, 68, 68);
view.defPopupPosition("X2", 80, 7, 68, 68);
view.defPopupPosition("X3", 150, 7, 68, 68);
view.defPopupPosition("X4", 220, 7, 68, 68);
}
| mit |
alexlarsson/gthree | gthree/gthreevectorkeyframetrack.h | 1588 | #ifndef __GTHREE_VECTOR_KEYFRAME_TRACK_H__
#define __GTHREE_VECTOR_KEYFRAME_TRACK_H__
#if !defined (__GTHREE_H_INSIDE__) && !defined (GTHREE_COMPILATION)
#error "Only <gthree/gthree.h> can be included directly."
#endif
#include <gthree/gthreekeyframetrack.h>
G_BEGIN_DECLS
#define GTHREE_TYPE_VECTOR_KEYFRAME_TRACK (gthree_vector_keyframe_track_get_type ())
#define GTHREE_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst), \
GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, \
GthreeVectorKeyframeTrack))
#define GTHREE_IS_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_TYPE ((inst), \
GTHREE_TYPE_VECTOR_KEYFRAME_TRACK))
#define GTHREE_VECTOR_KEYFRAME_TRACK_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, GthreeVectorKeyframeTrackClass))
typedef struct {
GthreeKeyframeTrack parent;
} GthreeVectorKeyframeTrack;
typedef struct {
GthreeKeyframeTrackClass parent_class;
} GthreeVectorKeyframeTrackClass;
G_DEFINE_AUTOPTR_CLEANUP_FUNC (GthreeVectorKeyframeTrack, g_object_unref)
GTHREE_API
GType gthree_vector_keyframe_track_get_type (void) G_GNUC_CONST;
GTHREE_API
GthreeKeyframeTrack *gthree_vector_keyframe_track_new (const char *name,
GthreeAttributeArray *times,
GthreeAttributeArray *values);
G_END_DECLS
#endif /* __GTHREE_VECTOR_KEYFRAME_TRACK_H__ */
| mit |
owlhouseconsultingllc/viz | scripts/PHPAuth/Auth.php | 15122 | <?php
namespace PHPAuth;
class Auth
{
protected $dbh;
public $config;
public $lang;
public function __construct(\PDO $dbh, $config, $language = "en_GB")
{
$this->dbh = $dbh;
$this->config = $config;
if (version_compare(phpversion(), '5.5.0', '<')) {
die('PHP 5.5.0 required for Auth engine!');
}
// Load language
require "languages/{$language}.php";
$this->lang = $lang;
date_default_timezone_set($this->config->site_timezone);
}
public function login($email, $password, $remember = 0, $captcha = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "verify") {
$return['message'] = $this->lang["user_verify_failed"];
return $return;
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
$validateEmail = $this->validateEmail($email);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif ($validatePassword['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif ($remember != 0 && $remember != 1) {
$this->addAttempt();
$return['message'] = $this->lang["remember_me_invalid"];
return $return;
}
$uid = $this->getUID(strtolower($email));
if (!$uid) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
$user = $this->getBaseUser($uid);
if (!password_verify($password, $user['password'])) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
if ($user['isactive'] != 1) {
$this->addAttempt();
$return['message'] = $this->lang["account_inactive"];
return $return;
}
$sessiondata = $this->addSession($user['uid'], $remember);
if ($sessiondata == false) {
$return['message'] = $this->lang["system_error"] . " #01";
return $return;
}
$return['error'] = false;
$return['message'] = $this->lang["logged_in"];
$return['hash'] = $sessiondata['hash'];
$return['expire'] = $sessiondata['expiretime'];
$return['cookie_name'] = $this->config->cookie_name;
return $return;
}
public function isEmailTaken($email)
{
$query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if ($query->fetchColumn() == 0) {
return false;
}
return true;
}
protected function addUser($email, $password, $params = array(), &$sendmail)
{
$return['error'] = true;
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_users} (isactive) VALUES (0)");
if (!$query->execute()) {
$return['message'] = $this->lang["system_error"] . " #03";
return $return;
}
$uid = $this->dbh->lastInsertId("{$this->config->table_users}_id_seq");
$email = htmlentities(strtolower($email));
$isactive = 1;
$password = $this->getHash($password);
if (is_array($params)&& count($params) > 0) {
$customParamsQueryArray = Array();
foreach($params as $paramKey => $paramValue) {
$customParamsQueryArray[] = array('value' => $paramKey . ' = ?');
}
$setParams = ', ' . implode(', ', array_map(function ($entry) {
return $entry['value'];
}, $customParamsQueryArray));
} else { $setParams = ''; }
$query = $this->dbh->prepare("UPDATE {$this->config->table_users} SET email = ?, password = ?, isactive = ? {$setParams} WHERE id = ?");
$bindParams = array_values(array_merge(array($email, $password, $isactive), $params, array($uid)));
if (!$query->execute($bindParams)) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$return['message'] = $this->lang["system_error"] . " #04";
return $return;
}
$return['error'] = false;
return $return;
}
public function getHash($password)
{
return password_hash($password, PASSWORD_BCRYPT, ['cost' => $this->config->bcrypt_cost]);
}
public function getUID($email)
{
$query = $this->dbh->prepare("SELECT id FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if(!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
return $row['id'];
}
public function isLogged()
{
return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name]));
}
public function getSessionHash()
{
return $_COOKIE[$this->config->cookie_name];
}
protected function getBaseUser($uid)
{
$query = $this->dbh->prepare("SELECT email, password, isactive FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$data = $query->fetch(\PDO::FETCH_ASSOC);
if (!$data) {
return false;
}
$data['uid'] = $uid;
return $data;
}
protected function addSession($uid, $remember)
{
$ip = $this->getIp();
$user = $this->getBaseUser($uid);
if (!$user) {
return false;
}
$data['hash'] = sha1($this->config->site_key . microtime());
$agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$this->deleteExistingSessions($uid);
if ($remember == true) {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_remember));
$data['expiretime'] = strtotime($data['expire']);
} else {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_forget));
$data['expiretime'] = 0;
}
$data['cookie_crc'] = sha1($data['hash'] . $this->config->site_key);
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_sessions} (uid, hash, expiredate, ip, agent, cookie_crc) VALUES (?, ?, ?, ?, ?, ?)");
if (!$query->execute(array($uid, $data['hash'], $data['expire'], $ip, $agent, $data['cookie_crc']))) {
return false;
}
$data['expire'] = strtotime($data['expire']);
return $data;
}
protected function deleteSession($hash)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
return $query->rowCount() == 1;
}
public function checkSession($hash)
{
$ip = $this->getIp();
$block_status = $this->isBlocked();
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return false;
}
if (strlen($hash) != 40) {
return false;
}
$query = $this->dbh->prepare("SELECT id, uid, expiredate, ip, agent, cookie_crc FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
$sid = $row['id'];
$uid = $row['uid'];
$expiredate = strtotime($row['expiredate']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
$db_ip = $row['ip'];
$db_agent = $row['agent'];
$db_cookie = $row['cookie_crc'];
if ($currentdate > $expiredate) {
$this->deleteExistingSessions($uid);
return false;
}
if ($ip != $db_ip) {
return false;
}
if ($db_cookie == sha1($hash . $this->config->site_key)) {
return true;
}
return false;
}
public function getSessionUID($hash)
{
$query = $this->dbh->prepare("SELECT uid FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if (!$row = $query->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
return $row['uid'];
}
protected function deleteExistingSessions($uid)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE uid = ?");
$query->execute(array($uid));
return $query->rowCount() == 1;
}
public function register($email, $password, $repeatpassword, $params = Array(), $captcha = NULL, $sendmail = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "verify") {
//if ($this->checkCaptcha($captcha) == false) {
$return['message'] = $this->lang["user_verify_failed"];
return $return;
//}
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
if ($password !== $repeatpassword) {
$return['message'] = $this->lang["password_nomatch"];
return $return;
}
// Validate email
$validateEmail = $this->validateEmail($email);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
}
// Validate password
$validatePassword = $this->validatePassword($password);
if ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
}
/*$zxcvbn = new Zxcvbn();
if ($zxcvbn->passwordStrength($password)['score'] < intval($this->config->password_min_score)) {
$return['message'] = $this->lang['password_weak'];
return $return;
}*/
if ($this->isEmailTaken($email)) {
$this->addAttempt();
$return['message'] = $this->lang["email_taken"];
return $return;
}
$addUser = $this->addUser($email, $password, $params, $sendmail);
if ($addUser['error'] != 0) {
$return['message'] = $addUser['message'];
return $return;
}
$return['error'] = false;
$return['message'] = ($sendmail == true ? $this->lang["register_success"] : $this->lang['register_success_emailmessage_suppressed'] );
return $return;
}
public function logout($hash)
{
if (strlen($hash) != 40) {
return false;
}
return $this->deleteSession($hash);
}
protected function validatePassword($password)
{
$return['error'] = true;
if (strlen($password) < (int)$this->config->verify_password_min_length ) {
$return['message'] = $this->lang["password_short"];
return $return;
}
$return['error'] = false;
return $return;
}
protected function validateEmail($email)
{
$return['error'] = true;
if (strlen($email) < (int)$this->config->verify_email_min_length ) {
$return['message'] = $this->lang["email_short"];
return $return;
} elseif (strlen($email) > (int)$this->config->verify_email_max_length ) {
$return['message'] = $this->lang["email_long"];
return $return;
}/* elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$return['message'] = $this->lang["email_invalid"];
return $return;
}
if ( (int)$this->config->verify_email_use_banlist ) {
$bannedEmails = json_decode(file_get_contents(__DIR__ . "/files/domains.json"));
if (in_array(strtolower(explode('@', $email)[1]), $bannedEmails)) {
$return['message'] = $this->lang["email_banned"];
return $return;
}
}*/
$return['error'] = false;
return $return;
}
public function isBlocked()
{
$ip = $this->getIp();
$this->deleteAttempts($ip, false);
$query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_attempts} WHERE ip = ?");
$query->execute(array($ip));
$attempts = $query->fetchColumn();
if ($attempts < intval($this->config->attempts_before_verify)) {
return "allow";
}
if ($attempts < intval($this->config->attempts_before_ban)) {
//return "verify";
return "block";
}
return "block";
}
protected function addAttempt()
{
$ip = $this->getIp();
$attempt_expiredate = date("Y-m-d H:i:s", strtotime($this->config->attack_mitigation_time));
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_attempts} (ip, expiredate) VALUES (?, ?)");
return $query->execute(array($ip, $attempt_expiredate));
}
protected function deleteAttempts($ip, $all = false)
{
if ($all==true) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE ip = ?");
return $query->execute(array($ip));
}
$query = $this->dbh->prepare("SELECT id, expiredate FROM {$this->config->table_attempts} WHERE ip = ?");
$query->execute(array($ip));
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$expiredate = strtotime($row['expiredate']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
if ($currentdate > $expiredate) {
$queryDel = $this->dbh->prepare("DELETE FROM {$this->config->table_attempts} WHERE id = ?");
$queryDel->execute(array($row['id']));
}
}
}
protected function getIp()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
}
| mit |
pootzko/InfluxData.Net | InfluxData.Net.InfluxDb/Models/Responses/User.cs | 346 | namespace InfluxData.Net.InfluxDb.Models.Responses
{
public class User
{
/// <summary>
/// User name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Whether or not the user is an administrator.
/// </summary>
public bool IsAdmin { get; set; }
}
}
| mit |
cjlucas/go-audiotag | src/github.com/cjlucas/audiotag/id3/util.go | 649 | package id3
import (
"bytes"
"errors"
"io"
"time"
)
var timestampFormats = []string{
"2006-01-02T15:04:05",
"2006-01-02T15:04",
"2006-01-02T15",
"2006-01-02",
"2006-01",
"2006",
}
func parseTime(timeStr string) (time.Time, error) {
for i := range timestampFormats {
t, err := time.Parse(timestampFormats[i], timeStr)
if err == nil {
return t, nil
}
}
return time.Time{}, errors.New("invalid time")
}
func readUntilTerminator(term []byte, buf []byte) ([]byte, error) {
for i := 0; i+len(term)-1 < len(buf); i += len(term) {
if bytes.Equal(term, buf[i:i+len(term)]) {
return buf[:i], nil
}
}
return nil, io.EOF
}
| mit |
alexeagle/material2 | src/demo-app/menu/menu-demo.html | 1753 | <div class="demo-menu">
<div class="menu-section">
<p>You clicked on: {{ selected }}</p>
<md-toolbar>
<button md-icon-button [md-menu-trigger-for]="menu">
<md-icon>more_vert</md-icon>
</button>
</md-toolbar>
<md-menu #menu="mdMenu">
<button md-menu-item *ngFor="let item of items" (click)="select(item.text)" [disabled]="item.disabled">
{{ item.text }}
</button>
</md-menu>
</div>
<div class="menu-section">
<p> Clicking these will navigate:</p>
<md-toolbar>
<button md-icon-button [md-menu-trigger-for]="anchorMenu">
<md-icon>more_vert</md-icon>
</button>
</md-toolbar>
<md-menu #anchorMenu="mdMenu">
<a md-menu-item *ngFor="let item of items" href="http://www.google.com" [disabled]="item.disabled">
{{ item.text }}
</a>
</md-menu>
</div>
<div class="menu-section">
<p>
Position x: before
</p>
<md-toolbar class="end-icon">
<button md-icon-button [md-menu-trigger-for]="posXMenu">
<md-icon>more_vert</md-icon>
</button>
</md-toolbar>
<md-menu x-position="before" #posXMenu="mdMenu" class="before">
<button md-menu-item *ngFor="let item of items" [disabled]="item.disabled">
{{ item.text }}
</button>
</md-menu>
</div>
<div class="menu-section">
<p>
Position y: above
</p>
<md-toolbar>
<button md-icon-button [md-menu-trigger-for]="posYMenu">
<md-icon>more_vert</md-icon>
</button>
</md-toolbar>
<md-menu y-position="above" #posYMenu="mdMenu">
<button md-menu-item *ngFor="let item of items" [disabled]="item.disabled">
{{ item.text }}
</button>
</md-menu>
</div>
</div>
| mit |
wikibus/Argolis | src/Examples/TestHydraApi/IssueFilter.cs | 356 | using Argolis.Hydra.Annotations;
using Argolis.Models;
using Vocab;
namespace TestHydraApi
{
public class IssueFilter : ITemplateParameters<Issue>
{
[Property(Schema.title)]
public string Title { get; set; }
[Property(Schema.BaseUri + "year")]
[Range(Xsd.integer)]
public int? Year { get; set; }
}
} | mit |
vinithanatarajan/Vini-training | c-exercises/structs/linked-list.c | 1014 | // make a linked list that has one member
// then make 5 nodes - with each node having 1,2,3,4,5 as data
// then print them out
// then work out how to reverse the list by only changing the pointers
// then print again
#include <stdio.h>
#include <stdlib.h> // Including this header to use malloc
struct node {
int num;
struct node *next;
};
struct node *head = NULL;
struct node *p = NULL;
void insert(int num) {
struct node *point = (struct node*) malloc(sizeof(struct node));
point->num = num;
point->next = NULL;
if(head==NULL) {
head = point;
head->next = point;
return;
}
p = head;
while(p->next != head){
p = p->next;
}
p->next = point;
point->next = head;
}
void printNum() {
struct node *pntr = head;
printf("\nhead:");
while(pntr->next != head) {
printf(" %d ", pntr->num);
pntr = pntr->next;
}
printf(" %d ", pntr->num);
printf("\n");
}
int main() {
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
printNum();
}
| mit |
jdavidberger/rikitiki | include/rikitiki/content_handler.h | 3280 | #pragma once
#include <rikitiki/http/content_types.h>
#include <vector>
#include <map>
#include <array>
#include <mxcomp/reflection.h>
#ifdef _MSC_VER
#define constexpr
#endif
namespace rikitiki {
class ConnContext;
struct Response;
template <typename T>
struct ContentHandler_ {
static constexpr std::array<ContentType::t, 1> ContentTypes() { return{ { ContentType::DEFAULT } }; };
};
struct OutProvider {
template<typename S, typename T>
static auto Make() -> void(*)(ConnContext&, S&) {
return [](ConnContext& ctx, S& s) {
T t;
t << s;
ctx << t;
};
}
};
struct InProvider {
template<typename S, typename T>
static auto Make() -> void(*)(ConnContext&, S&) {
return [](ConnContext& ctx, S& s) {
T t;
ctx >> t;
t >> s;
};
}
};
template <typename S, typename FProvider, typename... T>
struct TypeConversions {
typedef TypeConversions<S, FProvider, T...> thisType;
typedef TypeConversions<std::vector<S>, FProvider, T...> VectorType;
template <typename Th, typename...Tt>
struct HandlerAdders {
static void Add(thisType* _this){
HandlerAdders<Th>::Add(_this);
HandlerAdders<Tt...>::Add(_this);
}
};
template <typename Th>
struct HandlerAdders<Th> {
static auto Add(thisType* _this) -> void {
for (auto contentType : ContentHandler_<Th>::ContentTypes()){
assert(contentType > ContentType::DEFAULT &&
contentType < ContentType::MAX &&
"Invalid content type value in specialized handler");
_this->handlers[contentType] = FProvider::template Make<S, Th>();
}
}
};
typedef void(*Setter)(ConnContext&, S& s);
std::vector<Setter> handlers;
TypeConversions() {
handlers.resize(ContentType::MAX);
HandlerAdders<T...>::Add(this);
}
static thisType& Instance() {
static thisType Instance;
return Instance;
}
};
template<typename T, typename enable = void >
struct valid_conversions { };
}
#ifdef USE_JSONCPP
#include <rikitiki/jsoncpp/jsoncpp>
namespace rikitiki {
using namespace mxcomp;
template<typename T>
struct valid_conversions<T, typename std::enable_if< std::is_function <decltype(MetaClass_<T>::fields)>::value >::type > {
typedef TypeConversions<T, InProvider, Json::Value> In;
typedef TypeConversions<T, OutProvider, Json::Value> Out;
};
template <typename T>
struct valid_conversions<std::vector<T>, typename std::enable_if< std::is_class<valid_conversions<T> >::value >::type > {
typedef typename valid_conversions<T>::In::VectorType In;
typedef typename valid_conversions<T>::Out::VectorType Out;
};
}
#endif | mit |
perzy/slim-demo | vendor/autoload.php | 183 | <?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit037b77112e3f60b3fb10492299961fe0::getLoader();
| mit |
dchanko/Badger | BadgerAddin2010/Ribbon.cs | 2794 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Office = Microsoft.Office.Core;
// TODO: Follow these steps to enable the Ribbon (XML) item:
// 1: Copy the following code block into the ThisAddin, ThisWorkbook, or ThisDocument class.
// protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
// {
// return new Ribbon();
// }
// 2. Create callback methods in the "Ribbon Callbacks" region of this class to handle user
// actions, such as clicking a button. Note: if you have exported this Ribbon from the Ribbon designer,
// move your code from the event handlers to the callback methods and modify the code to work with the
// Ribbon extensibility (RibbonX) programming model.
// 3. Assign attributes to the control tags in the Ribbon XML file to identify the appropriate callback methods in your code.
// For more information, see the Ribbon XML documentation in the Visual Studio Tools for Office Help.
namespace BadgerAddin2010
{
[ComVisible(true)]
public class Ribbon : Office.IRibbonExtensibility
{
private Office.IRibbonUI ribbon;
public Ribbon()
{
}
#region IRibbonExtensibility Members
public string GetCustomUI(string ribbonID)
{
//if ("Microsoft.Outlook.Mail.Read" == ribbonID)
// return GetResourceText("BadgerAddin2010.Ribbon.xml");
//else
return null;
}
#endregion
#region Ribbon Callbacks
//Create callback methods here. For more information about adding callback methods, visit http://go.microsoft.com/fwlink/?LinkID=271226
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}
#endregion
#region Helpers
private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
#endregion
}
}
| mit |
Ico093/TelerikAcademy | WebServesesAndCloud/Homework/01.ASP.NETWebAPI/WebApi/MusicStore.Api/App_Start/WebApiConfig.cs | 591 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MusicStore.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit |
unclefrost/extrem.web | MVCForum.IOC/Bootstrapper.cs | 797 | using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc4;
namespace MVCForum.IOC
{
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
}
}
} | mit |
alphagov/notifications-admin | app/templates/views/pricing/billing-details.html | 3319 | {% extends "content_template.html" %}
{% from "components/page-header.html" import page_header %}
{% from "components/copy-to-clipboard.html" import copy_to_clipboard %}
{% block per_page_title %}
Billing details
{% endblock %}
{% block content_column_content %}
{{ page_header('Billing details') }}
<p class="govuk-body">
You can use the information on this page to add the Cabinet Office as a supplier. Your organisation may need to do this before you can raise a purchase order (PO).
</p>
<p class="govuk-body">
<a class="govuk-link govuk-link--no-visited-state" href="{{ url_for('main.support') }}">Contact us</a> if you need any other details.
</p>
<h2 class="heading-medium govuk-!-margin-top-7" id="supplier-details">
Supplier details
</h2>
<p class="govuk-body">
Cabinet Office
</p>
<p class="govuk-body">
The White Chapel Building <br>
10 Whitechapel High Street <br>
London <br>
E1 8QS
</p>
<h3 class="heading-small" id="email-addresses">
Email addresses
</h3>
<ul class="govuk-list govuk-list--bullet">
{% for email in billing_details['notify_billing_email_addresses'] %}
<li>
{{ email }}
</li>
{% endfor %}
</ul>
<h3 class="heading-small" id="vat-number">
<abbr title="Value Added Tax">VAT</abbr> number
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
'GB 88 88 010 80',
thing='<abbr title="Value Added Tax">VAT</abbr> number',
) }}
</div>
<h2 class="heading-medium govuk-!-margin-top-7" id="bank-details">
Bank details
</h2>
<p class="govuk-body">
National Westminster Bank PLC (part of RBS group) <br>
Government Banking Services Branch <br>
2nd Floor <br>
280 Bishopsgate <br>
London <br>
EC2M 4RB
</p>
<h3 class="heading-small" id="account-name">
Account name
</h3>
<p class="govuk-body">
Cabinet Office
</p>
<h3 class="heading-small" id="account-number">
Account number
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['account_number'],
thing='account number',
) }}
</div>
<h3 class="heading-small" id="sort-code">
Sort code
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['sort_code'],
thing='sort code',
) }}
</div>
<h3 class="heading-small" id="iban">
<abbr title="International Bank Account Number">IBAN</abbr>
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['IBAN'],
thing='IBAN',
) }}
</div>
<h3 class="heading-small" id="swift-code">
Swift code
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['swift'],
thing='Swift code',
) }}
</div>
<h2 class="heading-medium govuk-!-margin-top-7" id="invoice-address">
Invoice address
</h2>
<p class="govuk-body">
SSCL – Accounts Receivable <br>
PO Box 221 <br>
Thornton-Cleveleys <br>
Blackpool <br>
Lancashire <br>
FY1 9JN
</p>
{% endblock %}
| mit |
smo-key/NXTLib | nxtlib/src/Utils.cs | 1877 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
namespace NXTLib
{
public static class Utils
{
public static string AddressByte2String(byte[] address, bool withcolons)
{
//BluetoothAddress adr = new BluetoothAddress(address);
//string c = adr.ToString();
string[] str = new string[6];
for (int i = 0; i < 6; i++)
str[i] = address[5 - i].ToString("x2");
string sep = ":";
if (!withcolons) { sep = ""; }
string a = string.Join(sep, str);
return a;
}
public static byte[] AddressString2Byte(string address, bool withcolons)
{
byte[] a = new byte[6];
int sep = 3;
if (!withcolons) { sep = 2; }
for (int i = 0; i < 6; i++)
{
byte b = byte.Parse(address.Substring(i * sep, 2), System.Globalization.NumberStyles.HexNumber);
a[5 - i] = b;
}
return a;
}
public static List<Brick> Combine(List<Brick> bricks1, List<Brick> bricks2)
{
List<Brick> bricks = new List<Brick>();
bricks.AddRange(bricks1);
bricks.AddRange(bricks2);
return bricks;
}
private static Int64 GetValue(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return 0;
}
Int64 output;
// TryParse returns a boolean to indicate whether or not
// the parse succeeded. If it didn't, you may want to take
// some action here.
Int64.TryParse(value, out output);
return output;
}
}
}
| mit |
samuelclay/NewsBlur | blog/_site/2015/08/25/even-the-folders-have-rss-feeds/index.html | 6956 | <!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, initial-scale=1">
<link rel="shortcut icon" href="https://newsblur.com/media/img/favicon.ico" type="image/png" />
<link rel="icon" href="https://newsblur.com/media/img/favicon_32.png" sizes="32x32"/>
<link rel="icon" href="https://newsblur.com/media/img/favicon_64.png" sizes="64x64"/>
<link rel="alternate" type="application/rss+xml"
title="The NewsBlur Blog RSS feed"
href="/feed.xml" /><!-- Begin Jekyll SEO tag v2.7.1 -->
<title>Even the folders have RSS feeds | The NewsBlur Blog</title>
<meta name="generator" content="Jekyll v4.2.0" />
<meta property="og:title" content="Even the folders have RSS feeds" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what." />
<meta property="og:description" content="What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what." />
<link rel="canonical" href="https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/" />
<meta property="og:url" content="https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/" />
<meta property="og:site_name" content="The NewsBlur Blog" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2015-08-25T07:00:14-04:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="Even the folders have RSS feeds" />
<script type="application/ld+json">
{"publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":"https://blog.newsblur.com/assets/newsblur_logo_512.png"}},"url":"https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/","@type":"BlogPosting","headline":"Even the folders have RSS feeds","dateModified":"2015-08-25T07:00:14-04:00","datePublished":"2015-08-25T07:00:14-04:00","description":"What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what.","mainEntityOfPage":{"@type":"WebPage","@id":"https://blog.newsblur.com/2015/08/25/even-the-folders-have-rss-feeds/"},"@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="/assets/main.css">
<link rel="stylesheet" type="text/css" href="https://cloud.typography.com/6565292/711824/css/fonts.css" />
<link rel="stylesheet" type="text/css" href="https://cloud.typography.com/6565292/731824/css/fonts.css" /><link type="application/atom+xml" rel="alternate" href="https://blog.newsblur.com/feed.xml" title="The NewsBlur Blog" /></head>
<body><header class="site-header" role="banner">
<div class="wrapper"><a class="site-title" rel="author" href="/">
<div class="site-title-image">
<img src="/assets/newsblur_logo_512.png">
</div>
<div class="site-title-text">The NewsBlur Blog</div>
</a><nav class="site-nav">
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger">
<span class="menu-icon">
<svg viewBox="0 0 18 15" width="18px" height="15px">
<path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/>
</svg>
</span>
</label>
<div class="trigger"><a class="page-link" href="https://www.newsblur.com">Visit NewsBlur ➤</a></div>
</nav></div>
</header>
<header class="site-subheader" role="banner">
<div class="wrapper">
<div class="top">
NewsBlur is a personal news reader that brings people together to talk about the world.
</div>
<div class="bottom">
A new sound of an old instrument.
</div>
</div>
</header>
<main class="page-content" aria-label="Content">
<div class="wrapper">
<article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
<header class="post-header">
<h1 class="post-title p-name" itemprop="name headline">Even the folders have RSS feeds</h1>
<p class="post-meta">
<time class="dt-published" datetime="2015-08-25T07:00:14-04:00" itemprop="datePublished">Aug 25, 2015
</time></p>
</header>
<div class="post-content e-content" itemprop="articleBody">
<p>What would an RSS news reader be without its own RSS feeds? It’s be a pretty lonely reader is what.</p>
<p>NewsBlur now supports RSS feeds for each of your folders. Just right-click on the folder, go to Folder Settings, and behold:</p>
<p><img src="https://s3.amazonaws.com/static.newsblur.com/blog/folder_rss.png" alt="" /></p>
<p>These folders keep track of sites you add and remove from them. They also allow you to filter out stories you don’t want to read or even choose to only show the stories you have in focus.</p>
<p>All of your feed subscriptions in the folder, including subfolders, are merged into a single river of news in RSS format. Technically we use Atom 1.0 format for NewsBlur’s many RSS feeds, but I’m not choosing a side here.</p>
<p>The Folder RSS feeds join the Shared Stories RSS feeds and the Saved Story Tag RSS feeds that you can already use if you are a premium subscriber.</p>
</div><a class="u-url" href="/2015/08/25/even-the-folders-have-rss-feeds/" hidden></a>
</article>
</div>
</main><footer class="site-footer h-card">
<data class="u-url" href="/"></data>
<div class="wrapper">
<h2 class="footer-heading">The NewsBlur Blog</h2>
<div class="footer-col-wrapper">
<div class="footer-col footer-col-1"><ul class="social-media-list"><li><a href="https://github.com/samuelclay"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#github"></use></svg> <span class="username">samuelclay</span></a></li><li><a href="https://www.twitter.com/newsblur"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#twitter"></use></svg> <span class="username">newsblur</span></a></li><li><a href="mailto:[email protected]?subject=Hello from the NewsBlur blog"><svg class="svg-icon"><use xlink:href="/assets/minima-social-icons.svg#email"></use></svg> <span class="username">[email protected]</span></a></li></ul>
</div>
<div class="footer-col footer-col-3">
<p>NewsBlur is a personal news reader that brings people together to talk about the world.<br />
A new sound of an old instrument.<br />
</p>
</div>
</div>
</div>
</footer>
</body>
</html>
| mit |
wyrover/ionic-components | ionic-coffee/details/details.html | 1187 | <ion-view view-title="Coffee Shop">
<ion-content>
<div class="card">
<div class="item item-divider text-center">
<h2>{{biz.businessName}}</h2>
</div>
<div class="item text-center">
<div><strong>{{biz.street}}</strong></div>
<div><strong>{{biz.city}}, {{biz.state}} {{biz.zip}}</strong></div>
</div>
<div class="item text-center">
<a class="item" href="tel:{{biz.phone}}" style="font-size: 150%;">
<i class="icon ion-ios7-telephone" style="font-size: 150%;"></i>
Call {{biz.phone}}
</a>
</div>
</div>
<div class="card" map zoom="18" ng-init="initMap()"
disable-default-u-i="false"
disable-double-click-zoom="false"
draggable="true"
draggable-cursor="help"
dragging-cursor="move"
keyboard-shortcuts="false"
max-zoom="20"
min-zoom="8"
tilt="0"
map-type-id="ROADMAP" style=" height: 300px;">
</div>
</ion-content>
</ion-view>
| mit |
omniproject/ezstudio-tips-block | bundle/Installer/ContentTypeInstaller.php | 5989 | <?php
/**
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace Clash82\EzPlatformStudioTipsBlockBundle\Installer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use eZ\Publish\API\Repository\ContentTypeService;
use eZ\Publish\API\Repository\Exceptions\ForbiddenException;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Exceptions\UnauthorizedException;
use eZ\Publish\API\Repository\Repository;
use eZ\Publish\API\Repository\UserService;
class ContentTypeInstaller extends Command
{
/** @var int */
const ADMIN_USER_ID = 14;
/** @var \eZ\Publish\API\Repository\Repository */
private $repository;
/** @var \eZ\Publish\API\Repository\UserService */
private $userService;
/** @var \eZ\Publish\API\Repository\ContentTypeService */
private $contentTypeService;
/**
* @param \eZ\Publish\API\Repository\Repository $repository
* @param \eZ\Publish\API\Repository\UserService $userService
* @param \eZ\Publish\API\Repository\ContentTypeService $contentTypeService
*/
public function __construct(
Repository $repository,
UserService $userService,
ContentTypeService $contentTypeService
) {
$this->repository = $repository;
$this->userService = $userService;
$this->contentTypeService = $contentTypeService;
parent::__construct();
}
protected function configure()
{
$this->setName('ezstudio:tips-block:install')
->setHelp('Creates a new `Tip` ContentType.')
->addOption(
'name',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>name</info>',
'Tip'
)
->addOption(
'identifier',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>identifier</info>',
'tip'
)
->addOption(
'group_identifier',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>group_identifier</info>',
'Content'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$groupIdentifier = $input->getOption('group_identifier');
$identifier = $input->getOption('identifier');
$name = $input->getOption('name');
try {
$contentTypeGroup = $this->contentTypeService->loadContentTypeGroupByIdentifier($groupIdentifier);
} catch (NotFoundException $e) {
$output->writeln(sprintf('ContentType group with identifier %s not found', $groupIdentifier));
return;
}
// create basic ContentType structure
$contentTypeCreateStruct = $this->contentTypeService->newContentTypeCreateStruct($identifier);
$contentTypeCreateStruct->mainLanguageCode = 'eng-GB';
$contentTypeCreateStruct->nameSchema = '<title>';
$contentTypeCreateStruct->names = [
'eng-GB' => $identifier,
];
$contentTypeCreateStruct->descriptions = [
'eng-GB' => 'Tip of the day',
];
// add Title field
$titleFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('title', 'ezstring');
$titleFieldCreateStruct->names = [
'eng-GB' => 'Title',
];
$titleFieldCreateStruct->descriptions = [
'eng-GB' => 'Title',
];
$titleFieldCreateStruct->fieldGroup = 'content';
$titleFieldCreateStruct->position = 1;
$titleFieldCreateStruct->isTranslatable = true;
$titleFieldCreateStruct->isRequired = true;
$titleFieldCreateStruct->isSearchable = true;
$contentTypeCreateStruct->addFieldDefinition($titleFieldCreateStruct);
// add Description field
$bodyFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('body', 'ezrichtext');
$bodyFieldCreateStruct->names = [
'eng-GB' => 'Body',
];
$bodyFieldCreateStruct->descriptions = [
'eng-GB' => 'Body',
];
$bodyFieldCreateStruct->fieldGroup = 'content';
$bodyFieldCreateStruct->position = 2;
$bodyFieldCreateStruct->isTranslatable = true;
$bodyFieldCreateStruct->isRequired = true;
$bodyFieldCreateStruct->isSearchable = true;
$contentTypeCreateStruct->addFieldDefinition($bodyFieldCreateStruct);
try {
$contentTypeDraft = $this->contentTypeService->createContentType($contentTypeCreateStruct, [
$contentTypeGroup,
]);
$this->contentTypeService->publishContentTypeDraft($contentTypeDraft);
$output->writeln(sprintf(
'<info>%s ContentType created with ID %d</info>',
$name, $contentTypeDraft->id
));
} catch (UnauthorizedException $e) {
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
return;
} catch (ForbiddenException $e) {
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
return;
}
$output->writeln(sprintf(
'Place all your <info>%s</info> content objects into desired folder and then select it as a Parent container in eZ Studio Tips Block options form.',
$name
));
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->repository->setCurrentUser(
$this->userService->loadUser(self::ADMIN_USER_ID)
);
}
}
| mit |
jonboylailam/nodejs-react-app-starter | README.md | 495 | # Starter Web App
This is my attempt to create a dev workflow which hot reloads client and server side changes.
Note: This is still a work in progress
## Installation
git clone xyz
rm -rf .git
npm install
gulp (npm run dev)
open http://localhost:3000
## Deployment
gulp bundle (npm run bundle)
## What do you get
## Configuration
HOST_NAME - used when logging and sending stats to statsd. default is jonsmac
STATSD_HOST - the ip address for the statsd server | mit |
jsmestad/frankie | lib/frankie.rb | 6584 | # frankie - a plugin for sinatra that integrates with the facebooker gem
#
# written by Ron Evans (http://www.deadprogrammersociety.com)
#
# based on merb_facebooker (http://github.com/vanpelt/merb_facebooker)
# and the Rails classes in Facebooker (http://facebooker.rubyforge.org/) from Mike Mangino, Shane Vitarana, & Chad Fowler
#
require 'sinatra/base'
require 'yaml'
require 'uri'
gem 'mmangino-facebooker'
require 'facebooker'
module Sinatra
module Frankie
module Loader
def load_facebook_config(file, env=:development)
if File.exist?(file)
yaml = YAML.load_file(file)[env.to_s]
ENV['FACEBOOK_API_KEY'] = yaml['api_key']
ENV['FACEBOOK_SECRET_KEY'] = yaml['secret_key']
ENV['FACEBOOKER_RELATIVE_URL_ROOT'] = yaml['canvas_page_name']
end
end
end
module Helpers
def facebook_session
@facebook_session
end
def facebook_session_parameters
{:fb_sig_session_key=>params["fb_sig_session_key"]}
end
def set_facebook_session
session_set = session_already_secured? || secure_with_token! || secure_with_facebook_params!
if session_set
capture_facebook_friends_if_available!
Facebooker::Session.current = facebook_session
end
session_set
end
def facebook_params
@facebook_params ||= verified_facebook_params
end
def session_already_secured?
(@facebook_session = session[:facebook_session]) && session[:facebook_session].secured?
end
def secure_with_token!
if params['auth_token']
@facebook_session = new_facebook_session
@facebook_session.auth_token = params['auth_token']
@facebook_session.secure!
session[:facebook_session] = @facebook_session
end
end
def secure_with_facebook_params!
return unless request_is_for_a_facebook_canvas?
if ['user', 'session_key'].all? {|element| facebook_params[element]}
@facebook_session = new_facebook_session
@facebook_session.secure_with!(facebook_params['session_key'], facebook_params['user'], facebook_params['expires'])
session[:facebook_session] = @facebook_session
end
end
def create_new_facebook_session_and_redirect!
session[:facebook_session] = new_facebook_session
throw :halt, do_redirect(session[:facebook_session].login_url) unless @installation_required
end
def new_facebook_session
Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key)
end
def capture_facebook_friends_if_available!
return unless request_is_for_a_facebook_canvas?
if friends = facebook_params['friends']
facebook_session.user.friends = friends.map do |friend_uid|
Facebooker::User.new(friend_uid, facebook_session)
end
end
end
def blank?(value)
(value == '0' || value.nil? || value == '')
end
def verified_facebook_params
facebook_sig_params = params.inject({}) do |collection, pair|
collection[pair.first.sub(/^fb_sig_/, '')] = pair.last if pair.first[0,7] == 'fb_sig_'
collection
end
verify_signature(facebook_sig_params, params['fb_sig'])
facebook_sig_params.inject(Hash.new) do |collection, pair|
collection[pair.first] = facebook_parameter_conversions[pair.first].call(pair.last)
collection
end
end
# 48.hours.ago in sinatra
def earliest_valid_session
now = Time.now
now -= (60 * 60 * 48)
now
end
def verify_signature(facebook_sig_params,expected_signature)
raw_string = facebook_sig_params.map{ |*args| args.join('=') }.sort.join
actual_sig = Digest::MD5.hexdigest([raw_string, Facebooker::Session.secret_key].join)
raise Facebooker::Session::IncorrectSignature if actual_sig != expected_signature
raise Facebooker::Session::SignatureTooOld if Time.at(facebook_sig_params['time'].to_f) < earliest_valid_session
true
end
def facebook_parameter_conversions
@facebook_parameter_conversions ||= Hash.new do |hash, key|
lambda{|value| value}
end.merge('time' => lambda{|value| Time.at(value.to_f)},
'in_canvas' => lambda{|value| !blank?(value)},
'added' => lambda{|value| !blank?(value)},
'expires' => lambda{|value| blank?(value) ? nil : Time.at(value.to_f)},
'friends' => lambda{|value| value.split(/,/)}
)
end
def do_redirect(*args)
if request_is_for_a_facebook_canvas?
fbml_redirect_tag(args)
else
redirect args[0]
end
end
def fbml_redirect_tag(url)
"<fb:redirect url=\"#{url}\" />"
end
def request_is_for_a_facebook_canvas?
return false if params["fb_sig_in_canvas"].nil?
params["fb_sig_in_canvas"] == "1"
end
def application_is_installed?
facebook_params['added']
end
def ensure_authenticated_to_facebook
set_facebook_session || create_new_facebook_session_and_redirect!
end
def ensure_application_is_installed_by_facebook_user
@installation_required = true
authenticated_and_installed = ensure_authenticated_to_facebook && application_is_installed?
application_is_not_installed_by_facebook_user unless authenticated_and_installed
authenticated_and_installed
end
def application_is_not_installed_by_facebook_user
throw :halt, do_redirect(session[:facebook_session].install_url)
end
def set_fbml_format
params['format']="fbml" if request_is_for_a_facebook_canvas?
end
def fb_url_for(url)
url = "" if url == "/"
url = URI.escape(url)
return url if !request_is_for_a_facebook_canvas?
"http://apps.facebook.com/#{ENV['FACEBOOKER_RELATIVE_URL_ROOT']}/#{url}"
end
def do_redirect(*args)
if request_is_for_a_facebook_canvas?
fbml_redirect_tag(args[0])
else
redirect args[0]
end
end
def self.registered(app)
app.register Loader
app.helpers Helpers
end
end
end
| mit |
arapaka/algorithms-datastructures | algorithms/src/main/java/tutorialHorizon/arrays/InsertionSort.java | 813 | package tutorialHorizon.arrays;
/**
* Created by archithrapaka on 7/4/17.
*/
public class InsertionSort {
public static void insertionSort(int[] items, int n) {
int i, j;
for (i = 1; i < n; i++) {
j = i;
while (j > 0 && (items[j] < items[j - 1])) {
swap(items, j, j - 1);
j--;
}
}
}
public static void swap(int[] items, int i, int j) {
int temp = items[i];
items[i] = items[j];
items[j] = temp;
}
public static void display(int[] a) {
for (int i : a) {
System.out.print(i + " ");
}
}
public static void main(String[] args) {
int[] a = {100, 4, 30, 15, 98, 3};
insertionSort(a, a.length);
display(a);
}
}
| mit |
ProtonMail/WebClient | packages/components/containers/api/apiStatusContext.ts | 196 | import { createContext } from 'react';
export const defaultApiStatus = {
offline: false,
apiUnreachable: '',
appVersionBad: false,
};
export default createContext(defaultApiStatus);
| mit |
bjrmatos/docs | docs/embedding.md | 4609 | > Link jsreport browser sdk into your page and easily render a report from the browser or open limited version of jsreport studio inside any web application and let end users to customize their reports. There are various scenarios where this can be used. Typical example can be when application is sending invoices to the customers and allows them to modify invoice template to the required design.
##Getting started
To start using jsreport browser sdk you need to:
1. Include jquery into page
2. Include jsreport `embed.js` into page
3. Create `jsreportInit` function in the global scope with similar meaning as `$.ready`
4. Use global object `jsreport` to open editor or render a template
```html
<!DOCTYPE html>
<html>
<head lang="en">
<!-- jquery is required for jsreport embedding -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://local.net:2000/extension/embedding/public/js/embed.js"></script>
</head>
<body>
<script>
//jsreport will call jsreportInit function from global scope when its initialized
jsreportInit = function () {
//use jsreport object to render reports or open editor
};
</script>
</body>
</html>
```
##Rendering template
Use `jsreport.render` function to invoke template server side rendering. Function takes a whole template json definition or just a string shortid as a parameter. The output report is opened in a new browser tab by default. This can be overridden by setting the first function parameter to jquery object placeholder.
```js
//render a template into the new tab
jsreport.render({ conent: "foo", recipe: "phantom-pdf", engine: "jsrender" });
//render a template into the placeholder
jsreport.render($("#placeholder"), { conent: "foo", recipe: "phantom-pdf", engine: "jsrender" });
```
##Opening editor
Use `jseport.openEditor` function to pop up jsreport designer in the modal. This functions takes a whole template definition or just a string shortid as a parameter. Function returns an even emitter to which you can bind and listen to `close` or `template-change` events.
```js
jsreport.openEditor(template
.on("template-change", function (tmpl) {
//store changes
template= tmpl;
}).on("close", function() {
//save template to your storage
});
```
You can also submit additional options for jsreport extensions like sample data or custom script in the `openEditor` parameters.
```js
jsreport.openEditor({
content: "<h1>Hello World</h1>",
data: {
dataJson: {
price: "1234"
}
}
});
```
Where `dataJson` can be any json object or parse-able json string.
You can also set up a [custom script](/learn/scripts) to the report template loading input data for the report preview. Using custom scripts user can even specify desired input data source on its own.
###Using jsreport storage
The jsreport designer is by default stateless and doesn't store the template in any storage. It is expected you listen to the emitted events and store the template in your own storage if you want.
To enable storing templates in the jsreport storage just add `useStandardStorage` option when opening editor:
```js
//open template from jsreport storage
jsreport.openEditor("Z1vT7FHyU", { useStandardStorage: true });
```
## Security
Using `embed.js` to render or edit templates is possible only when the browser get's access to the jsreport server. Exposing unsecured jsreport server to the public audience doesn't need to be a good idea for the internet applications. In this case you can secure jsreport and keep using `embed.js` using following approaches.
One option is to use secure jsreport server using [authentication](/learn/authentication) and [authorization](/learn/authorization) extension to limit access to the jsreport. Anonymous user using `embed.js` can be then authorized using secure token generated by [public-templates](/learn/public-templates) extension.
Another options is to create a tunnel forwarding request to jsreport through your application. This hides jsreport behind your security layers and also eliminates cross domain calls. You basically just need to catch and resend requests to jsreport and add `serverUrl` query parameter to specify where the jsreport web client should route requests back. In other words you create a route in your web server which will proxy jsreport server. Example of such a proxy in asp.net can be found [here](https://github.com/jsreport/net/blob/master/jsreport/jsreport.Client/JsReportWebHandler.cs). Implementing such a tunnel in any other language should not be difficult.
| mit |
thecodebureau/epiphany | schemas/article.js | 10188 | module.exports = {
//"@context": { type: String, default: "http://schema.org" },
//"@type": { type: String, default: "Article" },
//>>Properties from NewsArticle
//dateline: String,//The location where the NewsArticle was produced.
//printColumn: String,//The number of the column in which the NewsArticle appears in the print edition.
//printEdition: String,//The edition of the print product in which the NewsArticle appears.
//printPage: String,//If this NewsArticle appears in print, this field indicates the name of the page on which the article is found. Please note that this field is intended for the exact page name (e.g. A5, B18).
//printSection: String,//If this NewsArticle appears in print, this field indicates the print section in which the article appeared.
//>>Properties from Article
articleBody: String ,//The actual body of the article.
//articleSection: String ,//Articles may belong to one or more 'sections' in a magazine or newspaper, such as Sports, Lifestyle, etc.
//pageEnd: String or Number ,//The page on which the work ends; for example "138" or "xvi".
//pageStart: String or Number ,//The page on which the work starts; for example "135" or "xiii".
//pagination: String ,//Any description of pages that is not separated into pageStart and pageEnd; for example, "1-6, 9, 55" or "10-12, 46-49".
wordCount: Number ,//The number of words in the text of the Article.
//>>Properties from CreativeWork
//about: Thing ,//The subject matter of the content.
//accessibilityAPI: String ,//Indicates that the resource is compatible with the referenced accessibility API (WebSchemas wiki lists possible values).
//accessibilityControl: String ,//Identifies input methods that are sufficient to fully control the described resource (WebSchemas wiki lists possible values).
//accessibilityFeature: String ,//Content features of the resource, such as accessible media, alternatives and supported enhancements for accessibility (WebSchemas wiki lists possible values).
//accessibilityHazard: String ,//A characteristic of the described resource that is physiologically dangerous to some users. Related to WCAG 2.0 guideline 2.3 (WebSchemas wiki lists possible values).
//accountablePerson: Person ,//Specifies the Person that is legally accountable for the CreativeWork.
//aggregateRating: AggregateRating ,//The overall rating, based on a collection of reviews or ratings, of the item.
//alternativeHeadline: String ,//A secondary title of the CreativeWork.
//associatedMedia: MediaObject ,//A media object that encodes this CreativeWork. This property is a synonym for encoding.
//audience: Audience ,//The intended audience of the item, i.e. the group for whom the item was created.
//audio: AudioObject ,//An embedded audio object.
//author: Organization or Person ,//The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangeably.
//award: String ,//An award won by this person or for this creative work. Supersedes awards.
//character: Person ,//Fictional person connected with a creative work.
//citation: String or CreativeWork ,//A citation or reference to another creative work, such as another publication, web page, scholarly article, etc.
//comment: UserComments or Comment ,//Comments, typically from users, on this CreativeWork.
//commentCount: Number ,//The number of comments this CreativeWork (e.g. Article, Question or Answer) has received. This is most applicable to works published in Web sites with commenting system; additional comments may exist elsewhere.
//contentLocation: Place ,//The location of the content.
//contentRating: String ,//Official rating of a piece of content—for example,'MPAA PG-13'.
//contributor: Organization or Person ,//A secondary contributor to the CreativeWork.
//copyrightHolder: Organization or Person ,//The party holding the legal copyright to the CreativeWork.
copyrightYear: Number ,//The year during which the claimed copyright for the CreativeWork was first asserted.
//creator: Organization or Person ,//The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
dateCreated: {
type: Date,//The date on which the CreativeWork was created.
default: Date.now
},
dateModified: Date ,//The date on which the CreativeWork was most recently modified.
datePublished: Date ,//Date of first broadcast/publication.
//discussionUrl: URL ,//A link to the page containing the comments of the CreativeWork.
//editor: Person ,//Specifies the Person who edited the CreativeWork.
//educationalAlignment: AlignmentObject ,//An alignment to an established educational framework.
//educationalUse: String ,//The purpose of a work in the context of education; for example, 'assignment', 'group work'.
//encoding: MediaObject ,//A media object that encodes this CreativeWork. This property is a synonym for associatedMedia. Supersedes encodings.
//exampleOfWork: CreativeWork ,//A creative work that this work is an example/instance/realization/derivation of. Inverse property: workExample.
//genre: String ,//Genre of the creative work or group.
//hasPart: CreativeWork ,//Indicates a CreativeWork that is (in some sense) a part of this CreativeWork. Inverse property: isPartOf.
headline: String ,//Headline of the article.
//inLanguage: String ,//The language of the content. please use one of the language codes from the IETF BCP 47 standard.
//interactionCount: String ,//A count of a specific user interactions with this item—for example, 20 UserLikes, 5 UserComments, or 300 UserDownloads. The user interaction type should be one of the sub types of UserInteraction.
//interactivityType: String ,//The predominant mode of learning supported by the learning resource. Acceptable values are 'active', 'expositive', or 'mixed'.
//isBasedOnUrl: URL ,//A resource that was used in the creation of this resource. This term can be repeated for multiple sources. For example, http://example.com/great-multiplication-intro.html.
//isFamilyFriendly: Boolean ,//Indicates whether this content is family friendly.
//isPartOf: CreativeWork ,//Indicates a CreativeWork that this CreativeWork is (in some sense) part of. Inverse property: hasPart.
//keywords: String ,//Keywords or tags used to describe this content. Multiple entries in a keywords list are typically delimited by commas.
//learningResourceType: String ,//The predominant type or kind characterizing the learning resource. For example, 'presentation', 'handout'.
//license: URL or CreativeWork ,//A license document that applies to this content, typically indicated by URL.
//mentions: Thing ,//Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
//offers: Offer ,//An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, or give away tickets to an event.
//position: String or Number ,//The position of an item in a series or sequence of items.
//producer: Organization or Person ,//The person or organization who produced the work (e.g. music album, movie, tv/radio series etc.).
//provider: Organization or Person ,//The service provider, service operator, or service performer; the goods producer. Another party (a seller) may offer those services or goods on behalf of the provider. A provider may also serve as the seller. Supersedes carrier.
//publisher: Organization ,//The publisher of the creative work.
//publishingPrinciples: URL ,//Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
//recordedAt: Event ,//The Event where the CreativeWork was recorded. The CreativeWork may capture all or part of the event. Inverse property: recordedIn.
//releasedEvent: PublicationEvent ,//The place and time the release was issued, expressed as a PublicationEvent.
//review: Review ,//A review of the item. Supersedes reviews.
//sourceOrganization: Organization ,//The Organization on whose behalf the creator was working.
//text: String ,//The textual content of this CreativeWork.
//thumbnailUrl: URL ,//A thumbnail image relevant to the Thing.
//timeRequired: Duration ,//Approximate or typical time it takes to work with or through this learning resource for the typical intended target audience, e.g. 'P30M', 'P1H25M'.
//translator: Organization or Person ,//Organization or person who adapts a creative work to different languages, regional differences and technical requirements of a target market.
//typicalAgeRange: String ,//The typical expected age range, e.g. '7-9', '11-'.
//version: Number ,//The version of the CreativeWork embodied by a specified resource.
//video: VideoObject ,//An embedded video object.
//workExample: CreativeWork ,//Example/instance/realization/derivation of the concept of this creative work. eg. The paperback edition, first edition, or eBook. Inverse property: exampleOfWork.
//>>Properties from Thing
//additionalType: URL ,//An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
//alternateName: String ,//An alias for the item.
//description: String ,//A short description of the item.
image: require('./image-object'),//An image of the item. This can be a URL or a fully described ImageObject.
//name: String ,//The name of the item.
//potentialAction: Action ,//Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
//sameAs: URL ,//URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Freebase page, or official website.
//url: URL,//URL of the item.
};
| mit |
griimick/feature-mlsite | app/liner/views.py | 1108 | from flask import Blueprint, request, render_template
from ..load import processing_results
from ..abbr import get_abbr_map
abbr_map = get_abbr_map()
liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static')
@liner_mod.route('/liner', methods=['GET', 'POST'])
def liner():
if request.method == 'POST':
query = request.form['liner-text']
text = query.split('.')[:-1]
if len(text) == 0:
return render_template('projects/line.html', message='Please separate each line with "."')
abbr_expanded_text = ""
for word in query.split():
if word in abbr_map:
abbr_expanded_text += abbr_map[word]
else:
abbr_expanded_text += word
abbr_expanded_text += " "
data, emotion_sents, score, line_sentiment, text, length = processing_results(text)
return render_template('projects/line.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length, abbr_expanded_text])
else:
return render_template('projects/line.html')
| mit |
lmazuel/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/models/dimension.py | 1562 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Dimension(Model):
"""Dimension of a resource metric. For e.g. instance specific HTTP requests
for a web app,
where instance name is dimension of the metric HTTP request.
:param name:
:type name: str
:param display_name:
:type display_name: str
:param internal_name:
:type internal_name: str
:param to_be_exported_for_shoebox:
:type to_be_exported_for_shoebox: bool
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'internal_name': {'key': 'internalName', 'type': 'str'},
'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'},
}
def __init__(self, name=None, display_name=None, internal_name=None, to_be_exported_for_shoebox=None):
super(Dimension, self).__init__()
self.name = name
self.display_name = display_name
self.internal_name = internal_name
self.to_be_exported_for_shoebox = to_be_exported_for_shoebox
| mit |
dryzhkov/ps-react-dr | README.md | 330 | # Pluralsight React Components
A library of React components created in "Creating Reusable React Components" on Pluralsight.
## Install
```
npm install ps-react-dr
```
## Issues
I'll add tips for common problems and address any known course issues here.
## Docs
[Component documentation](http://dryzhkov.github.io/ps-react-dr) | mit |
misizeji/StudyNote_201308 | webserver/html/qdbusabstractadaptor-members.html | 7196 | <?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/tools/qdbus/src/qdbusabstractadaptor.cpp -->
<head>
<title>Qt 4.3: List of All Members for QDBusAbstractAdaptor</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">List of All Members for QDBusAbstractAdaptor</h1>
<p>This is the complete list of members for <a href="qdbusabstractadaptor.html">QDBusAbstractAdaptor</a>, including inherited members.</p>
<p><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="45%" valign="top"><ul>
<li><div class="fn"/><a href="qdbusabstractadaptor.html#QDBusAbstractAdaptor">QDBusAbstractAdaptor</a> ( QObject * )</li>
<li><div class="fn"/><a href="qdbusabstractadaptor.html#dtor.QDBusAbstractAdaptor">~QDBusAbstractAdaptor</a> ()</li>
<li><div class="fn"/><a href="qdbusabstractadaptor.html#autoRelaySignals">autoRelaySignals</a> () const : bool</li>
<li><div class="fn"/><a href="qobject.html#blockSignals">blockSignals</a> ( bool ) : bool</li>
<li><div class="fn"/><a href="qobject.html#childEvent">childEvent</a> ( QChildEvent * )</li>
<li><div class="fn"/><a href="qobject.html#children">children</a> () const : const QObjectList &</li>
<li><div class="fn"/><a href="qobject.html#connect">connect</a> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType ) : bool</li>
<li><div class="fn"/><a href="qobject.html#connect-2">connect</a> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const : bool</li>
<li><div class="fn"/><a href="qobject.html#connectNotify">connectNotify</a> ( const char * )</li>
<li><div class="fn"/><a href="qobject.html#customEvent">customEvent</a> ( QEvent * )</li>
<li><div class="fn"/><a href="qobject.html#deleteLater">deleteLater</a> ()</li>
<li><div class="fn"/><a href="qobject.html#destroyed">destroyed</a> ( QObject * )</li>
<li><div class="fn"/><a href="qobject.html#disconnect">disconnect</a> ( const QObject *, const char *, const QObject *, const char * ) : bool</li>
<li><div class="fn"/><a href="qobject.html#disconnect-2">disconnect</a> ( const char *, const QObject *, const char * ) : bool</li>
<li><div class="fn"/><a href="qobject.html#disconnect-3">disconnect</a> ( const QObject *, const char * ) : bool</li>
<li><div class="fn"/><a href="qobject.html#disconnectNotify">disconnectNotify</a> ( const char * )</li>
<li><div class="fn"/><a href="qobject.html#dumpObjectInfo">dumpObjectInfo</a> ()</li>
<li><div class="fn"/><a href="qobject.html#dumpObjectTree">dumpObjectTree</a> ()</li>
<li><div class="fn"/><a href="qobject.html#dynamicPropertyNames">dynamicPropertyNames</a> () const : QList<QByteArray></li>
<li><div class="fn"/><a href="qobject.html#event">event</a> ( QEvent * ) : bool</li>
<li><div class="fn"/><a href="qobject.html#eventFilter">eventFilter</a> ( QObject *, QEvent * ) : bool</li>
<li><div class="fn"/><a href="qobject.html#findChild">findChild</a> ( const QString & ) const : T</li>
<li><div class="fn"/><a href="qobject.html#findChildren">findChildren</a> ( const QString & ) const : QList<T></li>
<li><div class="fn"/><a href="qobject.html#findChildren-2">findChildren</a> ( const QRegExp & ) const : QList<T></li>
<li><div class="fn"/><a href="qobject.html#inherits">inherits</a> ( const char * ) const : bool</li>
</ul></td><td valign="top"><ul>
<li><div class="fn"/><a href="qobject.html#installEventFilter">installEventFilter</a> ( QObject * )</li>
<li><div class="fn"/><a href="qobject.html#isWidgetType">isWidgetType</a> () const : bool</li>
<li><div class="fn"/><a href="qobject.html#killTimer">killTimer</a> ( int )</li>
<li><div class="fn"/><a href="qobject.html#metaObject">metaObject</a> () const : const QMetaObject *</li>
<li><div class="fn"/><a href="qobject.html#moveToThread">moveToThread</a> ( QThread * )</li>
<li><div class="fn"/><a href="qobject.html#objectName-prop">objectName</a> () const : QString</li>
<li><div class="fn"/><a href="qobject.html#parent">parent</a> () const : QObject *</li>
<li><div class="fn"/><a href="qobject.html#property">property</a> ( const char * ) const : QVariant</li>
<li><div class="fn"/><a href="qobject.html#receivers">receivers</a> ( const char * ) const : int</li>
<li><div class="fn"/><a href="qobject.html#removeEventFilter">removeEventFilter</a> ( QObject * )</li>
<li><div class="fn"/><a href="qobject.html#sender">sender</a> () const : QObject *</li>
<li><div class="fn"/><a href="qdbusabstractadaptor.html#setAutoRelaySignals">setAutoRelaySignals</a> ( bool )</li>
<li><div class="fn"/><a href="qobject.html#objectName-prop">setObjectName</a> ( const QString & )</li>
<li><div class="fn"/><a href="qobject.html#setParent">setParent</a> ( QObject * )</li>
<li><div class="fn"/><a href="qobject.html#setProperty">setProperty</a> ( const char *, const QVariant & ) : bool</li>
<li><div class="fn"/><a href="qobject.html#signalsBlocked">signalsBlocked</a> () const : bool</li>
<li><div class="fn"/><a href="qobject.html#startTimer">startTimer</a> ( int ) : int</li>
<li><div class="fn"/><a href="qobject.html#staticMetaObject-var">staticMetaObject</a> : const QMetaObject</li>
<li><div class="fn"/><a href="qobject.html#thread">thread</a> () const : QThread *</li>
<li><div class="fn"/><a href="qobject.html#timerEvent">timerEvent</a> ( QTimerEvent * )</li>
<li><div class="fn"/><a href="qobject.html#tr">tr</a> ( const char *, const char *, int ) : QString</li>
<li><div class="fn"/><a href="qobject.html#trUtf8">trUtf8</a> ( const char *, const char *, int ) : QString</li>
</ul>
</td></tr>
</table></p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright © 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
| mit |