code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
# Multidimensional image viewer for MicroManager (MdV)
[](https://david-dm.org/hirokai/MicroManagerViewer)
[](https://david-dm.org/hirokai/MicroManagerViewer#info=devDependencies)
> A prototype web app for viewing multidimensional images from [MicroManager](https://www.micro-manager.org/) microscopy software.
## Getting Started
1. Use a Python script (`backend/gen_csv.py`) to generate thumbnails and metadata.
1. Edit `datasets` variable in `backend/gen_csv.py` to define data sets.
1. Run `backend/gen_csv.py`, and it will generate:
1. Data set entries in `datasets.csv` file.
1. Metadata of each data set in `metadata` folder.
1. images in `images` folder.
1. The web interface, written with [React](http://facebook.github.io/react/), uses static JSON files and image thumbnails.
The server side just needs to serve static files. For example, run the following in the folder of index.html.
```shell
python -m SimpleHTTPServer 3000
```
Then just open [http://localhost:3000/](http://localhost:3000/) in a web browser.
## License
MIT license.
|
hirokai/MicroManagerViewer
|
README.md
|
Markdown
|
mit
| 1,234
|
#!/bin/sh
set -e
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
XCASSET_FILES=()
case "${TARGETED_DEVICE_FAMILY}" in
1,2)
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
;;
1)
TARGET_DEVICE_ARGS="--target-device iphone"
;;
2)
TARGET_DEVICE_ARGS="--target-device ipad"
;;
*)
TARGET_DEVICE_ARGS="--target-device mac"
;;
esac
install_resource()
{
if [[ "$1" = /* ]] ; then
RESOURCE_PATH="$1"
else
RESOURCE_PATH="${PODS_ROOT}/$1"
fi
if [[ ! -e "$RESOURCE_PATH" ]] ; then
cat << EOM
error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script.
EOM
exit 1
fi
case $RESOURCE_PATH in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\""
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\""
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd"
;;
*.xcmappingmodel)
echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\""
xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm"
;;
*.xcassets)
ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH"
XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE")
;;
*)
echo "$RESOURCE_PATH"
echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY"
;;
esac
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_resource "AMap3DMap/MAMapKit.framework/AMap.bundle"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_resource "AMap3DMap/MAMapKit.framework/AMap.bundle"
fi
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
then
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
while read line; do
if [[ $line != "${PODS_ROOT}*" ]]; then
XCASSET_FILES+=("$line")
fi
done <<<"$OTHER_XCASSETS"
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
|
himyfairy/EasyTrack
|
EasyTrack/Pods/Target Support Files/Pods-EasyTrack/Pods-EasyTrack-resources.sh
|
Shell
|
mit
| 5,229
|
# match-path

## install
```sh
$ npm install bloody-matchpath
```
## require
```javascript
var matchPath = require("bloody-matchpath")
```
## api
### `matchPath(string, matcher) > Boolean`
checks `string` using the `matcher` pattern.
### patterns
```javascript
"foo.*.bar"
// matches
"foo.bar.bar"
// but not
"foo.bar.baz.bar"
"foo.**.bar"
// matches both
"foo.bar.bar"
// and
"foo.bar.baz.bar"
```
|
bloodyowl/match-path
|
README.md
|
Markdown
|
mit
| 503
|
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
)
type Graph struct {
nodes map[int]Node
}
type Node struct {
payload byte
adj map[int]struct{}
}
func NewGraph() Graph {
return Graph{make(map[int]Node)}
}
func (g *Graph) addNode(key int, data byte) {
g.nodes[key] = Node{payload: data, adj: make(map[int]struct{})}
}
func (g *Graph) addEdge(src, dst int) {
g.nodes[src].adj[dst] = struct{}{}
g.nodes[dst].adj[src] = struct{}{}
}
func createMazeGraph(in []byte) Graph {
g := NewGraph()
// create matrix
matrix := make([][]byte, 0)
line := make([]byte, 0)
for _, block := range in {
if block != '\n' {
line = append(line, block)
} else {
matrix = append(matrix, line)
line = make([]byte, 0)
}
fmt.Print(string(block))
}
// create node
count := 0
for _, row := range matrix {
for _, col := range row {
g.addNode(count, col)
count++
}
}
// create edge
length := len(matrix[0])
for r, row := range matrix {
for c, _ := range row {
if c-1 >= 0 {
g.addEdge(r*length+c, r*length+c-1)
}
if r-1 >= 0 {
g.addEdge(r*length+c, (r-1)*length+c)
}
if r+1 < len(matrix) {
g.addEdge(r*length+c, (r+1)*length+c)
}
if c+1 < len(row) {
g.addEdge(r*length+c, r*length+c+1)
}
}
}
return g
}
func (g *Graph) bfs() []int {
sNode, err := g.findStartNode()
if err != nil {
panic(err)
}
visited := make(map[int]struct{})
parent := make(map[int]int)
queue := []int{sNode}
var answer []int
for len(queue) != 0 {
cur := queue[0]
visited[cur] = struct{}{}
queue = queue[1:]
switch g.nodes[cur].payload {
case ' ', 'S':
for key, _ := range g.nodes[cur].adj {
if _, ok := visited[key]; ok {
continue
}
parent[key] = cur
queue = append(queue, key)
}
case '|', '-':
continue
case 'E':
answer = append(answer, cur)
// backtrack to get answer
for _, ok := parent[cur]; ok; _, ok = parent[cur] {
cur = parent[cur]
answer = append(answer, cur)
}
break
}
}
return answer
}
func (g *Graph) findStartNode() (int, error) {
for key, node := range g.nodes {
if node.payload == 'S' {
return key, nil
}
}
return 0, errors.New("Cannot find start node")
}
func (g *Graph) dfs() []int {
sNode, err := g.findStartNode()
if err != nil {
panic(err)
}
visited := make(map[int]struct{})
answer := make([]int, 0)
g.dfs2(sNode, visited, &answer)
return answer
}
func (g *Graph) dfs2(cur int, visited map[int]struct{}, answer *[]int) bool {
if _, ok := visited[cur]; ok {
return false
}
visited[cur] = struct{}{}
switch g.nodes[cur].payload {
case '|', '-':
return false
case 'E':
return true
}
for i, _ := range g.nodes[cur].adj {
if g.dfs2(i, visited, answer) {
*answer = append(*answer, i)
return true
}
}
return false
}
func mimicAnswer(in []byte, answer []int) []byte {
out := make([]byte, len(in))
copy(out, in)
count := 0
for idx, char := range in {
for _, pos := range answer {
if count == pos {
out[idx] = 'X'
break
}
}
if char != '\n' {
count++
}
}
return out
}
func main() {
in, _ := ioutil.ReadAll(os.Stdin)
g := createMazeGraph(in)
answer := g.dfs()
out := mimicAnswer(in, answer)
fmt.Println(string(out))
answer = g.bfs()
out = mimicAnswer(in, answer)
fmt.Println(string(out))
}
|
parnurzeal/go-graphsearch
|
adj_graph2/main.go
|
GO
|
mit
| 3,319
|
{% extends 'bookbase.html' %}
{% block title %}
CHAPTER I
— {{ SITENAME }}{% endblock %}
{% block content %}
{% include '_include/crimeandpunishment26.html' %}
{% endblock %}
|
charlesreid1/wordswordswords
|
pelican/crimeandpunishment/fdcp26.html
|
HTML
|
mit
| 189
|
(function (angular) {
"use strict";
angular
.module("Cerberus.TemplateEditor")
.controller("Cerberus.TemplateEditor.Controller.ComponentEditor.Navigation.Link", function () { });
})(window.angular);
|
AgronKabashi/TemplateEngine
|
src/templateeditor/controller/componentEditor/navigation/link.js
|
JavaScript
|
mit
| 211
|
'use strict'
import React, { PropTypes } from 'react';
import { Button } from 'antd';
import { Link } from 'react-router';
import * as actions from '../action/note'
class Notes_item extends React.Component{
onDeleteNote (event) {
event.preventDefault()
this.props.onDeleteNote(this.props.note._id)
}
render() {
let date = this.props.note.date;
let postDate = 'posted @' + date;
let deleteChoice
if (this.props.note.isLogin) {
deleteChoice = (
<span className="deleteNote" onClick={ this.onDeleteNote.bind(this) }> 删除 </span>
)
}
return (
<div>
<div className="notes_item" >
<h4><Link to={ '/note/' + this.props.note._id }>{ this.props.note.title }</Link></h4>
<p>{ this.props.note.content.substr(0,50) + '...' }</p>
<span className="tag">
<span>{ '作者:' + this.props.note.author } </span>
<span className="tag-left">{ postDate }</span>
<span className="tag-right">浏览({ this.props.note.pv || 0 }){' '}留言({ this.props.note.commentCnt || 0})</span>
{ deleteChoice }
</span>
</div>
</div>
);
}
}
export default Notes_item;
|
cashyu/reactNode
|
client/src/components/note_item.js
|
JavaScript
|
mit
| 1,231
|
using System.IO;
using TQVaultAE.Domain.Entities;
namespace TQVaultAE.Domain.Contracts.Providers
{
public interface ISackCollectionProvider
{
/// <summary>
/// Encodes the sack into binary form
/// </summary>
/// <param name="writer">BinaryWriter instance</param>
void Encode(SackCollection sc, BinaryWriter writer);
/// <summary>
/// Parses the binary sack data to internal data
/// </summary>
/// <param name="reader">BinaryReader instance</param>
void Parse(SackCollection sc, BinaryReader reader);
}
}
|
EtienneLamoureux/TQVaultAE
|
src/TQVaultAE.Domain/Contracts/Providers/ISackCollectionProvider.cs
|
C#
|
mit
| 532
|
package io.keepcoding.everpobre.util;
public class Constants {
public static String appName = "io.keepcoding.everpobre";
public static String intent_key_notebook_id = "io.keepcoding.everpobre.notebook.id";
}
|
dfreniche/Everpobre
|
app/src/main/java/io/keepcoding/everpobre/util/Constants.java
|
Java
|
mit
| 219
|
Package.describe({
summary: "Sentinel role based authorization."
});
Package.on_use(function (api) {
var both = ['client', 'server'];
api.use(['coffeescript', 'underscore', 'accounts-base'], both);
api.add_files('sentinel.litcoffee', both);
api.export && api.export('Sentinel');
});
|
ai10/sentinel-meteor
|
package.js
|
JavaScript
|
mit
| 315
|
//
// Created by Neo on 16/9/13.
//
#ifndef RAYTRACING_CL_GRADIENT_H
#define RAYTRACING_CL_GRADIENT_H
#include <string>
#include "cl_utils/context.h"
#include "cl_utils/kernel.h"
#include "volume_data.h"
class CLGradient {
public:
CLGradient(std::string kernel_path,
std::string kernel_name,
cl_utils::Context *cl_context);
~CLGradient();
void Init(VolumeData &volume_data);
void Compute();
unsigned char* volume_gradient;
private:
size_t global_work_size[3];
cl_utils::Context *context_;
cl_kernel kernel_;
cl_mem volume_raw_;
cl_mem volume_gradient_;
};
#endif //RAYTRACING_CL_GRADIENT_H
|
theNded/RayTracing
|
include/cl_gradient.h
|
C
|
mit
| 705
|
/*
*
* ToolPage reducer
*
*/
import { fromJS } from 'immutable';
import {
DEFAULT_ACTION,
REAL_WORLD_EXAMPLE,
CONTRIBUTED_BY,
LEARN_MORE,
SET_CHOSEN_SECTION,
RESET_TOOL_STATE,
SET_EXPAND_ALL
} from './constants';
const initialState = fromJS({
expandAll: false,
chosenSection: REAL_WORLD_EXAMPLE,
});
function toolPageReducer(state = initialState, action) {
switch (action.type) {
case DEFAULT_ACTION:
return state;
case RESET_TOOL_STATE:
return initialState;
case SET_CHOSEN_SECTION:
return state.set('chosenSection', action.chosenSection);
case SET_EXPAND_ALL:
return state.set('expandAll', action.isExpandAll);
default:
return state;
}
}
export default toolPageReducer;
|
BeautifulTrouble/beautifulrising-client
|
app/containers/ToolPage/reducer.js
|
JavaScript
|
mit
| 752
|
'use strict';
const DateRange = require('../../../api/lib/DateRange');
const moment = require('moment');
describe('DateRange', () => {
describe('constructor', () => {
it('should assign properties correctly', () => {
var from = new Date();
var to = new Date();
var result = new DateRange(from, to);
expect(result).to.have.property('from', from);
expect(result).to.have.property('to', to);
});
});
describe('contains', () => {
it('should return true if the date falls within the date range', () => {
var date = new Date();
var from = moment(date).subtract(1, 'second').toDate();
var to = moment(date).add(1, 'second').toDate();
var dateRange = new DateRange(from, to);
expect(dateRange.contains(date)).to.equal(true);
expect(dateRange.contains(from)).to.equal(true);
expect(dateRange.contains(to)).to.equal(true);
});
it('should return false if the date falls outside the date range', () => {
var date = new Date();
var from = moment(date).subtract(1, 'second').toDate();
var to = moment(date).add(1, 'second').toDate();
var dateRange = new DateRange(from, to);
expect(dateRange.contains(moment(from).subtract(1, 'second').toDate())).to.equal(false);
expect(dateRange.contains(moment(to).add(1, 'second').toDate())).to.equal(false);
});
});
describe('widen', () => {
it('should return a DateRange from the earliest point, to the latest point of n DateRanges', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04'));
const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06'));
const result = DateRange.widen(r3,r2,r1);
expect(result.from).to.equal(r1.from);
expect(result.to).to.equal(r3.to);
});
it('should return the same result regardless of argument order', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04'));
const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06'));
const result = DateRange.widen(r3,r2,r1);
const result2 = DateRange.widen(r1,r3,r2);
expect(result.from).to.equal(result2.from);
expect(result.to).to.equal(result2.to);
});
it('should work with overlapping ranges', () => {
const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02'));
const r2 = new DateRange(new Date('2015/12/03'), new Date('2016/01/02'));
const r3 = new DateRange(new Date('2016/01/01'), new Date('2016/02/06'));
const result = DateRange.widen(r3,r2,r1);
expect(result.from).to.equal(r2.from);
expect(result.to).to.equal(r3.to);
});
});
});
|
UKHomeOffice/removals_integration
|
test/unit/lib/DateRange.test.js
|
JavaScript
|
mit
| 2,871
|
/*!@addtogroup other
* @{
* @defgroup holitdata HDS Motor MUX
* Holit Data Systems Motor MUX
* @{
*/
#ifndef __HDMMUX_H__
#define __HDMMUX_H__
/** \file holitdata-motormux.h
* \brief Holit Data Systems Motor MUX driver
*
* holitdata-motormux.h provides an API for the Holit Data Systems Motor MUX.
*
* Changelog:
* - 0.1: Initial release
* - 0.2: Replaced array structs with typedefs\n
* Uses new split off include file MMUX-common.h
*
* Credits:
* - Big thanks to Holit Data Systems for providing me with the hardware necessary to write and test this.
* - Thanks to Cheh from Holit Data Systems for the extensive testing and subsequent bug reports :)
*
* TODO:
* - Add support for multiple MUXes per sensor port
* - Ramping up and down of motors
*
* License: You may use this code as you wish, provided you give credit where its due.
*
* THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 4.10 AND HIGHER
* \author Xander Soldaat (xander_at_botbench.com)
* \date 20 February 2011
* \version 0.2
* \example holitdata-motormux-test1.c
* \example holitdata-motormux-test2.c
*/
#pragma systemFile
#ifndef __COMMON_H__
#include "common.h"
#endif
#ifndef __MMUX_H__
#include "common-MMUX.h"
#endif
// device address - byte 0
#define HDMMUX_I2C_ADDR 0x02 /*!< HDMMUX I2C device address */
// Command type - byte 1
#define HDMMUX_CMD_MOTOR 0x01
#define HDMMUX_CMD_ADDRCHNG 0x02
#define HDMMUX_CMD_RST_TACH_A 0x03
#define HDMMUX_CMD_RST_TACH_B 0x04
#define HDMMUX_CMD_RST_TACH_C 0x05
// motor indicator - byte 2
#define HDMMUX_MOTOR_A 0x01
#define HDMMUX_MOTOR_B 0x02
#define HDMMUX_MOTOR_C 0x03
#define HDMMUX_MOTOR_OTHER 0x04
#define HDMMUX_MOTOR_RIGHT 0x02
#define HDMMUX_MOTOR_LEFT 0x00
// rotation parameters - byte 3
#define HDMMUX_ROT_FORWARD (0x01 << 6)
#define HDMMUX_ROT_REVERSE (0x02 << 6)
#define HDMMUX_ROT_STOP (0x03 << 6)
#define HDMMUX_ROT_CONSTSPEED (0x01 << 4)
#define HDMMUX_ROT_RAMPUP (0x02 << 4)
#define HDMMUX_ROT_RAMPDOWN (0x03 << 4)
#define HDMMUX_ROT_UNLIMITED (0x00 << 2)
#define HDMMUX_ROT_DEGREES (0x01 << 2)
#define HDMMUX_ROT_ROTATIONS (0x02 << 2)
#define HDMMUX_ROT_SECONDS (0x03 << 2)
#define HDMMUX_ROT_POWERCONTROL (0x01 << 1)
#define HDMMUX_ROT_BRAKE 0x01
#define HDMMUX_ROT_FLOAT 0x00
tByteArray HDMMUX_I2CRequest; /*!< Array to hold I2C command data */
tByteArray HDMMUX_I2CReply; /*!< Array to hold I2C reply data */
// Function prototypes
void HDMMUXinit();
bool HDMMUXreadStatus(tSensors link, ubyte &motorStatus, long &tachoA, long &tachoB, long &tachoC);
bool HDMMUXsendCommand(tSensors link, ubyte mode, ubyte channel, ubyte rotparams, long duration, byte power, byte steering);
bool HDMMotor(tMUXmotor muxmotor, byte power);
bool HDMotorStop(tMUXmotor muxmotor);
bool HDMotorStop(tMUXmotor muxmotor, bool brake);
void HDMMotorSetRotationTarget(tMUXmotor muxmotor, float rottarget);
void HDMMotorSetTimeTarget(tMUXmotor muxmotor, float timetarget);
void HDMMotorSetEncoderTarget(tMUXmotor muxmotor, long enctarget);
long HDMMotorEncoder(tMUXmotor muxmotor);
bool HDMMotorEncoderReset(tMUXmotor muxmotor);
bool HDMMotorEncoderResetAll(tSensors link);
bool HDMMotorBusy(tMUXmotor muxmotor);
void HDMMotorSetBrake(tMUXmotor muxmotor);
void HDMMotorSetFloat(tMUXmotor muxmotor);
void HDMMotorSetSpeedCtrl(tMUXmotor muxmotor, bool constspeed);
void HDMMotorSetRamping(tMUXmotor muxmotor, ubyte ramping);
/*
* Initialise the mmuxData array needed for keeping track of motor settings
*/
void HDMMUXinit(){
for (short i = 0; i < 4; i++) {
memset(mmuxData[i].runToTarget[0], false, 4);
memset(mmuxData[i].brake[0], true, 4);
memset(mmuxData[i].pidcontrol[0], true, 4);
memset(mmuxData[i].target[0], 0, 4*4);
memset(mmuxData[i].ramping[0], HDMMUX_ROT_CONSTSPEED, 4);
memset(mmuxData[i].targetUnit[0], HDMMUX_ROT_UNLIMITED, 4);
mmuxData[i].initialised = true;
}
}
/**
* Read the status of the motors and tacho counts of the MMUX
*
* motorStatus is made of 3 bits, 1: motor is running, 0: motor is idle\n
* bit 0: motor A\n
* bit 1: motor B\n
* bit 2: motor C\n
*
* @param link the MMUX port number
* @param motorStatus status of the motors
* @param tachoA Tacho count for motor A
* @param tachoB Tacho count for motor B
* @param tachoC Tacho count for motor C
* @return true if no error occured, false if it did
*/
bool HDMMUXreadStatus(tSensors link, ubyte &motorStatus, long &tachoA, long &tachoB, long &tachoC) {
memset(HDMMUX_I2CRequest, 0, sizeof(tByteArray));
HDMMUX_I2CRequest[0] = 10; // Message size
HDMMUX_I2CRequest[1] = HDMMUX_I2C_ADDR; // I2C Address
if (!writeI2C(link, HDMMUX_I2CRequest, HDMMUX_I2CReply, 13))
return false;
motorStatus = HDMMUX_I2CReply[0];
// Assemble and assign the encoder values
tachoA = (HDMMUX_I2CReply[1] << 24) + (HDMMUX_I2CReply[2] << 16) + (HDMMUX_I2CReply[3] << 8) + (HDMMUX_I2CReply[4] << 0);
tachoB = (HDMMUX_I2CReply[5] << 24) + (HDMMUX_I2CReply[6] << 16) + (HDMMUX_I2CReply[7] << 8) + (HDMMUX_I2CReply[8] << 0);
tachoC = (HDMMUX_I2CReply[9] << 24) + (HDMMUX_I2CReply[10] << 16) + (HDMMUX_I2CReply[11] << 8) + (HDMMUX_I2CReply[12] << 0);
return true;
}
/**
* Send a command to the MMUX.
*
* Note: this is an internal function and shouldn't be used directly
* @param link the MMUX port number
* @param mode the mode the MMX should operate in, controlling motors, resetting tachos or settings new address
* @param channel the motors the command applies to
* @param rotparams the additional parameters that make up the command
* @param duration the number of units (can be seconds, rotations or degrees) the command should be run for
* @param power the amount of power to be applied to the motor(s)
* @param steering used for syncronised movement to control the amount of steering
* @return true if no error occured, false if it did
*/
bool HDMMUXsendCommand(tSensors link, ubyte mode, ubyte channel, ubyte rotparams, long duration, byte power, byte steering) {
memset(HDMMUX_I2CRequest, 0, sizeof(tByteArray));
HDMMUX_I2CRequest[0] = 10; // Message size
HDMMUX_I2CRequest[1] = HDMMUX_I2C_ADDR; // I2C Address
HDMMUX_I2CRequest[2] = mode;
HDMMUX_I2CRequest[3] = channel;
HDMMUX_I2CRequest[4] = rotparams;
HDMMUX_I2CRequest[5] = (duration >> 24) & 0xFF;
HDMMUX_I2CRequest[6] = (duration >> 16) & 0xFF;
HDMMUX_I2CRequest[7] = (duration >> 8) & 0xFF;
HDMMUX_I2CRequest[8] = (duration >> 0) & 0xFF;
HDMMUX_I2CRequest[9] = power;
HDMMUX_I2CRequest[10] = (byte)(steering & 0xFF);
return writeI2C(link, HDMMUX_I2CRequest);
}
/**
* Run motor with specified speed.
*
* @param muxmotor the motor-MUX motor
* @param power power the amount of power to apply to the motor, value between -100 and +100
* @return true if no error occured, false if it did
*/
bool HDMMotor(tMUXmotor muxmotor, byte power) {
ubyte command = 0;
bool retval = true;
long target = mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)];
command |= (mmuxData[SPORT(muxmotor)].brake[MPORT(muxmotor)]) ? HDMMUX_ROT_BRAKE : HDMMUX_ROT_FLOAT;
command |= mmuxData[SPORT(muxmotor)].ramping[MPORT(muxmotor)];
command |= (mmuxData[SPORT(muxmotor)].pidcontrol[MPORT(muxmotor)]) ? HDMMUX_ROT_POWERCONTROL : 0;
command |= (power > 0) ? HDMMUX_ROT_FORWARD : HDMMUX_ROT_REVERSE;
command |= mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)];
retval = HDMMUXsendCommand((tSensors)SPORT(muxmotor), HDMMUX_CMD_MOTOR, (ubyte)MPORT(muxmotor) + 1, command, target, abs(power), 0);
// Reset the data
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_UNLIMITED;
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = 0;
return retval;
}
/**
* Stop the motor. Uses the brake method specified with HDMMotorSetBrake or HDMMotorSetFloat.
* The default is to use braking.
*
* @param muxmotor the motor-MUX motor
* @return true if no error occured, false if it did
*/
bool HDMotorStop(tMUXmotor muxmotor) {
ubyte command = 0;
bool retval = true;
command |= (mmuxData[SPORT(muxmotor)].brake[MPORT(muxmotor)]) ? HDMMUX_ROT_BRAKE : HDMMUX_ROT_FLOAT;
command |= HDMMUX_ROT_STOP;
retval = HDMMUXsendCommand((tSensors)SPORT(muxmotor), HDMMUX_CMD_MOTOR, (ubyte)MPORT(muxmotor) + 1, command, 0, 0, 0);
// Reset the data
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_UNLIMITED;
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = 0;
return retval;
}
/**
* Stop the motor. This function overrides the preconfigured braking method.
*
* @param muxmotor the motor-MUX motor
* @param brake when set to true: use brake, false: use float
* @return true if no error occured, false if it did
*/
bool HDMotorStop(tMUXmotor muxmotor, bool brake) {
ubyte command = 0;
bool retval = true;
command |= (brake) ? HDMMUX_ROT_BRAKE : HDMMUX_ROT_FLOAT;
command |= HDMMUX_ROT_STOP;
retval = HDMMUXsendCommand((tSensors)SPORT(muxmotor), HDMMUX_CMD_MOTOR, (ubyte)MPORT(muxmotor) + 1, command, 0, 0, 0);
// Reset the data
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_UNLIMITED;
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = 0;
return retval;
}
/**
* Set rotation target for specified mux motor. Rotations can be specified in
* increments of 0.01. To rotate the motor 10.54 degrees, specify a value of 10.54.
*
* @param muxmotor the motor-MUX motor
* @param rottarget the rotation target value
* @return true if no error occured, false if it did
*/
void HDMMotorSetRotationTarget(tMUXmotor muxmotor, float rottarget) {
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = (long)(rottarget * 100);
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_ROTATIONS;
}
/**
* Set time target for specified mux motor. Seconds can be specified in
* increments of 0.01. To rotate the motor for 10.21 seconds, specify a value of 10.21.
*
* @param muxmotor the motor-MUX motor
* @param timetarget the time target value in seconds.
* @return true if no error occured, false if it did
*/
void HDMMotorSetTimeTarget(tMUXmotor muxmotor, float timetarget) {
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = (long)(timetarget * 100);
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_SECONDS;
}
/**
* Set encoder target for specified mux motor.
*
* @param muxmotor the motor-MUX motor
* @param enctarget the encoder target value in degrees.
* @return true if no error occured, false if it did
*/
void HDMMotorSetEncoderTarget(tMUXmotor muxmotor, long enctarget) {
mmuxData[SPORT(muxmotor)].target[MPORT(muxmotor)] = enctarget;
mmuxData[SPORT(muxmotor)].targetUnit[MPORT(muxmotor)] = HDMMUX_ROT_DEGREES;
}
/**
* Fetch the current encoder value for specified motor channel
*
* @param muxmotor the motor-MUX motor
* @return the current value of the encoder
*/
long HDMMotorEncoder(tMUXmotor muxmotor) {
long encA = 0;
long encB = 0;
long encC = 0;
ubyte dummy = 0;
HDMMUXreadStatus((tSensors)SPORT(muxmotor), dummy, encA, encB, encC);
switch ((ubyte)MPORT(muxmotor)) {
case 0: return encA;
case 1: return encB;
case 2: return encC;
}
return 0;
}
/**
* Reset target encoder for specified motor channel, use only at
* the start of your program. If you are using the standard NXT wheels
* you will not run into problems with a wrap-around for the first 500kms
* or so.
*
* @param muxmotor the motor-MUX motor
* @return true if no error occured, false if it did
*/
bool HDMMotorEncoderReset(tMUXmotor muxmotor) {
ubyte mode = 0;
switch ((ubyte)MPORT(muxmotor)) {
case 0: mode = HDMMUX_CMD_RST_TACH_A; break;
case 1: mode = HDMMUX_CMD_RST_TACH_B; break;
case 2: mode = HDMMUX_CMD_RST_TACH_C; break;
}
return HDMMUXsendCommand((tSensors)SPORT(muxmotor), mode, 0, 0, 0, 0, 0);
}
/**
* Reset all encoders on the specified motor-MUX. Use only at
* the start of your program. If you are using the standard NXT wheels
* you will not run into problems with a wrap-around for the first 500kms
* or so.
*
* @param link the MMUX port number
* @return true if no error occured, false if it did
*/
bool HDMMotorEncoderResetAll(tSensors link) {
if (!HDMMUXsendCommand(link, HDMMUX_CMD_RST_TACH_A, 0, 0, 0, 0, 0))
return false;
if (!HDMMUXsendCommand(link, HDMMUX_CMD_RST_TACH_B, 0, 0, 0, 0, 0))
return false;
if (!HDMMUXsendCommand(link, HDMMUX_CMD_RST_TACH_C, 0, 0, 0, 0, 0))
return false;
return true;
}
/**
* Check if the specified motor is running or not.
*
* @param muxmotor the motor-MUX motor
* @return true if the motor is still running, false if it's idle
*/
bool HDMMotorBusy(tMUXmotor muxmotor) {
long dummy = 0;
ubyte motorStatus = 0;
HDMMUXreadStatus((tSensors)SPORT(muxmotor), motorStatus, dummy, dummy, dummy);
switch ((ubyte)MPORT(muxmotor)) {
case 0: return ((motorStatus & 0x01) == 0x01);
case 1: return ((motorStatus & 0x02) == 0x02);
case 2: return ((motorStatus & 0x04) == 0x04);
}
return true;
}
/**
* Set the stopping method for the specified motor to brake.
*
* @param muxmotor the motor-MUX motor
*/
void HDMMotorSetBrake(tMUXmotor muxmotor) {
mmuxData[SPORT(muxmotor)].brake[MPORT(muxmotor)] = true;
}
/**
* Set the stopping method for the specified motor to float.
*
* @param muxmotor the motor-MUX motor
*/
void HDMMotorSetFloat(tMUXmotor muxmotor) {
mmuxData[SPORT(muxmotor)].brake[MPORT(muxmotor)] = false;
}
/**
* Set the motor speed control for the specified motor.
*
* @param muxmotor the motor-MUX motor
* @param constspeed whether or not to use speed control
*/
void HDMMotorSetSpeedCtrl(tMUXmotor muxmotor, bool constspeed) {
mmuxData[SPORT(muxmotor)].pidcontrol[MPORT(muxmotor)] = true;
}
/**
* Set the motor ramping type the specified motor.
* ramping can be one of\n
* - HDMMUX_ROT_CONSTSPEED
* - HDMMUX_ROT_RAMPUP
* - HDMMUX_ROT_RAMPDOWN
*
* @param muxmotor the motor-MUX motor
* @param ramping the type of ramping to be used
*/
void HDMMotorSetRamping(tMUXmotor muxmotor, ubyte ramping) {
mmuxData[SPORT(muxmotor)].ramping[MPORT(muxmotor)] = ramping;
}
#endif // __HDMMUX_H__
/* @} */
/* @} */
|
dlacres/GeekMyBot
|
RobotC/include/holitdata-motormux.h
|
C
|
mit
| 14,314
|
-- boundary3.test
--
-- db eval {
-- SELECT t2.a FROM t2 NATURAL JOIN t1
-- WHERE t1.rowid <= 36028797018963967 ORDER BY t1.a DESC
-- }
SELECT t2.a FROM t2 NATURAL JOIN t1
WHERE t1.rowid <= 36028797018963967 ORDER BY t1.a DESC
|
bkiers/sqlite-parser
|
src/test/resources/boundary3.test_1683.sql
|
SQL
|
mit
| 236
|
"""
@file
@brief Buffer as a logging function.
"""
from io import StringIO
class BufferedPrint:
"""
Buffered display. Relies on :epkg:`*py:io:StringIO`.
Use it as follows:
.. runpython::
:showcode:
def do_something(fLOG=None):
if fLOG:
fLOG("Did something.")
return 3
from pyquickhelper.loghelper import BufferedPrint
buf = BufferedPrint()
do_something(fLOG=buf.fprint)
print(buf)
"""
def __init__(self):
"constructor"
self.buffer = StringIO()
def fprint(self, *args, **kwargs):
"print function"
mes = " ".join(str(_) for _ in args)
self.buffer.write(mes)
self.buffer.write("\n")
def __str__(self):
"Returns the content."
return self.buffer.getvalue()
|
sdpython/pyquickhelper
|
src/pyquickhelper/loghelper/buffered_flog.py
|
Python
|
mit
| 844
|
# Webpage
Webpage object contains the rules of webpage to be excluded.
### Service
+ [CampaignWebpageService](../../services/CampaignWebpageService.md)
### Namespace
[CampaignWebpageService#Namespace](../../services/CampaignWebpageService.md#namespace)
| Field | Type | Description | response | add | remove
|---|---|---|---|---|---|
|targetId | xsd:long | Unique ID for each webpage | yes | Ignore | Requirement
|targetTrackId | xsd:long | Unique tracking ID for each Webpage | yes | Ignore | Ignore
|parameter | [WebpageParameter](./WebpageParameter.md) | Rules of excluded settings | yes | Requirement | Ignore
<a rel="license" href="http://creativecommons.org/licenses/by-nd/2.1/jp/"><img alt="クリエイティブ・コモンズ・ライセンス" style="border-width:0" src="https://i.creativecommons.org/l/by-nd/2.1/jp/88x31.png" /></a><br />この 作品 は <a rel="license" href="http://creativecommons.org/licenses/by-nd/2.1/jp/">クリエイティブ・コモンズ 表示 - 改変禁止 2.1 日本 ライセンスの下に提供されています。</a>
|
yahoojp-marketing/sponsored-search-api-documents
|
docs/en/api_reference/data/CampaignWebpage/Webpage.md
|
Markdown
|
mit
| 1,074
|
package premailer
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestBasicHTMLFromFile(t *testing.T) {
p, err := NewPremailerFromFile("data/markup_test.html", nil)
assert.Nil(t, err)
resultHTML, err := p.Transform()
assert.Nil(t, err)
assert.Contains(t, resultHTML, "<h1 style=\"width:50px;color:red\" width=\"50\">Hi!</h1>")
assert.Contains(t, resultHTML, "<h2 style=\"vertical-align:top\">There</h2>")
assert.Contains(t, resultHTML, "<h3 style=\"text-align:right\">Hello</h3>")
assert.Contains(t, resultHTML, "<p><strong style=\"text-decoration:none\">Yes!</strong></p>")
assert.Contains(t, resultHTML, "<div style=\"background-color:green\">Green color</div>")
}
func TestFromFileNotFound(t *testing.T) {
p, err := NewPremailerFromFile("data/blablabla.html", nil)
assert.NotNil(t, err)
assert.Nil(t, p)
}
|
vanng822/go-premailer
|
premailer/premailer_from_file_test.go
|
GO
|
mit
| 843
|
<div class="content">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="content">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#detail" aria-controls="1" role="tab" data-toggle="tab">Detail</a></li>
<li role="presentation"><a href="#image" aria-controls="2" role="tab" data-toggle="tab">Gambar</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="detail">
<br>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nama Produk</label>
<input type="text" class="form-control border-input" id="name" value="<?=$records->name?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Kategori</label>
<select id="pc_option" class="form-control border-input">
<?php
if(isset($pc_options)){
foreach($pc_options as $opt)
{
if($opt->id == $records->product_category_id){
echo "<option value=".$opt->id." selected>".$opt->name."</option>";
} else {
echo "<option value=".$opt->id." >".$opt->name."</option>";
}
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Merchant</label>
<select id="merchant_option" class="form-control border-input">
<?php
if(isset($mc_options)){
foreach($mc_options as $opt)
{
if($opt->id == $records->merchant_id){
echo "<option value=".$opt->id." selected>".$opt->name."</option>";
} else {
echo "<option value=".$opt->id.">".$opt->name."</option>";
}
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Harga Produk</label>
<input type="number" class="form-control border-input" id="price" value="<?=$records->price?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Satuan Produk (ex : per kg, per m)</label>
<input type="text" class="form-control border-input" id="dimension" value="<?=$records->dimension?>" placeholder="kg,ons,m,pcs,biji,buah">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Deskripsi</label>
<textarea class="form-control border-input" id="desc"><?=$records->description?></textarea>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="image">
<br>
<div class="row">
<?php
foreach($old_img as $img){
if($img['sort'] == '0'){
?>
<div class="col-md-12">
<div class="form-group">
<label>Gambar Utama</label>
<div class="row">
<div class="col-md-4">
<input type="file" accept="image/*" class="" name="utama" onchange="load_utama(event)" id="utama">
</div>
<div class="col-md-8">
<button class="btn btn-sm pull-left" onclick="delete_img_utama()"><i class="fa fa-trash" title="hapus"></i></button>
</div>
</div>
<input type="hidden" id="utama_old" value='<?= $img['name'] ?>'>
<input type="hidden" id="utama_new" value=''>
<br>
<img id="output_utama" style="width:40%;height:50%" class="img img-thumbnail" src="<?=base_url().$img['url']?>"/>
<br><br>
<script>
var load_utama = function (event) {
var output_utama = document.getElementById('output_utama');
output_utama.src = URL.createObjectURL(event.target.files[0]);
$('#utama_new').val(event.target.files[0].name);
};
var delete_img_utama = function () {
var old = $('#utama_old').val();
$(".end").append("<input type='hidden' class='to_delete' value="+old+">");
output_utama.src = '<?=base_url().NO_IMG?>';
$('#utama_old').val('');
$('#utama_new').val('');
$('#utama').val('');
};
</script>
</div>
</div>
<?php
} else {
$sort = $img['sort'];
?>
<div class="col-md-6">
<div class="form-group">
<label>Gambar <?=$sort?></label>
<div class="row">
<div class="col-md-4">
<input type="file" accept="image/*" class="" name="img_<?=$sort?>" onchange="load_img_<?=$sort?>(event)" id="img_<?=$sort?>">
</div>
<div class="col-md-8">
<button class="btn btn-sm pull-left" onclick="delete_img_<?=$sort?>()"><i class="fa fa-trash" title="hapus"></i></button>
</div>
</div>
<input type="hidden" id="img_<?=$sort?>_old" value='<?= $img['name'] ?>'>
<input type="hidden" id="img_<?=$sort?>_new" value=''>
<br>
<img id="output_img_<?=$sort?>" style="width:80%;height:50%" class="img img-thumbnail" src="<?= base_url().$img['url']?>"/>
<br><br>
<script>
var load_img_<?=$sort?> = function (event) {
var output_img_<?=$sort?> = document.getElementById('output_img_<?=$sort?>');
output_img_<?=$sort?>.src = URL.createObjectURL(event.target.files[0]);
$('#img_<?=$sort?>_new').val(event.target.files[0].name);
};
var delete_img_<?=$sort?> = function () {
var old = $('#img_<?=$sort?>_old').val();
$(".end").append("<input type='hidden' class='to_delete' value="+old+">");
output_img_<?=$sort?>.src = '<?=base_url().NO_IMG?>';
$('#img_<?=$sort?>_new').val('');
$('#img_<?=$sort?>').val('');
};
</script>
</div>
</div>
<?php
} }
?>
</div>
</div>
</div>
<div class="row end">
<div class="col-md-6">
<div class="text-left">
<a href="<?=base_url().'admin/product/'?>" class="btn btn-warning btn-fill btn-wd" onclick="">Kembali</a>
</div>
</div>
<input type="hidden" class="form-control border-input" id="edit_id" value="<?=$records->id?>">
<input type="hidden" class="form-control border-input" id="merchant_last_id" value="<?=$records->merchant_id?>">
<div class="col-md-6">
<div class="text-right">
<button class="btn btn-info btn-fill btn-wd" onclick="Put()">Simpan</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
toriqpriad/depousaha
|
application/views/admin/product/detail.php
|
PHP
|
mit
| 8,514
|
package xrest
type Plugger interface {
Plug(Handler) Handler
}
|
AlexanderChen1989/xrest
|
plug.go
|
GO
|
mit
| 65
|
class PowerAttribute < ActiveRecord::Base
belongs_to :power
end
|
Gonozal/Character-Sheet
|
app/models/power_attribute.rb
|
Ruby
|
mit
| 66
|
from django.contrib import admin
from bananas.apps.appointment.forms import AppointmentForm
from bananas.apps.appointment.models import Appointment
from bananas.apps.appointment.models import AppointmentType
@admin.register(Appointment)
class AppointmentAdmin(admin.ModelAdmin):
list_display = (
'time',
'client_name',
'client_phone',
'client_email',
'appointment_type_name',
'counselor_name'
)
search_fields = (
'time',
'client_first_name',
'client_last_name',
'client_email',
'client_phone',
'appointment_type__name',
'counselor__first_name',
'counselor__last_name',
'counselor__email',
'counselor__phone',
)
list_filter = ('time', )
form = AppointmentForm
def get_queryset(self, request):
queryset = super(AppointmentAdmin, self).get_queryset(request)
return queryset.filter(deleted=False)
def client_name(self, obj):
return "{} {}".format(
obj.client_first_name, obj.client_last_name)
def counselor_name(self, obj):
return "{} {}".format(
obj.counselor.first_name, obj.counselor.last_name)
def appointment_type_name(self, obj):
return obj.appointment_type.name
client_name.short_description = 'Client'
counselor_name.short_description = 'Counselor'
appointment_type_name.short_description = 'Appointment type'
@admin.register(AppointmentType)
class AppointmentTypeAdmin(admin.ModelAdmin):
list_display = (
'name',
'appointment_count',
'message_template_count'
)
search_fields = (
'name',
)
def appointment_count(self, obj):
return obj.appointments.all().count()
def message_template_count(self, obj):
return obj.message_templates.all().count()
|
tmcdonnell87/bananas
|
bananas/apps/appointment/admin.py
|
Python
|
mit
| 1,876
|
# ExtensionClassContainerImpl1map
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ioPeriodjenkinsPeriodblueoceanPeriodservicePeriodembeddedPeriodrestPeriodPipelineImpl** | [**ExtensionClassImpl**](ExtensionClassImpl.md) | | [optional] [default to null]
**ioPeriodjenkinsPeriodblueoceanPeriodservicePeriodembeddedPeriodrestPeriodMultiBranchPipelineImpl** | [**ExtensionClassImpl**](ExtensionClassImpl.md) | | [optional] [default to null]
**Underscoreclass** | **string** | | [optional] [default to null]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
cliffano/swaggy-jenkins
|
clients/bash/generated/docs/ExtensionClassContainerImpl1map.md
|
Markdown
|
mit
| 735
|
<h1>ESTATÍSTICAS</h1>
<div class="ui piled segment">
<div class="ui huge four statistics">
<div class="statistic">
<div class="value">
22.581
</div>
<div class="label">
POSTS APROVADOS
</div>
</div>
<div class="statistic">
<div class="value">
980
</div>
<div class="label">
POSTS Pendentes
</div>
</div>
<div class="statistic">
<div class="value">
<i class="database icon"></i> 32
</div>
<div class="label">
SOURCES ATIVOS
</div>
</div>
<div class="statistic">
<div class="value">
29/0
</div>
<div class="label">
CLUBES/LIGAS
</div>
</div>
</div>
</div>
<div class="ui piled segment">
<div class="ui huge three statistics">
<div class="statistic">
<div class="value">
<img src="https://zfc.s3.amazonaws.com/production/club/shield/15/2000px-S_C3_ADmbolo_da_Chapecoense_sem_estrelas.svg.png"
class="ui inline image">
2.410
</div>
<div class="label">
MAIS ZUADO
</div>
</div>
<div class="red statistic" style="max-width: 365px;">
<div class="text value">
CORINTHIANS, <br>
SÃO PAULO e GRÊMIO
</div>
<div class="label">
POUCAS ZUEIRAS
</div>
</div>
<div class="statistic" style="max-width: 365px;">
<div class="text value">
COMO É BOM SER COLORADO
</div>
<div class="label">
MUITAS REPROVAÇÕES
</div>
</div>
</div>
</div>
</div>
|
zueirafc/client-app
|
app/resources/components/views/admin/dash.html
|
HTML
|
mit
| 1,626
|
//This snippet is a sample of using a JavaScript client library to access a public API
//require the https module to enable a connection to the https protocol URL of the public API
let http = require('http');
let key = require('./modules/auth.js');
let _key = key;
let location = 'Lagos';
//Use the GET method to send a request to the API which will pass the response to the callback
const request = http.get('http://api.apixu.com/v1/current.json?key='+_key+'&q='+location, function(response){
let weatherData = "";
//console.log(response.statusCode);
//Call a data event that will be used to retrieve the data sent from the API in JSON format to the callback
response.on("data", function(data){
weatherData += data;
if (response.statusCode === 200) {
try{
weatherInfo = JSON.parse(weatherData);
console.log(weatherInfo);
}catch(e){
console.log("We encountered error while processing your request");
}
}else {
console.log("There was an error in your request! Try again later");
}
}).on("error", function(e){
console.error("The API is unavailable");
});
});
request.end();
//check for weather current condition text (current.condition.text)
//weather locaation
|
codefusser/BootcampLOS21HomeSessions
|
Client library_API/weatherapi.js
|
JavaScript
|
mit
| 1,211
|
taskName = "Problem3.DeepCopy";
function Main(bufferElement) {
function createDeepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var copy = obj.constructor();
for (var prop in obj) {
copy[prop] = createDeepCopy(obj[prop]);
}
return copy;
}
var person = {
firstName: 'Pesho',
lastName: 'Peshov',
marks: {
C1: 6,
C2: 6,
COOP: 5,
HTML: 4,
CSS: 6
}
},
copy = createDeepCopy(person);
person.marks.COOP = 4;
WriteLine('Person COOP: ' + person.marks.COOP);
WriteLine('Copy COOP' + copy.marks.COOP);
}
|
DJBuro/Telerik
|
JavaScriptFund/UsingObjects/Problem3.DeepCopy/js/script.js
|
JavaScript
|
mit
| 737
|
--[[
Jamba - Jafula's Awesome Multi-Boxer Assistant
Copyright 2008 - 2015 Michael "Jafula" Miller
License: The MIT License
]]--
local L = LibStub( "AceLocale-3.0" ):NewLocale( "Jamba-Toon", "enUS", true )
L["Slash Commands"] = true
L["Toon: Warnings"] = true
L["Push Settings"] = true
L["Push the toon settings to all characters in the team."] = true
L["Settings received from A."] = function( characterName )
return string.format( "Settings received from %s.", characterName )
end
L["Toon"] = true
L[": "] = true
L["I'm Attacked!"] = true
L["Not Targeting!"] = true
L["Not Focus!"] = true
L["Low Health!"] = true
L["Low Mana!"] = true
L["Merchant"] = true
L["Auto Repair"] = true
L["Auto Repair With Guild Funds"] = true
L["Send Request Message Area"] = true
L["Requests"] = true
L["Auto Deny Duels"] = true
L["Auto Deny Guild Invites"] = true
L["Auto Accept Resurrect Request"] = true
L["Send Request Message Area"] = true
L["Combat"] = true
L["Health / Mana"] = true
L["Bag Space"] = true
L["Bags Full!"] = true
L["Warn If All Regular Bags Are Full"] = true
L["Bags Full Message"] = true
L["Warn If Hit First Time In Combat (Slave)"] = true
L["Hit First Time Message"] = true
L["Warn If Target Not Master On Combat (Slave)"] = true
L["Warn Target Not Master Message"] = true
L["Warn If Focus Not Master On Combat (Slave)"] = true
L["Warn Focus Not Master Message"] = true
L["Warn If My Health Drops Below"] = true
L["Health Amount - Percentage Allowed Before Warning"] = true
L["Warn Health Drop Message"] = true
L["Warn If My Mana Drops Below"] = true
L["Mana Amount - Percentage Allowed Before Warning"] = true
L["Warn Mana Drop Message"] = true
L["Send Warning Area"] = true
L["I refused a guild invite to: X from: Y"] = function( guild, inviter )
return string.format( "I refused a guild invite to: %s from: %s", guild, inviter )
end
L["I refused a duel from: X"] = function( challenger )
return string.format( "I refused a duel from: %s", challenger )
end
L["I do not have enough money to repair all my items."] = true
L["Repairing cost me: X"] = function( costString )
return string.format( "Repairing cost me: %s", costString )
end
L["I am inactive!"] = true
L["Warn If Toon Goes Inactive (PVP)"] = true
L["Inactive Message"] = true
-- Brgin special.
-- This is the inactive buff - you need to make sure it is localized correctly.
-- http://www.wowhead.com/spell=43681
L["Inactive"] = true
-- End special.
L["Currency"] = true
L["Justice Points"] = true
L["JP"] = true
L["Valor Points"] = true
L["VP"] = true
L["Honor Points"] = true
L["HP"] = true
L["Conquest Points"] = true
L["CP"] = true
L["Tol Barad Commendation"] = true
L["TBC"] = true
L["Champion's Seal"] = true
L["CS"] = true
L["Illustrious Jewelcrafter's Token"] = true
L["IJT"] = true
L["Dalaran Jewelcrafting Token"] = true
L["DJT"] = true
L["Ironpaw Token"] = true
L["IT"] = true
L["Epicurean's Award"] = true
L["EA"] = true
L["Lesser Charm of Good Fortune"] = true
L["LCGF"] = true
L["Elder Charm of Good Fortune"] = true
L["ECGF"] = true
L["Mogu Rune Of Fate"] = true
L["MROF"] = true
L["Timeless Coin"] = true
L["TC"] = true
L["Bloody Coin"] = true
L["BC"] = true
L["Warforged Seal"] = true
L["WS"] = true
L["Show Currency"] = true
L["Show the current toon the currency values for all members in the team."] = true
L["Blizzard Tooltip"] = true
L["Blizzard Dialog Background"] = true
L["Curr"] = true
L["Jamba Currency"] = true
L["Update"] = true
L["Gold"] = true
L["Include Gold In Guild Bank"] = true
L["Total"] = true
L["Guild"] = true
L[" ("] = true
L[")"] = true
L["Currency Selection"] = true
L["Scale"] = true
L["Transparency"] = true
L["Border Style"] = true
L["Border Colour"] = true
L["Background"] = true
L["Background Colour"] = true
L["Appearance & Layout"] = true
L["Space For Name"] = true
L["Space For Gold"] = true
L["Space For Points"] = true
L["Space Between Values"] = true
L["Lock Currency List (enables mouse click-through)"] = true
L["Open Currency List On Start Up (Master Only)"] = true
L["Hide Currency"] = true
L["Hide the currency values for all members in the team."] = true
|
Dual-Boxing/Jamba
|
Modules/Jamba-Toon/Locales/JambaToon-Locale-enUS.lua
|
Lua
|
mit
| 4,089
|
using System;
namespace BankAccounts
{
public class Individual : Customer
{
private DateTime dateOfBirth;
private string personalIdNumber;
public DateTime DateOfBirth
{
get
{
return this.dateOfBirth;
}
private set
{
if (!this.IsOfAge(value))
{
throw new ArgumentException("Customer must be atleast 18 year old.");
}
this.dateOfBirth = value;
}
}
private bool IsOfAge(DateTime dateOfBirth)
{
DateTime today = DateTime.Today;
int age = today.Year - dateOfBirth.Year;
if (dateOfBirth > today.AddYears(-age)) age--;
if (age >= 18)
{
return true;
}
return false;
}
public string PersonalIdNumber
{
get
{
return this.personalIdNumber;
}
private set
{
if (this.personalIdNumberIsValid(value))
{
throw new ArgumentException("Invalid personal ID number.");
}
this.personalIdNumber = value;
}
}
private bool personalIdNumberIsValid(string personalIdNumber)
{
if (string.IsNullOrEmpty(personalIdNumber) || personalIdNumber.Length!=10)
{
return false;
}
foreach (var ch in personalIdNumber)
{
if (!char.IsDigit(ch))
{
return false;
}
}
return true;
}
public Gender Gender
{
get;
private set;
}
public Individual(string customerNumber, string name, string persoalIdNumber, DateTime dateOfBirth, Gender gender) :
base(customerNumber, name)
{
this.PersonalIdNumber = persoalIdNumber;
this.DateOfBirth = dateOfBirth;
this.Gender = gender;
}
}
}
|
Redsart/Telerik-Software-Academy
|
C#/OOP/05.OOP-Principles-Part-2/BankAccounts/Individual.cs
|
C#
|
mit
| 2,189
|
/*
* Core Owl Carousel CSS File
*/
.slider-wrapper .owl-wrapper:after {
line-height: 0;
display: block;
visibility: hidden;
clear: both;
height: 0;
content: '.';
}
.slider-wrapper {
position: relative;
display: none;
-ms-touch-action: pan-y;
}
.slider-wrapper .owl-wrapper {
position: relative;
display: none;
-webkit-transform: translate3d(0px, 0px, 0px);
}
.slider-wrapper .owl-wrapper-outer {
position: relative;
overflow: hidden;
width: 100%;
}
.slider-wrapper .owl-wrapper-outer.autoHeight {
-webkit-transition: height 500ms ease-in-out;
-moz-transition: height 500ms ease-in-out;
-ms-transition: height 500ms ease-in-out;
-o-transition: height 500ms ease-in-out;
transition: height 500ms ease-in-out;
}
.slider-wrapper .owl-item {
float: left;
}
.owl-controls .owl-page,
.owl-controls .owl-buttons div {
cursor: pointer;
}
.owl-controls {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-khtml-user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
/* mouse grab icon */
.grabbing {
cursor: url('../../images/grabbing.png') 8 8, move;
}
/* fix */
.slider-wrapper .owl-wrapper,
.slider-wrapper .owl-item {
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
}
/* CSS3 Transitions */
.owl-origin {
-webkit-perspective: 1200px;
-webkit-perspective-origin-x: 50%;
-webkit-perspective-origin-y: 50%;
-moz-perspective: 1200px;
-moz-perspective-origin-x: 50%;
-moz-perspective-origin-y: 50%;
perspective: 1200px;
}
/* fade */
.owl-fade-out {
z-index: 10;
-webkit-animation: fadeOut .7s both ease;
-moz-animation: fadeOut .7s both ease;
animation: fadeOut .7s both ease;
}
.owl-fade-in {
-webkit-animation: fadeIn .7s both ease;
-moz-animation: fadeIn .7s both ease;
animation: fadeIn .7s both ease;
}
/* backSlide */
.owl-backSlide-out {
-webkit-animation: backSlideOut 1s both ease;
-moz-animation: backSlideOut 1s both ease;
animation: backSlideOut 1s both ease;
}
.owl-backSlide-in {
-webkit-animation: backSlideIn 1s both ease;
-moz-animation: backSlideIn 1s both ease;
animation: backSlideIn 1s both ease;
}
/* goDown */
.owl-goDown-out {
-webkit-animation: scaleToFade .7s ease both;
-moz-animation: scaleToFade .7s ease both;
animation: scaleToFade .7s ease both;
}
.owl-goDown-in {
-webkit-animation: goDown .6s ease both;
-moz-animation: goDown .6s ease both;
animation: goDown .6s ease both;
}
/* scaleUp */
.owl-fadeUp-in {
-webkit-animation: scaleUpFrom .5s ease both;
-moz-animation: scaleUpFrom .5s ease both;
animation: scaleUpFrom .5s ease both;
}
.owl-fadeUp-out {
-webkit-animation: scaleUpTo .5s ease both;
-moz-animation: scaleUpTo .5s ease both;
animation: scaleUpTo .5s ease both;
}
/* Keyframes */
/*empty*/
@-webkit-keyframes empty {
0% {
opacity: 1;
}
}
@-moz-keyframes empty {
0% {
opacity: 1;
}
}
@keyframes empty {
0% {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-moz-keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-webkit-keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@-moz-keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@-webkit-keyframes backSlideOut {
25% {
-webkit-transform: translateZ(-500px);
opacity: .5;
}
75% {
-webkit-transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
100% {
-webkit-transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
}
@-moz-keyframes backSlideOut {
25% {
-moz-transform: translateZ(-500px);
opacity: .5;
}
75% {
-moz-transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
100% {
-moz-transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
}
@keyframes backSlideOut {
25% {
transform: translateZ(-500px);
opacity: .5;
}
75% {
transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
100% {
transform: translateZ(-500px) translateX(-200%);
opacity: .5;
}
}
@-webkit-keyframes backSlideIn {
0%, 25% {
-webkit-transform: translateZ(-500px) translateX(200%);
opacity: .5;
}
75% {
-webkit-transform: translateZ(-500px);
opacity: .5;
}
100% {
-webkit-transform: translateZ(0) translateX(0);
opacity: 1;
}
}
@-moz-keyframes backSlideIn {
0%, 25% {
-moz-transform: translateZ(-500px) translateX(200%);
opacity: .5;
}
75% {
-moz-transform: translateZ(-500px);
opacity: .5;
}
100% {
-moz-transform: translateZ(0) translateX(0);
opacity: 1;
}
}
@keyframes backSlideIn {
0%, 25% {
transform: translateZ(-500px) translateX(200%);
opacity: .5;
}
75% {
transform: translateZ(-500px);
opacity: .5;
}
100% {
transform: translateZ(0) translateX(0);
opacity: 1;
}
}
@-webkit-keyframes scaleToFade {
to {
-webkit-transform: scale(.8);
opacity: 0;
}
}
@-moz-keyframes scaleToFade {
to {
-moz-transform: scale(.8);
opacity: 0;
}
}
@keyframes scaleToFade {
to {
transform: scale(.8);
opacity: 0;
}
}
@-webkit-keyframes goDown {
from {
-webkit-transform: translateY(-100%);
}
}
@-moz-keyframes goDown {
from {
-moz-transform: translateY(-100%);
}
}
@keyframes goDown {
from {
transform: translateY(-100%);
}
}
@-webkit-keyframes scaleUpFrom {
from {
-webkit-transform: scale(1.5);
opacity: 0;
}
}
@-moz-keyframes scaleUpFrom {
from {
-moz-transform: scale(1.5);
opacity: 0;
}
}
@keyframes scaleUpFrom {
from {
transform: scale(1.5);
opacity: 0;
}
}
@-webkit-keyframes scaleUpTo {
to {
-webkit-transform: scale(1.5);
opacity: 0;
}
}
@-moz-keyframes scaleUpTo {
to {
-moz-transform: scale(1.5);
opacity: 0;
}
}
@keyframes scaleUpTo {
to {
transform: scale(1.5);
opacity: 0;
}
}
.slider-wrapper .item {
float: left;
}
.owl-controls {
text-align: center;
color: #fff;
}
.owl-controls .owl-buttons .owl-prev {
left: 20px;
right: auto;
}
.owl-controls .owl-buttons .owl-next {
right: 20px;
left: auto;
}
.slider-wrapper .owl-pagination {
position: absolute;
bottom: -35px;
width: 100%;
}
.slider-wrapper .owl-pagination .owl-page span { background:#ccc; }
.carousel-wrapper .owl-pagination {
position: relative;
bottom: -10px;
}
.owl-slider-np .owl-pagination { display:none; }
.owl-controls .owl-buttons div {
display: block;
font-size: 55px;
height: 40px;
line-height: 40px;
width: 30px;
position: absolute;
top: 50%;
margin-top: -20px;
text-align: center;
-moz-opacity:0.60;
filter:alpha(opacity:60);
opacity:0.60;
}
.owl-controls .owl-buttons div:hover {
-moz-opacity:0.80;
filter:alpha(opacity:80);
opacity:0.80;
}
.owl-controls .owl-buttons div i {
height: 40px;
line-height: 40px;
display: block;
width: 30px;
}
.carousel-wrapper .owl-controls .owl-buttons div {
margin-top: -30px;
}
.carousel-wrapper-alt .owl-controls .owl-buttons div {
margin-top: -45px;
}
.carousel-container .owl-controls .owl-buttons .owl-next {
right: -30px;
}
.carousel-container .owl-controls .owl-buttons .owl-prev {
left: -30px;
}
.carousel-wrapper-alt .owl-controls .owl-pagination {
display: none;
}
.arrows-outside.carousel-wrapper .owl-controls .owl-buttons .owl-next {
right: -40px;
}
.arrows-outside.carousel-wrapper .owl-controls .owl-buttons .owl-prev {
left: -40px;
}
.owl-controls .owl-page {
display: inline-block;
zoom: 1;
*display: inline;
}
.owl-controls .owl-page span{
display: block;
width: 12px;
height: 12px;
margin: 0 3px;
filter: Alpha(Opacity=30);
opacity: 0.3;
border-radius: 20px;
background: #fff;
}
.owl-controls .owl-page.active span,
.slider-wrapper .owl-controls.clickable .owl-page:hover span{
filter: Alpha(Opacity=100);
opacity: 1;
}
.owl-controls .owl-page span.owl-numbers{
height: auto;
width: auto;
color: #FFF;
padding: 2px 10px;
font-size: 12px;
border-radius: 30px;
}
.owl-item.loading {
min-height: 150px;
background: url('../../assets/dummy-images/loader.gif') no-repeat center center
}
|
TABuApp/tabu-admin
|
assets/widgets/owlcarousel/owlcarousel.css
|
CSS
|
mit
| 9,307
|
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Carousel Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="../../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="../../css/menu.css" rel="stylesheet">
<link href="../../css/helpScout.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Custom styles for this template -->
</head>
<!-- NAVBAR
================================================== -->
<body>
<div class="o-container">
<!-- Static navbar -->
<nav class="navbar custom-navbar">
<div class="custom-container">
<div class="container-center">
<div class="navbar-header container-center_icon" >
<div class="container-center">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand custom-butten" href="/index.php/helpScout"><img src="../../images/logo1.png"></a>
</div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ><a href="/index.php/helpDesk" class="custom-butten" ><b>Help Desk</b></a></li>
<li><a href="/index.php/emailManagement" class="custom-butten"><b>Email Management</b></a></li>
<li><a href="/index.php/pricing" class="custom-butten"><b>Pricing</b></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle custom-butten" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><b>Content</b> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/index.php/blog" class="custom-butten">Blog</a></li>
<li><a href="/index.php/resources" class="custom-butten">Resources</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle custom-butten" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><b>Get Help</b> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/index.php/getADemo" class="custom-butten">Get a Demo</a></li>
<li><a href="/index.php/helpDocs" class="custom-butten">Help Docs</a></li>
<li><a href="/index.php/contact" class="custom-butten">Contact</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<!--<li class="active"><a href="./">Default <span class="sr-only">(current)</span></a></li>-->
<li><a href="/index.php/logIn" class="custom-butten"><b>Log in</b></a></li>
<li class="btn-padding"><a class="btn btn-primary" href="/index.php/signUp" class="custom-butten"><b>Sign up</b></a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/ .container-center -->
</div><!--/.container-fluid -->
</nav>
|
MerlinWilian/mipagina
|
application/views/template/header.php
|
PHP
|
mit
| 4,408
|
# ElasticSearch Cheat Sheet
## Open ports
9200 - HTTP for JSON
9300 -
GET /_cat/indices?v
## Mapping
curl -XPUT 'http://localhost:9200/user' -d '
{
"mappings": {
"userinfo": {...
}
'
curl -XPUT 'http://localhost:9200/user/_mapping/userinfo' -d '
{
"userinfo" {
...
}
}
'
### New in v. 5.0
Instead of using string type, use `text` for full-text search, and `keyword` for exact match.
In Kibana 5.0, no need to install sense. just use Kibana's DevTools
http://localhost:5601/app/kibana#/dev_tools/console?_g=()
|
ysahnpark/claroforma
|
docs/kb/elasticsearch.md
|
Markdown
|
mit
| 547
|
#pragma once
class Resources
{
public:
Resources(int mineralPatches = 9, int gasGeysers = 1, char race = 't');
void addExpansion(int mineralPatches = 7, int gasGeysers = 1);
int getMinerals() const { return mMinerals; }
int getGas() const { return mGas; }
int getSupply() const { return mSupply; }
int getAvailableSupply() const { return mSupplyMax - mSupply; }
int getSupplyMax() const { return mSupplyMax; }
int getFrame() const { return mFrame; }
int getMineralPatches() const { return mMineralPatches; }
int getGasGeysers() const { return mGasGeysers; }
int getBaseMineRate() const;
char getRace() const { return mRace; }
void clear() { mMinerals = 0; mGas = 0; mSupply = 0; mSupplyMax = 0; mFrame = 0; }
void reset(int mineralPatches = 9, int gasGeysers = 1);
// increment minerals, gas, supply, frame
void addMinerals(int minerals = 8) { mMinerals += minerals; }
void addGas(int gas = 8) { mGas += gas; }
void addSupplyMax(int supply = 8) { mSupplyMax += supply; }
void nextFrame(int frame = 1) { mFrame += frame; }
void setRace(char race = 't') { mRace = race; }
void useMinerals(int minerals) { mMinerals -= minerals; }
void useGas(int gas) { mGas -= gas; }
void useSupply(int supply) { mSupply += supply; }
private:
int mMinerals, mGas, mSupply, mSupplyMax, mFrame;
int mMineralPatches, mGasGeysers;
char mRace;
};
|
olichen/bwbot
|
archive/include/resources.h
|
C
|
mit
| 1,384
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.metricsadvisor.models;
import com.azure.core.annotation.Fluent;
/**
* Describes the additional parameters for the API to list anomalies in an alert.
*/
@Fluent
public final class ListAnomaliesAlertedOptions {
private Integer maxPageSize;
private Integer skip;
/**
* Gets limit indicating the number of items that will be included in a service returned page.
*
* @return The max page size value.
*/
public Integer getMaxPageSize() {
return this.maxPageSize;
}
/**
* Gets the number of items in the queried collection that are to be skipped and not included
* in the returned result.
*
* @return The skip value.
*/
public Integer getSkip() {
return this.skip;
}
/**
* Sets limit indicating the number of items to be included in a service returned page.
*
* @param maxPageSize The max page size value.
* @return The ListAnomaliesAlertedOptions itself.
*/
public ListAnomaliesAlertedOptions setMaxPageSize(Integer maxPageSize) {
this.maxPageSize = maxPageSize;
return this;
}
/**
* Sets the number of items in the queried collection that are to be skipped and not included
* in the returned result.
*
* @param skip The skip value.
* @return ListAnomaliesAlertedOptions itself.
*/
public ListAnomaliesAlertedOptions setSkip(Integer skip) {
this.skip = skip;
return this;
}
}
|
Azure/azure-sdk-for-java
|
sdk/metricsadvisor/azure-ai-metricsadvisor/src/main/java/com/azure/ai/metricsadvisor/models/ListAnomaliesAlertedOptions.java
|
Java
|
mit
| 1,600
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
/** List of supported capabilities persisted on the disk resource for VM use. */
@Fluent
public final class SupportedCapabilities {
/*
* True if the image from which the OS disk is created supports accelerated
* networking.
*/
@JsonProperty(value = "acceleratedNetwork")
private Boolean acceleratedNetwork;
/*
* CPU architecture supported by an OS disk.
*/
@JsonProperty(value = "architecture")
private Architecture architecture;
/**
* Get the acceleratedNetwork property: True if the image from which the OS disk is created supports accelerated
* networking.
*
* @return the acceleratedNetwork value.
*/
public Boolean acceleratedNetwork() {
return this.acceleratedNetwork;
}
/**
* Set the acceleratedNetwork property: True if the image from which the OS disk is created supports accelerated
* networking.
*
* @param acceleratedNetwork the acceleratedNetwork value to set.
* @return the SupportedCapabilities object itself.
*/
public SupportedCapabilities withAcceleratedNetwork(Boolean acceleratedNetwork) {
this.acceleratedNetwork = acceleratedNetwork;
return this;
}
/**
* Get the architecture property: CPU architecture supported by an OS disk.
*
* @return the architecture value.
*/
public Architecture architecture() {
return this.architecture;
}
/**
* Set the architecture property: CPU architecture supported by an OS disk.
*
* @param architecture the architecture value to set.
* @return the SupportedCapabilities object itself.
*/
public SupportedCapabilities withArchitecture(Architecture architecture) {
this.architecture = architecture;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
Azure/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/SupportedCapabilities.java
|
Java
|
mit
| 2,289
|
<html><body>
<h4>Windows 10 x64 (18363.900)</h4><br>
<h2>_WHEAP_ERROR_RECORD_WRAPPER</h2>
<font face="arial"> +0x000 WorkEntry : <a href="./_LIST_ENTRY.html">_LIST_ENTRY</a><br>
+0x010 Length : Uint4B<br>
+0x014 ProcessorNumber : Uint4B<br>
+0x018 Flags : <a href="./_WHEAP_ERROR_RECORD_WRAPPER_FLAGS.html">_WHEAP_ERROR_RECORD_WRAPPER_FLAGS</a><br>
+0x01c InUse : Int4B<br>
+0x020 ErrorSource : Ptr64 <a href="./_WHEAP_ERROR_SOURCE.html">_WHEAP_ERROR_SOURCE</a><br>
+0x028 ErrorRecord : <a href="./_WHEA_ERROR_RECORD.html">_WHEA_ERROR_RECORD</a><br>
</font></body></html>
|
epikcraw/ggool
|
public/Windows 10 x64 (18363.900)/_WHEAP_ERROR_RECORD_WRAPPER.html
|
HTML
|
mit
| 651
|
var HTTP = require("q-io/http");
HTTP.read('http://localhost:1337')
.then(JSON.parse)
.then(function(response) {
console.log(response);
})
.done();
|
Gisonrg/collections
|
nodeschool/promiseit/solution-q/09-fetch-json.js
|
JavaScript
|
mit
| 173
|
# -*- coding: utf-8 -*-
import datetime
import os
#compsiteとcommandをあわせたような形
#ContextがhandlerでCommandが処理
class JobCommand(object):
def execute(self, context):
if context.getCurrentCommand() != 'begin':
raise Exception('illegal command ' + str(context.getCurrentCommand()))
command_list = CommandListCommand()
command_list.execute(context.next())
class CommandListCommand(object):
def execute(self, context):
while (True):
current_command = context.getCurrentCommand()
if current_command is None:
raise Exception('"end" not found ')
elif current_command == 'end':
break
else:
command = CommandCommand()
command.execute(context)
context.next()
class CommandCommand(object):
def execute(self, context):
current_command = context.getCurrentCommand()
if current_command == 'diskspace':
free_size = 100000000.0
max_size = 210000000.0
ratio = free_size / max_size * 100
print( 'Disk Free : %dMB (%.2f%%)' % (free_size / 1024 / 1024, ratio))
elif current_command == 'date':
print datetime.datetime.today().strftime("%Y/%m/%d")
elif current_command == 'line':
print '--------------------'
else:
raise Exception('invalid command [' + str(current_command) + ']')
class Context(object):
def __init__(self, command):
self.commands = []
self.current_index = 0
self.max_index = 0
self.commands = command.strip().split()
print self.commands
self.max_index = len(self.commands)
def next(self):
self.current_index += 1
print self.current_index
return self
def getCurrentCommand(self):
if self.current_index > len(self.commands):
return None
return self.commands[self.current_index].strip()
def execute(command):
job = JobCommand()
try:
job.execute(Context(command))
except Exception, e:
print e.args
if __name__ == '__main__':
command = 'begin date line diskspace end'
if command != '':
execute(command)
|
t10471/python
|
practice/src/design_pattern/Interpreter.py
|
Python
|
mit
| 2,299
|
from copy import copy
import silk.utils.six as six
from silk.singleton import Singleton
def default_permissions(user):
if user:
return user.is_staff
return False
class SilkyConfig(six.with_metaclass(Singleton, object)):
defaults = {
'SILKY_DYNAMIC_PROFILING': [],
'SILKY_IGNORE_PATHS': [],
'SILKY_HIDE_COOKIES': True,
'SILKY_IGNORE_QUERIES': [],
'SILKY_META': False,
'SILKY_AUTHENTICATION': False,
'SILKY_AUTHORISATION': False,
'SILKY_PERMISSIONS': default_permissions,
'SILKY_MAX_REQUEST_BODY_SIZE': -1,
'SILKY_MAX_RESPONSE_BODY_SIZE': -1,
'SILKY_INTERCEPT_PERCENT': 100,
'SILKY_INTERCEPT_FUNC': None,
'SILKY_PYTHON_PROFILER': False,
}
def _setup(self):
from django.conf import settings
options = {option: getattr(settings, option) for option in dir(settings) if option.startswith('SILKY')}
self.attrs = copy(self.defaults)
self.attrs.update(options)
def __init__(self):
super(SilkyConfig, self).__init__()
self._setup()
def __getattr__(self, item):
return self.attrs.get(item, None)
def __setattribute__(self, key, value):
self.attrs[key] = value
|
Alkalit/silk
|
silk/config.py
|
Python
|
mit
| 1,268
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>src\storage\filesystem.js - muskepeer-client</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title="muskepeer-client"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: 0.0.1</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/Computation.html">Computation</a></li>
<li><a href="../classes/Crypto.html">Crypto</a></li>
<li><a href="../classes/Database.html">Database</a></li>
<li><a href="../classes/FileSystem.html">FileSystem</a></li>
<li><a href="../classes/GeoLocation.html">GeoLocation</a></li>
<li><a href="../classes/Job.html">Job</a></li>
<li><a href="../classes/Jobs.html">Jobs</a></li>
<li><a href="../classes/Logger.html">Logger</a></li>
<li><a href="../classes/Mediator.html">Mediator</a></li>
<li><a href="../classes/MuskepeerClient.html">MuskepeerClient</a></li>
<li><a href="../classes/MuskepeerModule.html">MuskepeerModule</a></li>
<li><a href="../classes/Network.html">Network</a></li>
<li><a href="../classes/Node.html">Node</a></li>
<li><a href="../classes/Nodes.html">Nodes</a></li>
<li><a href="../classes/Peer.html">Peer</a></li>
<li><a href="../classes/Peers.html">Peers</a></li>
<li><a href="../classes/Pool.html">Pool</a></li>
<li><a href="../classes/Project.html">Project</a></li>
<li><a href="../classes/Result.html">Result</a></li>
<li><a href="../classes/Results.html">Results</a></li>
<li><a href="../classes/Service.html">Service</a></li>
<li><a href="../classes/Settings.html">Settings</a></li>
<li><a href="../classes/Storage.html">Storage</a></li>
<li><a href="../classes/Uuid.html">Uuid</a></li>
<li><a href="../classes/Worker.html">Worker</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/Computation.html">Computation</a></li>
<li><a href="../modules/Crypto.html">Crypto</a></li>
<li><a href="../modules/Database.html">Database</a></li>
<li><a href="../modules/FileSystem.html">FileSystem</a></li>
<li><a href="../modules/GeoLocation.html">GeoLocation</a></li>
<li><a href="../modules/Jobs.html">Jobs</a></li>
<li><a href="../modules/Logger.html">Logger</a></li>
<li><a href="../modules/Mediator.html">Mediator</a></li>
<li><a href="../modules/MuskepeerClient.html">MuskepeerClient</a></li>
<li><a href="../modules/Network.html">Network</a></li>
<li><a href="../modules/Pool.html">Pool</a></li>
<li><a href="../modules/Project.html">Project</a></li>
<li><a href="../modules/Results.html">Results</a></li>
<li><a href="../modules/Settings.html">Settings</a></li>
<li><a href="../modules/Storage.html">Storage</a></li>
<li><a href="../modules/Uuid.html">Uuid</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: src\storage\filesystem.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
/**
* FileSystem
*
* @module FileSystem
* @class FileSystem
*
* @see http://www.html5rocks.com/de/tutorials/file/filesystem/
* @see https://gist.github.com/robnyman/1894032
* @see https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL
* @see http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-filesystemurls
*
*/
define(['lodash', 'crypto/index', 'q', 'project', 'settings'], function (_, crypto, Q, project, settings) {
/**
* @final
* @property CHUNK_SIZE
* @type {Number}
*/
var CHUNK_SIZE = 512;
var _self,
_db,
_fs;
/**
* Request access to the local fileSystem,
* will cause a user prompt at first attempt
*
* @private
* @method requestFileSystem
* @return {Promise}
*/
function requestFileSystem() {
var deferred = Q.defer();
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, settings.fileStorageSize, deferred.resolve, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
/**
* Request a specific stoage-quota
* will cause a user prompt at first attempt
*
* @private
* @method requestQuota
* @return {Promise}
*/
function requestQuota() {
var deferred = Q.defer();
navigator.webkitPersistentStorage = navigator.webkitPersistentStorage || window.webkitStorageInfo;
navigator.webkitPersistentStorage.requestQuota(settings.fileStorageSize || 50 * 1024 * 1024, deferred.resolve, deferred.reject);
return deferred.promise;
}
/**
* Parse a fileName from an uri
*
* @private
* @method getFileNameFromUri
* @param {String} uri
* @return {String}
*/
function getFileNameFromUri(uri) {
var regex = new RegExp(/[^\\/]+$/);
return uri.match(regex)[0];
}
/**
* Create a directory in filesystem
*
* @private
* @method createSubDirectory
* @param {String} dir
* @return {Promise}
*/
function createSubDirectory(dir) {
var deferred = Q.defer();
_fs.root.getDirectory(dir, {create: true}, deferred.resolve, deferred.reject);
return deferred.promise;
}
/**
*
* @param fileInfo
* @param mode
* @param offset
* @param completeFile
* @returns {Promise}
*/
function readFile(fileInfo, mode, offset, completeFile) {
var deferred = Q.defer();
mode = mode || 'blob';
completeFile = completeFile || false;
_fs.root.getFile(project.uuid + '/' + fileInfo.uuid, {}, function (fileEntry) {
fileEntry.file(function (file) {
var start = offset || 0,
end = start + CHUNK_SIZE,
blob;
// Every file has an end
if (start + CHUNK_SIZE > file.size) {
end = file.size;
}
// Slice that file
if (!completeFile) {
blob = file.slice(start, end);
} else {
blob = file;
}
// Blob Mode, no need for FileReader
if (mode === 'blob') {
deferred.resolve(blob);
}
// Using FileReader
else {
var reader = new FileReader();
reader.onloadend = function (e) {
if (e.target.readyState === FileReader.DONE) {
if (mode === 'dataUrl') {
// Remove data attribute prefix
var chunk = reader.result.match(/,(.*)$/);
if (chunk) {
deferred.resolve(chunk[1]);
} else {
deferred.reject();
}
} else {
deferred.resolve(reader.result);
}
reader = null;
} else {
deferred.reject();
}
};
// DataUrl Mode
if (mode === 'dataUrl') {
reader.readAsDataURL(blob);
// ArrayBuffer Mode
} else if (mode === 'arrayBuffer') {
reader.readAsArrayBuffer(blob);
}
}
}, deferred.reject);
}, deferred.reject);
return deferred.promise;
}
/**
* Gets a file via XHR and returns a promise,
* resolve will contain a Blob
*
* @private
* @method download
*
* @param {Object} file
* @return {Promise}
*
*/
function downloadViaXHR(file) {
var deferred = Q.defer(),
xhr = new XMLHttpRequest(),
data;
xhr.open('GET', file.uri, true);
xhr.responseType = 'blob';
xhr.addEventListener('progress', function (e) {
// Maybe somehow there will already be some chunks in here
if (e.target.response instanceof Blob) {
data = {
blob: e.target.response,
position: e.position,
totalSize: e.totalSize
};
}
else {
// If not at least we can store these info
data = {totalSize: e.totalSize}
}
deferred.notify(data);
});
xhr.addEventListener('load', function (e) {
if (xhr.status === 200) {
data = {
blob: e.target.response,
position: e.position,
totalSize: e.target.response.size
};
deferred.resolve(data);
} else {
deferred.reject('Error downloading file');
}
}, false);
xhr.send();
return deferred.promise;
}
/**
* Updates the list by getting the newest info from db
*
* @private
* @method updateFileList
* @return {Promise}
*/
function updateFileList() {
return _self.getFileList()
.then(function (files) {
_self.list = files;
});
}
/**
* Converts a base64 String to a Blob
*
* @private
* @method base64toBlob
* @see http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
*
* @param {String} base64
* @param {String} [contentType]
*
* @return {Blob}
*/
function base64toBlob(base64, contentType) {
contentType = contentType || '';
var byteCharacters = atob(base64);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += CHUNK_SIZE) {
var slice = byteCharacters.slice(offset, offset + CHUNK_SIZE);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
}
return {
/**
* List of related files in db,
* will always be updated automatically
*
* @property list
* @type {Array}
*/
list: null,
/**
* Initialize fileStorage
*
* @chainable
* @method init
*
* @param db Instance of database submodule
* @return {Object}
*/
init: function (db) {
_self = this;
_db = db;
return requestQuota()
.then(requestFileSystem)
.then(function (fileSystem) {
_fs = fileSystem;
if (!project.uuid) {
logger.error('Filesystem', 'No project uuid set, can not create dir!');
throw Error('Filesystem', 'No project uuid set');
}
return createSubDirectory(project.uuid);
})
.then(function () {
return updateFileList();
});
},
/**
* Write a file/blob to the local filesystem
*
* @method write
*
* @param {Object} fileInfo
* @param {Blob|String} blob or base64-String
* @param {Number} [pos]
*
* @return {Promise}
*/
write: function (fileInfo, blob, pos) {
var deferred = Q.defer(),
writtenBytes = 0,
isNewFile = true;
// Test if we need to convert from base64
if (!blob instanceof Blob) {
blob = base64toBlob(blob);
}
// Does the file exist in database?
_db.read('files', fileInfo.uuid, {uuidIsHash: true})
.then(function (info) {
// Just to make sure, we have data that is up to date
fileInfo = info;
//Is it marked as complete?)
if (!fileInfo || fileInfo.isComplete) {
deferred.reject('File does not exist, or is already complete');
}
writtenBytes = fileInfo.position;
isNewFile = writtenBytes === 0;
// We won't overwrite fileDate
if (pos < writtenBytes) {
deferred.reject('Position is lower than already written bytes!');
}
})
.then(function () {
// Append bytes
_fs.root.getFile(project.uuid + '/' + fileInfo.uuid, {create: isNewFile }, function (fileEntry) {
fileEntry.createWriter(function (writer) {
// Start at given position or EOF
pos = pos || writer.length;
writer.seek(pos);
writer.write(blob);
}, deferred.reject);
}, deferred.reject);
})
.then(function () {
// Update fileInfo in database
var currentPosition = fileInfo.position + blob.size;
return _db.update('files', {uuid: fileInfo.uuid, isComplete: currentPosition >= fileInfo.size, position: currentPosition}, {uuidIsHash: true});
})
.then(updateFileList);
return deferred.promise;
},
/**
* Get a local url to a file in fileSystem
*
* @method readFileAsLocalUrl
* @param {Object} fileInfo
* @return {Promise}
*/
readFileAsLocalUrl: function (fileInfo) {
var deferred = Q.defer();
_fs.root.getFile(project.uuid + '/' + fileInfo.uuid, {}, function (fileEntry) {
deferred.resolve(fileEntry.toURL());
}, deferred.reject);
return deferred.promise;
},
/**
* Get an ObjectUrl to a file from FileSystem
*
* @method readFileAsObjectUrl
* @param {Object} fileInfo
* @return {Promise}
*/
readFileAsObjectUrl: function (fileInfo) {
var deferred = Q.defer();
_fs.root.getFile(project.uuid + '/' + fileInfo.uuid, {}, function (fileEntry) {
fileEntry.file(function (file) {
deferred.resolve(URL.createObjectURL(file));
}, deferred.reject);
}, deferred.reject);
return deferred.promise;
},
/**
* Read some chunks from the file, which will resul in a Blob-Instance.
* Chunk size is defined globally by CHUNK_SIZE.
* Slicing can be disabled using completeFile param.
*
* @method readFileChunkAsBlob
* @param {Object} file
* @param {Number} offset
* @param {Boolean} completeFile
* @return {Promise}
*/
readFileChunkAsBlob: function (file, offset, completeFile) {
return readFile(file, 'blob', offset, completeFile);
},
/**
* Read some chunks from the file, which will be base64 encodded.
* Chunk size is defined globally by CHUNK_SIZE.
* Slicing can be disabled using completeFile param.
*
* @method readFileChunkAsDataUrl
* @param {Object} file
* @param {Number} offset
* @param {Boolean} completeFile
* @return {Promise}
*/
readFileChunkAsDataUrl: function (file, offset, completeFile) {
return readFile(file, 'dataUrl', offset, completeFile);
},
/**
* Read some chunks from the file and return an ArrayBuffer.
* Chunk size is defined globally by CHUNK_SIZE.
* Slicing can be disabled using completeFile param.
*
* @method readFileChunkAsArrayBuffer
* @param {Object} file
* @param {Number} offset
* @param {Boolean} completeFile
* @return {Promise}
*/
readFileChunkAsArrayBuffer: function (file, offset, completeFile) {
return readFile(file, 'arrayBuffer', offset, completeFile);
},
/**
* Add file-entries to the storage database,
* not to the filesystem.
*
* @method add
* @param {Array|String} files
* @return {Promise}
*/
add: function (files) {
var promises = [];
//just a single uri?
if (!_.isArray(files)) {
files = [files];
}
files.forEach(function (file) {
var fileInfo = {
name: file.name || getFileNameFromUri(file.url),
uri: file.url,
size: 0,
position: 0,
type: file.type || 'text/plain',
isComplete: false,
uuid: crypto.hash(file.url)
};
var promise = _db.read('files', fileInfo.uuid, {uuidIsHash: true})
.then(function (result) {
if (!result) {
return _db.save('files', fileInfo, {allowDuplicates: false, uuidIsHash: true});
}
});
promises.push(promise);
});
return Q.all(promises).then(updateFileList);
},
/**
* Get an array of incomplete files from storage-database
*
* @method getListOfIncompleteFiles
* @return {Promise}
*/
getIncompleteFileList: function () {
return _db.findAndReduceByObject('files', {filterDuplicates: false}, {projectUuid: project.uuid, isComplete: false});
},
/**
* Get an array of all files from storage-database
*
* @method getFileList
* @return {Promise}
*/
getFileList: function () {
return _db.findAndReduceByObject('files', {filterDuplicates: false}, {projectUuid: project.uuid});
},
/**
* This will download all incomplete files from their urls.
* Should be used if you know, that there are no other peers in you pool,
* that can deliver the files you need.
*
* @method downloadIncompleteFiles
* @return [Promise}
*/
downloadIncompleteFiles: function () {
// Get incomplete files from database
return this.getIncompleteFileList()
.then(function (files) {
var promises = [];
files.forEach(function (file) {
var deferred = Q.defer();
promises.push(deferred.promise);
downloadViaXHR(file)
.progress(function (data) {
// We gort some chunks
if (data.blob && data.position) {
_db.update('files', {uuid: file.uuid, size: data.totalSize, position: data.position}, {uuidIsHash: true})
.then(function () {
_self.write(file, data.blob, data.position);
});
}
// We only got some info
else {
_db.update('files', {uuid: file.uuid, size: data.totalSize}, {uuidIsHash: true})
}
})
.catch(function (err) {
logger.error('FileSystem', file.uri, 'error during download!');
})
.done(function (data) {
logger.log('FileSystem', file.uri, 'download complete!');
_db.update('files', {uuid: file.uuid, isComplete: true, position: data.blob.size, size: data.blob.size}, {uuidIsHash: true});
_self.write(file, data.blob).then(updateFileList);
deferred.resolve();
});
});
return Q.all(promises);
});
},
/**
* Retrieve a filInfo object from storage (db) by uuid (hash).
*
* @method getFileInfoByUuid
*
* @param uuid
* @return {Object}
*/
getFileInfoByUuid: function (uuid) {
return _db.read('files', uuid, {uuidIsHash: true});
},
/**
* Retrieve a fileInfo object from storage by url.
*
* @method getFileInfoByUri
*
* @param uri
* @return {Array} can be multiple files
*/
getFileInfoByUri: function (uri) {
return _db.findAndReduceByObject('files', {}, {uri: uri});
},
/**
* etrieve a fileInfo object from storage by name.
*
* @param name
* @return {Array}
*/
getFileInfoByName: function (name) {
return _db.findAndReduceByObject('files', {}, {name: name});
},
/**
* Will delete all files/folders inside the project-dir recursively
* as well as the references (fileInfo) in database
*
* @method clear
* @return {Promise}
*/
clear: function () {
var deferred = Q.defer();
// Delete form filesystem
_fs.root.getDirectory(project.uuid, {}, function (dirEntry) {
dirEntry.removeRecursively(function () {
deferred.resolve();
}, deferred.reject);
}, deferred.reject);
return deferred.promise
.then(_self.getFileList)
.then(function (files) {
var promises = [];
//Delete from database
files.forEach(function (file) {
promises.push(_db.remove('files', file.uuid, {uuidIsHash: true}));
});
return Q.all(promises);
}).then(function () {
logger.log('FileStorage', 'removed all files/folders from file-system!');
return updateFileList();
});
}
};
})
;
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>
|
casatt/muskepeer-client
|
doc/files/src_storage_filesystem.js.html
|
HTML
|
mit
| 27,495
|
--
-- TOC entry 170 (class 1259 OID 16521)
-- Name: articulos; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE articulos (
id_articulo integer NOT NULL,
id_tipo_mueble integer,
progresivo bigint,
caracteristicas character varying(300),
id_estatus integer
);
ALTER TABLE public.articulos OWNER TO postgres;
--
-- TOC entry 171 (class 1259 OID 16524)
-- Name: articulos_id_articulo_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE articulos_id_articulo_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.articulos_id_articulo_seq OWNER TO postgres;
--
-- TOC entry 2019 (class 0 OID 0)
-- Dependencies: 171
-- Name: articulos_id_articulo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE articulos_id_articulo_seq OWNED BY articulos.id_articulo;
--
-- TOC entry 172 (class 1259 OID 16526)
-- Name: cat_direccion_ejecutiva; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE cat_direccion_ejecutiva (
id_direccion_ejecutiva integer NOT NULL,
nombre character varying(50)
);
ALTER TABLE public.cat_direccion_ejecutiva OWNER TO postgres;
--
-- TOC entry 173 (class 1259 OID 16529)
-- Name: cat_direccion_ejecutiva_id_direccion_ejecutiva_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE cat_direccion_ejecutiva_id_direccion_ejecutiva_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.cat_direccion_ejecutiva_id_direccion_ejecutiva_seq OWNER TO postgres;
--
-- TOC entry 2020 (class 0 OID 0)
-- Dependencies: 173
-- Name: cat_direccion_ejecutiva_id_direccion_ejecutiva_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE cat_direccion_ejecutiva_id_direccion_ejecutiva_seq OWNED BY cat_direccion_ejecutiva.id_direccion_ejecutiva;
--
-- TOC entry 174 (class 1259 OID 16531)
-- Name: cat_estatus; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE cat_estatus (
id_estatus integer NOT NULL,
descripcion character varying(100)
);
ALTER TABLE public.cat_estatus OWNER TO postgres;
--
-- TOC entry 175 (class 1259 OID 16534)
-- Name: cat_estatus_id_estatus_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE cat_estatus_id_estatus_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.cat_estatus_id_estatus_seq OWNER TO postgres;
--
-- TOC entry 2021 (class 0 OID 0)
-- Dependencies: 175
-- Name: cat_estatus_id_estatus_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE cat_estatus_id_estatus_seq OWNED BY cat_estatus.id_estatus;
--
-- TOC entry 176 (class 1259 OID 16536)
-- Name: cat_tipo_mueble; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE cat_tipo_mueble (
id_tipo_mueble integer NOT NULL,
descripcion character varying(400),
estatus character varying(50),
clave integer
);
ALTER TABLE public.cat_tipo_mueble OWNER TO postgres;
--
-- TOC entry 177 (class 1259 OID 16539)
-- Name: cat_tipo_mueble_id_tipo_mueble_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE cat_tipo_mueble_id_tipo_mueble_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.cat_tipo_mueble_id_tipo_mueble_seq OWNER TO postgres;
--
-- TOC entry 2022 (class 0 OID 0)
-- Dependencies: 177
-- Name: cat_tipo_mueble_id_tipo_mueble_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE cat_tipo_mueble_id_tipo_mueble_seq OWNED BY cat_tipo_mueble.id_tipo_mueble;
--
-- TOC entry 178 (class 1259 OID 16541)
-- Name: cat_tipo_usuario; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE cat_tipo_usuario (
id_tipo_usuario integer NOT NULL,
descripcion character varying(30)
);
ALTER TABLE public.cat_tipo_usuario OWNER TO postgres;
--
-- TOC entry 179 (class 1259 OID 16544)
-- Name: cat_tipo_usuario_id_tipo_usuario_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE cat_tipo_usuario_id_tipo_usuario_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.cat_tipo_usuario_id_tipo_usuario_seq OWNER TO postgres;
--
-- TOC entry 2023 (class 0 OID 0)
-- Dependencies: 179
-- Name: cat_tipo_usuario_id_tipo_usuario_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE cat_tipo_usuario_id_tipo_usuario_seq OWNED BY cat_tipo_usuario.id_tipo_usuario;
--
-- TOC entry 180 (class 1259 OID 16546)
-- Name: usuario_has_articulo; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE usuario_has_articulo (
id_usuario_articulo integer NOT NULL,
id_usuario integer,
id_articulo integer
);
ALTER TABLE public.usuario_has_articulo OWNER TO postgres;
--
-- TOC entry 181 (class 1259 OID 16549)
-- Name: usuario_has_articulo_id_usuario_articulo_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE usuario_has_articulo_id_usuario_articulo_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.usuario_has_articulo_id_usuario_articulo_seq OWNER TO postgres;
--
-- TOC entry 2024 (class 0 OID 0)
-- Dependencies: 181
-- Name: usuario_has_articulo_id_usuario_articulo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE usuario_has_articulo_id_usuario_articulo_seq OWNED BY usuario_has_articulo.id_usuario_articulo;
--
-- TOC entry 182 (class 1259 OID 16551)
-- Name: usuarios; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE usuarios (
id_usuario integer NOT NULL,
nombre character varying(50),
ap_paterno character varying(50),
ap_materno character varying(50),
cargo character varying(50),
num_empleado integer,
id_direccion_ejecutiva integer,
id_tipo_usuario integer NOT NULL,
email character varying(50),
contrasenia character varying(20),
estatus smallint
);
ALTER TABLE public.usuarios OWNER TO postgres;
--
-- TOC entry 183 (class 1259 OID 16554)
-- Name: usuarios_id_tipo_usuario_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE usuarios_id_tipo_usuario_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.usuarios_id_tipo_usuario_seq OWNER TO postgres;
--
-- TOC entry 2025 (class 0 OID 0)
-- Dependencies: 183
-- Name: usuarios_id_tipo_usuario_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE usuarios_id_tipo_usuario_seq OWNED BY usuarios.id_tipo_usuario;
--
-- TOC entry 184 (class 1259 OID 16556)
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE usuarios_id_usuario_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.usuarios_id_usuario_seq OWNER TO postgres;
--
-- TOC entry 2026 (class 0 OID 0)
-- Dependencies: 184
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE usuarios_id_usuario_seq OWNED BY usuarios.id_usuario;
--
-- TOC entry 1861 (class 2604 OID 16558)
-- Name: id_articulo; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY articulos ALTER COLUMN id_articulo SET DEFAULT nextval('articulos_id_articulo_seq'::regclass);
--
-- TOC entry 1862 (class 2604 OID 16559)
-- Name: id_direccion_ejecutiva; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY cat_direccion_ejecutiva ALTER COLUMN id_direccion_ejecutiva SET DEFAULT nextval('cat_direccion_ejecutiva_id_direccion_ejecutiva_seq'::regclass);
--
-- TOC entry 1863 (class 2604 OID 16560)
-- Name: id_estatus; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY cat_estatus ALTER COLUMN id_estatus SET DEFAULT nextval('cat_estatus_id_estatus_seq'::regclass);
--
-- TOC entry 1864 (class 2604 OID 16561)
-- Name: id_tipo_mueble; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY cat_tipo_mueble ALTER COLUMN id_tipo_mueble SET DEFAULT nextval('cat_tipo_mueble_id_tipo_mueble_seq'::regclass);
--
-- TOC entry 1865 (class 2604 OID 16562)
-- Name: id_tipo_usuario; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY cat_tipo_usuario ALTER COLUMN id_tipo_usuario SET DEFAULT nextval('cat_tipo_usuario_id_tipo_usuario_seq'::regclass);
--
-- TOC entry 1866 (class 2604 OID 16563)
-- Name: id_usuario_articulo; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuario_has_articulo ALTER COLUMN id_usuario_articulo SET DEFAULT nextval('usuario_has_articulo_id_usuario_articulo_seq'::regclass);
--
-- TOC entry 1867 (class 2604 OID 16564)
-- Name: id_usuario; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuarios ALTER COLUMN id_usuario SET DEFAULT nextval('usuarios_id_usuario_seq'::regclass);
--
-- TOC entry 1868 (class 2604 OID 16565)
-- Name: id_tipo_usuario; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuarios ALTER COLUMN id_tipo_usuario SET DEFAULT nextval('usuarios_id_tipo_usuario_seq'::regclass);
--
-- TOC entry 1996 (class 0 OID 16521)
-- Dependencies: 170
-- Data for Name: articulos; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (1, 1, 222, 'silla azul', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (2, 1, 223, 'silla verde', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (3, 1, 224, 'silla amarilla', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (5, 1, 0, 'jhgfds', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (10, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (19, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (20, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (4, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (9, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (11, 1, 0, 'Silla de metal', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (6, 2, 76543, 'Esquinero de madera', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (7, 1, 7655, 'Silla de metal azul', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (8, 3, 1234, 'manta de papel', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (12, 4, 1334132, 'manta de plastico', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (13, 6, 45345, 'cajon de madera', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (14, 6, 45345, 'cajon de madera', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (15, 7, 1312, '4vvte', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (16, 4, 123123, 'dfrv', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (17, 4, 1341, 'njrjnjfrk', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (18, 6, 313, 'silla de papel', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (21, 2, 7655689, 'mesa de selofan', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (22, 5, 759474, 'telefono de metal', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (23, 4, 542421444142422442, 'asus', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (24, 4, 987989, 'uihgibhui', 1);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (25, 2, 0, 'uhgutiuie', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (26, 5, 4756758575, 'jusrhuyih', 2);
INSERT INTO articulos (id_articulo, id_tipo_mueble, progresivo, caracteristicas, id_estatus) VALUES (27, 2, 7575869696797, 'jiahiuhuibhsuiybhsiyhi', 2);
--
-- TOC entry 2027 (class 0 OID 0)
-- Dependencies: 171
-- Name: articulos_id_articulo_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('articulos_id_articulo_seq', 27, true);
--
-- TOC entry 1998 (class 0 OID 16526)
-- Dependencies: 172
-- Data for Name: cat_direccion_ejecutiva; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO cat_direccion_ejecutiva (id_direccion_ejecutiva, nombre) VALUES (1, 'CGM');
--
-- TOC entry 2028 (class 0 OID 0)
-- Dependencies: 173
-- Name: cat_direccion_ejecutiva_id_direccion_ejecutiva_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('cat_direccion_ejecutiva_id_direccion_ejecutiva_seq', 1, true);
--
-- TOC entry 2000 (class 0 OID 16531)
-- Dependencies: 174
-- Data for Name: cat_estatus; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO cat_estatus (id_estatus, descripcion) VALUES (1, 'Deteriorado');
INSERT INTO cat_estatus (id_estatus, descripcion) VALUES (2, 'Optimo');
INSERT INTO cat_estatus (id_estatus, descripcion) VALUES (3, 'Inactivo');
--
-- TOC entry 2029 (class 0 OID 0)
-- Dependencies: 175
-- Name: cat_estatus_id_estatus_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('cat_estatus_id_estatus_seq', 3, true);
--
-- TOC entry 2002 (class 0 OID 16536)
-- Dependencies: 176
-- Data for Name: cat_tipo_mueble; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (1, 'silla', '1', 100);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (2, 'escritorio', '1', 101);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (3, 'escritorio', '1', 1001);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (4, 'pc escritorio', '1', 1002);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (5, 'pc escritorio 2', '1', 1003);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (6, 'pc escritorio 2', '1', 1002);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (7, 'pc escritorio 3', '1', 1003);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (8, 'pc escritorio 4', '1', 1004);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (9, 'pc escritorio 5', '1', 1005);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (10, 'pc escritorio 6', '1', 1006);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (11, 'pc escritorio 7', '1', 1007);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (12, 'pc escritorio 8', '1', 1008);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (13, 'pc escritorio 9', '1', 1009);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (14, 'pc escritorio 10', '1', 1010);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (15, 'pc escritorio 11', '1', 1011);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (16, 'pc escritorio 12', '1', 1012);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (17, 'pc escritorio 13', '1', 1013);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (18, 'pc escritorio 14', '1', 1014);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (19, 'pc escritorio 15', '1', 1015);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (20, 'silla', NULL, 123);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (21, 'silla', '1', 123);
INSERT INTO cat_tipo_mueble (id_tipo_mueble, descripcion, estatus, clave) VALUES (22, 'Silla', '1', 12343);
--
-- TOC entry 2030 (class 0 OID 0)
-- Dependencies: 177
-- Name: cat_tipo_mueble_id_tipo_mueble_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('cat_tipo_mueble_id_tipo_mueble_seq', 22, true);
--
-- TOC entry 2004 (class 0 OID 16541)
-- Dependencies: 178
-- Data for Name: cat_tipo_usuario; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO cat_tipo_usuario (id_tipo_usuario, descripcion) VALUES (1, 'Administrador');
--
-- TOC entry 2031 (class 0 OID 0)
-- Dependencies: 179
-- Name: cat_tipo_usuario_id_tipo_usuario_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('cat_tipo_usuario_id_tipo_usuario_seq', 1, true);
--
-- TOC entry 2006 (class 0 OID 16546)
-- Dependencies: 180
-- Data for Name: usuario_has_articulo; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO usuario_has_articulo (id_usuario_articulo, id_usuario, id_articulo) VALUES (4, 3, 1);
INSERT INTO usuario_has_articulo (id_usuario_articulo, id_usuario, id_articulo) VALUES (6, 3, 3);
INSERT INTO usuario_has_articulo (id_usuario_articulo, id_usuario, id_articulo) VALUES (5, 3, 2);
--
-- TOC entry 2032 (class 0 OID 0)
-- Dependencies: 181
-- Name: usuario_has_articulo_id_usuario_articulo_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('usuario_has_articulo_id_usuario_articulo_seq', 6, true);
--
-- TOC entry 2008 (class 0 OID 16551)
-- Dependencies: 182
-- Data for Name: usuarios; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO usuarios (id_usuario, nombre, ap_paterno, ap_materno, cargo, num_empleado, id_direccion_ejecutiva, id_tipo_usuario, email, contrasenia, estatus) VALUES (3, 'Ernesto', 'Andrade', 'Luna', 'Director', 210310108, 1, 1, 'n3to', '123', 1);
INSERT INTO usuarios (id_usuario, nombre, ap_paterno, ap_materno, cargo, num_empleado, id_direccion_ejecutiva, id_tipo_usuario, email, contrasenia, estatus) VALUES (1, 'nombre', 'apP', 'apM', 'cargo', 0, 1, 1, 'email', '0', 1);
INSERT INTO usuarios (id_usuario, nombre, ap_paterno, ap_materno, cargo, num_empleado, id_direccion_ejecutiva, id_tipo_usuario, email, contrasenia, estatus) VALUES (4, 'usuario1', 'usuario', 'usuario', 'El de los chescos', 11111, 1, 1, 'usuario1', '000', 1);
INSERT INTO usuarios (id_usuario, nombre, ap_paterno, ap_materno, cargo, num_empleado, id_direccion_ejecutiva, id_tipo_usuario, email, contrasenia, estatus) VALUES (5, 'Oscar', 'Amaya', 'Ordoñez', 'Administrador', 26424676, 1, 1, 'osskar_the_pimp@hotmail.com', '123', 1);
INSERT INTO usuarios (id_usuario, nombre, ap_paterno, ap_materno, cargo, num_empleado, id_direccion_ejecutiva, id_tipo_usuario, email, contrasenia, estatus) VALUES (6, 'Oscar', 'Amaya', 'Ordoñez', 'Administrador', 26424676, 1, 1, 'osskar_the_pimp@hotmail.com', '123', 1);
--
-- TOC entry 2033 (class 0 OID 0)
-- Dependencies: 183
-- Name: usuarios_id_tipo_usuario_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('usuarios_id_tipo_usuario_seq', 1, false);
--
-- TOC entry 2034 (class 0 OID 0)
-- Dependencies: 184
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('usuarios_id_usuario_seq', 6, true);
--
-- TOC entry 1870 (class 2606 OID 16567)
-- Name: id_articulo; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY articulos
ADD CONSTRAINT id_articulo PRIMARY KEY (id_articulo);
--
-- TOC entry 1872 (class 2606 OID 16569)
-- Name: id_direccion_ejecutiva; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY cat_direccion_ejecutiva
ADD CONSTRAINT id_direccion_ejecutiva PRIMARY KEY (id_direccion_ejecutiva);
--
-- TOC entry 1874 (class 2606 OID 16571)
-- Name: id_estatus; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY cat_estatus
ADD CONSTRAINT id_estatus PRIMARY KEY (id_estatus);
--
-- TOC entry 1876 (class 2606 OID 16573)
-- Name: id_tipo_mueble; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY cat_tipo_mueble
ADD CONSTRAINT id_tipo_mueble PRIMARY KEY (id_tipo_mueble);
--
-- TOC entry 1878 (class 2606 OID 16575)
-- Name: id_tipo_usuario; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY cat_tipo_usuario
ADD CONSTRAINT id_tipo_usuario PRIMARY KEY (id_tipo_usuario);
--
-- TOC entry 1882 (class 2606 OID 16577)
-- Name: id_usuario; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY usuarios
ADD CONSTRAINT id_usuario PRIMARY KEY (id_usuario);
--
-- TOC entry 1880 (class 2606 OID 16579)
-- Name: id_usuario_articulo; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY usuario_has_articulo
ADD CONSTRAINT id_usuario_articulo PRIMARY KEY (id_usuario_articulo);
--
-- TOC entry 1885 (class 2606 OID 16580)
-- Name: id_articulo; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuario_has_articulo
ADD CONSTRAINT id_articulo FOREIGN KEY (id_articulo) REFERENCES articulos(id_articulo);
--
-- TOC entry 1887 (class 2606 OID 16585)
-- Name: id_direccion_ejecutiva; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuarios
ADD CONSTRAINT id_direccion_ejecutiva FOREIGN KEY (id_direccion_ejecutiva) REFERENCES cat_direccion_ejecutiva(id_direccion_ejecutiva);
--
-- TOC entry 1883 (class 2606 OID 16590)
-- Name: id_estatus; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY articulos
ADD CONSTRAINT id_estatus FOREIGN KEY (id_estatus) REFERENCES cat_estatus(id_estatus);
--
-- TOC entry 1884 (class 2606 OID 16595)
-- Name: id_tipo_mueble; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY articulos
ADD CONSTRAINT id_tipo_mueble FOREIGN KEY (id_tipo_mueble) REFERENCES cat_tipo_mueble(id_tipo_mueble);
--
-- TOC entry 1888 (class 2606 OID 16600)
-- Name: id_tipo_usuario; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuarios
ADD CONSTRAINT id_tipo_usuario FOREIGN KEY (id_tipo_usuario) REFERENCES cat_tipo_usuario(id_tipo_usuario);
--
-- TOC entry 1886 (class 2606 OID 16605)
-- Name: id_usuario; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY usuario_has_articulo
ADD CONSTRAINT id_usuario FOREIGN KEY (id_usuario) REFERENCES usuarios(id_usuario);
--
-- TOC entry 2017 (class 0 OID 0)
-- Dependencies: 6
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
-- Completed on 2015-05-19 17:21:32
--
-- PostgreSQL database dump complete
--
|
jezrelmx/inventarioCGMA
|
db/inventarioCGMA2.sql
|
SQL
|
mit
| 23,989
|
package s_mach.codetools
import org.scalatest.{FlatSpec, Matchers}
object IsValueClassTest {
implicit class Weight(val underlying: Double) extends AnyVal with IsValueClass[Double]
}
class IsValueClassTest extends FlatSpec with Matchers {
import IsValueClassTest._
"IsValueClass.toString" should "return underlying.toString" in {
val test = 50.0
Weight(test).toString should equal(test.toString)
}
}
|
S-Mach/s_mach.codetools
|
codetools/src/test/scala/s_mach/codetools/IsValueClassTest.scala
|
Scala
|
mit
| 418
|
# -*- coding: utf-8 -*-
import django_dynamic_fixture as fixture
from unittest import mock
from django import urls
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.auth.models import User
from django.test import TestCase
from readthedocs.core.models import UserProfile
from readthedocs.projects.models import Project
class ProjectAdminActionsTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.owner = fixture.get(User)
cls.profile = fixture.get(UserProfile, user=cls.owner, banned=False)
cls.admin = fixture.get(User, is_staff=True, is_superuser=True)
cls.project = fixture.get(
Project,
main_language_project=None,
users=[cls.owner],
)
def setUp(self):
self.client.force_login(self.admin)
def test_project_ban_owner(self):
self.assertFalse(self.owner.profile.banned)
action_data = {
ACTION_CHECKBOX_NAME: [self.project.pk],
'action': 'ban_owner',
'index': 0,
}
resp = self.client.post(
urls.reverse('admin:projects_project_changelist'),
action_data,
)
self.assertTrue(self.project.users.filter(profile__banned=True).exists())
self.assertFalse(self.project.users.filter(profile__banned=False).exists())
def test_project_ban_multiple_owners(self):
owner_b = fixture.get(User)
profile_b = fixture.get(UserProfile, user=owner_b, banned=False)
self.project.users.add(owner_b)
self.assertFalse(self.owner.profile.banned)
self.assertFalse(owner_b.profile.banned)
action_data = {
ACTION_CHECKBOX_NAME: [self.project.pk],
'action': 'ban_owner',
'index': 0,
}
resp = self.client.post(
urls.reverse('admin:projects_project_changelist'),
action_data,
)
self.assertFalse(self.project.users.filter(profile__banned=True).exists())
self.assertEqual(self.project.users.filter(profile__banned=False).count(), 2)
@mock.patch('readthedocs.projects.admin.clean_project_resources')
def test_project_delete(self, clean_project_resources):
"""Test project and artifacts are removed."""
action_data = {
ACTION_CHECKBOX_NAME: [self.project.pk],
'action': 'delete_selected',
'index': 0,
'post': 'yes',
}
resp = self.client.post(
urls.reverse('admin:projects_project_changelist'),
action_data,
)
self.assertFalse(Project.objects.filter(pk=self.project.pk).exists())
clean_project_resources.assert_has_calls([
mock.call(
self.project,
),
])
|
rtfd/readthedocs.org
|
readthedocs/rtd_tests/tests/projects/test_admin_actions.py
|
Python
|
mit
| 2,812
|
class Base(object):
def meth(self):
pass
class Derived1(Base):
def meth(self):
return super().meth()
class Derived2(Derived1):
def meth(self):
return super().meth()
class Derived3(Derived1):
pass
class Derived4(Derived3, Derived2):
def meth(self):
return super().meth()
class Derived5(Derived1):
def meth(self):
return super().meth()
class Derived6(Derived5, Derived2):
def meth(self):
return super().meth()
|
github/codeql
|
python/ql/test/3/library-tests/PointsTo/inheritance/test.py
|
Python
|
mit
| 496
|
(function () {
// The default state core singleton for {@link SceneJS.View} nodes
var defaultCore = {
type:"view",
stateId:SceneJS._baseStateId++,
scissorTestEnabled:false
};
var coreStack = [];
var stackLen = 0;
SceneJS_events.addListener(
SceneJS_events.SCENE_COMPILING,
function (params) {
params.engine.display.view = defaultCore;
stackLen = 0;
});
/**
* @class Scene graph node which configures view parameters such as depth range, scissor test and viewport
* @extends SceneJS.Node
* void depthRange(floatzNear, floatzFar)
zNear: Clamped to the range 0 to 1 Must be <= zFar
zFar: Clamped to the range 0 to 1.
void scissor(int x, int y, long width, long height)
void viewport(int x, int y, long width, long height)
*/
SceneJS.View = SceneJS_NodeFactory.createNodeType("view");
SceneJS.View.prototype._init = function (params) {
if (params.scissorTestEnabled != undefined) {
this.setScissorTestEnabled(params.scissorTestEnabled);
} else if (this._core.useCount == 1) { // This node defines the core
this.setScissorTestEnabled(false);
}
};
/**
* Enable or disables scissor test.
*
* When enabled, the scissor test will discards fragments that are outside the scissor box.
*
* Scissor test is initially disabled.
*
* @param scissorTestEnabled Specifies whether scissor test is enabled or not
* @return {*}
*/
SceneJS.View.prototype.setScissorTestEnabled = function (scissorTestEnabled) {
if (this._core.scissorTestEnabled != scissorTestEnabled) {
this._core.scissorTestEnabled = scissorTestEnabled;
this._engine.display.imageDirty = true;
}
return this;
};
/**
* Get whether or not scissor test is enabled.
* Initial value will be false.
*
* @return Boolean
*/
SceneJS.View.prototype.getScissorTestEnabled = function () {
return this._core.scissorTestEnabled;
};
SceneJS.View.prototype._compile = function (ctx) {
this._engine.display.view = coreStack[stackLen++] = this._core;
this._compileNodes(ctx);
this._engine.display.view = (--stackLen > 0) ? coreStack[stackLen - 1] : defaultCore;
};
})();
|
dayo7116/scenejs
|
src/core/scene/view.js
|
JavaScript
|
mit
| 2,390
|
"use strict";
define(['dou', 'build/ComponentRegistry'],
function (dou, ComponentRegistry) {
describe('ComponentRegistry', function () {
var componentRegistry;
var specs = [ {
type: 'A',
name: 'Component A',
description: 'description for Component A',
defaults: {
attr1: '1',
attr2: 'A',
attr3: 100
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
}, {
type: 'B',
name: 'Component B',
description: 'description for Component B',
defaults: {
attr1: '2',
attr2: 'B',
attr3: 200
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
} ];
beforeEach(function() {
componentRegistry = new ComponentRegistry();
specs.forEach(function(spec) {
componentRegistry.register(spec);
});
});
afterEach(function() {
componentRegistry.dispose()
});
describe('register', function() {
it('should ', function () {
componentRegistry.register({
type: 'C',
name: 'Component C',
description: 'description for Component C',
defaults: {
attr1: '3',
attr2: 'C',
attr3: 300
},
shape_factory: dou.define({
}),
handle_factory: dou.define({
}),
toolbox_image: 'toolbox_small.png'
});
var specs = componentRegistry.list();
Object.keys(specs).length.should.equal(3);
});
});
describe('list', function() {
it('should return list of registered component specs.', function () {
var specs = componentRegistry.list();
var inst = new ComponentRegistry();
specs.length.should.equal(2);
});
});
describe('get', function() {
it('should get component spec by type of spec as a key', function () {
var spec = componentRegistry.get('B');
spec.name.should.equal('Component B');
spec.defaults.attr2.should.equal('B');
});
it('should not be able to change attributes of regietered spec.', function () {
var spec = componentRegistry.get('B');
var origin = spec.name;
spec.name = origin + ' Changed';
var spec = componentRegistry.get('B');
spec.name.should.equal(origin);
});
});
});
});
|
heartyoh/infopik
|
test/spec/component_registry_spec.js
|
JavaScript
|
mit
| 2,543
|
<?php namespace Pianke\Providers;
use Illuminate\Support\ServiceProvider;
class ConfigServiceProvider extends ServiceProvider {
/**
* Overwrite any vendor / package configuration.
*
* This service provider is intended to provide a convenient location for you
* to overwrite any "vendor" or package configuration that you may want to
* modify before the application handles the incoming request / command.
*
* @return void
*/
public function register()
{
config([
//
]);
}
}
|
xrain0610/php-laravel-rbac
|
app/Providers/ConfigServiceProvider.php
|
PHP
|
mit
| 505
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe LessonPolicy do
describe 'permissions' do
subject { LessonPolicy.new current_user, lesson }
context 'as a Super Administrator' do
let(:current_user) { create :super_admin }
context 'on a Lesson Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on any existing lesson' do
let(:lesson) { Lesson.create }
it { is_expected.to permit_action :show }
end
context 'on a new lesson' do
let(:lesson) { build :lesson }
it { is_expected.to permit_action :create }
end
end
context 'as a Global Administrator' do
let(:current_user) { create :global_admin }
context 'on a Lesson Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on any existing lesson' do
let(:lesson) { Lesson.create }
it { is_expected.to permit_action :show }
end
context 'on a new lesson' do
let(:lesson) { build :lesson }
it { is_expected.to permit_action :create }
end
end
context 'as a Global Guest' do
let(:current_user) { create :global_guest }
context 'on a Lesson Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on any existing lesson' do
let(:lesson) { Lesson.create }
it { is_expected.to permit_action :show }
end
context 'on a new lesson' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
context 'as a Global Researcher' do
let(:current_user) { create :global_researcher }
context 'on a Lesson Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on any existing lesson' do
let(:lesson) { Lesson.create }
it { is_expected.to permit_action :show }
end
context 'on a new lesson' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
context 'as a Local Administrator' do
let(:org) { create :organization }
let(:chapter) { create :chapter, organization: org }
let(:group) { create :group, chapter: chapter }
let(:current_user) { create :admin_of, organization: org }
context 'on a Lesson Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on a lesson inside own\'s organization' do
let(:lesson) { create :lesson, group: group }
it { is_expected.to permit_action :show }
end
context 'on a lesson outside of own\'s organization' do
let(:lesson) { create :lesson, group: create(:group) }
it { is_expected.to forbid_action :show }
end
context 'on a new lesson in own organization' do
let(:lesson) { build :lesson, group: group }
it { is_expected.to permit_action :create }
end
context 'on a new lesson outside of own organization' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
context 'as a Local Teacher' do
let(:org) { create :organization }
let(:chapter) { create :chapter, organization: org }
let(:group) { create :group, chapter: chapter }
let(:current_user) { create :teacher_in, organization: org }
context 'on a User Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on a lesson inside own\'s organization' do
let(:lesson) { create :lesson, group: group }
it { is_expected.to permit_action :show }
end
context 'on a lesson outside of own\'s organization' do
let(:lesson) { create :lesson }
it { is_expected.to forbid_action :show }
end
context 'on a new lesson in own organization' do
let(:lesson) { build :lesson, group: group }
it { is_expected.to permit_action :create }
end
context 'on a new lesson outside of own organization' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
context 'as a Local Guest' do
let(:org) { create :organization }
let(:chapter) { create :chapter, organization: org }
let(:group) { create :group, chapter: chapter }
let(:current_user) { create :guest_in, organization: org }
context 'on a User Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on a lesson inside own\'s organization' do
let(:lesson) { create :lesson, group: group }
it { is_expected.to permit_action :show }
end
context 'on a lesson outside of own\'s organization' do
let(:lesson) { create :lesson }
it { is_expected.to forbid_action :show }
end
context 'on a new lesson in own organization' do
let(:lesson) { build :lesson, group: group }
it { is_expected.to forbid_action :create }
end
context 'on a new lesson outside of own organization' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
context 'as a Local Researcher' do
let(:org) { create :organization }
let(:chapter) { create :chapter, organization: org }
let(:group) { create :group, chapter: chapter }
let(:current_user) { create :researcher_in, organization: org }
context 'on a User Resource' do
let(:lesson) { Lesson }
it { is_expected.to permit_action :index }
end
context 'on a lesson inside own\'s organization' do
let(:lesson) { create :lesson, group: group }
it { is_expected.to permit_action :show }
end
context 'on a lesson outside of own\'s organization' do
let(:lesson) { create :lesson }
it { is_expected.to forbid_action :show }
end
context 'on a new lesson in own organization' do
let(:lesson) { build :lesson, group: group }
it { is_expected.to forbid_action :create }
end
context 'on a new lesson outside of own organization' do
let(:lesson) { build :lesson }
it { is_expected.to forbid_action :create }
end
end
end
describe 'scope' do
RSpec.shared_examples :global_user_lesson_scope do
subject(:result) { LessonPolicy::Scope.new(current_user, Lesson).resolve }
let(:org1) { create :organization }
let(:org2) { create :organization }
let(:lessons_in_org1) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org1)) }
let(:lessons_in_org2) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org2)) }
it 'returns all lessons from the first organization' do
expect(result).to include(*lessons_in_org1)
end
it 'returns all lessons from second organization' do
expect(result).to include(*lessons_in_org2)
end
end
RSpec.shared_examples :local_user_lesson_scope do
subject(:result) { LessonPolicy::Scope.new(current_user, Lesson).resolve }
let(:org2) { create :organization }
let(:lessons_in_org) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org)) }
let(:lessons_in_org2) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org2)) }
it 'includes all lessons from the first organization' do
expect(result).to include(*lessons_in_org)
end
it 'does not include lessons from the second organization' do
expect(result).not_to include(*lessons_in_org2)
end
end
context 'As a Super Administrator' do
let(:current_user) { create :super_admin }
it_behaves_like :global_user_lesson_scope
end
context 'As a Global Administrator' do
let(:current_user) { create :global_admin }
it_behaves_like :global_user_lesson_scope
end
context 'As a Global Guest' do
let(:current_user) { create :global_guest }
it_behaves_like :global_user_lesson_scope
end
context 'As a Global Researcher' do
let(:current_user) { create :global_researcher }
it_behaves_like :global_user_lesson_scope
end
context 'As a Local Administrator' do
let(:org) { create :organization }
let(:current_user) { create :admin_of, organization: org }
it_behaves_like :local_user_lesson_scope
end
context 'As a Local Teacher' do
let(:org) { create :organization }
let(:current_user) { create :teacher_in, organization: org }
it_behaves_like :local_user_lesson_scope
end
context 'As a Local Guest' do
let(:org) { create :organization }
let(:current_user) { create :guest_in, organization: org }
it_behaves_like :local_user_lesson_scope
end
context 'As a Local Researcher' do
let(:org) { create :organization }
let(:current_user) { create :researcher_in, organization: org }
it_behaves_like :local_user_lesson_scope
end
context 'As a User with roles in multiple organizations' do
subject(:result) { LessonPolicy::Scope.new(current_user, Lesson).resolve }
let(:org1) { create :organization }
let(:org2) { create :organization }
let(:current_user) do
u = create :admin_of, organization: org1
u.add_role :teacher, org2
u
end
let(:lessons_in_org1) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org1)) }
let(:lessons_in_org2) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: org2)) }
let(:lessons_in_org3) { create_list :lesson, 3, group: create(:group, chapter: create(:chapter, organization: create(:organization))) }
it 'includes all lessons from the first organization' do
expect(result).to include(*lessons_in_org1)
end
it 'includes all lessons from the second organization' do
expect(result).to include(*lessons_in_org2)
end
it 'does not include lessons from a different organization' do
expect(result).not_to include(*lessons_in_org3)
end
end
end
end
|
MindLeaps/tracker
|
spec/policies/lesson_policy_spec.rb
|
Ruby
|
mit
| 10,538
|
package s3
import (
"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/crowdmob/goamz/aws"
)
var originalStrategy = attempts
func SetAttemptStrategy(s *aws.AttemptStrategy) {
if s == nil {
attempts = originalStrategy
} else {
attempts = *s
}
}
func Sign(auth aws.Auth, method, path string, params, headers map[string][]string) {
sign(auth, method, path, params, headers)
}
func SetListPartsMax(n int) {
listPartsMax = n
}
func SetListMultiMax(n int) {
listMultiMax = n
}
|
djbarber/ipfs-hack
|
Godeps/_workspace/src/github.com/crowdmob/goamz/s3/export_test.go
|
GO
|
mit
| 501
|
package be.seriousbusiness.brusselnieuws.rss.datastore.hsqldb;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
|
seriousbusinessbe/java-brusselnieuws-rss
|
java/brusselnieuws-rss/brusselnieuws-rss-datastore-hsqldb/src/main/java/be/seriousbusiness/brusselnieuws/rss/datastore/hsqldb/App.java
|
Java
|
mit
| 216
|
# repetier-host-1405
Custom configuration files for the Printrbot 1405 3D printer, both for a stock printer and an updated printer with a heated bed and auto leveling probe.
## More help
For more information about getting strted with the simple maker 1405:
http://printrbot.com/project/simple-makers/
## License
```
The MIT License (MIT)
Copyright (c) 2015 Daniel Blair
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
|
CMDann/repetier-host-1405
|
README.md
|
Markdown
|
mit
| 1,404
|
using System.Threading;
namespace BreadWinner.UnitTests.TestDoubles
{
public class WorkerTestRunResult
{
public ThreadState ThreadState { get; }
public CancellationToken CancellationToken { get; }
public WorkerTestRunResult(ThreadState threadState, CancellationToken cancellationToken)
{
ThreadState = threadState;
CancellationToken = cancellationToken;
}
}
}
|
gugu91/bread-winner
|
tests/BreadWinner.UnitTests/TestDoubles/WorkerTestRunResult.cs
|
C#
|
mit
| 455
|
---
layout: post
title: mybatis 源码分析之 XMLStatementBuilder
categories: mybatis
tags: 笔记, mybatis
---
## XMLStatementBuilder.parseStatementNode 第四步
第四步就一句话,但是里面的内容很多,我们慢慢分析:
```java
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
```
看英文注释,主要的作用就是解析 selectKey 并且在当前节点下移除掉。
selectKey 节点只可能在 insert 和 update 当中出现。
继续看详细代码:
```java
private void processSelectKeyNodes(String id, Class<?> parameterTypeClass, LanguageDriver langDriver) {
List<XNode> selectKeyNodes = context.evalNodes("selectKey");
if (configuration.getDatabaseId() != null) {
parseSelectKeyNodes(id, selectKeyNodes, parameterTypeClass, langDriver, configuration.getDatabaseId());
}
parseSelectKeyNodes(id, selectKeyNodes, parameterTypeClass, langDriver, null);
removeSelectKeyNodes(selectKeyNodes);
}
```
先解析 selectKey,然后移除 selectKey。
```java
private void parseSelectKeyNodes(String parentId, List<XNode> list, Class<?> parameterTypeClass, LanguageDriver langDriver, String skRequiredDatabaseId) {
for (XNode nodeToHandle : list) {
String id = parentId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
String databaseId = nodeToHandle.getStringAttribute("databaseId");
if (databaseIdMatchesCurrent(id, databaseId, skRequiredDatabaseId)) {
parseSelectKeyNode(id, nodeToHandle, parameterTypeClass, langDriver, databaseId);
}
}
}
```
循环全部的 selectKey 的节点,如果没有那么什么操作都不作。
```java
private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> parameterTypeClass, LanguageDriver langDriver, String databaseId) {
String resultType = nodeToHandle.getStringAttribute("resultType");
// 当中省略了基本属性的解析
ResultSetType resultSetTypeEnum = null;
SqlSource sqlSource = langDriver.createSqlSource(configuration, nodeToHandle, parameterTypeClass);
SqlCommandType sqlCommandType = SqlCommandType.SELECT;
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);
id = builderAssistant.applyCurrentNamespace(id, false);
MappedStatement keyStatement = configuration.getMappedStatement(id, false);
configuration.addKeyGenerator(id, new SelectKeyGenerator(keyStatement, executeBefore));
}
```
这个重载的方法里面主要做如下几个事情:
1. 解析 selectKey 的基本属性
2. 通过 langDriver 生成 SqlSource
3. 创建 selectKey 查询语句的 KeyGenerator,添加到 configuration 当中
下面详细分析 langDriver 生成 SqlSource 的过程:
首先看 LanguageDriver 是一个接口:
```java
public interface LanguageDriver {
ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
}
```
LanguageDriver 有三个方法,一个是创建参数 Handler,另外两个是创建 SqlSource。
LanguageDriver
- XMLLanguageDriver
- RawLanguageDriver
上面是 LanguageDriver 的继承结构。
当然在 Configuration 的构造方法当中,我们以及设置了默认的 Driver class : languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
在这个 parseSelectKeyNode 方法当中传递进来的也是默认的 XMLLanguageDriver 的实例。
下面就是 XMLLanguageDriver.createSqlSource 方法:
```java
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
return builder.
();
}
```
可以看到是通过创建 XMLScriptBuilder 实例来继而调用 parseScriptNode 方法获得到 SqlSource。
XMLScriptBuilder 同样继承了 BaseBuilder。
```java
public class XMLScriptBuilder extends BaseBuilder {
private XNode context;
private boolean isDynamic;
private Class<?> parameterType;
}
```
下面是 parseScriptNode 方法:
```java
public SqlSource parseScriptNode() {
List<SqlNode> contents = parseDynamicTags(context);
MixedSqlNode rootSqlNode = new MixedSqlNode(contents);
SqlSource sqlSource = null;
if (isDynamic) {
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
} else {
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
}
return sqlSource;
}
List<SqlNode> parseDynamicTags(XNode node) {
List<SqlNode> contents = new ArrayList<SqlNode>();
NodeList children = node.getNode().getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
XNode child = node.newXNode(children.item(i));
if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
String data = child.getStringBody("");
TextSqlNode textSqlNode = new TextSqlNode(data);
if (textSqlNode.isDynamic()) {
contents.add(textSqlNode);
isDynamic = true;
} else {
contents.add(new StaticTextSqlNode(data));
}
} else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
String nodeName = child.getNode().getNodeName();
NodeHandler handler = nodeHandlers(nodeName);
if (handler == null) {
throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
}
handler.handleNode(child, contents);
isDynamic = true;
}
}
return contents;
}
```
首先判断当前的节点是不是有动态的 tag,动态的 tag 包括一些 where、choose 等。
看 parseDynamicTags 的代码的判断入下:
1. 获取 SelectKey 的所有子节点
2. 循环判断如果子节点的元素类型的 ELEMENT 那么这个一定是动态的,并且根据不同的元素生成不同的 NodeHandler
3. 生成 SqlNode 的 list 并且返回
根据代码再来一遍流程:
```java
if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
//如果是文本的子节点
String data = child.getStringBody("");//获取文本信息
TextSqlNode textSqlNode = new TextSqlNode(data);//创建TextSqlNode
if (textSqlNode.isDynamic()) {//如果 sql 当中包含有未被属性替换的 ${} 字符串那么就是动态的
contents.add(textSqlNode);//添加到 list 当中
isDynamic = true;
} else {
contents.add(new StaticTextSqlNode(data));
}
}
```
下面在看下 SqlNode 接口:
```java
public interface SqlNode {
boolean apply(DynamicContext context);
}
```
TextSqlNode 和 StaticTextSqlNode 有时间,单独分析,他的体系,他们都实现了 SqlNode 接口。
继续看其他的 if 分支:
```java
else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
String nodeName = child.getNode().getNodeName();//获取子节点的name
NodeHandler handler = nodeHandlers(nodeName);//根据name获取到NodeHandler
if (handler == null) {
throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
}
handler.handleNode(child, contents);
isDynamic = true;
}
NodeHandler nodeHandlers(String nodeName) {
Map<String, NodeHandler> map = new HashMap<String, NodeHandler>();
map.put("trim", new TrimHandler());
map.put("where", new WhereHandler());
map.put("set", new SetHandler());
map.put("foreach", new ForEachHandler());
map.put("if", new IfHandler());
map.put("choose", new ChooseHandler());
map.put("when", new IfHandler());
map.put("otherwise", new OtherwiseHandler());
map.put("bind", new BindHandler());
return map.get(nodeName);
}
```
解析动态的 tag 并且获得了 SqlNode 的 list 之后,需要根据是否是动态的创建响应的 SqlSource:
```java
public SqlSource parseScriptNode() {
List<SqlNode> contents = parseDynamicTags(context);
MixedSqlNode rootSqlNode = new MixedSqlNode(contents);
SqlSource sqlSource = null;
if (isDynamic) {
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
} else {
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
}
return sqlSource;
}
```
SqlSource 以后仔细分析。
至此 XMLStatementBuilder.parseSelectKeyNode 的创建 SqlSource 已经完成。
方法下面就是通过 builderAssistant 创建 MappedStatement:
```java
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);
```
builderAssistant.addMappedStatement 里面代码就不贴了,基本上套路相同先创建 MappedStatement.Builder 实例,然后设置各种传递进来的参数,最后添加到 configuration 当中。
在 configuration 当中添加完 MappedStatement 后,继续在 configuration 当中添加 SelectKeyGenerator。
这样 XMLStatementBuilder.parseStatementNode 第四步完成。
## XMLStatementBuilder.parseStatementNode 第五步
第五步比较简单就是创建当前 insert 或者 update 的 MappedStatement 对象,并且添加到 configuration 当中。
```java
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute("resultSets");
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? new Jdbc3KeyGenerator() : new NoKeyGenerator();
}
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
```
上面代码省略了一部分。
以后继续分析没有完善的内容
---EOF---
|
renchunxiao/rcxblog.github.io
|
_posts/2016-03-03-mybatis6.md
|
Markdown
|
mit
| 11,205
|
{% extends "main.html" %}
{% load static %}
{% load i18n %}
{% block title %}{% trans "Tamil-Inayavaani SpellChecker + Tamil-Sandhi Checker" %}{% endblock %}
{% block content %}
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script src={% static 'tinymce/js/jquery/jquery-1.12.1.min.js' %}></script>
<script src={% static 'tinymce/js/tinymce/tinymce.dev.js' %}></script>
<script src={% static 'tinymce/js/tinymce/tinymce.jquery.js' %}></script>
<script>
function ta_spellchecker_cb(method, text, success, failure) {
var words_to_check = text.split(/\s/);
//debug
console.log(words_to_check.join('|\n'));
var request = $.ajax({
url: "/en/tamilinayavaani_spellchecker",
method: "POST",
dataType: "json",
data: {
lang: 'ta_IN', /*this.getLanguage()*/
text: words_to_check.join('\n')
}
});
request.done(
function (result) {
console.log(result);
success(result);
});
request.fail(function (xhr, errorStatus) {
failure("Spellcheck error:" + errorStatus);
});
};
/* Ref: https://www.tinymce.com/docs/plugins/spellchecker/ */
function init() {
tinymce.init({
mode: "textareas",
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
"searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
"save table contextmenu directionality emoticons template paste"
],
valid_elements: '*[*]',
add_unload_trigger: false,
editor_selector: 'editable',
spellchecker_language: 'ta_IN',
spellchecker_callback: ta_spellchecker_cb
});
};
init();
</script>
<div>
<h3>தமிழ் திருத்தி ( தமிழிணையவாணி + தமிழ் சந்திப்பிழைத்திருத்தி)</h3>
<div><b> usage: Tools > Spellchecker </b></div>
<div>
<div id="container1">
<textarea id="elm1" name="elm1" rows="25" cols="80" style="width: 80%" class="editable">
கலுதைக்கு தெரியுமா கல்பூரம் வாசொனை
</textarea>
</div>
<a href="#" onclick="tinymce.DOM.show('container1');return false;" alt="காட்டு">[+]</a>
<a href="#" onclick="tinymce.DOM.hide('container1');return false;" alt="மரை">[-]</a>
</div>
</div>
<!-- credits -->
<div>
<h2>Tamilinaiyam - Pizhaithiruthi (Spellchecker)</h2>
</div>
<div id="python-package">
<h2>Python Package</h2>
<p>Python Port of TamilInaiya spell checker is named ‘tamilinayavaani’
and available as Python module form same name. It can be used with a UTF-8 encoded text file as follows,</p>
<div id="installation">
<h3>Installation</h3>
<pre>$ python3 -m pip install --upgrade tamilinayavaani><span class="o">=</span><span class="m">0</span>.13
</pre>
</div>
<div id="usage-in-memory">
<h3>Usage - in-memory</h3>
<pre><span class="kn">from</span> <span class="nn">tamilinaiyavaani</span> <span
class="kn">import</span> <span class="n">SpellChecker</span>
<span class="n">flag</span><span class="p">,</span><span class="n">suggs</span><span class="o">=</span><span class="n">SpellChecker</span><span
class="o">.</span><span class="n">REST_interface</span><span class="p">(</span><span class="s1">'வாழை'</span><span
class="p">,</span><span class="s1">'பழம்'</span><span class="p">)</span>
<span class="n">expected</span><span class="o">=</span><span class="p">[</span><span class="s1">'வாழைப்'</span><span
class="p">,</span> <span class="s1">'பழம்'</span><span class="p">]</span>
<span class="k">assert</span> <span class="ow">not</span> <span class="n">flag</span>
<span class="k">assert</span> <span class="n">expected</span><span class="p">[</span><span class="mi">0</span><span
class="p">]</span><span class="o">==</span><span class="n">suggs</span><span
class="p">[</span><span class="mi">0</span><span class="p">]</span>
</pre>
</div>
<div id="usage-file-based">
<h3>Usage - file-based</h3>
<p>An file-based use of the library would look like,</p>
<pre><span class="kn">from</span> <span class="nn">tamilinaiyavaani</span> <span
class="kn">import</span> <span class="n">SpellChecker</span><span class="p">,</span> <span
class="n">SpellCheckerResult</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">SpellChecker</span><span class="p">(</span><span
class="n">fname</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span
class="p">()</span> <span class="c1">#fname is a full filename</span>
<span class="c1"># result is a list of SpellCheckerResult objects.</span>
</pre>
</div>
</div>
<div id="source">
<h2>Source</h2>
<p>Tamil Virtual Academy release sources at <a
href="http://www.tamilvu.org/ta/content/%E0%AE%A4%E0%AE%AE%E0%AE%BF%E0%AE%B4%E0%AF%8D%E0%AE%95%E0%AF%8D-%E0%AE%95%E0%AE%A3%E0%AE%BF%E0%AE%A9%E0%AE%BF%E0%AE%95%E0%AF%8D-%E0%AE%95%E0%AE%B0%E0%AF%81%E0%AE%B5%E0%AE%BF%E0%AE%95%E0%AE%B3%E0%AF%8D"
rel="nofollow">link.</a></p>
</div>
<div id="license">
<h2>License</h2>
<p>This code is licensed under terms of GNU GPL V2. Check <a
href="https://commons.wikimedia.org/wiki/File:Tamil-Virtual-Academy-Copyright-Declaration.jpg"
rel="nofollow">link</a> for license info.</p>
</div>
<div id="credits">
<h2>Credits</h2>
<ul>
<li>Thanks to Tamil Virtual Academy, Chennai for releasing ths source code of this application. This work is
open-source
publication of Vaani from <a href="http://vaani.neechalkaran.com" rel="nofollow">link</a>
You can support the close-source Vaani project, an 8 yr effort
as of 2020, by donating here <a href="http://neechalkaran.com/p/donate.html"
rel="nofollow">donate(link)</a></li>
<li>Python Port was enabled by Kaniyam Foundation, T. Shrinivasan, @manikk, Ashok Ramachandran, and others.
You can support Kaniyam Foundation and its mission by donating via instructions
here, <a href="http://www.kaniyam.com" rel="nofollow">Kaniyam</a>
The Python port depends on tamilsandhichecker project <a
href="https://github.com/nithyadurai87/tamil-sandhi-checker" rel="nofollow">link</a> and the
Open-Tamil
project <a href="https://pypi.org/project/Open-Tamil/" rel="nofollow">link:</a>
</div>
{% endblock %}
|
Ezhil-Language-Foundation/open-tamil
|
webapp/opentamilapp/templates/tamilinayavaani_spell_check.html
|
HTML
|
mit
| 7,595
|
'use strict';
var git = require('../')
console.log('git.short() => ' + git.short());
// 75bf4ee
console.log('git.long() => ' + git.long());
// 75bf4eea9aa1a7fd6505d0d0aa43105feafa92ef
console.log('git.branch() => ' + git.branch());
// master
// console.log('git.tag() => ', git.tag());
// console.log('git.log() => ', git.log());
console.log('git.message() => ' + git.message());
// initial commit
|
hongkongkiwi/git-rev-sync
|
example/simple.js
|
JavaScript
|
mit
| 404
|
require 'ostruct'
require 'active_support/core_ext/string/inflections'
module Lol
# DynamicModel extends OpenStruct adding the following features:
# - nested generation ({a: {}}) results in DynamicModel(a: DynamicModel)
# - parsing of date/time when property name ends with _at or _date and the value is a number
class DynamicModel < OpenStruct
def initialize(hash={})
raise ArgumentError, 'An hash is required as parameter' unless hash.is_a? Hash
@table = {}
@hash_table = {}
hash.each do |k,v|
key = k.to_s.underscore
set_property key, v
new_ostruct_member(key)
end
end
def to_h
@hash_table
end
def as_json opts={}
@table.as_json
end
private
def date_key? key
key.match(/^(.+_)?(at|date)$/)
end
def set_property key, v
if date_key?(key) && v.is_a?(Fixnum)
@table[key.to_sym] = @hash_table[key.to_sym] = value_to_date v
else
@table[key.to_sym] = convert_object v
@hash_table[key.to_sym] = v
end
end
def value_to_date v
Time.at(v / 1000)
end
def convert_object obj
if obj.is_a? Hash
self.class.new obj
elsif obj.respond_to?(:map)
obj.map { |o| convert_object o }
else
obj
end
end
end
end
|
emaserafini/ruby-lol
|
lib/lol/dynamic_model.rb
|
Ruby
|
mit
| 1,335
|
import { message } from 'antd'
import { changePasswordAction } from '../request/password'
export const changePassword = (data, cb) => (dispatch, getState) => {
dispatch(changePasswordAction(data)).then(action => {
action.data.body.opResult == '1' ?
message.success('密码修改成功!') :
message.error('密码修改失败,请重试!')
if (cb) cb()
})
}
|
OwlAford/IFP
|
src/reducers/common/password.js
|
JavaScript
|
mit
| 385
|
<!DOCTYPE html>
<html lang="ca-es" data-theme="">
<head>
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer-when-downgrade">
<title>La vista cansada</title>
<meta name="description" content="">
<link rel="icon" type="image/x-icon" href="https://carlesbellver.github.io/favicon.ico">
<link rel="apple-touch-icon-precomposed" href="https://carlesbellver.github.io/favicon.png">
<link rel="stylesheet" href="https://carlesbellver.github.io/css/light.css?rnd=1602439751" />
<style>
[data-theme="dark"] {
--font-color: #eee;
--bg-color: #212121;
--link-color:#599ada;
--link-state-color:#ff5858;
--link-state-border-color: rgba(238, 54, 54, 0.5);
--thead-bg-color: #343a40;
--table-border-color: lightgrey;
--pre-color: #333;
--pre-bg-color: #f1f1f1;
--bq-color: #ccc;
--hr-color: #333;
--pagination-bg-color: #373737;
--pagination-link-color: #b6b6b6;
--post-info-color: grey;
--switcher-color: #333;
--switcher-bg-color: #fff;
}
</style>
<link rel="stylesheet" href="https://carlesbellver.github.io/css/style.css?rnd=1602439751" />
<meta property="og:title" content="" />
<meta property="og:description" content="📎 Una aplicación inconstitucional del artículo 155
Joaquín Urías, professor de Dret Constitucional i ex-lletrat del Tribunal Constitucional. ¿Carta blanca per usurpar les competències de qualsevol comunitat autònoma amb què es discrepe?" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://carlesbellver.github.io/2017/10/23/una-aplicacin-inconstitucional.html" />
<meta property="article:published_time" content="2017-10-23T10:27:00+00:00" />
<meta property="article:modified_time" content="2017-10-23T10:27:00+00:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content=""/>
<meta name="twitter:description" content="📎 Una aplicación inconstitucional del artículo 155
Joaquín Urías, professor de Dret Constitucional i ex-lletrat del Tribunal Constitucional. ¿Carta blanca per usurpar les competències de qualsevol comunitat autònoma amb què es discrepe?"/>
</head>
<body>
<a class="skip-main" href="#main">Anar al contingut principal</a>
<div class="container">
<header class="common-header">
<h1 class="site-title">
<a href="/">La vista cansada</a>
</h1>
<nav>
<a class="" href="https://carlesbellver.github.io/about/" title="">Informació</a>
<a class="" href="https://carlesbellver.github.io/tags/" title="">Etiquetes</a>
</nav>
</header>
<main id="main" tabindex="-1">
<article class="post retalls h-entry">
<header class="post-header">
<h1 class="post-title p-name"></h1>
</header>
<div class="content e-content">
<p>📎 <a href="http://www.eldiario.es/tribunaabierta/aplicacion-inconstitucional-articulo_6_699990004.html">Una aplicación inconstitucional del artículo 155</a></p>
<p>Joaquín Urías, professor de Dret Constitucional i ex-lletrat del Tribunal Constitucional. ¿Carta blanca per usurpar les competències de qualsevol comunitat autònoma amb què es discrepe?</p>
</div>
<div class="post-info">
<a class="u-url" href="/2017/10/23/una-aplicacin-inconstitucional.html"><div class="post-date dt-published">2017-10-23</div></a>
<div class="post-taxonomies">
<ul class="post-tags">
<li><a href="https://carlesbellver.github.io/tags/retalls">#retalls</a></li>
</ul>
</div>
</div>
</article>
</main>
<footer class="common-footer">
<div class="common-footer-bottom">
<div class="copyright">
<p>Carles Bellver Torlà </p>
</div>
<button class="theme-switcher">
Tema fosc
</button>
<script>
const STORAGE_KEY = 'user-color-scheme'
const defaultTheme = "light"
let currentTheme
let switchButton
let autoDefinedScheme = window.matchMedia('(prefers-color-scheme: dark)')
const autoChangeScheme = e => {
currentTheme = e.matches ? 'dark' : 'light'
document.documentElement.setAttribute('data-theme', currentTheme)
changeButtonText()
}
document.addEventListener('DOMContentLoaded', function() {
switchButton = document.querySelector('.theme-switcher')
currentTheme = detectCurrentScheme()
if (currentTheme == 'dark') {
document.documentElement.setAttribute('data-theme', 'dark')
}
if (currentTheme == 'auto') {
autoChangeScheme(autoDefinedScheme);
autoDefinedScheme.addListener(autoChangeScheme);
}
changeButtonText()
switchButton.addEventListener('click', switchTheme, false)
})
function detectCurrentScheme() {
if (localStorage.getItem(STORAGE_KEY)) {
return localStorage.getItem(STORAGE_KEY)
}
if (defaultTheme) {
return defaultTheme
}
if (!window.matchMedia) {
return 'light'
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
}
return 'light'
}
function changeButtonText()
{
switchButton.textContent = currentTheme == 'dark' ? "Tema clar" : "Tema fosc"
}
function switchTheme(e) {
if (currentTheme == 'dark') {
localStorage.setItem(STORAGE_KEY, 'light')
document.documentElement.setAttribute('data-theme', 'light')
currentTheme = 'light'
} else {
localStorage.setItem(STORAGE_KEY, 'dark')
document.documentElement.setAttribute('data-theme', 'dark')
currentTheme = 'dark'
}
changeButtonText()
}
</script>
</div>
</footer>
</div>
</body>
</html>
|
carlesbellver/carlesbellver.github.io
|
2017/10/23/una-aplicacin-inconstitucional.html
|
HTML
|
mit
| 6,290
|
// https://github.com/jgthms/bulma/issues/238 thanks!
document.getElementById("nav-toggle").addEventListener("click", toggleNav);
function toggleNav() {
var nav = document.getElementById("nav-menu");
var className = nav.getAttribute("class");
if(className == "nav-right nav-menu") {
nav.className = "nav-right nav-menu is-active";
} else {
nav.className = "nav-right nav-menu";
}
}
// for the random quote in the header
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "/quotes.txt", true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n");
randLine = lines[Math.floor((Math.random() * lines.length) + 1)];
document.getElementById('quote').innerHTML = randLine ||
"Intelligence is the ability to adapt to change."; // fallback quote
}
}
};
txtFile.send(null);
document.getElementById("search-text").addEventListener("keydown", function(e) {
// search
if (e.keyCode == 13) { searchHandler(); }
}, false);
function searchHandler() {
var searchInput = document.getElementById('search-text');
var text = searchInput.value;
// add site:example.com in the placeholder
window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text;
}
|
wangxin1248/wangxin1248.github.io
|
assets/js/custom.js
|
JavaScript
|
mit
| 1,483
|
require 'rails_helper'
RSpec.describe ListItemsController, type: :controller do
end
|
AESM/UpAhead
|
spec/controllers/list_items_controller_spec.rb
|
Ruby
|
mit
| 88
|
<?php
/*
* This file is part of the Spira framework.
*
* @link https://github.com/spira/spira
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
namespace App\Providers;
use App\Extensions\Rbac\UserAssignmentStorage;
use Laravel\Lumen\Application;
use Spira\Rbac\Providers\RBACProvider;
use Spira\Rbac\Storage\AssignmentStorageInterface;
use Spira\Rbac\Storage\File\ItemStorage;
use Spira\Rbac\Storage\ItemStorageInterface;
class AccessServiceProvider extends RBACProvider
{
protected $defaultRoles = ['user'];
protected function registerAssignmentStorage()
{
$this->app->singleton(AssignmentStorageInterface::class, function (Application $app) {
return $app->make(UserAssignmentStorage::class);
});
}
protected function registerItemStorage()
{
$this->app->singleton(ItemStorageInterface::class, function (Application $app) {
return new ItemStorage($app->basePath().'/config/permissions.php');
});
}
}
|
spira/spira
|
api/app/Providers/AccessServiceProvider.php
|
PHP
|
mit
| 1,075
|
---
layout: tei
tei: '../tei/117.xml'
prev: '116'
self: '117'
next: '118'
---
|
alter-rebbe/collector
|
docs/archive/documents/117.html
|
HTML
|
mit
| 78
|
// Copyright (c) 2014 Estimote. All rights reserved.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class EILLocation;
@class EILPoint;
@class EILOrientedPoint;
/**
* Width of the border around location shape.
* Non-zero value is needed for objects like beacons
* to be rendered inside view.
*/
static const int kShapeLayerMargin = 20;
extern NSString * const kPositionViewIdentifier;
#ifdef IB_DESIGNABLE
IB_DESIGNABLE
#endif
/**
* The `EILIndoorLocationViewDelegate` protocol defines the methods to receive identifier of selected object.
*/
@class EILIndoorLocationView;
@protocol EILIndoorLocationViewDelegate <NSObject>
@optional
/**
* Tells the delegate that an object in the location view was selected.
*
* @param indoorLocationView Location view on which the object was selected.
* @param identifier Identifier of the selected object.
*/
- (void) indoorLocationView:(EILIndoorLocationView *)indoorLocationView
didSelectObjectWithIdentifier:(NSString *)identifier;
@end
/**
* A view for drawing EILLocation and user position within it.
*/
@interface EILIndoorLocationView : UIView
#pragma mark Properties
///-----------------------------------------
/// @name Properties
///-----------------------------------------
/** The delegate object to receive identifier of selected object in location view. */
@property (nonatomic, weak) id <EILIndoorLocationViewDelegate> delegate;
/** `EILLocation` object to be drawn. */
@property (nonatomic, strong, readonly) EILLocation *location;
/** If YES, then a trace will be displayed. */
@property (nonatomic, assign) BOOL showTrace;
/** If YES, then the view will be rotated so the position indicator will always be pointing up. */
@property (nonatomic, assign) BOOL rotateOnPositionUpdate;
/** Determines if location was drawn successfully. */
@property (nonatomic, assign, readonly) BOOL locationDrawn;
#pragma mark Styling properties
///-----------------------------------------
/// @name Styling properties
///-----------------------------------------
/** View representing current position indicator. */
@property (nonatomic, strong) UIView *positionView;
/** Image used as current position indicator. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIImage *positionImage;
#else
@property (nonatomic, strong) UIImage *positionImage;
#endif
/** Color of the location boundary. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *locationBorderColor;
#else
@property (nonatomic, strong) UIColor *locationBorderColor;
#endif
/** Thickness of the location boundary. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable NSInteger locationBorderThickness;
#else
@property (nonatomic, assign) NSInteger locationBorderThickness;
#endif
/** Color of the location door. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *doorColor;
#else
@property (nonatomic, strong) UIColor *doorColor;
#endif
/** Thickness of the location door. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable NSInteger doorThickness;
#else
@property (nonatomic, assign) NSInteger doorThickness;
#endif
/** Color of the location window. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *windowColor;
#else
@property (nonatomic, strong) UIColor *windowColor;
#endif
/** Color of the location window background. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *windowBackgroundColor;
#else
@property (nonatomic, strong) UIColor *windowBackgroundColor;
#endif
/** Thickness of the location window. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable NSInteger windowThickness;
#else
@property (nonatomic, assign) NSInteger windowThickness;
#endif
/** Color of the location trace. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *traceColor;
#else
@property (nonatomic, strong) UIColor *traceColor;
#endif
/** Thickness of the trace. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable NSInteger traceThickness;
#else
@property (nonatomic, assign) NSInteger traceThickness;
#endif
/** Color of the wall length labels. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, strong) IBInspectable UIColor *wallLengthLabelsColor;
#else
@property (nonatomic, strong) UIColor *wallLengthLabelsColor;
#endif
/** If YES, then wall length labels will be displayed. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable BOOL showWallLengthLabels;
#else
@property (nonatomic, assign) BOOL showWallLengthLabels;
#endif
/** Font size for wall length labels. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable NSInteger wallLengthLabelFontSize;
#else
@property (nonatomic, assign) NSInteger wallLengthLabelFontSize;
#endif
/** If YES, then beacons will be displayed. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
@property (nonatomic, assign) IBInspectable BOOL showBeacons;
#else
@property (nonatomic, assign) BOOL showBeacons;
#endif
#pragma mark Drawing location
///-----------------------------------------
/// @name Drawing location
///-----------------------------------------
/**
* Draws a graphical representation of `EILLocation` object.
*
* @param location Object representing current location.
*/
- (void)drawLocation:(EILLocation *)location;
/**
* Draws a graphical representation of `EILLocation` object
* cropped to only include things explicitly inside the chosen
* region (defined by bounding box).
*
* @param location Object representing current location.
* @param regionOfInterest Region of interest to be drawn
*/
- (void)drawLocation:(EILLocation *)location
inRegionOfInterest:(CGRect)regionOfInterest;
#pragma mark Handling position updates
///-----------------------------------------
/// @name Handling position updates
///-----------------------------------------
/**
* Updates current position indicator to the given position. If position is nil, indicator is hidden.
* Will throw an exception if called without first calling `drawLocation:`.
*
* @param position Object representing current position in the location.
*/
- (void)updatePosition:(EILOrientedPoint *)position;
#pragma mark Drawing trace
///-----------------------------------------
/// @name Drawing trace
///-----------------------------------------
/**
* Clears the trace.
*
* Will throw an exception if called without first calling `drawLocation:`.
*/
- (void)clearTrace;
#pragma mark Drawing user objects
///-----------------------------------------
/// @name Drawing user objects
///-----------------------------------------
/**
* Draws a view that represents a real object at given position in background.
*
* Background objects are drawn in order of addition below all other views.
* Object will be rotated with regard to location to match orientation of the position.
* Will throw an exception if called without first calling `drawLocation:`.
* Chosen identifier cannot be same as any beacon MAC address or kPositionViewIdentifier ("com.estimote.position.view").
*
* @param object View representing a real object. Cannot be nil.
* @param position Object representing position in the location. Cannot be nil.
* @param identifier Unique identifier by which view will be identified. Cannot be nil.
*/
- (void)drawObjectInBackground:(UIView *)object
withPosition:(EILOrientedPoint *)position
identifier:(NSString *)identifier;
/**
* Draws a view that represents a real object at given position in foreground.
*
* Foreground objects are drawn in order of addition on top of background objects,
* location and trace, but below position view. Object will be rotated with
* regard to location to match orientation of the position.
* Will throw an exception if called without first calling `drawLocation:`.
* Chosen identifier cannot be same as any beacon MAC address or kPositionViewIdentifier ("com.estimote.position.view").
*
* @param object View representing a real object. Cannot be nil.
* @param position Object representing position in the location. Cannot be nil.
* @param identifier Unique identifier by which view will be identified. Cannot be nil.
*/
- (void)drawObjectInForeground:(UIView *)object
withPosition:(EILOrientedPoint *)position
identifier:(NSString *)identifier;
/**
* Returns view for object that was previously added to location view.
*
* For tapped beacon its MAC address will be returned.
* For tapped position view kPositionViewIdentifier ("com.estimote.position.view") will be returned.
*
* @param identifier Unique identifier by which view is identified. Cannot be nil.
*
* @return view for object with provided identifier.
*/
- (UIView *)objectWithidentifier:(NSString *)identifier;
/**
* Moves an object identified by identifier to a given position.
*
* Object will be be rotated with regard to location to match orientation of the position.
* If animated is set to true, the transition will be animated with 0.1 s duration.
* Will throw an exception, if there is no view with corresponding identifier.
*
* @param identifier Unique identifier by which view will be identified. Cannot be nil.
* @param position Object representing position in the location. Cannot be nil.
* @param animated Whether transition should be animated.
*/
- (void)moveObjectWithIdentifier:(NSString *)identifier
toPosition:(EILOrientedPoint *)position
animated:(BOOL)animated;
/**
* Removes an object identified by identifier from the view.
*
* Will throw an exception, if there is no view with corresponding identifier.
*
* @param identifier Unique identifier by which view will be identified. Cannot be nil.
*/
- (void)removeObjectWithIdentifier:(NSString *)identifier;
#pragma mark Real to image coordinate calculations
///-----------------------------------------
/// @name Real to image coordinate calculations
///-----------------------------------------
/**
* Calculates X in view coordinate system from X in physical coordinate system.
*
* @param realX X coordinate in physical coordinate system (in meters).
*
* @return X coordinate in view coordinate system (in pixels).
*/
- (CGFloat)calculatePictureCoordinateForRealX:(double)realX;
/**
* Calculates Y in view coordinate system from Y in physical coordinate system.
*
* @param realY Y coordinate in physical coordinate system (in meters).
*
* @return Y coordinate in view coordinate system (in pixels).
*/
- (CGFloat)calculatePictureCoordinateForRealY:(double)realY;
/**
* Calculates point in view coordinate system from point in physical coordinate system.
*
* @param realPoint Point with coordinates in physical coordinate system (in meters).
*
* @return Point with coordinates in view coordinate system (in pixels).
*/
- (CGPoint)calculatePicturePointFromRealPoint:(EILPoint *)realPoint;
/**
* Calculates X in physical coordinate system from X in view coordinate system.
*
* @param realX X coordinate in view coordinate system (in pixels).
*
* @return X coordinate in physical coordinate system (in meters).
*/
- (double)calculateRealCoordinateForPictureX:(CGFloat)pictureX;
/**
* Calculates Y in physical coordinate system from T in view coordinate system.
*
* @param realY Y coordinate in view coordinate system (in pixels).
*
* @return Y coordinate in physical coordinate system (in meters).
*/
- (double)calculateRealCoordinateForPictureY:(CGFloat)pictureY;
/**
* Calculates point in physical coordinate system from point in view coordinate system.
*
* @param realPoint Point with coordinates in view coordinate system (in pixels).
*
* @return Point with coordinates in physical coordinate system (in meters).
*/
- (EILPoint *)calculateRealPointFromPicturePoint:(CGPoint)picturePoint;
@end
|
BrandeisXDemandware/iOS-App
|
Pods/EstimoteIndoorSDK/EstimoteIndoorLocationSDK/Headers/EILIndoorLocationView.h
|
C
|
mit
| 12,245
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 The NovaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "miner.h"
#include "kernel.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
extern unsigned int nMinerSleep;
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
int64_t nLastCoinStakeSearchInterval = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
// CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake, int64_t* pFees)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
CBlockIndex* pindexPrev = pindexBest;
int nHeight = pindexPrev->nHeight + 1;
if (!IsProtocolV2(nHeight))
pblock->nVersion = 6;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
if (!fProofOfStake)
{
CReserveKey reservekey(pwallet);
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
txNew.vout[0].scriptPubKey.SetDestination(pubkey.GetID());
}
else
{
// Height first in coinbase required for block.version=2
txNew.vin[0].scriptSig = (CScript() << nHeight) + COINBASE_FLAGS;
assert(txNew.vin[0].scriptSig.size() <= 100);
txNew.vout[0].SetEmpty();
}
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Fee-per-kilobyte amount considered the same as "free"
// Be careful setting this: if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
int64_t nMinTxFee = MIN_TX_FEE;
if (mapArgs.count("-mintxfee"))
ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
// Collect memory pool transactions into the block
int64_t nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !IsFinalTx(tx, nHeight))
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64_t nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
continue;
// Transaction fee
int64_t nMinFee = tx.GetMinFee(nBlockSize, GMF_BLOCK);
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
if (!fProofOfStake)
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nHeight, nFees);
if (pFees)
*pFees = nFees;
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime(), nHeight));
if (!fProofOfStake)
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
}
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hashBlock = pblock->GetHash();
uint256 hashProof = pblock->GetPoWHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if(!pblock->IsProofOfWork())
return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
if (hashProof > hashTarget)
return error("CheckWork() : proof-of-work not meeting target");
//// debug print
printf("CheckWork() : new proof-of-work block found \n proof hash: %s \ntarget: %s\n", hashProof.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckWork() : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckWork() : ProcessBlock, block not accepted");
}
return true;
}
bool CheckStake(CBlock* pblock, CWallet& wallet)
{
uint256 proofHash = 0, hashTarget = 0;
uint256 hashBlock = pblock->GetHash();
if(!pblock->IsProofOfStake())
return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
// verify hash target and signature of coinstake tx
if (!CheckProofOfStake(mapBlockIndex[pblock->hashPrevBlock], pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
return error("CheckStake() : proof-of-stake checking failed");
//// debug print
printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("CheckStake() : generated block is stale");
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[hashBlock] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("CheckStake() : ProcessBlock, block not accepted");
}
return true;
}
void StakeMiner(CWallet *pwallet)
{
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("crackcoin-miner");
bool fTryToSync = true;
while (true)
{
if (fShutdown)
return;
while (pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
MilliSleep(1000);
if (fShutdown)
return;
}
while (vNodes.empty() || IsInitialBlockDownload())
{
nLastCoinStakeSearchInterval = 0;
fTryToSync = true;
MilliSleep(1000);
if (fShutdown)
return;
}
if (fTryToSync)
{
fTryToSync = false;
if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
{
MilliSleep(60000);
continue;
}
}
//
// Create new block
//
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true, &nFees));
if (!pblock.get())
return;
// Trying to sign a block
if (pblock->SignBlock(*pwallet, nFees))
{
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckStake(pblock.get(), *pwallet);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
MilliSleep(500);
}
else
MilliSleep(nMinerSleep);
}
}
|
OfficialCrackCoin/CrackCoin
|
src/miner.cpp
|
C++
|
mit
| 20,148
|
var gulp = require('gulp'),
watch = require('gulp-watch'),
run = require('gulp-run'),
sourcemaps = require('gulp-sourcemaps'),
rename = require('gulp-rename'),
mochify = require('mochify'),
to5 = require('gulp-6to5');
gulp.task('6to5', function() {
return gulp.src('**/*.es6')
.pipe(sourcemaps.init())
.pipe(to5({
experimental: true,
loose: 'all'
}))
.pipe(sourcemaps.write())
.pipe(rename({
extname: '.js'
}))
.pipe(gulp.dest('./'));
});
gulp.task('test', ['6to5'], function() {
mochify('./test.js', {
reporter: 'tap'
}).bundle();
});
gulp.task('default', ['test'], function() {
gulp.watch('**/*.es6', ['test']);
});
|
fp-dom/fd-select
|
gulpfile.js
|
JavaScript
|
mit
| 692
|
/**
* TPPLeague Admin Commands
* TPPLeague - https://tppleague.me/
*
* This command namespace is used internally by the client to communicate
* for the Adventure Builder / TPPLeague Administration room(s).
*
* For the API, see chat-plugins/COMMANDS.md
*
* @license MIT license
*/
/* global Rooms */
'use strict';
const proxy = require("../save-proxy.js");
const LEAGUE_CONFIG_FILE = require.resolve("../config/league/league_setup.json");
const DEL_TIMEOUT = 1000*60*2;
var delConfirm = {};
if (!global.LeagueSetup) global.LeagueSetup = proxy(LEAGUE_CONFIG_FILE, '\t');
/* global LeagueSetup */
const alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function createToken() {
let id = "";
for (let i = 0; i < 11; i++) {
id += alpha[Math.floor(Math.random()*alpha.length)];
}
return id;
}
function confirmToken(token) {
// If we have a confirmation token
// console.log(`confirmToken(${token}) => delConfirm[]=${delConfirm[token]} => ${delConfirm[token] + DEL_TIMEOUT} > ${Date.now()} => ${delConfirm[token] + DEL_TIMEOUT > Date.now()}`);
if (token) {
// If the confirmation token is valid and is in date
if (delConfirm[token] && delConfirm[token] + DEL_TIMEOUT > Date.now()) {
// Allow the deletion to go through
delete delConfirm[token];
return true;
}
if (delConfirm[token] + DEL_TIMEOUT > Date.now()) {
delete delConfirm[token];
}
}
return false;
}
function commandCheck(ctx) {
if (ctx.cmdToken === '!') { ctx.errorReply("You cannot broadcast this command."); return false; }
if (Rooms.global.lockdown) { ctx.connection.send(`|queryresponse|adventbuilder|{"err":"lockdown"}`); return false; }
if (!ctx.user.registered) { ctx.connection.send(`|queryresponse|adventbuilder|{"err":"unregistered"}`); return false; }
return true;
}
function createTrainerID() {
let id = require("crypto").randomBytes(4);
let secretId = id.readUInt16LE(0);
let trainerId = id.readUInt16LE(2);
return [secretId, trainerId];
}
// function sendFormats(){
// let list = [
// // ValidatorRules
// 'Nickname Clause','Item Clause','Ability Clause','-ate Clause','OHKO Clause',
// 'Evasion Abilities Clause','Evasion Moves Clause','Moody Clause','Swagger Clause',
// 'Baton Pass Clause','Baton Pass Speed Clause',
// // Battle Rules
// 'Endless Battle Clause','Sleep Clause Mod','Freeze Clause Mod','Same Type Clause',
// 'Mega Rayquaza Clause',
// 'HP Percentage Mod','Exact HP Mod',
// //'Groundsource Mod',
// ];
// this.sendReply(`|adventbuilder|league-extra-formats|${JSON.stringify()}`);
// }
function getGymInfo(json){
json = json || {};
json.elites = {};
json.gyms = {};
Object.keys(LeagueSetup.elites).forEach((key)=>{
if (LeagueSetup.elites[key].isHidden) return;
json.elites[key] = {
name: LeagueSetup.elites[key].name,
types: LeagueSetup.elites[key].types,
battletype: LeagueSetup.elites[key].battletype,
avatar: LeagueSetup.elites[key].avatar,
isChamp: LeagueSetup.elites[key].isChamp,
banlist: LeagueSetup.elites[key].banlist,
};
});
Object.keys(LeagueSetup.gyms).forEach((key)=>{
if (LeagueSetup.gyms[key].isHidden) return;
json.gyms[key] = {
name: LeagueSetup.gyms[key].name,
types: LeagueSetup.gyms[key].types,
battletype: LeagueSetup.gyms[key].battletype,
avatar: LeagueSetup.gyms[key].avatar,
badge: LeagueSetup.gyms[key].badge,
banlist: LeagueSetup.gyms[key].banlist,
trialdesc: LeagueSetup.gyms[key].trialdesc,
};
});
return json;
}
function LeagueSetupSend(msg) {
if (!msg) return;
if (!msg.room) msg.room = Rooms.global;
switch (msg.type) {
case 'new': {
switch (msg.event) {
case 'gym' : {
if (!LeagueSetup.gyms[msg.userid]) {
LeagueSetup.gyms[msg.userid] = {
name: msg.username || msg.userid,
types: [],
battletype: 'singles',
avatar: 167, // Questionmark Napoleon
pending: [],
};
LeagueSetup.markDirty();
}
return LeagueSetup.gyms[msg.userid];
}
case 'elite': {
if (!LeagueSetup.elites[msg.userid]) {
LeagueSetup.elites[msg.userid] = {
isChamp: false,
types: [],
battletype: 'singles',
name: "",
avatar: 167, // Questionmark Napoleon
pending: [],
};
LeagueSetup.markDirty();
}
return LeagueSetup.elites[msg.userid];
}
case 'hallOfFame': {
if (typeof msg.user === 'string') msg.user = Users.get(msg.user);
let hof = LeagueSetup.hallOfFame[msg.type || 'singles'];
let chall = LeagueSetup.challengers[msg.user.userid];
let entry = {
num: hof.length+1,
name: msg.user.name,
trainerid: chall.trainerid,
team: msg.team,
};
hof.unshift(entry);
LeagueSetup.markDirty();
return entry;
}
}
} return;
case 'e4fight': {
console.log(msg.otherInfo);
if (!msg.p1) return msg.room.add('|html|<div class="broadcast-red">Unable to determine elite member! Tustin, you fucked it up!</div>');
if (!msg.p2) return msg.room.add('|html|<div class="broadcast-red">Unable to determine challenger! Tustin, you fucked it up!</div>');
if (!LeagueSetup.challengers[msg.p2]) return msg.room.add(`|error|Unable to ${msg.event} challenger: Challenger has no league challenge!`);
let user = Users.get(msg.p2);
let elite = Users.get(msg.p1) || {};
if (!LeagueSetup.challengers[msg.p2].e4wins) LeagueSetup.challengers[msg.p2].e4wins = {};
switch(msg.event) {
case 'restart':
// A challenger failed their e4 fight
LeagueSetup.challengers[msg.p2].e4wins = {};
LeagueSetup.markDirty();
setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue">The challenger ${user.name} has lost the battle against ${elite.name}. The challenger will have to restart their Elite Four run.</div>`), 4000);
return;
case 'advance':
// A challenger advanced in their e4 fight
LeagueSetup.challengers[msg.p2].e4wins[msg.p1] = true;
LeagueSetup.markDirty();
let adv = "The challenger may advance to the next Elite Member!";
if (Object.keys(LeagueSetup.challengers[msg.p2].e4wins).length >= 4) {
adv = "The challenger is ready to challenge the League Champion!";
}
setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue">The challenger ${user.name} has won the battle against ${elite.name}. ${adv}</div>`), 4000);
return;
case 'complete': {
// A challenger has defeated the champion and has become champion himself!
let hof = LeagueSetup.send({
type:"new",
event:"hallOfFame",
user:user,
type: msg.otherInfo[0],
team: msg.otherInfo[1],
});
let settings = LeagueSetup.send({type:"new", event:"elite", userid: user.userid, username: user.name});
settings.isChamp = true;
settings.isFormerChamp = false;
settings.avatar = user.avatar;
LeagueSetup.elites[elite.userid].isFormerChamp = true;
LeagueSetup.elites[elite.userid].isHidden = true;
let num = hof.num;
num = num + (['th','st','nd','rd'][num%10]||'th');
if (num==='11st'||num==='12nd'||num==='13rd') num=num.slice(0,2)+"th";
setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue"><b>The challenger ${user.name} has won against ${elite.name}! Congratuations to our new ${num} TPPLeague Champion, ${user.name}!</b></div>`), 4000);
Rooms.global.add(`|html|<div class="broadcast-blue"><b>Congratuations to our new ${num} TPPLeague Champion, ${user.name}!</b></div>`);
BotManager.announceNotify(`Congratuations to our new ${num} TPPLeague Champion, ${user.name}!`);
} return;
}
} return;
case 'champion': {
switch (msg.event) {
case 'prep':
BotManager.announceNotify(`TPPLeague Champion Battle will be beginning soon!`);
Users.users.forEach(curUser => curUser.send('|champnotify|notify') );
return;
case 'begin':
BotManager.announceNotify(`TPPLeague Champion Battle has begun! https://tppleague.me/${msg.battleid}`);
return;
case 'ongoing': //sent about every 10 rounds
BotManager.announce(`TPPLeague Champion Battle is in progress! https://tppleague.me/${msg.battleid}`);
return;
case 'finished':
BotManager.announce(`TPPLeague Champion Battle has completed! https://tppleague.me/${msg.battleid}`);
Users.users.forEach(curUser => curUser.send('|champnotify|finished') );
return;
case 'finished-lose':
BotManager.announce(`TPPLeague Champion Battle has completed! The Champion has defended their title! https://tppleague.me/${msg.battleid}`);
Users.users.forEach(curUser => curUser.send('|champnotify|finished') );
return;
}
} return;
}
}
LeagueSetup.send = LeagueSetupSend; // Note: this always runs on hotpatch
exports.commands = {
adventbuilder : {
reload : function() {
if (!this.can('hotpatch')) return false;
try {
let setup = proxy(LEAGUE_CONFIG_FILE, '\t');
LeagueSetup.dispose();
global.LeagueSetup = setup;
LeagueSetup.send = LeagueSetupSend;
} catch (e) {
if (e.name === 'SyntaxError') {
this.errorReply("League Setup file is malformatted! Fix your JSON!");
this.errorReply(e.message);
} else {
this.errorReply("Unexpected error while reloading league setup: "+e.message);
}
return;
}
return this.sendReply("The TPPLeague setup has been reloaded from disk.");
},
request : {
// /adventbuilder request options
options : function(target, room, user) {
if (!commandCheck(this)) return;
let opts = [];
if (LeagueSetup.admins.includes(user.userid)) {
opts.push("league-admin");
}
opts.push("view-league");
if (LeagueSetup.elites[user.userid]) {
if (LeagueSetup.elites[user.userid].isChamp) {
opts.push("league-champ");
} else {
opts.push("league-elite");
}
}
if (LeagueSetup.gyms[user.userid]) {
opts.push("league-gym");
}
if (LeagueSetup.challengers[user.userid]) {
opts.push("league-challenge");
} else {
opts.push("league-challenge:new");
}
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify( {screen:"opts", info:opts} )}`);
},
'league-admin': function(target, room, user) {
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let json = {
options: LeagueSetup.options,
elites: LeagueSetup.elites,
gyms: LeagueSetup.gyms,
challengers: LeagueSetup.challengers
};
let resp = {
screen: 'league-admin',
info: json,
};
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify( resp )}`);
},
'league-champ': 'league-elite',
'league-elite': function(target, room, user) {
if (!commandCheck(this)) return;
if (!LeagueSetup.elites[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let resp = {
screen: 'league-elite',
options: LeagueSetup.options,
info: LeagueSetup.elites[user.userid],
user: {
name: this.user.name,
avatar: this.user.avatar,
},
};
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`);
},
'league-gym': function(target, room, user) {
if (!commandCheck(this)) return;
if (!LeagueSetup.gyms[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let resp = {
screen: 'league-gym',
options: LeagueSetup.options,
info: LeagueSetup.gyms[user.userid],
user: {
name: this.user.name,
avatar: this.user.avatar,
},
};
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`);
},
'view-league': function(target, room, user) {
if (this.cmdToken === '!') { this.errorReply("You cannot broadcast this command."); return false; }
let resp = {
screen: 'view-league',
league: getGymInfo(),
};
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`);
},
'league-challenge': function(target, room, user) {
if (!commandCheck(this)) return;
if (!LeagueSetup.challengers[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let resp = {
screen: 'league-challenge',
//must clone this, so we don't modify the original below
info: Object.assign({}, LeagueSetup.challengers[user.userid]),
league: getGymInfo(),
user: {
name: this.user.name,
avatar: this.user.avatar,
},
};
// Gen 7 trainer ids: secretid + trainerid * 65536, last 6 digits
let trid = resp.info.trainerid;
resp.info.trainerid = String(trid[0] + trid[1] * 65536).substr(-6);
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`);
},
},
'new' : {
// /adventbuilder new league-challenge - Creates a new league challenge for this user
'league-challenge': function(target, room, user) {
if (!commandCheck(this)) return;
if (LeagueSetup.challengers[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"League Challenge already exists for this user."}`);
LeagueSetup.challengers[user.userid] = {
teams : {},
badges: {},
trainerid: createTrainerID(),
startdate: Date.now(),
};
LeagueSetup.markDirty();
let resp = {
welcome: "league-challenge",
};
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`);
this.parse('/adventbuilder request league-challenge');
},
},
'del' : {
// /adventbuilder del league-challenge [confirmtoken] - Deletes the user's league challenge
'league-challenge': function(target) {
if (!commandCheck(this)) return;
if (!LeagueSetup.challengers[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
if (!confirmToken(target)) {
let confirmid = createToken();
delConfirm[confirmid] = Date.now();
return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`);
}
delete LeagueSetup.challengers[this.user.userid];
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"League Challenge has been forfeited successfully."}`);
this.parse('/adventbuilder request options');
},
},
// /adventbuilder teamcommit [type]|[oldid]|[newid]|[teamstring] - Commits a saved team.
teamcommit : function(target, room, user) {
if (!commandCheck(this)) return;
target = target.split('|');
let type;
switch (target[0]) {
case 'elite': type = "elites"; break;
case 'gym': type = "gyms"; break;
case 'trainer': type = "challengers"; break;
}
if (!LeagueSetup[type][user.userid]) return this.errorReply("Cannot commit team: unauthorized access.");
let save = LeagueSetup[type][user.userid];
let oldid = target[1];
let newid = target[2];
if (newid != oldid) {
delete save.teams[oldid];
}
save.teams[newid] = target.slice(3).join('|');
LeagueSetup.markDirty();
},
commit : {
// /adventbuilder commit leagueopts [json] - Sent by the Admin screen to commit league-wide options
leagueopts : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
try {
let obj = JSON.parse(target);
let save = LeagueSetup.options;
Object.keys(obj).forEach((key)=> save[key] = obj[key] );
} catch (e) {
console.log("Illegal commit: "+target);
console.log("Error: ", e);
return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.');
}
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"League Options saved!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit rmchal [username] [confirmtoken] - Sent by the Admin screen to remove a challenger
rmchal : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
target = target.split(" ");
let other = { userid: toId(target[0]), name: target[0] };
if (!LeagueSetup.challengers[other.userid]) {
other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] };
}
if (!LeagueSetup.challengers[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Challenger profile for '${other.name}'"}`);
if (!confirmToken(target[1])) {
let confirmid = createToken();
delConfirm[confirmid] = Date.now();
return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`);
}
delete LeagueSetup.challengers[other.userid];
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"Challenger profile for '${other.name}' deleted!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit addgym [username] - Sent by the Admin screen to add a new gymleader
addgym : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let other = { userid: toId(target), name: target };
if (!LeagueSetup.gyms[other.userid]) {
other = Users.get(target) || { userid: toId(target), name: target };
}
if (LeagueSetup.gyms[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"Gym already exists for user ${other.name}."}`);
LeagueSetup.send({type:"new", event:"gym", userid: other.userid, username: other.name});
this.connection.send(`|queryresponse|adventbuilder|{"success":"Gym for '${other.name}' added!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit rmgym [username] [confirmtoken] - Sent by the Admin screen to remove a gymleader
rmgym : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
target = target.split(" ");
let other = { userid: toId(target[0]), name: target[0] };
if (!LeagueSetup.gyms[other.userid]) {
other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] };
}
if (!LeagueSetup.gyms[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Gym for '${other.name}'"}`);
if (!confirmToken(target[1])) {
let confirmid = createToken();
delConfirm[confirmid] = Date.now();
return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`);
}
delete LeagueSetup.gyms[other.userid];
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"Gym for '${other.name}' deleted!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit addelite [username] - Sent by the Admin screen to add a new elite member
addelite : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let other = { userid: toId(target), name: target };
if (!LeagueSetup.elites[other.userid]) {
other = Users.get(target) || { userid: toId(target), name: target };
}
if (LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"Elite settings already exist for user ${other.name}."}`);
LeagueSetup.send({type:"new", event:"elite", userid: other.userid, username: other.name});
this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite for '${other.name}' added!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit rmelite [username] [confirmtoken] - Sent by the Admin screen to remove an elite member
rmelite : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
target = target.split(" ");
let other = { userid: toId(target[0]), name: target[0] };
if (!LeagueSetup.elites[other.userid]) {
other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] };
}
if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}'"}`);
if (!confirmToken(target[1])) {
let confirmid = createToken();
delConfirm[confirmid] = Date.now();
return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`);
}
delete LeagueSetup.elites[other.userid];
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite for '${other.name}' deleted!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit promotechamp [username] - Sent by the Admin screen to set an elite member as chamption
promotechamp : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let other = { userid: toId(target), name: target };
if (!LeagueSetup.elites[other.userid]) {
other = Users.get(target) || { userid: toId(target), name: target };
}
if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}"}'`);
LeagueSetup.elites[other.userid].isChamp = true;
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite '${other.name}' has been promoted to Champion!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit demotechamp [username] - Sent by the Admin screen to unset am elite member as champion
demotechamp : function(target){
if (!commandCheck(this)) return;
if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let other = { userid: toId(target), name: target };
if (!LeagueSetup.elites[other.userid]) {
other = Users.get(target) || { userid: toId(target), name: target };
}
if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}"}'`);
LeagueSetup.elites[other.userid].isChamp = false;
LeagueSetup.markDirty();
this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite '${other.name}' has been demoted to Elite Four member!"}`);
this.parse('/adventbuilder request league-admin');
},
// /adventbuilder commit elite {json} - Sent by the Elite settings screen to commit changed made by the screen
elite : function(target) {
if (!commandCheck(this)) return;
if (!LeagueSetup.elites[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let errors = [];
try {
let obj = JSON.parse(target);
let save = LeagueSetup.elites[this.user.userid];
// Limit the values we save, and validate them on the way in.
if (obj.name) {
if (LeagueSetup.options.titleRename) {
save.name = Chat.escapeHTML(obj.name.substr(0, 32));
} else if (obj.name !== save.name) {
errors.push("Changing of E4 titles is not allowed at this time by League Admin mandate.");
}
}
if (obj.types) {
let val = obj.types
//TODO validate
save.types = val;
}
if (obj.bgimg) {
let val = obj.bgimg;
save.bgimg = Config.stadium.background().convertToId(val);
}
if (obj.bgmusic) {
let val = obj.bgmusic;
if (Config.stadium.music().isValidBattle(val)) {
save.bgmusic = val;
} else {
errors.push("Background music is not valid.");
}
}
if (obj.battletype) {
let val = obj.battletype;
if (/singles|doubles|triples/.test(val)) {
save.battletype = val;
} else {
errors.push("Battle type is not valid.");
}
}
if (obj.ruleset) {
let val = obj.ruleset;
if (Array.isArray(val) && val.every(x => typeof x == 'string')) {
save.ruleset = val.map(x=>x.trim()).filter(x => !!x);
} else {
errors.push("Ruleset is invalid.");
}
}
if (obj.banlist) {
let val = obj.banlist;
if (Array.isArray(val) && val.every(x => typeof x == 'string')) {
save.banlist = val.map(x=>x.trim()).filter(x => !!x);
} else {
errors.push("Banlist is invalid.");
}
}
save.avatar = this.user.avatar; //Save off the avatar for later use by others
LeagueSetup.markDirty();
} catch (e) {
console.log("Illegal commit: "+target);
console.log("Error: ", e);
return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.');
}
let repl = { success: "Settings saved!" };
if (errors.length) {
repl.success = "Settings saved with the following caveats:\n\n- "+errors.join("\n- ");
}
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(repl)}`);
this.parse('/adventbuilder request league-elite');
},
// /adventbuilder commit gym {json} - Sent by the Gym settings screen to commit changed made by the screen
gym : function(target) {
if (!commandCheck(this)) return;
if (!LeagueSetup.gyms[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`);
let errors = [];
try {
let obj = JSON.parse(target);
let save = LeagueSetup.gyms[this.user.userid];
// Limit the values we save
// Limit the values we save, and validate them on the way in.
if (obj.name) {
if (LeagueSetup.options.gymRename){
save.name = Chat.escapeHTML(obj.name.substr(0, 16));
} else if (obj.name !== save.name) {
errors.push("Changing of gym names is not allowed at this time by League Admin mandate.");
}
}
if (obj.badge) {
if (LeagueSetup.options.badgeRename) {
let val = obj.badge;
if (val === 'undefined' || val === '') val = undefined;
else val = val.replace(/[^a-zA-Z- ]/, "").substr(0, 32);
// Check badged uniqueness
{
let dup = false;
Object.keys(LeagueSetup.gyms).forEach((g)=>{
if (val === LeagueSetup.gyms[g].badge) {
dup = true;
}
});
if (dup) {
val = save.badge;
errors.push("Badge name is not unique.");
}
}
if (save.badge !== val) {
let old = save.badge;
save.badge = val;
// Object.keys(LeagueSetup.challengers).forEach((c)=>{
// if (LeagueSetup.challengers[c].badges[old] === 1) {
// delete LeagueSetup.challengers[c].badges[old];
// LeagueSetup.challengers[c].badges[val] = 1;
// }
// });
}
} else if (obj.badge !== save.badge) {
errors.push("Changing of badge names is not allowed at this time by League Admin mandate.");
}
}
if (obj.types) {
let val = obj.types;
//TODO validate
save.types = val;
}
if (obj.bgimg) {
let val = obj.bgimg;
save.bgimg = Config.stadium.background().convertToId(val);
}
if (obj.bgmusic) {
let val = obj.bgmusic;
if (Config.stadium.music().isValidBattle(val)) {
save.bgmusic = val;
} else {
errors.push("Background music is not valid.");
}
}
if (obj.battletype) {
let val = obj.battletype;
if (/singles|doubles|triples|trial/.test(val)) {
save.battletype = val;
} else {
errors.push("Battle type is not valid.");
}
}
if (obj.ruleset) {
let val = obj.ruleset;
if (Array.isArray(val) && val.every(x => typeof x == 'string')) {
save.ruleset = val.map(x=>x.trim()).filter(x => !!x);
} else {
errors.push("Ruleset is invalid.");
}
}
if (obj.banlist) {
let val = obj.banlist;
if (Array.isArray(val) && val.every(x => typeof x == 'string')) {
save.banlist = val.map(x=>x.trim()).filter(x => !!x);
} else {
errors.push("Banlist is invalid.");
}
}
if (obj.trialdesc) {
var val = obj.trialdesc;
if (val === 'undefined' || val === '') val = undefined;
else val = val.trim().substr(0, 1000);
save.trialdesc = val;
}
save.avatar = this.user.avatar; //Save off the avatar for later use by others
LeagueSetup.markDirty();
} catch (e) {
console.log("Illegal commit: "+target);
console.log("Error: ", e);
return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.');
}
let repl = { success: "Settings saved!" };
if (errors.length) {
repl.success = "Settings saved with the following caveats:\n\n- "+errors.join("\n- ");
}
this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(repl)}`);
this.parse('/adventbuilder request league-gym');
},
},
},
adventbuilderhelp : [
'/adventbuilder - Command used internally by the Adventure Builder. Use the "TPPLeague" tab instead.',
],
pendingchallenges : function(target) {
if (this.cmdToken === '!') return this.errorReply('You cannot broadcast this command.');
let silent = (target === 'silent');
// if (Rooms.global.lockdown) return this.errorReply('The server is in lockdown. You cannot hand out badges at this time.');
if (!this.user.registered) {
if (!silent) this.errorReply('Please log in first.');
return;
}
let gym = LeagueSetup.gyms[this.user.userid];
if (gym) {
if (gym.pending.length) {
this.sendReply("Challengers waiting to fight your gym: "+gym.pending.join(","));
} else if (!silent) {
this.sendReply("There are no challengers waiting to fight your gym right now.");
}
}
gym = LeagueSetup.elites[this.user.userid];
if (gym) {
if (gym.pending.length) {
this.sendReply("Challengers waiting to fight your E4 team: "+gym.pending.join(","));
} else if (!silent) {
this.sendReply("There are no challengers waiting to fight your E4 team right now.");
}
}
},
pendingchallengeshelp : [
'/pendingchallenges - Show any pending challenges you have.',
],
givebadge : function(target) {
if (this.cmdToken === '!') return this.errorReply('You cannot broadcast this command.');
if (Rooms.global.lockdown) return this.errorReply('The server is in lockdown. You cannot hand out badges at this time.');
if (!this.user.registered) return this.errorReply('Please log in first.');
if (!LeagueSetup.options.badgeGive) return this.errorReply("No badges are allowed to be handed out at this time, by League Administration mandate.");
let gym = LeagueSetup.gyms[this.user.userid];
if (!gym && !LeagueSetup.admins.includes(this.user.userid)) {
return this.errorReply("You are not a registered gym leader.");
}
let badge = gym.badge;
let other = null;
let admin = "";
if (this.room.battle) {
if (!this.room.battle.ended) return this.errorReply(`But the battle in this room isn't finished!`);
if (this.room.battle.format === 'tppleaguegym' && this.room.battle.p1 === this.user) {
other = this.room.battle.p2;
}
}
if (!other) {
if (!target) return this.errorReply(`No target user.`);
let b = this.splitTarget(target);
if (!this.targetUser) return this.errorReply(`User is not online to recieve their badge.`);
other = this.targetUser;
if (b) {
if (LeagueSetup.admins.includes(this.user.userid)) {
badge = b;
admin = ", on behalf of the League Administration,";
} else {
return this.errorReply("Only League Administrators can hand out arbitrary badges.");
}
}
}
if (!badge) {
return this.errorReply(`You have not defined a badge for your gym.`);
}
if (Date.now() < (gym.lastBadgeGivenTime || 0)+1000*60*6){ // 6 minnutes
return this.errorReply(`You are giving out badges too quickly. Legit fights do not last 30 seconds after all.`);
}
if (other === this.user || other.userid === this.user.userid) {
return this.errorReply('You cannot give your own badge to yourself, cheater.');
}
let challenge = LeagueSetup.challengers[other.userid];
if (!challenge) {
// other.sendTo(this.room, `|html|<div class="message-error">${this.user.name} is attempting to give you a TPPLeague badge, but you do not have a TPPLeague challenge set up to recieve the badge. If you wish to recieve this badge, please user the TPPLeague button on the main menu to begin a league challenge.</div>`);
return this.errorReply(`${other.name} does not have a TPPLeague challenge set up. Cannot give badge.`);
}
if (challenge.badges[badge]) {
return this.errorReply(`${other.name} already owns the ${badge} Badge.`);
}
gym.lastBadgeGivenTime = Date.now();
challenge.badges[badge] = 1;
LeagueSetup.markDirty();
this.add(`|html|<div class="infobox badgeget" for="${other.userid}" style="text-align:center;"><p style='font-weight:bold;'>${this.user.name}${admin} presents ${other.name} with the ${badge} Badge!</p><img src="/badges/${badge}.png" width="80" height="80"/></div>`);
other.send(`|badgeget|${badge}`);
this.parse('/savereplay silent');
},
givebadgehelp: [
'/givebadge [user] - If you are a gym leader, gives your gym badge to the named user. User must be present.',
],
};
|
azum4roll/Pokemon-Showdown
|
chat-plugins/league-admin.js
|
JavaScript
|
mit
| 34,300
|
<?php
/*
* Copyright (c) 2011-2015, Celestino Diaz <celestino.diaz@gmx.de>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Brickoo\Component\IO\Stream;
use Brickoo\Component\Common\Assert;
/**
* SocketStreamConfig
*
* Implements a socket stream configuration.
* @author Celestino Diaz <celestino.diaz@gmx.de>
*/
class SocketStreamConfig {
/** @var string */
private $serverAddress;
/** @var integer */
private $serverPort;
/** @var integer */
private $connectionTimeout;
/** @var integer */
private $connectionType;
/** @var array */
private $context;
/**
* Class constructor.
* @param string $address
* @param integer $port
* @param integer $timeout
* @param integer $connectionType
* @param array $context
*/
public function __construct($address, $port, $timeout = 30, $connectionType = STREAM_CLIENT_CONNECT, array $context = array()) {
Assert::isString($address);
Assert::isInteger($timeout);
Assert::isInteger($connectionType);
$this->serverAddress = $address;
$this->serverPort = $port;
$this->connectionTimeout = $timeout;
$this->connectionType = $connectionType;
$this->context = $context;
}
/**
* Returns the server address.
* @return string the server address
*/
public function getAddress() {
return $this->serverAddress;
}
/**
* Returns the server port number.
* @return integer the server port number
*/
public function getPort() {
return $this->serverPort;
}
/**
* Returns the complete socket address.
* @return string the socket address
*/
public function getSocketAddress() {
return sprintf("%s:%d", $this->getAddress(), $this->getPort());
}
/**
* Returns the connection timeout.
* @return integer the connection timeout
*/
public function getConnectionTimeout() {
return $this->connectionTimeout;
}
/**
* Return one of the connection type flags.
* @return integer the connection type
*/
public function getConnectionType() {
return $this->connectionType;
}
/**
* Returns the connection context.
* @return array the connection context
*/
public function getContext() {
return $this->context;
}
}
|
brickoo/components
|
src/IO/Stream/SocketStreamConfig.php
|
PHP
|
mit
| 3,438
|
package main.model.tower;
import main.model.Vector2D;
/**
* @author Luis Gallet Zambrano
*
*/
public class MortarTower extends Tower {
public MortarTower(Vector2D position) {
//Level 1 characteristics of the MortarTower
super(40,175,175,1,350, 1, 1800, position);
//range,refund value, power, rate of fire, buying cost, level, upgrading cost, position
}
}
|
ECSE321/TD-Final
|
src/main/model/tower/MortarTower.java
|
Java
|
mit
| 380
|
/**
Data comes from a docker inspect command output
*/
function Container(data)
{
for (d in data) {
this[d] = data[d];
}
}
Container.prototype.name = function()
{
return this.Name.ltrim('/');
}
Container.prototype.shortName = function()
{
return this.name();
}
Container.prototype.shortId = function()
{
return this.Id.substr(0, 12);
}
Container.prototype.links = function()
{
if (this.HostConfig == undefined || this.HostConfig.Links == undefined) {
return [];
}
return this.HostConfig.Links.reduce(function (arr, str) {
var name = str.split(':')[0];
if (arr.indexOf(name) < 0) {
arr.push(name);
}
return arr;
}, []);
}
Container.prototype.linksShortNames = function()
{
if (this.HostConfig == undefined || this.HostConfig.Links == undefined) {
return {};
}
return this.HostConfig.Links.reduce(function (arr, str) {
var parts = str.split(':');
var name = parts[0];
var sname = parts.last().split('/').last();
if (!(name in arr) || sname.length < arr[name].length) {
arr[name] = sname;
}
return arr;
}, {});
}
Container.prototype.stringPorts = function()
{
if (this.NetworkSettings == undefined || this.NetworkSettings.Ports == undefined) {
return []
}
var ports = []
for (ph in this.NetworkSettings.Ports) {
var list = this.NetworkSettings.Ports[ph]
ports = ports.concat(list.map(function(o) {
return o.HostIp+':'+o.HostPort+'->'+ph
}))
}
return ports
}
module.exports = Container;
|
devster/docktop
|
lib/docker/container.js
|
JavaScript
|
mit
| 1,651
|
# -*- coding: utf-8 -*-
import sys
def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
barLength - Optional : character length of bar (Int)
copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
With slight adjustment so that it allows just one iteration (total = 0)
"""
formatStr = "{0:." + str(decimals) + "f}"
percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100)
filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength))
bar = '█' * filledLength + '-' * (barLength - filledLength)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
|
DawudH/scrapy_real-estate
|
plot/print_progressbar.py
|
Python
|
mit
| 1,262
|
package com.oohtml.compiler;
import java.util.HashMap;
/**
* A small class that calls the parsers in order.
* */
public class Processor {
private static Parser[] parsers = new Parser[] {new ExtendParser(), new BlockParser()}; // The parsers to apply to each block, in order.
private static HashMap<String, NamedNode> parsedNodes = new HashMap<String, NamedNode>();
/**
* The method to parse a NamedNode. It maintains a list of all previously parsed NamedNodes and checks to see if it has already parsed one before it parses it.
* @param nn The NamedNode to parse.
* @return The parsed NamedNode.
* */
public static NamedNode processNamedNode(NamedNode nn){
if(parsedNodes.containsKey(nn.path)) return parsedNodes.get(nn.path);
for (Parser p : parsers) {
nn = p.parseDocument(nn);
}
parsedNodes.put(nn.path, nn);
return nn;
}
}
|
Michaelkielstra/Object-oriented-HTML
|
src/com/oohtml/compiler/Processor.java
|
Java
|
mit
| 862
|
<ion-navbar *navbar>
<ion-title>Feed</ion-title>
</ion-navbar>
<ion-content padding class="feed">
<div class="spinner" *ngIf="loading" >
<ion-spinner class="spinner"></ion-spinner>
</div>
<p *ngIf="error">An error ocurred. Try again</p>
<p *ngIf="(!memes || memes.length == 0) && !loading" >Nothing to show...</p>
<ion-refresher (ionRefresh)="refresh($event)">
<ion-refresher-content
pullingIcon="arrow-down"
refreshingSpinner="circles">
</ion-refresher-content>
</ion-refresher>
<meme-card *ngFor="let meme of memes" (click)="showMeme(meme)"
[title]="meme.text0" [imageUrl]="meme.instanceImageUrl"
[text]="meme.displayName">
</meme-card>
<ion-infinite-scroll (ionInfinite)="loadNextPage($event)">
<ion-infinite-scroll-content
loadingSpinner="bubbles"
loadingText="Loading more awesome memes for you">
</ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
|
samfcmc/ionic2_tutorial
|
memeapp/app/pages/feed/feed.html
|
HTML
|
mit
| 943
|
package com.bafomdad.realfilingcabinet.items;
import java.util.List;
import com.bafomdad.realfilingcabinet.NewConfigRFC.ConfigRFC;
import com.bafomdad.realfilingcabinet.LogRFC;
import com.bafomdad.realfilingcabinet.RealFilingCabinet;
import com.bafomdad.realfilingcabinet.TabRFC;
import com.bafomdad.realfilingcabinet.api.IFolder;
import com.bafomdad.realfilingcabinet.helpers.StringLibs;
import com.bafomdad.realfilingcabinet.init.RFCItems;
import com.bafomdad.realfilingcabinet.items.capabilities.CapabilityFolder;
import com.bafomdad.realfilingcabinet.items.capabilities.CapabilityProviderFolder;
import com.bafomdad.realfilingcabinet.utils.NBTUtils;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemDyedFolder extends Item implements IFolder {
public ItemDyedFolder() {
setRegistryName("dyedfolder");
setTranslationKey(RealFilingCabinet.MOD_ID + ".dyedfolder");
setHasSubtypes(true);
setMaxStackSize(1);
}
@Override
public NBTTagCompound getNBTShareTag(ItemStack stack) {
if (!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))
return super.getNBTShareTag(stack);
NBTTagCompound tag = stack.hasTagCompound() ? stack.getTagCompound().copy() : new NBTTagCompound();
tag.setTag("folderCap", stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).serializeNBT());
LogRFC.debug("Sharing tag: " + tag.toString());
return tag;
}
@Override
public String getTranslationKey(ItemStack stack) {
return getTranslationKey() + "." + EnumDyeColor.values()[stack.getItemDamage()].getName().toLowerCase();
}
@Override
public void addInformation(ItemStack stack, World player, List<String> list, ITooltipFlag whatisthis) {
if (stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))
stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).addTooltips(player, list, whatisthis);
list.add("Limit: " + ConfigRFC.folderSizeLimit);
}
public ItemStack getContainerItem(ItemStack stack) {
if (!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))
return ItemStack.EMPTY;
CapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);
long count = cap.getCount();
long extract = 0;
if (count > 0 && cap.isItemStack())
extract = Math.min(cap.getItemStack().getMaxStackSize(), count);
if (NBTUtils.getBoolean(stack, StringLibs.RFC_TAPED, false))
return ItemStack.EMPTY;
ItemStack copy = stack.copy();
ItemFolder.remove(copy, extract);
return copy;
}
public boolean hasContainerItem(ItemStack stack) {
return !getContainerItem(stack).isEmpty();
}
public static int add(ItemStack stack, long count) {
if (!(stack.getItem() instanceof ItemDyedFolder)) {
ItemFolder.add(stack, count);
return Integer.MAX_VALUE;
}
long current = ItemFolder.getFileSize(stack);
long newCount = Math.min(count + current, ConfigRFC.folderSizeLimit);
long remainder = ConfigRFC.folderSizeLimit - ItemFolder.getFileSize(stack);
ItemFolder.setFileSize(stack, newCount);
return (int)remainder;
}
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
ItemStack stack = player.getHeldItem(hand);
if (ItemFolder.getObject(stack) != null) {
if (((ItemStack)ItemFolder.getObject(stack)).getItem() instanceof ItemBlock) {
long count = ItemFolder.getFileSize(stack);
if (count > 0) {
ItemStack stackToPlace = new ItemStack(((ItemStack)ItemFolder.getObject(stack)).getItem(), 1, ((ItemStack)ItemFolder.getObject(stack)).getItemDamage());
ItemStack savedfolder = player.getHeldItem(hand);
player.setHeldItem(hand, stackToPlace);
EnumActionResult ear = stackToPlace.onItemUse(player, world, pos, hand, side, hitX, hitY, hitZ);
player.setHeldItem(hand, savedfolder);
if (ear == EnumActionResult.SUCCESS) {
if (!player.capabilities.isCreativeMode) {
ItemFolder.remove(stack, 1);
}
return EnumActionResult.SUCCESS;
}
}
}
}
return EnumActionResult.PASS;
}
@Override
public void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {
if (!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null) || !stack.hasTagCompound() || !stack.getTagCompound().hasKey("folderCap", 10))
return;
CapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);
LogRFC.debug("Deserializing: " + stack.getTagCompound().getCompoundTag("folderCap").toString());
cap.deserializeNBT(stack.getTagCompound().getCompoundTag("folderCap"));
stack.getTagCompound().removeTag("folderCap");
if (stack.getTagCompound().getSize() <= 0)
stack.setTagCompound(null);
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldstack, ItemStack newstack, boolean slotchanged) {
return oldstack.getItem() != newstack.getItem() || (oldstack.getItem() == newstack.getItem() && oldstack.getItemDamage() != newstack.getItemDamage());
}
@Override
public ItemStack isFolderEmpty(ItemStack stack) {
return new ItemStack(RFCItems.emptyDyedFolder, 1, stack.getItemDamage());
}
}
|
bafomdad/realfilingcabinet
|
com/bafomdad/realfilingcabinet/items/ItemDyedFolder.java
|
Java
|
mit
| 5,892
|
/* globals mocha, chai */
import {jml, glue, nbsp, $, $$, body} from '../src/jml.js';
mocha.setup('bdd');
mocha.globals(['jml', 'glue', 'nbsp']);
window.jml = jml;
window.glue = glue;
window.nbsp = nbsp;
window.$ = $;
window.$$ = $$;
window.body = body;
window.assert = chai.assert;
window.expect = chai.expect;
|
brettz9/jamilih
|
test-helpers/loadTests.js
|
JavaScript
|
mit
| 315
|
/*
.reveal .slides {
text-align: left;
}
.reveal li pre {
width: auto;
}
.no-transforms .reveal .slides {
text-align: left;
}
*/
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 {
line-height: 2 !important;
}
.reveal .slides section {
line-height: 1.8 !important;
}
|
MichaelHu/fast-slides
|
lib/slides/css/markdown.css
|
CSS
|
mit
| 306
|
let webpack = require('webpack');
let path = require( 'path');
const AssetsPlugin = require('assets-webpack-plugin');
let projectRoot = process.cwd();
let assetsPath = path.join(projectRoot, "public", "build");
let publicPath = `/build/`;
let host = "0.0.0.0";
let config = {
devServer: {
inline: true,
host,
port: 3100,
hot: true,
disableHostCheck: true,
contentBase: assetsPath,
watchOptions: {
poll: true
}
},
cache: false,
// devtool: 'cheap-module-eval-source-map',
devtool: 'eval',
mode: "development",
context: process.cwd(),
entry: {
bundle: [
path.resolve(projectRoot, './webpack/util/polyfills.js'),
path.resolve(projectRoot, './src/client/index.js'),
]
},
target: 'web',
output: {
path: assetsPath, // Note: Physical files are only output by the production build task `npm run build`.
publicPath: publicPath,
pathinfo: false,
filename: 'bundle/[name].js',
chunkFilename: 'bundle/chunk-[name].js',
hotUpdateChunkFilename: '[hash].hot-update.js', // use for AssetsPlugin to filter out hot updates
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.BROWSER': true,
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DllReferencePlugin({
context: path.join(projectRoot, "src" , "client"),
manifest: require("../dll/commons-manifest.json")
}),
new AssetsPlugin({
fullPath: true,
path: path.join(projectRoot, './dev')
})
],
module: {
noParse: /ffmpeg/,
rules: [
{
test: /\.s[ac]ss$/i,
include: [
path.resolve(projectRoot, './src/shared/'),
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/stylesheets/'),
],
use: [
"style-loader",
"css-loader?url=false",
"sass-loader",
],
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: "url-loader" ,
options: {
limit: 10000,
mimetype: 'application/font-woff',
name: 'fonts/[name].[ext]'
},
include: [
path.resolve(projectRoot, './src/shared/fonts/') ,
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') ,
path.resolve(projectRoot, './node_modules/font-awesome/fonts/') ,
],
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: "file-loader" ,
options: {
name: 'fonts/[name].[ext]'
},
include: [
path.resolve(projectRoot, './src/shared/fonts/') ,
path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') ,
path.resolve(projectRoot, './node_modules/font-awesome/fonts/') ,
],
},
{
test: /(\.jsx)|(\.js)$/i,
exclude: [/node_modules/, /ffmpeg/],
include: [
path.join(projectRoot, "src" , "client"),
path.join(projectRoot, "src" , "shared")
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
"@babel/preset-react",
[
"@babel/preset-env",
{
"modules": false,
"debug": true,
"loose": true,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 ChromeAndroid versions",
"last 2 Edge versions",
"last 2 Firefox versions",
"last 2 FirefoxAndroid versions",
"last 2 iOS versions",
"last 2 Opera versions",
"last 2 Safari versions",
"ie >= 11"
]
},
}
],
],
plugins: [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-proposal-class-properties",
],
},
}
],
},
]
},
resolveLoader: {
modules: [
"node_modules"
],
},
resolve: {
modules: [
"node_modules"
],
unsafeCache : true,
},
profile: true
}
module.exports = config;
|
Grace951/grace951.github.io
|
webpack/webpack.config.dev.client.js
|
JavaScript
|
mit
| 3,984
|
package commands.direction;
/**
* The Class Left.
*/
public class Left extends Direction{
@Override
public double changeDirection(Double degrees) {
return degrees;
}
}
|
leeweisberger/Slogo
|
src/commands/direction/Left.java
|
Java
|
mit
| 182
|
import * as types from '../../mutation-types'
import lazyLoader from './lazyLoader'
const state = {
items: [
{
name: 'Home',
path: '/',
meta: {
label: ['主頁面'],
link: 'Home.vue',
icon: ['fas', 'home'],
permission: 99
},
components: lazyLoader('Home')
},
{
name: 'Server Status',
path: '/status',
meta: {
label: ['伺服器'],
link: 'Server.vue',
icon: ['fas', 'server'],
permission: 99
},
components: lazyLoader('Server')
},
{
name: 'Files',
path: '/files',
meta: {
label: ['檔案庫'],
link: 'File.vue',
icon: ['fas', 'database'],
permission: 0
},
components: lazyLoader('File')
},
{
name: 'Monit',
path: '/monit',
meta: {
label: ['監視器'],
link: 'Monit.vue',
icon: ['fas', 'video'],
permission: 1
},
components: lazyLoader('Monit')
},
{
name: 'Todo List',
path: '/todos',
meta: {
label: ['待辦事項'],
link: 'Todos.vue',
icon: ['fas', 'calendar-check'],
permission: 2
},
components: lazyLoader('Todos')
},
{
name: 'Post',
path: '/post',
meta: {
label: ['新增文章'],
link: 'Post.vue',
icon: ['fas', 'file'],
permission: 3
},
components: lazyLoader('Post/Add')
},
{
name: 'Post List',
path: '/post-list',
meta: {
label: ['文章列表'],
link: 'Post.vue',
icon: ['fas', 'list-alt'],
permission: 3
},
components: lazyLoader('Post/List')
},
{
name: 'News',
path: '/news',
meta: {
label: ['新增新聞'],
link: 'News.vue',
icon: ['fas', 'plus'],
permission: 2
},
components: lazyLoader('News/Add')
},
{
name: 'News List',
path: '/news-list',
meta: {
label: ['新聞列表'],
link: 'News.vue',
icon: ['fas', 'newspaper'],
permission: 2
},
components: lazyLoader('News/List')
}
]
}
const mutations = {
[types.EXPAND_MENU] (state, menuItem) {
if (menuItem.index > -1) {
if (state.items[menuItem.index] && state.items[menuItem.index].meta) {
state.items[menuItem.index].meta.expanded = menuItem.expanded
}
} else if (menuItem.item && 'expanded' in menuItem.item.meta) {
menuItem.item.meta.expanded = menuItem.expanded
}
}
}
export default {
state,
mutations
}
|
Limeishu/LCMS
|
src/store/modules/menu/index.js
|
JavaScript
|
mit
| 2,654
|
<?php
spl_autoload_register(function($class_name)
{
include 'classes/' . $class_name . '.php';
});
?>
|
hizzely/latihan-koding
|
Latihan PHP OOP/classes/autoload.php
|
PHP
|
mit
| 121
|
using System;
using System.Collections.Generic;
namespace TeamCityTheatre.Core.Models {
/*
sample:
{
"id": 212673,
"buildTypeId": "Pro_ProMaster_Compile",
"number": "6.11.0.4856",
"status": "FAILURE",
"state": "finished",
"branchName": "develop",
"href": "/httpAuth/app/rest/builds/id:212673",
"webUrl": "http://vm64-teamcity:8001/viewLog.html?buildId=212673&buildTypeId=Pro_ProMaster_Compile",
"statusText": "Compilation error: UltraGendaPro.Patients\src\UltraGendaPro.Patients.WebApi\UltraGendaPro.Patients.WebApi.csproj (new)",
"buildType": {
"id": "Pro_ProMaster_Compile",
"name": "Compile",
"projectName": "Pro :: Pro Git",
"projectId": "Pro_ProMaster",
"href": "/httpAuth/app/rest/buildTypes/id:Pro_ProMaster_Compile",
"webUrl": "http://vm64-teamcity:8001/viewType.html?buildTypeId=Pro_ProMaster_Compile"
},
"queuedDate": "20150914T093735+0200",
"startDate": "20150914T093741+0200",
"finishDate": "20150914T094913+0200",
"triggered": {
"type": "buildType",
"date": "20150914T093735+0200",
"user": {
"username": "nassereb",
"name": "Nassere Besseghir",
"id": 14,
"href": "/httpAuth/app/rest/users/id:14"
},
"buildType": {
"id": "Pro_ProMaster_Create64bitInstaller",
"name": "Create 64bit Installer",
"projectName": "Pro :: Pro Git",
"projectId": "Pro_ProMaster",
"href": "/httpAuth/app/rest/buildTypes/id:Pro_ProMaster_Create64bitInstaller",
"webUrl": "http://vm64-teamcity:8001/viewType.html?buildTypeId=Pro_ProMaster_Create64bitInstaller"
}
},
"lastChanges": {
"count": 1,
"change": [
{
"id": 78420,
"version": "7f88ba007daa401a91baec180c16b1798dceff0e",
"username": "nbesseghir",
"date": "20150914T093624+0200",
"href": "/httpAuth/app/rest/changes/id:78420",
"webUrl": "http://vm64-teamcity:8001/viewModification.html?modId=78420&personal=false"
}
]
},
"changes": {
"href": "/httpAuth/app/rest/changes?locator=build:(id:212673)"
},
"revisions": {
"count": 1,
"revision": [
{
"version": "7f88ba007daa401a91baec180c16b1798dceff0e",
"vcs-root-instance": {
"id": "538",
"vcs-root-id": "Pro_Git",
"name": "Pro_Git",
"href": "/httpAuth/app/rest/vcs-root-instances/id:538"
}
}
]
},
"agent": {
"id": 8,
"name": "VM-BUILDAGENT5",
"typeId": 8,
"href": "/httpAuth/app/rest/agents/id:8"
},
"problemOccurrences": {
"count": 2,
"href": "/httpAuth/app/rest/problemOccurrences?locator=build:(id:212673)",
"newFailed": 2,
"default": false
},
"artifacts": {
"href": "/httpAuth/app/rest/builds/id:212673/artifacts/children/"
},
"relatedIssues": {
"href": "/httpAuth/app/rest/builds/id:212673/relatedIssues"
},
"properties": {
"count": 8,
"property": [
{
"name": "ProjectBuildNumber",
"value": "6.8.1"
},
{
"name": "SupportedProductVersionBuildNumber1",
"value": "6.7.2"
},
{
"name": "SupportedProductVersionBuildNumber2",
"value": "6.6.5"
},
{
"name": "system.PreviousSupportedReleaseVersion1",
"value": "%SupportedProductVersionBuildNumber1%"
},
{
"name": "system.PreviousSupportedReleaseVersion2",
"value": "%SupportedProductVersionBuildNumber2%"
},
{
"name": "system.UltraGendaProVersion",
"value": "%env.BUILD_NUMBER%"
},
{
"name": "TestServer_X64",
"value": "VM-PRO-TEST64"
},
{
"name": "TestServer_X86",
"value": "VM-PRO-TEST32"
}
]
},
"statistics": {
"href": "/httpAuth/app/rest/builds/id:212673/statistics"
}
}
*/
public interface IDetailedBuild : IBasicBuild {
string StatusText { get; }
IBasicBuildConfiguration BuildConfiguration { get; }
DateTime QueuedDate { get; }
DateTime StartDate { get; }
DateTime FinishDate { get; }
IReadOnlyCollection<IDetailedBuildChange> LastChanges { get; }
IBasicAgent Agent { get; }
IReadOnlyCollection<Property> Properties { get; }
IReadOnlyCollection<IBasicBuild> SnapshotDependencies { get; }
IReadOnlyCollection<IBasicBuild> ArtifactDependencies { get; }
}
}
|
amoerie/teamcity-theatre
|
src/TeamCityTheatre.Core/Models/IDetailedBuild.cs
|
C#
|
mit
| 4,370
|
<?php
/**
* Site-wide styles
*
* If SCSS or LESS is used, the first such file determines the type used for the whole set. These cannot be mixed within one set.
*/
$allowedFormats = array();
$temp = $servant->settings()->formats('stylesheets');
unset($temp['css']);
foreach ($temp as $type => $extensions) {
foreach ($extensions as $extension) {
$allowedFormats[$extension] = $type;
}
}
unset($temp, $type, $extensions, $extension);
/**
* URL manipulation
*/
$actionsPath = $servant->paths()->root('domain');
$assetsRootUrl = $servant->paths()->assets('domain');
$urlManipulator = new UrlManipulator();
/**
* Go through files
*/
$styles = array('format' => false, 'content' => '',);
foreach ($servant->site()->stylesheets('plain') as $path) {
// Special format is used
$extension = pathinfo($path, PATHINFO_EXTENSION);
if (array_key_exists($extension, $allowedFormats)) {
// Set's format has not been selected yet, we'll do it now
if (!$styles['format']) {
$styles['format'] = $allowedFormats[$extension];
// Mixing preprocessor formats will fail
} else if ($styles['format'] !== $allowedFormats[$extension]) {
fail('CSS preprocessor formats cannot be mixed in assets');
}
}
unset($extension);
// We can parse relative path
$relativeUrl = substr((dirname($path).'/'), strlen($servant->paths()->assets('plain')));
// Get CSS file contents with URLs replaced
$styles['content'] .= $urlManipulator->cssUrls(file_get_contents($servant->paths()->format($path, 'server')), $assetsRootUrl, $relativeUrl, $actionsPath);
}
/**
* Output
*/
$output = '';
// Parse LESS
if ($styles['format'] === 'less') {
$servant->utilities()->load('less');
$parser = new lessc();
// Don't compress in debug mode
if (!$servant->debug()) {
$parser->setFormatter('compressed');
}
$output .= $parser->parse($styles['content']);
// Parse SCSS
} else if ($styles['format'] === 'scss') {
$servant->utilities()->load('scss');
$parser = new scssc();
// Don't compress in debug mode
if (!$servant->debug()) {
$parser->setFormatter('scss_formatter_compressed');
}
$output .= $parser->compile($styles['content']);
// Raw CSS, apparently
} else {
$output .= $styles['content'];
}
$action->output(trim($output));
?>
|
Eiskis/baseline-php
|
docs/backend/actions/sitestyles/run.php
|
PHP
|
mit
| 2,246
|
rmdir /s /q tmp
rmdir /s /q debug
del Makefile
del Makefile.Release
del Makefile.Debug
|
horsicq/nfdx64dbg
|
clear.bat
|
Batchfile
|
mit
| 94
|
import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def test_source_folder_works():
folder = temp_folder()
os.chdir(folder)
save_toolchain_args({
"configure_args": "-foo bar",
"make_args": ""}
)
conanfile = ConanFileMock()
conanfile.folders.set_base_install(folder)
sources = "/path/to/sources"
conanfile.folders.set_base_source(sources)
autotools = Autotools(conanfile)
autotools.configure(build_script_folder="subfolder")
assert conanfile.command.replace("\\", "/") == '"/path/to/sources/subfolder/configure" -foo bar'
autotools.configure()
assert conanfile.command.replace("\\", "/") == '"/path/to/sources/configure" -foo bar'
|
conan-io/conan
|
conans/test/unittests/tools/gnu/autotools_test.py
|
Python
|
mit
| 857
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextAdventures.Quest.Scripts;
namespace TextAdventures.Quest
{
public interface IField<T>
{
string Property { get; }
}
internal class FieldDef<T> : IField<T>
{
private string m_property;
public FieldDef(string property)
{
m_property = property;
}
public string Property { get { return m_property; } }
}
public static class FieldDefinitions
{
public static IField<string> Alias = new FieldDef<string>("alias");
public static IField<QuestList<string>> DisplayVerbs = new FieldDef<QuestList<string>>("displayverbs");
public static IField<QuestList<string>> InventoryVerbs = new FieldDef<QuestList<string>>("inventoryverbs");
public static IField<Element> To = new FieldDef<Element>("to");
public static IField<bool> LookOnly = new FieldDef<bool>("lookonly");
public static IField<QuestList<string>> ParamNames = new FieldDef<QuestList<string>>("paramnames");
public static IField<IScript> Script = new FieldDef<IScript>("script");
public static IField<string> ReturnType = new FieldDef<string>("returntype");
public static IField<string> Pattern = new FieldDef<string>("pattern");
public static IField<string> Unresolved = new FieldDef<string>("unresolved");
public static IField<string> Property = new FieldDef<string>("property");
public static IField<string> DefaultTemplate = new FieldDef<string>("defaulttemplate");
public static IField<bool> IsVerb = new FieldDef<bool>("isverb");
public static IField<string> DefaultText = new FieldDef<string>("defaulttext");
public static IField<string> GameName = new FieldDef<string>("gamename");
public static IField<string> Text = new FieldDef<string>("text");
public static IField<IFunction> Function = new FieldDef<IFunction>("text");
public static IField<string> Filename = new FieldDef<string>("filename");
public static IField<QuestList<string>> Steps = new FieldDef<QuestList<string>>("steps");
public static IField<string> Element = new FieldDef<string>("element");
public static IField<string> Type = new FieldDef<string>("type");
public static IField<string> Src = new FieldDef<string>("src");
public static IField<bool> Anonymous = new FieldDef<bool>("anonymous");
public static IField<string> TemplateName = new FieldDef<string>("templatename");
public static IField<string> OriginalPattern = new FieldDef<string>("originalpattern");
public static IField<int> TimeElapsed = new FieldDef<int>("timeelapsed");
public static IField<int> Trigger = new FieldDef<int>("trigger");
public static IField<int> Interval = new FieldDef<int>("interval");
public static IField<bool> Enabled = new FieldDef<bool>("enabled");
public static IField<string> Background = new FieldDef<string>("defaultbackground");
public static IField<string> Author = new FieldDef<string>("author");
public static IField<string> Version = new FieldDef<string>("version");
public static IField<string> VersionCode = new FieldDef<string>("versioncode");
public static IField<string> ProductId = new FieldDef<string>("productid");
public static IField<string> AppTabGame = new FieldDef<string>("app_tab_game");
public static IField<string> AppTabInventory = new FieldDef<string>("app_tab_inventory");
public static IField<string> AppTabObjects = new FieldDef<string>("app_tab_objects");
public static IField<string> AppTabExits = new FieldDef<string>("app_tab_exits");
public static IField<string> AppTabMore = new FieldDef<string>("app_tab_more");
public static IField<string> AppButtonOptions = new FieldDef<string>("app_button_options");
public static IField<string> AppButtonRestart = new FieldDef<string>("app_button_restart");
public static IField<string> AppButtonUndo = new FieldDef<string>("app_button_undo");
public static IField<string> AppButtonWait = new FieldDef<string>("app_button_wait");
public static IField<string> AppTextCancel = new FieldDef<string>("app_text_cancel");
public static IField<string> AppTextStatus = new FieldDef<string>("app_text_status");
public static IField<string> AppTextEmpty = new FieldDef<string>("app_text_empty");
public static IField<string> AppTextNone = new FieldDef<string>("app_text_none");
public static IField<string> AppTextInputPlaceholder = new FieldDef<string>("app_text_inputplaceholder");
}
public static class MetaFieldDefinitions
{
public static IField<string> Filename = new FieldDef<string>("filename");
public static IField<bool> Library = new FieldDef<bool>("library");
public static IField<bool> EditorLibrary = new FieldDef<bool>("editorlibrary");
public static IField<bool> DelegateImplementation = new FieldDef<bool>("delegateimplementation");
public static IField<int> SortIndex = new FieldDef<int>("sortindex");
public static IField<string> MappedName = new FieldDef<string>("mappedname");
}
public class Fields
{
#region Indexed Properties
public string this[IField<string> field]
{
get
{
return GetAsType<string>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public QuestList<string> this[IField<QuestList<string>> field]
{
get
{
return GetAsType<QuestList<string>>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public IScript this[IField<IScript> field]
{
get
{
return GetAsType<IScript>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public Element this[IField<Element> field]
{
get
{
return GetAsType<Element>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public bool this[IField<bool> field]
{
get
{
return GetAsType<bool>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public int this[IField<int> field]
{
get
{
return GetAsType<int>(field.Property);
}
set
{
Set(field.Property, value);
}
}
public IFunction this[IField<IFunction> field]
{
get
{
return GetAsType<IFunction>(field.Property);
}
set
{
Set(field.Property, value);
}
}
#endregion
private Dictionary<string, object> m_attributes = new Dictionary<string, object>();
private List<string> m_typeNames = new List<string>();
private Stack<Element> m_types = new Stack<Element>();
private Dictionary<string, string> m_objectReferences = new Dictionary<string, string>();
private Dictionary<string, List<string>> m_objectLists = new Dictionary<string, List<string>>();
private Dictionary<string, IDictionary<string, string>> m_objectDictionaries = new Dictionary<string, IDictionary<string, string>>();
public T GetAsType<T>(string attribute)
{
object value = Get(attribute);
if (value is T) return (T)value;
return default(T);
}
public void Set(string attribute, object value)
{
m_attributes[attribute] = value;
}
public object Get(string attribute)
{
if (m_attributes.ContainsKey(attribute))
{
return m_attributes[attribute];
}
object result = null;
foreach (Element type in m_types)
{
if (type.Fields.Exists(attribute))
{
result = type.Fields.Get(attribute);
break;
}
}
return result;
}
private bool Exists(string attribute)
{
if (m_attributes.ContainsKey(attribute)) return true;
foreach (Element type in m_types)
{
if (type.Fields.Exists(attribute)) return true;
}
return false;
}
public IEnumerable<string> FieldNames
{
get
{
IEnumerable<string> result = m_attributes.Keys;
foreach (Element type in m_types)
{
result = result.Union(type.Fields.FieldNames);
}
return result.Distinct();
}
}
public IEnumerable<string> TypeNames
{
get { return m_types.Select(t => t.Name); }
}
public void AddTypeName(string name)
{
m_typeNames.Add(name);
}
public void AddObjectRef(string attribute, string name)
{
m_objectReferences.Add(attribute, name);
}
public void AddObjectList(string attribute, List<string> value)
{
m_objectLists.Add(attribute, value);
}
public void AddObjectDictionary(string attribute, IDictionary<string, string> value)
{
m_objectDictionaries.Add(attribute, value);
}
public void Resolve(GameLoader loader)
{
foreach (string typeName in m_typeNames)
{
if (loader.Elements.ContainsKey(typeName))
{
m_types.Push(loader.Elements[typeName]);
}
}
foreach (var objectRef in m_objectReferences)
{
Set(objectRef.Key, loader.Elements[objectRef.Value]);
}
foreach (var objectList in m_objectLists)
{
QuestList<Element> newList = new QuestList<Element>(objectList.Value.Select(l => loader.Elements[l]));
Set(objectList.Key, newList);
}
foreach (var objectDict in m_objectDictionaries)
{
QuestDictionary<Element> newDict = new QuestDictionary<Element>();
foreach (var item in objectDict.Value)
{
newDict.Add(item.Key, loader.Elements[item.Value]);
}
Set(objectDict.Key, newDict);
}
}
}
}
|
textadventures/quest-js
|
Compiler/Fields.cs
|
C#
|
mit
| 11,076
|
<?php
namespace App\Http\Controllers;
use App\PageConent;
use Illuminate\Http\Request;
class PagesConentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\PageConent $pageConent
* @return \Illuminate\Http\Response
*/
public function show(PageConent $pageConent)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\PageConent $pageConent
* @return \Illuminate\Http\Response
*/
public function edit(PageConent $pageConent)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\PageConent $pageConent
* @return \Illuminate\Http\Response
*/
public function update(Request $request, PageConent $pageConent)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\PageConent $pageConent
* @return \Illuminate\Http\Response
*/
public function destroy(PageConent $pageConent)
{
//
}
}
|
simondavies/Personal-Website
|
app/Http/Controllers/Site/PagesConentController.php
|
PHP
|
mit
| 1,690
|
module Api
module V2
class FuzzySearchPresenter
attr_reader :result
def initialize(result)
@result = result
end
def id
1
end
def type
'fuzzy_match'
end
def goods_nomenclature_match
result.results[:goods_nomenclature_match]
end
def reference_match
result.results[:reference_match]
end
end
end
end
|
bitzesty/trade-tariff-backend
|
app/presenters/api/v2/fuzzy_search_presenter.rb
|
Ruby
|
mit
| 449
|
class DummyModelWithoutEncryption < ActiveRecord::Base
end
|
payout/encrypted_store
|
spec/dummy/app/models/dummy_model_without_encryption.rb
|
Ruby
|
mit
| 59
|
require_relative 'address.rb'
require_relative 'data.rb'
require_relative 'element.rb'
#require_relative 'excel_tools.rb'
require_relative 'section.rb'
require_relative 'sheet.rb'
module RubyExcel
#
# Example data to use in tests / demos
#
def self.sample_data
[
[ 'Part', 'Ref1', 'Ref2', 'Qty', 'Cost' ],
[ 'Type1', 'QT1', '231', 1, 35.15 ],
[ 'Type2', 'QT3', '123', 1, 40 ],
[ 'Type3', 'XT1', '321', 3, 0.1 ],
[ 'Type1', 'XY2', '132', 1, 30.00 ],
[ 'Type4', 'XT3', '312', 2, 3 ],
[ 'Type2', 'QY2', '213', 1, 99.99 ],
[ 'Type1', 'QT4', '123', 2, 104 ]
]
end
#
# Example hash to demonstrate imports
#
def self.sample_hash
{
Part1: {
Type1: {
SubType1: 1, SubType2: 2, SubType3: 3
},
Type2: {
SubType1: 4, SubType2: 5, SubType3: 6
}
},
Part2: {
Type1: {
SubType1: 1, SubType2: 2, SubType3: 3
},
Type2: {
SubType1: 4, SubType2: 5, SubType3: 6
}
}
}
end
#
# Shortcut to create a Sheet with example data
#
def self.sample_sheet
Workbook.new.load RubyExcel.sample_data
end
#
# Shortcut to import a WIN32OLE Workbook or Sheet
#
def self.import( *args )
Workbook.new.import( *args )
end
end
|
VirtuosoJoel/RubyExcel
|
lib/rubyexcel/rubyexcel_components.rb
|
Ruby
|
mit
| 1,424
|
<?php
/**
* Data object containing the SQL and PHP code to migrate the database
* up to version 1479334068.
* Generated on 2016-11-16 22:07:48 by sacredskull
*/
class PropelMigration_1479334068
{
public $comment = '';
public function preUp($manager)
{
// add the pre-migration code here
}
public function postUp($manager)
{
// add the post-migration code here
}
public function preDown($manager)
{
// add the pre-migration code here
}
public function postDown($manager)
{
// add the post-migration code here
}
/**
* Get the SQL statements for the Up migration
*
* @return array list of the SQL strings to execute for the Up migration
* the keys being the datasources
*/
public function getUpSQL()
{
return array (
'assemble' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;
DROP INDEX `unique_name` ON `assemblegroup`;
CREATE UNIQUE INDEX `unique_name` ON `assemblegroup` (`name`(100));
DROP INDEX `unique_name` ON `interest`;
CREATE UNIQUE INDEX `unique_name` ON `interest` (`name`(60));
DROP INDEX `unique_username` ON `person`;
DROP INDEX `unique_email` ON `person`;
CREATE UNIQUE INDEX `unique_username` ON `person` (`username`(30));
CREATE UNIQUE INDEX `unique_email` ON `person` (`email`(120));
# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
}
/**
* Get the SQL statements for the Down migration
*
* @return array list of the SQL strings to execute for the Down migration
* the keys being the datasources
*/
public function getDownSQL()
{
return array (
'assemble' => '
# This is a fix for InnoDB in MySQL >= 4.1.x
# It "suspends judgement" for fkey relationships until are tables are set.
SET FOREIGN_KEY_CHECKS = 0;
DROP INDEX `unique_name` ON `assemblegroup`;
CREATE UNIQUE INDEX `unique_name` ON `assemblegroup` (`name`);
DROP INDEX `unique_name` ON `interest`;
CREATE UNIQUE INDEX `unique_name` ON `interest` (`name`);
DROP INDEX `unique_username` ON `person`;
DROP INDEX `unique_email` ON `person`;
CREATE UNIQUE INDEX `unique_username` ON `person` (`username`);
CREATE UNIQUE INDEX `unique_email` ON `person` (`email`);
# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;
',
);
}
}
|
AssembleGroup/original-group-app-server
|
src/Assemble/Config/Propel/generated-migrations/PropelMigration_1479334068.php
|
PHP
|
mit
| 2,535
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="display.css">
</head>
<body>
<div class="wrapper">
<div class="inner-wrapper">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<div class="test-display">
This is a box
</div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
</body>
</html>
|
stinaq/education
|
CSS/display.html
|
HTML
|
mit
| 1,553
|
<?php
namespace Oro\Bundle\GridBundle\Tests\Unit\Action;
use Oro\Bundle\GridBundle\Action\ActionInterface;
use Oro\Bundle\GridBundle\Action\DeleteAction;
class DeleteActionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DeleteAction
*/
protected $model;
protected function setUp()
{
$this->model = new DeleteAction();
$this->model->setName('delete');
}
protected function tearDown()
{
unset($this->model);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage There is no option "link" for action "delete".
*/
public function testSetOptionsError()
{
$this->model->setOptions(array());
}
public function testGetType()
{
$this->assertEquals(ActionInterface::TYPE_DELETE, $this->model->getType());
}
/**
* @param array $toSet
* @param array $expected
* @dataProvider optionsProvider
*/
public function testSetOptions($toSet, $expected)
{
$this->model->setOptions($toSet);
$this->assertEquals($expected, $this->model->getOptions());
}
/**
* @return array
*/
public function optionsProvider()
{
return array(
'options equals to provided' => array(
'to set' => array(
'link' => '/delete_link',
'confirmation' => true,
),
'expected from get' => array(
'link' => '/delete_link',
'confirmation' => true,
),
),
'option confirmation is true by default' => array(
'to set' => array(
'link' => '/delete_link',
),
'expected from get' => array(
'link' => '/delete_link',
'confirmation' => true,
),
)
);
}
}
|
umpirsky/platform
|
src/Oro/Bundle/GridBundle/Tests/Unit/Action/DeleteActionTest.php
|
PHP
|
mit
| 1,991
|
using System.Windows.Controls;
namespace BudgetAnalyser.LedgerBook
{
/// <summary>
/// Interaction logic for BankBalanceUserControl.xaml
/// </summary>
public partial class BankBalanceUserControl : UserControl
{
public BankBalanceUserControl()
{
InitializeComponent();
}
}
}
|
Benrnz/BudgetAnalyser
|
BudgetAnalyser/LedgerBook/BankBalanceUserControl.xaml.cs
|
C#
|
mit
| 356
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="layoutclass_first_pic"><table class="fmt0table"><tr><th class="zt1"><b><font class=""></font></b></th><td class="zc1">右盼左顧</td></tr>
</td></tr></table></div> <!-- layoutclass_first_pic --><div class="layoutclass_second_pic"></div> <!-- layoutclass_second_pic --></div> <!-- layoutclass_pic --></td></tr></table>
|
BuzzAcademy/idioms-moe-unformatted-data
|
all-data/3000-3999/3422-33.html
|
HTML
|
mit
| 571
|
<?php
namespace Server;
use Util\Dictionary;
class Request
{
const WILDCARD_PREFIX = 'wildcard_';
protected $scheme;
protected $version;
protected $method;
protected $path;
protected $query;
protected $data;
protected $headers;
public function __construct($method = 'GET', $uri = '/', array $data = [], array $headers = [])
{
$this->scheme = 'HTTP';
$this->version = '1.1';
$this->method = $method;
$this->setUri($uri);
$this->data = new Dictionary($data);
$this->headers = new Dictionary($headers);
}
public function __get($property)
{
switch ($property) {
case 'scheme':
return $this->scheme;
case 'version':
return $this->version;
case 'method':
return $this->method;
case 'uri':
return $this->path.(strlen($this->query) ? '?'.$this->query : '');
case 'path':
return $this->path;
case 'query':
return $this->query;
case 'data':
return $this->data;
case 'headers':
return $this->headers;
default:
throw new Error('Nonexisting request property: '.$property);
}
}
public function setUri($uri)
{
$info = parse_url($uri) + array(
'path' => '',
'query' => ''
);
$this->path = $info['path'];
$this->query = $info['query'];
}
public function isAjax()
{
return (isset($this->headers['X-Requested-With']))
&& ('xmlhttprequest' === strtolower($this->headers['X-Requested-With']));
}
public function dump()
{
return [
'scheme' => $this->scheme,
'version' => $this->version,
'method' => $this->method,
'uri' => $this->uri,
'path' => $this->path,
'query' => $this->query,
'data' => $this->data->get(),
'headers' => $this->headers->get()
];
}
}
|
mariuslundgard/php-server
|
src/Server/Request.php
|
PHP
|
mit
| 2,148
|
Instance Variables:
history <BioProjectHistory>
usage <BioProjectUsage>
credentials <ProtoObject | PseudoContext>
project <GTProject>
history
- The project history object is responsible of registering information about a project, for example: Project Creation, Deletion, Modification.
usage
- The project usage is responsible to maintain information, for example: Project users, last accesses, data set unions, intersections, etc.
project
- Link to the project which owns the project information
|
biosmalltalk/biopharo
|
BioProject.package/BioProjectInformation.class/README.md
|
Markdown
|
mit
| 525
|
using UnityEngine;
using System.Collections;
public class RightLauncherAnimationEvent : MonoBehaviour
{
// Use this for initialization
public void ReloadAnimationEnd()
{
GameObject.Find("MissilePlatform_2").GetComponent<LauncherControl>().Reload(); ;
}
}
|
TRBrown/Work_Examples
|
Unity/MissileCommandGame/Assets/Scripts/RightLauncherAnimationEvent.cs
|
C#
|
mit
| 284
|
using System;
using System.IO;
using Common;
using Microsoft.Synchronization;
namespace SyncFrameWork.Controllers
{
public class LocalStore : KnowledgeSyncProvider, INotifyingChangeApplierTarget
{
private string folderPath;
private SyncSessionContext currentSessionContext;
private uint requestedBatchSize = 1;
public LocalSyncDetails sync = null;
MemoryConflictLog _memConflictLog;
public LocalStore(string folderPath)
{
sync = new LocalSyncDetails(folderPath, true);
this.folderPath = folderPath;
}
private string FolderPath
{
get { return folderPath; }
}
public uint RequestedBatchSize
{
get { return requestedBatchSize; }
set { requestedBatchSize = value; }
}
public override void BeginSession(Microsoft.Synchronization.SyncProviderPosition providerPosition, SyncSessionContext syncSessionContext)
{
currentSessionContext = syncSessionContext;
_memConflictLog = new MemoryConflictLog(IdFormats);
}
public override void EndSession(SyncSessionContext syncSessionContext)
{
sync.Save();
System.Diagnostics.Debug.WriteLine("_____ Ending Session On LocalStore ______" );
}
public override ChangeBatch GetChangeBatch(uint batchSize, SyncKnowledge destinationKnowledge, out object changeDataRetriever)
{
return sync.GetChangeBatch(batchSize, destinationKnowledge, out changeDataRetriever);
}
public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval,out object changeDataRetriever)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public override void GetSyncBatchParameters(out uint batchSize, out SyncKnowledge knowledge)
{
if (sync == null)
throw new InvalidOperationException("Knowledge not yet loaded.");
sync.SetLocalTickCount();
batchSize = RequestedBatchSize;
knowledge = sync.SyncKnowledge.Clone();
}
public override SyncIdFormatGroup IdFormats
{
get { return sync.IdFormats; }
}
/// <summary>
/// Download Mechanism
/// </summary>
/// <param name="resolutionPolicy"></param>
/// <param name="sourceChanges"></param>
/// <param name="changeDataRetriever"></param>
/// <param name="syncCallback"></param>
/// <param name="sessionStatistics"></param>
public override void ProcessChangeBatch(ConflictResolutionPolicy resolutionPolicy, ChangeBatch sourceChanges,
object changeDataRetriever, SyncCallbacks syncCallback, SyncSessionStatistics sessionStatistics)
{
ChangeBatch localVersions = sync.GetChanges(sourceChanges);
ForgottenKnowledge destinationForgottenKnowledge = new ForgottenKnowledge(sync.IdFormats, sync.SyncKnowledge);
NotifyingChangeApplier changeApplier = new NotifyingChangeApplier(sync.IdFormats);
changeApplier.ApplyChanges(resolutionPolicy, CollisionConflictResolutionPolicy.Merge, sourceChanges,
(IChangeDataRetriever)changeDataRetriever, localVersions, sync.SyncKnowledge.Clone(),
destinationForgottenKnowledge, this, _memConflictLog, currentSessionContext, syncCallback);
}
public override void ProcessFullEnumerationChangeBatch(ConflictResolutionPolicy resolutionPolicy,
FullEnumerationChangeBatch sourceChanges,
object changeDataRetriever, SyncCallbacks syncCallback, SyncSessionStatistics sessionStatistics)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public ulong GetNextTickCount()
{
return sync.GetNextTickCount();
}
#region IChangeDataRetriever Members
public object LoadChangeData(LoadChangeContext loadChangeContext)
{
throw new NotImplementedException();
}
#endregion
#region INotifyingChangeApplierTarget Members
public void SaveConflict(ItemChange conflictingChange, object conflictingChangeData, SyncKnowledge conflictingChangeKnowledge)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public bool TryGetDestinationVersion(ItemChange sourceChange, out ItemChange destinationVersion)
{
return sync.TryGetDestinationVersion(sourceChange, out destinationVersion);
}
public IChangeDataRetriever GetDataRetriever()
{
throw new NotImplementedException();
}
public void StoreKnowledgeForScope(SyncKnowledge knowledge, ForgottenKnowledge forgottenKnowledge)
{
sync.SyncKnowledge = knowledge;
sync.ForgottenKnowledge = forgottenKnowledge;
System.Diagnostics.Debug.WriteLine("Local.StoreKnowledgeForScope:" + knowledge + "ForgottenKnowledge:" + forgottenKnowledge);
}
#endregion
public void SaveConstraintConflict(ItemChange conflictingChange, SyncId conflictingItemId, ConstraintConflictReason reason, object conflictingChangeData, SyncKnowledge conflictingChangeKnowledge, bool temporary)
{
throw new NotImplementedException();
}
/// <summary>
/// Download Mechanism
/// </summary>
/// <param name="saveChangeAction"></param>
/// <param name="change"></param>
/// <param name="context"></param>
public void SaveItemChange(SaveChangeAction saveChangeAction, ItemChange change, SaveChangeContext context)
{
DataTransfer data = context.ChangeData as DataTransfer;
ItemMetadata item = sync.GetItemMetaData(saveChangeAction, change, data);
switch (saveChangeAction)
{
case SaveChangeAction.Create:
{
System.Diagnostics.Debug.WriteLine("Create File: " + item.Uri);
UpdateOrCreateFile(data, item);
break;
}
case SaveChangeAction.UpdateVersionAndData:
{
System.Diagnostics.Debug.WriteLine("UpdateVersion And Data File: " + item.Uri);
UpdateOrCreateFile(data, item);
break;
}
case SaveChangeAction.DeleteAndStoreTombstone:
{
System.Diagnostics.Debug.WriteLine(" Delete File: " + item.Uri);
File.Delete(Path.Combine(folderPath, item.Uri));
break;
}
default:
{
throw new NotImplementedException(saveChangeAction + " ChangeAction is not implemented!");
}
}
sync.GetUpdatedKnowledge(context);
}
private void UpdateOrCreateFile(DataTransfer data, ItemMetadata item)
{
FileInfo fileInfo = new FileInfo(Path.Combine(folderPath, item.Uri));
if (!fileInfo.Directory.Exists)
fileInfo.Directory.Create();
using (FileStream outputStream = new FileStream(Path.Combine(folderPath, item.Uri), FileMode.OpenOrCreate))
{
const int copyBlockSize = 4096;
byte[] buffer = new byte[copyBlockSize];
int bytesRead;
while ((bytesRead = data.DataStream.Read(buffer, 0, copyBlockSize)) > 0)
outputStream.Write(buffer, 0, bytesRead);
outputStream.SetLength(outputStream.Position);
}
item.LastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
data.DataStream.Close();
}
public void SaveChangeWithChangeUnits(ItemChange change, SaveChangeWithChangeUnitsContext context)
{
throw new NotImplementedException();
}
}
}
|
labrinth1/RemoteSync
|
SyncFrameWork/Stores/LocalStore.cs
|
C#
|
mit
| 8,431
|
package skin.support.animator.activityAnimator;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.BounceInterpolator;
import skin.support.animator.Action;
import skin.support.animator.SkinAnimator;
/**
* Created by erfli on 2/25/17.
*/
public class TranslationAnimator2 implements SkinAnimator {
protected ObjectAnimator preAnimator;
protected ObjectAnimator afterAnimator;
protected View targetView;
private TranslationAnimator2() {
}
public static TranslationAnimator2 getInstance() {
TranslationAnimator2 skinAlphaAnimator = new TranslationAnimator2();
return skinAlphaAnimator;
}
@Override
public SkinAnimator apply(@NonNull View view, @Nullable final Action action) {
this.targetView = view;
preAnimator = ObjectAnimator.ofPropertyValuesHolder(targetView,
PropertyValuesHolder.ofFloat("translationX",
view.getLeft(), view.getRight()))
.setDuration(PRE_DURATION * 3);
preAnimator.setInterpolator(new AccelerateInterpolator());
afterAnimator = ObjectAnimator.ofPropertyValuesHolder(targetView,
PropertyValuesHolder.ofFloat("translationX",
view.getLeft() - view.getWidth(), view.getLeft()))
.setDuration(AFTER_DURATION * 3);
afterAnimator.setInterpolator(new BounceInterpolator());
preAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (action != null) {
action.action();
}
afterAnimator.start();
}
});
return this;
}
@Override
public SkinAnimator setPreDuration() {
return this;
}
@Override
public SkinAnimator setAfterDuration() {
return this;
}
@Override
public SkinAnimator setDuration() {
return this;
}
@Override
public void start() {
preAnimator.start();
}
}
|
wutongke/AndroidSkinAnimator
|
skin-support/src/main/java/skin/support/animator/activityAnimator/TranslationAnimator2.java
|
Java
|
mit
| 2,431
|
require 'spec_helper'
require 'rails_helper'
describe SpotsController do
describe "#index" do
it "assigns all spots to @spots" do
get :index
expect(assigns(:spots)).to eq Spot.all.order(:favorites_count)
end
it "renders the #index template" do
get :index
expect(response).to render_template :index
end
end
describe "#new" do
it "assigns a new spot to @spot" do
get :new
expect(assigns(:spot)).to be_an_instance_of Spot
end
it "renders the #new template" do
get :new
expect(response).to render_template :new
end
end
describe "#create" do
context "with valid attributes" do
it "saves the new spot to the database" do
expect{
post :create, spot: {name: "Cookie's Cookies", address: "48 Wall Street New York NY 10003", phone: "212-456-1234", price: 4}
}.to change(Spot, :count).by(1)
end
it "redirects to the #show page" do
post :create, spot: {name: "Cookie's Cookies", address: "48 Wall Street New York NY 10003", phone: "212-456-1234", price: 4}
spot = Spot.last
expect(response).to redirect_to spot_path(assigns[:spot])
end
end
context "with invalid attributes" do
it "does not save the new spot to the database"
it "redirects to the #new page"
it "assigns a flash to notify user of error"
end
end
describe "#show" do
it "assigns the spot to @spot" do
user = User.create!(username:"polly123", email:"polly@gmail.com",password:"password", password_confirmation: "password")
spot = Spot.create!(name:"Sarah's Bakery", address:"100 Fifth Avenue New York, NY 10003", phone:"212-555-555", price: 2)
get :show, id: spot
expect(assigns(:spot)).to eq spot
end
it "renders the show template" do
user = User.create!(username:"polly123", email:"polly@gmail.com",password:"password", password_confirmation: "password")
spot = Spot.create!(name:"Sarah's Bakery", address:"100 Fifth Avenue New York, NY 10003", phone:"212-555-555", price: 2)
get :show, id: spot
expect(response).to render_template :show
end
end
describe "#edit" do
it "assigns the spot to @spot" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
get :edit, id: spot
expect(assigns(:spot)).to eq spot
end
it "renders the :edit template" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
get :edit, id: spot
expect(response).to render_template :edit
end
end
describe "#update" do
context "with valid attributes" do
it "updates the database" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
new_name = "Rafa's"
put :update, id: spot, spot: {name: new_name}
spot.reload
expect(spot.name).to eq(new_name)
end
it "redirects to spot#show" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
new_name = "Rafa's"
put :update, id: spot, spot: {name: new_name}
expect(response).to redirect_to spot_path(assigns[:spot])
end
end
context "with invalid attributes" do
it "does not update the database"
it "redirects to spot#edit"
end
end
describe "#destroy" do
it "deletes the spot from the database" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
delete :destroy, id: spot
expect(Spot.all).to_not include spot
end
it "redirects to spot index" do
spot = Spot.create!(name:"Rafael's Bakery", address:"100 Ninth Avenue New York, NY 10013", phone:"212-999-9555", price: 4)
delete :destroy, id: spot
expect(response).to redirect_to spots_path
end
end
end
|
mud-turtles-2014/TheSpot
|
spec/controllers/spot_controller_spec.rb
|
Ruby
|
mit
| 4,079
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports LevelRowColumnUrlBuilder
* @version $Id: LevelRowColumnUrlBuilder.js 2643 2015-01-09 20:37:58Z tgaskins $
*/
define([
'../error/ArgumentError',
'../util/Logger',
'../util/WWUtil'
],
function (ArgumentError,
Logger,
WWUtil) {
"use strict";
/**
* Constructs a URL builder for level/row/column tiles.
* @alias LevelRowColumnUrlBuilder
* @constructor
* @classdesc Provides a factory to create URLs for level/row/column tile REST requests.
* <p>
* URLs are formed by appending the specified server address with the specified path and appending
* a path of the form <em>/level/row/row_column.image-format</em>, where image-format is the corresponding
* suffix to the image mime type specified when a URL is requested. For example, if the specified server
* address is <em>http://worldwindserver.net/webworldwind</em> and the specified path-to-data is
* <em>../data/Earth/BMNG256</em>, and the requested tile's level, row and column are 0, 5 and 9 respectively,
* and the image format is <em>image/jpeg</em>, the composed URL is
* <em>http://worldwindserver.net/webworldwind/../data/Earth/BMNG256/0/5/5_9.jpg.
*
* @param {String} serverAddress The server address. May be null, in which case the address is assumed to be
* the current location (see <code>window.location</code>) minus the last path component.
* @param {String} pathToData The path to the dataset on the server. May be null or empty to indicate that
* the data is directly relative to the specified server address.
*
*/
var LevelRowColumnUrlBuilder = function (serverAddress, pathToData) {
/**
* The server address.
* @type {String}
*/
this.serverAddress = serverAddress;
if (!serverAddress || serverAddress.length === 0) {
this.serverAddress = WWUtil.currentUrlSansFilePart();
}
/**
* The server-side path to the dataset.
* @type {String}
*/
this.pathToData = pathToData;
};
/**
* Creates the URL string for a WMS Get Map request.
* @param {Tile} tile The tile for which to create the URL.
* @param {String} imageFormat The image format to request.
* @throws {ArgumentError} If the specified tile or image format are null or undefined.
*/
LevelRowColumnUrlBuilder.prototype.urlForTile = function (tile, imageFormat) {
if (!tile) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile", "missingTile"));
}
if (!imageFormat) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile",
"The image format is null or undefined."));
}
var sb = this.serverAddress;
if (this.pathToData) {
sb = sb + "/" + this.pathToData;
}
sb = sb + "/" + tile.level.levelNumber.toString();
sb = sb + "/" + tile.row.toString();
sb = sb + "/" + tile.row.toString() + "_" + tile.column.toString();
sb = sb + "." + WWUtil.suffixForMimeType(imageFormat);
sb = sb.replace(" ", "%20");
return sb;
};
return LevelRowColumnUrlBuilder;
});
|
NASAWorldWindResearch/AgroSphere
|
src/util/LevelRowColumnUrlBuilder.js
|
JavaScript
|
mit
| 3,906
|
<?php
$now = date("Y-m-d");
$dayList = array(
'Sun' => 'Minggu',
'Mon' => 'Senin',
'Tue' => 'Selasa',
'Wed' => 'Rabu',
'Thu' => 'Kamis',
'Fri' => 'Jumat',
'Sat' => 'Sabtu'
);
if($atletWellnessDate == $now AND $atletWellnessValue != 0){
if($atletWellnessValue <= 59){
$wellness = "#FF0000";
}elseif($atletWellnessValue >= 60 && $atletWellnessValue <= 69) {
$wellness = "#FF9D00";
}elseif($atletWellnessValue >= 70 && $atletWellnessValue <= 79){
$wellness = "#E1FF00";
}elseif($atletWellnessValue >= 80 && $atletWellnessValue <= 89){
$wellness = "#9BFF77";
}else{
$wellness = "#00CE25";
}
}else{
$wellness = "#607D8B";
}
$ret = "";
if($pmcList){
$tmpDate = 1;
$ret .= '<table class="striped">';
foreach($pmcList as $key){
$detail_id = $key->monotonyDetailID;
$detail_date = $key->monotonyDetailDate;
$detailSession = $key->monotonyDetailSession;
$detailVolume = $key->monotonyVolume;
$warmup = $key->warmup;
$core = $key->core;
$coolDown = $key->cooldown;
$volcore = $key->volcore;
$volwarm = $key->volwarm;
$volcool = $key->volcool;
if($role_type == "KSC" OR $role_type == "CHC"){
$warmup = $this->ModelPMC->optionActualWarmUp($warmup);
$core = $this->ModelPMC->optionActualCore($core);
$coolDown = $this->ModelPMC->optionActualCoolDown($coolDown);
$volcore = '
<div class="input-field col s12">
<input placeholder="60" id="volcore" name="volcore[]" type="number" class="validate" value="'.$volcore.'">
<label for="first_name">Volume Core</label>
</div>
';
$volwarm = '
<div class="input-field col s12">
<input placeholder="60" id="volwarm" name="volwarm[]" type="number" class="validate" value="'.$volwarm.'">
<label for="first_name">Volume Warm Up</label>
</div>
';
$volcool = '
<div class="input-field col s12">
<input placeholder="60" id="volcool" name="volcool[]" type="number" class="validate" value="'.$volcool.'">
<label for="first_name">Volume Cool Down</label>
</div>
';
}
$daySet = array("Minggu","Senin","Selasa","Rabu","Kamis","Jum`at","Sabtu");
$day = date("w", strtotime($detail_date));
$hari = $daySet[$day];
$tangal = date("d M Y", strtotime($detail_date));
if($tmpDate<>$detail_date){
$ret .='
<thead><tr><th colspan="3" class="indigo white-text"><h6><b>'.$hari.', '.$tangal.'</b></h6></th></tr></thead>
';
$tmpDate = $detail_date;
}
$ret .='<tbody>'
. '<input type="hidden" name="detail_id[]" value="'.$detail_id.'"/>'
. '<input type="hidden" name="detailSession[]" value="'.$detailSession.'"/>'
. '<tr><th class="red white-text" colspan="2"><h6><b>Session Name : '.$detailSession.'</b></h6></th>'
. '<th class="red white-text">Volume : '.$detailVolume.' Min</th></tr>'
. '<tr><td><b>Warm Up : </b></td><td>'.$warmup.'</td><td>'.$volwarm.'</td></tr>'
. '<tr><td><b>Core : </b></td><td>'.$core.'</td><td>'.$volcore.'</td></tr>'
. '<tr><td><b>Cool Down : </b></td><td>'.$coolDown.'</td><td>'.$volcool.'</td></tr>'
. '</tbody>';
}
$ret .="</table>";
}else{
$ret .="Data Tidak Ditemukan";
};
?>
<div class="container">
<div class="section">
<!-- profile-page-content -->
<div class="row">
<!-- profile-page-sidebar-->
<div class="col s12 m12 l12">
<!-- Profile About -->
<div class="card sea-games center" style="height:350px">
<div id="imgArea" class="card-avatar">
<img style="border: solid 5px <?php echo $wellness ?>" src="<?php echo $atletPic?>" alt="profile image" class="circle z-depth-2 responsive-img activator">
</div>
<div class="card-content center">
<div class="col s12 m12 l12">
<p style="margin-bottom:15px"><?php echo $labelAtlet?></p>
<p><div class="chip cyan white-text" <?php echo $labelGroup?>><?php echo $atletGroup ?> / <?php echo $atletEvent ?></div></p>
<p style="margin-top:15px"><button class="btn red">PMC Data</button></p>
</div>
</div>
</div>
</div>
<!-- profile-page-sidebar-->
</div>
<div class="row">
<div class="col m12 s12 l12" id="DataMonotony">
<form id="formPMC">
<table class="bordered striped responsive-table">
<?php echo $ret ?>
<?php if($role_type == "CHC" OR $role_type == "KSC"){ ?>
<tr>
<td>
<button class="btn cyan" onClick="savePMC()">Simpan</button>
</td>
</tr>
<?php } ?>
<tr><td id="loading"></td></tr>
</table>
</form>
</div>
</div>
</div>
</div>
|
fashahd/iamprima
|
application/modules/pmc/views/pmcData.php
|
PHP
|
mit
| 4,748
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.