code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package jelly.exception.level;
public class LevelNotFound extends Exception {
}
| kicholen/jelly-gp-server | src/main/java/jelly/exception/level/LevelNotFound.java | Java | mit | 85 |
import { dealsService } from '../services';
const fetchDealsData = () => {
return dealsService().getDeals()
.then(res => {
return res.data
})
// Returning [] as a placeholder now so it does not error out when this service
// fails. We should be handling this in our DISPATCH_REQUEST_FAILURE
.catch(() => []);
};
export default fetchDealsData;
| mohammed52/something.pk | app/fetch-data/fetchDealsData.js | JavaScript | mit | 374 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quicken.Core.Index.Enumerations
{
public enum TargetType
{
File = 0,
Desktop = 1,
Metro = 2
}
}
| hrudham/Quicken | Core/Enumerations/TargetType.cs | C# | mit | 262 |
import { createPlugin } from 'draft-extend';
// TODO(mime): can't we just use LINK? i forget why we're using ANCHOR separately..., something with images probably :-/
const ENTITY_TYPE = 'ANCHOR';
// TODO(mime): one day, maybe switch wholesale to draft-extend. for now, we have a weird hybrid
// of draft-extend/draft-convert/draft-js-plugins
export default createPlugin({
htmlToEntity: (nodeName, node, create) => {
if (nodeName === 'a') {
const mutable = node.firstElementChild?.nodeName === 'IMG' ? 'IMMUTABLE' : 'MUTABLE';
const { href, target } = node;
return create(ENTITY_TYPE, mutable, { href, target });
}
},
entityToHTML: (entity, originalText) => {
if (entity.type === ENTITY_TYPE) {
const { href } = entity.data;
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${originalText}</a>`;
}
return originalText;
},
});
export const AnchorDecorator = (props) => {
const { href } = props.contentState.getEntity(props.entityKey).getData();
return (
<a href={href} target="_blank" rel="noopener noreferrer">
{props.children}
</a>
);
};
export function anchorStrategy(contentBlock, callback, contentState) {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return entityKey !== null && contentState.getEntity(entityKey).getType() === ENTITY_TYPE;
}, callback);
}
| mimecuvalo/helloworld | packages/hello-world-editor/plugins/Anchor.js | JavaScript | mit | 1,418 |
public class Prime {
private Prime() { }
public static void printPrimes(int max) {
boolean[] flags = sieveOfEratosthenes(max);
System.out.println("== Primes up to " + max + " ==");
for (int i = 0; i < flags.length; i++) {
if (flags[i]) {
System.out.println("* " + i);
}
}
}
public static boolean[] sieveOfEratosthenes(int max) {
boolean[] flags = new boolean[max + 1];
// initialize flags except 0 and 1
for (int i = 2; i < flags.length; i++) {
flags[i] = true;
}
int prime = 2;
while (prime * prime <= max) {
crossOff(flags, prime);
prime = getNextPrime(flags, prime);
}
return flags;
}
private static void crossOff(boolean[] flags, int prime) {
for (int i = prime * prime; i < flags.length; i += prime) {
flags[i] = false;
}
}
private static int getNextPrime(boolean[] flags, int prime) {
int next = prime + 1;
while (next < flags.length && !flags[next]) {
next++;
}
return next;
}
public static boolean isPrime(int num) {
if (num < 2) return false;
int prime = 2;
while (prime * prime <= num) {
if (num % prime == 0) return false;
++prime;
}
return true;
}
}
| sadikovi/algorithms | src/Prime.java | Java | mit | 1,245 |
import Vector from '../prototype'
import {componentOrder, allComponents} from './components'
export const withInvertedCurryingSupport = f => {
const curried = right => left => f(left, right)
return (first, second) => {
if (second === undefined) {
// check for function to allow usage by the pipeline function
if (Array.isArray(first) && first.length === 2 && !(first[0] instanceof Function) && !(first[0] instanceof Number)) {
return f(first[0], first[1])
}
// curried form uses the given single parameter as the right value for the operation f
return curried(first)
}
return f(first, second)
}
}
export const skipUndefinedArguments = (f, defaultValue) => (a, b) => a === undefined || b === undefined
? defaultValue
: f(a, b)
export const clone = v => {
if (Array.isArray(v)) {
const obj = Object.create(Vector.prototype)
v.forEach((value, i) => {
obj[allComponents[i]] = value
})
return [...v]
}
const prototype = Object.getPrototypeOf(v)
return Object.assign(Object.create(prototype === Object.prototype ? Vector.prototype : prototype), v)
}
| senritsu/grid-utils | vector/util/misc.js | JavaScript | mit | 1,138 |
module.exports = function() {
return {
server: {
src: ['<%= tmp %>/index.html'],
ignorePath: /\.\.\//
}
}
};
| genu/lowkey | grunt/wiredep.js | JavaScript | mit | 133 |
require 'trajectory/exceptions/missing_attribute_error'
require 'trajectory/exceptions/velocity_equal_to_zero_error'
require 'trajectory/exceptions/velocity_always_equal_to_zero_error'
require 'trajectory/exceptions/bad_environment_error'
| lminaudier/trajectory | lib/trajectory/exceptions.rb | Ruby | mit | 239 |
import babylon from '../../babel-parser'
import Documentation from '../../Documentation'
import resolveExportedComponent from '../../utils/resolveExportedComponent'
import classDisplayNameHandler from '../classDisplayNameHandler'
jest.mock('../../Documentation')
function parse(src: string) {
const ast = babylon().parse(src)
return resolveExportedComponent(ast)[0]
}
describe('classDisplayNameHandler', () => {
let documentation: Documentation
beforeEach(() => {
documentation = new Documentation('dummy/path')
})
it('should extract the name of the component from the classname', () => {
const src = `
@Component
export default class Decorum extends Vue{
}
`
const def = parse(src).get('default')
if (def) {
classDisplayNameHandler(documentation, def)
}
expect(documentation.set).toHaveBeenCalledWith('displayName', 'Decorum')
})
it('should extract the name of the component from the decorators', () => {
const src = `
@Component({name: 'decorum'})
export default class Test extends Vue{
}
`
const def = parse(src).get('default')
if (def) {
classDisplayNameHandler(documentation, def)
}
expect(documentation.set).toHaveBeenCalledWith('displayName', 'decorum')
})
})
| vue-styleguidist/vue-styleguidist | packages/vue-docgen-api/src/script-handlers/__tests__/classDisplayNameHandler.ts | TypeScript | mit | 1,242 |
'use strict';
angular.module('mpApp')
.factory(
'preloader',
function($q, $rootScope) {
// I manage the preloading of image objects. Accepts an array of image URLs.
function Preloader(imageLocations) {
// I am the image SRC values to preload.
this.imageLocations = imageLocations;
// As the images load, we'll need to keep track of the load/error
// counts when announing the progress on the loading.
this.imageCount = this.imageLocations.length;
this.loadCount = 0;
this.errorCount = 0;
// I am the possible states that the preloader can be in.
this.states = {
PENDING: 1,
LOADING: 2,
RESOLVED: 3,
REJECTED: 4
};
// I keep track of the current state of the preloader.
this.state = this.states.PENDING;
// When loading the images, a promise will be returned to indicate
// when the loading has completed (and / or progressed).
this.deferred = $q.defer();
this.promise = this.deferred.promise;
}
// ---
// STATIC METHODS.
// ---
// I reload the given images [Array] and return a promise. The promise
// will be resolved with the array of image locations. 111111
Preloader.preloadImages = function(imageLocations) {
var preloader = new Preloader(imageLocations);
return (preloader.load());
};
// ---
// INSTANCE METHODS.
// ---
Preloader.prototype = {
// Best practice for "instnceof" operator.
constructor: Preloader,
// ---
// PUBLIC METHODS.
// ---
// I determine if the preloader has started loading images yet.
isInitiated: function isInitiated() {
return (this.state !== this.states.PENDING);
},
// I determine if the preloader has failed to load all of the images.
isRejected: function isRejected() {
return (this.state === this.states.REJECTED);
},
// I determine if the preloader has successfully loaded all of the images.
isResolved: function isResolved() {
return (this.state === this.states.RESOLVED);
},
// I initiate the preload of the images. Returns a promise. 222
load: function load() {
// If the images are already loading, return the existing promise.
if (this.isInitiated()) {
return (this.promise);
}
this.state = this.states.LOADING;
for (var i = 0; i < this.imageCount; i++) {
this.loadImageLocation(this.imageLocations[i]);
}
// Return the deferred promise for the load event.
return (this.promise);
},
// ---
// PRIVATE METHODS.
// ---
// I handle the load-failure of the given image location.
handleImageError: function handleImageError(imageLocation) {
this.errorCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
this.state = this.states.REJECTED;
this.deferred.reject(imageLocation);
},
// I handle the load-success of the given image location.
handleImageLoad: function handleImageLoad(imageLocation) {
this.loadCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
// Notify the progress of the overall deferred. This is different
// than Resolving the deferred - you can call notify many times
// before the ultimate resolution (or rejection) of the deferred.
this.deferred.notify({
percent: Math.ceil(this.loadCount / this.imageCount * 100),
imageLocation: imageLocation
});
// If all of the images have loaded, we can resolve the deferred
// value that we returned to the calling context.
if (this.loadCount === this.imageCount) {
this.state = this.states.RESOLVED;
this.deferred.resolve(this.imageLocations);
}
},
// I load the given image location and then wire the load / error
// events back into the preloader instance.
// --
// NOTE: The load/error events trigger a $digest. 333
loadImageLocation: function loadImageLocation(imageLocation) {
var preloader = this;
// When it comes to creating the image object, it is critical that
// we bind the event handlers BEFORE we actually set the image
// source. Failure to do so will prevent the events from proper
// triggering in some browsers.
var image = angular.element(new Image())
.bind('load', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageLoad(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.bind('error', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageError(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.attr('src', imageLocation);
}
};
// Return the factory instance.
return (Preloader);
}
);
| 59023g/mpdotcom | app/scripts/services/preloader.js | JavaScript | mit | 6,121 |
module SapphireBot
module Events
# Notifies user that bot is ready to use.
module ReadyMessage
extend Discordrb::EventContainer
ready do
BOT.game = nil
LOGGER.info 'Bot is ready'
end
end
end
end
| PoVa/sapphire_bot | lib/sapphire_bot/events/ready.rb | Ruby | mit | 245 |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Multivendor
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct PhysicalDeviceVertexAttributeDivisorProperties
{
/// <summary>
///
/// </summary>
public uint MaxVertexAttribDivisor
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal static unsafe PhysicalDeviceVertexAttributeDivisorProperties MarshalFrom(SharpVk.Interop.Multivendor.PhysicalDeviceVertexAttributeDivisorProperties* pointer)
{
PhysicalDeviceVertexAttributeDivisorProperties result = default(PhysicalDeviceVertexAttributeDivisorProperties);
result.MaxVertexAttribDivisor = pointer->MaxVertexAttribDivisor;
return result;
}
}
}
| FacticiusVir/SharpVk | src/SharpVk/Multivendor/PhysicalDeviceVertexAttributeDivisorProperties.gen.cs | C# | mit | 2,199 |
package com.sonnytron.sortatech.pantryprep.Fragments.IngredientFilters;
import android.os.Bundle;
import com.sonnytron.sortatech.pantryprep.Fragments.IngredientsListFragment;
import com.sonnytron.sortatech.pantryprep.Models.Ingredient;
import com.sonnytron.sortatech.pantryprep.Service.IngredientManager;
import java.util.List;
public class ProteinFragment extends IngredientsListFragment {
public ProteinFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void updateUI() {
IngredientManager ingredientManager = IngredientManager.get(getActivity());
List<Ingredient> ingredients = ingredientManager.getIngredientsProtein();
addAll(ingredients);
setSpinner(1);
}
}
| PantryPrep/PantryPrep | app/src/main/java/com/sonnytron/sortatech/pantryprep/Fragments/IngredientFilters/ProteinFragment.java | Java | mit | 872 |
<?php
namespace Brainapp\CoreBundle\Entity\GroupEntities;
use Doctrine\ORM\EntityRepository;
/**
* GroupAccountRepository
*
* @author Chris Schneider
*/
class GroupAccountRepository extends EntityRepository
{
}
| thebrain1/brainapp | src/Brainapp/CoreBundle/Entity/GroupEntities/GroupAccountRepository.php | PHP | mit | 233 |
# frozen_string_literal: true
module ProxyFetcher
module Providers
# FreeProxyList provider class.
class Proxypedia < Base
# Provider URL to fetch proxy list
def provider_url
"https://proxypedia.org"
end
# [NOTE] Doesn't support filtering
def xpath
"//main/ul/li[position()>1]"
end
# Converts HTML node (entry of N tags) to <code>ProxyFetcher::Proxy</code>
# object.]
#
# @param html_node [Object]
# HTML node from the <code>ProxyFetcher::Document</code> DOM model.
#
# @return [ProxyFetcher::Proxy]
# Proxy object
#
def to_proxy(html_node)
addr, port = html_node.content_at("a").to_s.split(":")
ProxyFetcher::Proxy.new.tap do |proxy|
proxy.addr = addr
proxy.port = Integer(port)
proxy.country = parse_country(html_node)
proxy.anonymity = "Unknown"
proxy.type = ProxyFetcher::Proxy::HTTP
end
end
private
def parse_country(html_node)
text = html_node.content.to_s
text[/\((.+?)\)/, 1] || "Unknown"
end
end
ProxyFetcher::Configuration.register_provider(:proxypedia, Proxypedia)
end
end
| nbulaj/proxy_fetcher | lib/proxy_fetcher/providers/proxypedia.rb | Ruby | mit | 1,241 |
namespace abremir.AllMyBricks.Data.Interfaces
{
public interface IReferenceDataRepository
{
T GetOrAdd<T>(string value) where T : IReferenceData, new();
}
}
| zmira/abremir.AllMyBricks | abremir.AllMyBricks.Data/Interfaces/IReferenceDataRepository.cs | C# | mit | 180 |
var gulp = require('gulp');
gulp.task('dist', ['setProduction', 'sass:dist', 'browserify:dist']);
| wearemechanic/generator-mechanic | app/templates/gulp/tasks/dist.js | JavaScript | mit | 99 |
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', { '': value });
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({ '': j }, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
} ()); | DanielLangdon/ExpressForms | ExpressForms/ExpressFormsExample/Scripts/json2.js | JavaScript | mit | 16,986 |
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/elazarl/goproxy"
)
const (
AppendLog int = iota
ReopenLog int = iota
)
var (
emptyResp = &http.Response{}
emptyReq = &http.Request{}
)
type LogData struct {
action int
req *http.Request
resp *http.Response
user string
err error
time time.Time
}
type ProxyLogger struct {
path string
logChannel chan *LogData
errorChannel chan error
}
func fprintf(nr *int64, err *error, w io.Writer, pat string, a ...interface{}) {
if *err != nil {
return
}
var n int
n, *err = fmt.Fprintf(w, pat, a...)
*nr += int64(n)
}
func getAuthenticatedUserName(ctx *goproxy.ProxyCtx) string {
user, ok := ctx.UserData.(string)
if !ok {
user = "-"
}
return user
}
func (m *LogData) writeTo(w io.Writer) (nr int64, err error) {
if m.resp != nil {
if m.resp.Request != nil {
fprintf(&nr, &err, w,
"%v %v %v %v %v %v %v\n",
m.time.Format(time.RFC3339),
m.resp.Request.RemoteAddr,
m.resp.Request.Method,
m.resp.Request.URL,
m.resp.StatusCode,
m.resp.ContentLength,
m.user)
} else {
fprintf(&nr, &err, w,
"%v %v %v %v %v %v %v\n",
m.time.Format(time.RFC3339),
"-",
"-",
"-",
m.resp.StatusCode,
m.resp.ContentLength,
m.user)
}
} else if m.req != nil {
fprintf(&nr, &err, w,
"%v %v %v %v %v %v %v\n",
m.time.Format(time.RFC3339),
m.req.RemoteAddr,
m.req.Method,
m.req.URL,
"-",
"-",
m.user)
}
return
}
func newProxyLogger(conf *Configuration) *ProxyLogger {
var fh *os.File
if conf.AccessLog != "" {
var err error
fh, err = os.OpenFile(conf.AccessLog, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
log.Fatalf("Couldn't open log file: %v", err)
}
}
logger := &ProxyLogger{
path: conf.AccessLog,
logChannel: make(chan *LogData),
errorChannel: make(chan error),
}
go func() {
for m := range logger.logChannel {
if fh != nil {
switch m.action {
case AppendLog:
if _, err := m.writeTo(fh); err != nil {
log.Println("Can't write meta", err)
}
case ReopenLog:
err := fh.Close()
if err != nil {
log.Fatal(err)
}
fh, err = os.OpenFile(conf.AccessLog, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
log.Fatalf("Couldn't reopen log file: %v", err)
}
}
}
}
logger.errorChannel <- fh.Close()
}()
return logger
}
func (logger *ProxyLogger) logResponse(resp *http.Response, ctx *goproxy.ProxyCtx) {
if resp == nil {
resp = emptyResp
}
logger.writeLogEntry(&LogData{
action: AppendLog,
resp: resp,
user: getAuthenticatedUserName(ctx),
err: ctx.Error,
time: time.Now(),
})
}
func (logger *ProxyLogger) writeLogEntry(data *LogData) {
logger.logChannel <- data
}
func (logger *ProxyLogger) log(ctx *goproxy.ProxyCtx) {
data := &LogData{
action: AppendLog,
req: ctx.Req,
resp: ctx.Resp,
user: getAuthenticatedUserName(ctx),
err: ctx.Error,
time: time.Now(),
}
logger.writeLogEntry(data)
}
func (logger *ProxyLogger) close() error {
close(logger.logChannel)
return <-logger.errorChannel
}
func (logger *ProxyLogger) reopen() {
logger.writeLogEntry(&LogData{action: ReopenLog})
}
| thekvs/microproxy | log.go | GO | mit | 3,286 |
'use strict';
import Chart from 'chart.js';
import Controller from './controller';
import Scale, {defaults} from './scale';
// Register the Controller and Scale
Chart.controllers.smith = Controller;
Chart.defaults.smith = {
aspectRatio: 1,
scale: {
type: 'smith',
},
tooltips: {
callbacks: {
title: () => null,
label: (bodyItem, data) => {
const dataset = data.datasets[bodyItem.datasetIndex];
const d = dataset.data[bodyItem.index];
return dataset.label + ': ' + d.real + ' + ' + d.imag + 'i';
}
}
}
};
Chart.scaleService.registerScaleType('smith', Scale, defaults);
| chartjs/Chart.smith.js | src/index.js | JavaScript | mit | 602 |
var packageInfo = require('./package.json');
var taskList = [{name:'default'},{name:'delete'},{name:'build'},{name:'copy'},{name:'minify'}];
var gulpTalk2me = require('gulp-talk2me');
var talk2me = new gulpTalk2me(packageInfo,taskList);
var del = require('del');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate');
var bytediff = require('gulp-bytediff');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var templateCache = require('gulp-angular-templatecache');
var series = require('stream-series');
var angularFilesort = require('gulp-angular-filesort');
console.log(talk2me.greeting);
gulp.task('default',function(callback){
runSequence('build',callback);
});
gulp.task('delete',function(callback){
del('dist/**/*', callback());
});
gulp.task('build',function(callback){
runSequence('delete',['copy','minify'],callback);
});
gulp.task('copy',function(){
return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js']))
.pipe(sourcemaps.init())
.pipe(angularFilesort())
.pipe(concat('bs-fa-boolean-directive.js', {newLine: ';\n'}))
.pipe(ngAnnotate({
add: true
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('minify',function(){
return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js']))
.pipe(sourcemaps.init())
.pipe(angularFilesort())
.pipe(concat('bs-fa-boolean-directive.js', {newLine: ';'}))
.pipe(rename(function (path) {
path.basename += ".min";
}))
.pipe(ngAnnotate({
add: true
}))
.pipe(bytediff.start())
.pipe(uglify({mangle: true}))
.pipe(bytediff.stop())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
function genTemplateStream () {
return gulp.src(['src/**/*.view.html'])
.pipe(templateCache({standalone:true,module:'bs-fa-boolean.template'}));
} | belgac/bs-fa-boolean-directive | Gulpfile.js | JavaScript | mit | 2,022 |
package tunnel
import (
"bytes"
stdcrypto "crypto"
"encoding/base64"
"errors"
"fmt"
"net"
"net/url"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/Lafeng/deblocus/auth"
"github.com/Lafeng/deblocus/crypto"
"github.com/Lafeng/deblocus/exception"
"github.com/go-ini/ini"
"github.com/kardianos/osext"
)
const (
CF_CLIENT = "deblocus.Client"
CF_SERVER = "deblocus.Server"
CF_URL = "URL"
CF_KEY = "Key"
CF_CRYPTO = "Crypto"
CF_PRIVKEY = "PrivateKey"
CF_CREDENTIAL = "Credential"
CF_PAC = "PAC.Server"
CF_FILE = "File"
CONFIG_NAME = "deblocus.ini"
SIZE_UNIT = "BKMG"
)
var (
UNRECOGNIZED_SYMBOLS = exception.New("Unrecognized symbols")
LOCAL_BIND_ERROR = exception.New("Local bind error")
CONF_MISS = exception.New("Missed field in config:")
CONF_ERROR = exception.New("Error field in config:")
)
type ServerRole uint32
const (
SR_AUTO ServerRole = ^ServerRole(0)
SR_CLIENT ServerRole = 0x0f
SR_SERVER ServerRole = 0xf0
)
type ConfigMan struct {
filepath string
iniInstance *ini.File
sConf *serverConf
cConf *clientConf
}
func DetectConfig(specifiedFile string) (*ConfigMan, error) {
var paths []string
if specifiedFile == NULL {
paths = []string{CONFIG_NAME} // cwd
var ef, home string
var err error
// same path with exe
ef, err = osext.ExecutableFolder()
if err == nil {
paths = append(paths, filepath.Join(ef, CONFIG_NAME))
}
// home
if u, err := user.Current(); err == nil {
home = u.HomeDir
} else {
home = os.Getenv("HOME")
}
if home != NULL {
paths = append(paths, filepath.Join(home, CONFIG_NAME))
}
// etc
if runtime.GOOS != "windows" {
paths = append(paths, "/etc/deblocus/"+CONFIG_NAME)
}
} else {
paths = []string{specifiedFile}
}
var file *string
for _, f := range paths {
if f != NULL && !IsNotExist(f) {
file = &f
break
}
}
if file == nil {
msg := fmt.Sprintf("Not found `%s` in [ %s ]\n", CONFIG_NAME, strings.Join(paths, "; "))
msg += "Create config in typical path or specify it with option `--config/-c`."
return nil, errors.New(msg)
}
iniInstance, err := ini.Load(*file)
return &ConfigMan{
filepath: *file,
iniInstance: iniInstance,
}, err
}
func (cman *ConfigMan) InitConfigByRole(expectedRole ServerRole) (r ServerRole, err error) {
if expectedRole&SR_CLIENT != 0 {
if _, err = cman.iniInstance.GetSection(CF_CLIENT); err == nil {
r |= SR_CLIENT
cman.cConf, err = cman.ParseClientConf()
} else if expectedRole == SR_AUTO { // AUTO ignore
err = nil
}
if err != nil {
goto abort
}
}
if expectedRole&SR_SERVER != 0 {
if _, err = cman.iniInstance.GetSection(CF_SERVER); err == nil {
r |= SR_SERVER
cman.sConf, err = cman.ParseServConf()
} else if expectedRole == SR_AUTO { // AUTO ignore
err = nil
}
if err != nil {
goto abort
}
}
cman.iniInstance = nil
abort:
return r, err
}
func (cman *ConfigMan) LogV(expectedRole ServerRole) int {
if expectedRole&SR_SERVER != 0 {
return cman.sConf.Verbose
}
if expectedRole&SR_CLIENT != 0 {
return cman.cConf.Verbose
}
return -1
}
func (cman *ConfigMan) ListenAddr(expectedRole ServerRole) *net.TCPAddr {
if expectedRole&SR_SERVER != 0 {
return cman.sConf.ListenAddr
}
if expectedRole&SR_CLIENT != 0 {
return cman.cConf.ListenAddr
}
return nil
}
func (cman *ConfigMan) KeyInfo(expectedRole ServerRole) string {
var buf = new(bytes.Buffer)
if expectedRole&SR_SERVER != 0 {
key := cman.sConf.publicKey
fmt.Fprintln(buf, "Server Key in", cman.filepath)
fmt.Fprintln(buf, " type:", NameOfKey(key))
fmt.Fprintln(buf, " fingerprint:", FingerprintOfKey(key))
}
if expectedRole&SR_CLIENT != 0 {
key := cman.cConf.connInfo.sPubKey
fmt.Fprintln(buf, "Credential Key in", cman.filepath)
fmt.Fprintln(buf, " type:", NameOfKey(key))
fmt.Fprintln(buf, " fingerprint:", FingerprintOfKey(key))
}
return buf.String()
}
// client config definitions
type clientConf struct {
Listen string `importable:":9009"`
Verbose int `importable:"1"`
ListenAddr *net.TCPAddr `ini:"-"`
connInfo *connectionInfo
}
func (c *clientConf) validate() error {
if c.connInfo == nil {
return CONF_MISS.Apply("Not found credential")
}
if c.Listen == NULL {
return CONF_MISS.Apply("Listen")
}
a, e := net.ResolveTCPAddr("tcp", c.Listen)
if e != nil {
return LOCAL_BIND_ERROR.Apply(e)
}
pkType := NameOfKey(c.connInfo.sPubKey)
if pkType != c.connInfo.pkType {
return CONF_ERROR.Apply(pkType)
}
if c.connInfo.pacFile != NULL && IsNotExist(c.connInfo.pacFile) {
return CONF_ERROR.Apply("File Not Found " + c.connInfo.pacFile)
}
c.ListenAddr = a
return nil
}
type connectionInfo struct {
sAddr string
provider string
cipher string
user string
pass string
pkType string
pacFile string
sPubKey stdcrypto.PublicKey
rawURL string
}
func (d *connectionInfo) RemoteName() string {
if d.provider != NULL {
return d.provider
} else {
return d.sAddr
}
}
func newConnectionInfo(uri string) (*connectionInfo, error) {
url, err := url.Parse(uri)
if err != nil {
return nil, err
}
if url.Scheme != "d5" {
return nil, CONF_ERROR.Apply(url.Scheme)
}
_, err = net.ResolveTCPAddr("tcp", url.Host)
if err != nil {
return nil, HOST_UNREACHABLE.Apply(err)
}
var tmp string
var info = connectionInfo{sAddr: url.Host}
if len(url.Path) > 1 {
info.provider, tmp = SubstringBefore(url.Path[1:], "=")
}
if info.provider == NULL {
return nil, CONF_MISS.Apply("Provider")
}
info.pkType, info.cipher = SubstringBefore(tmp, "/")
_, err = GetAvailableCipher(info.cipher)
if err != nil {
return nil, err
}
user := url.User
if user == nil || user.Username() == NULL {
return nil, CONF_MISS.Apply("user")
}
passwd, ok := user.Password()
if !ok || passwd == NULL {
return nil, CONF_MISS.Apply("passwd")
}
info.user = user.Username()
info.pass = passwd
info.rawURL = uri
return &info, nil
}
// public for external handler
func (cman *ConfigMan) CreateClientConfig(file string, user string, addonAddr string) (err error) {
var f *os.File
if file == NULL {
f = os.Stdout
} else {
f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
}
defer f.Sync()
var sAddr string
var conf = new(clientConf)
var newIni = ini.Empty()
setFieldsDefaultValue(conf)
// client section
dc, _ := newIni.NewSection(CF_CLIENT)
dc.Comment = _CLT_CONF_HEADER[1:]
dc.ReflectFrom(conf)
// prepare server addr
if addonAddr == NULL {
sAddr = findFirstUnicastAddress()
if sAddr == NULL {
sAddr = "localhost:9008"
} else {
sPort := findServerListenPort(cman.sConf.Listen)
sAddr = fmt.Sprint(sAddr, ":", sPort)
}
cman.sConf.Listen = sAddr
} else {
err = IsValidHost(addonAddr)
cman.sConf.Listen = addonAddr
if err != nil {
return
}
}
err = cman.sConf.generateConnInfoOfUser(newIni, user)
if err == nil {
_, err = newIni.WriteTo(f)
if addonAddr == NULL {
var notice = strings.Replace(_NOTICE_MOD_ADDR, "ADDR", sAddr, -1)
fmt.Fprint(f, notice)
}
}
return
}
// public for external
func (cman *ConfigMan) ParseClientConf() (conf *clientConf, err error) {
ii := cman.iniInstance
secDc, err := ii.GetSection(CF_CLIENT)
if err != nil {
return
}
conf = new(clientConf)
err = secDc.MapTo(conf)
if err != nil {
return
}
cr, err := ii.GetSection(CF_CREDENTIAL)
if err != nil {
return
}
url, err := cr.GetKey(CF_URL)
if err != nil {
return
}
connInfo, err := newConnectionInfo(url.String())
if err != nil {
return
}
pubkeyObj, err := cr.GetKey(CF_KEY)
if err != nil {
return
}
pubkeyBytes, err := base64.StdEncoding.DecodeString(pubkeyObj.String())
if err != nil {
return
}
pubkey, err := UnmarshalPublicKey(pubkeyBytes)
if err != nil {
return
}
secPac, _ := ii.GetSection(CF_PAC)
if secPac != nil && secPac.Haskey(CF_FILE) {
pacFile, _ := secPac.GetKey(CF_FILE)
connInfo.pacFile = pacFile.String()
}
connInfo.sPubKey = pubkey
conf.connInfo = connInfo
err = conf.validate()
return
}
// Server config definitions
type serverConf struct {
Listen string `importable:":9008"`
Auth string `importable:"file://_USER_PASS_FILE_PATH_"`
Cipher string `importable:"AES128CTR"`
ServerName string `importable:"_MY_SERVER"`
Parallels int `importable:"2"`
Verbose int `importable:"1"`
DenyDest string `importable:"OFF"`
ErrorFeedback string `importable:"true"`
AuthSys auth.AuthSys `ini:"-"`
ListenAddr *net.TCPAddr `ini:"-"`
errFeedback bool
privateKey stdcrypto.PrivateKey
publicKey stdcrypto.PublicKey
}
func (d *serverConf) validate() error {
if len(d.Listen) < 1 {
return CONF_MISS.Apply("Listen")
}
a, e := net.ResolveTCPAddr("tcp", d.Listen)
if e != nil {
return LOCAL_BIND_ERROR.Apply(e)
}
d.ListenAddr = a
if len(d.Auth) < 1 {
return CONF_MISS.Apply("Auth")
}
d.AuthSys, e = auth.GetAuthSysImpl(d.Auth)
if e != nil {
return e
}
if len(d.Cipher) < 1 {
return CONF_MISS.Apply("Cipher")
}
_, e = GetAvailableCipher(d.Cipher)
if e != nil {
return e
}
if d.ServerName == NULL {
return CONF_MISS.Apply("ServerName")
}
if d.Parallels < 2 || d.Parallels > 16 {
return CONF_ERROR.Apply("Parallels")
}
if d.privateKey == nil {
return CONF_MISS.Apply("PrivateKey")
}
if len(d.DenyDest) > 0 {
if d.DenyDest == "OFF" || d.DenyDest == "off" {
d.DenyDest = NULL
} else if !regexp.MustCompile("[A-Za-z]{2}").MatchString(d.DenyDest) {
return CONF_ERROR.Apply("DenyDest must be ISO3166-1 2-letter Country Code")
}
}
if len(d.ErrorFeedback) > 0 {
d.errFeedback, e = strconv.ParseBool(d.ErrorFeedback)
if e != nil {
return CONF_ERROR.Apply("ErrorFeedback")
}
}
return nil
}
// public for external handler
func (cman *ConfigMan) ParseServConf() (d5s *serverConf, err error) {
ii := cman.iniInstance
sec, err := ii.GetSection(CF_SERVER)
if err != nil {
return
}
d5s = new(serverConf)
if err = sec.MapTo(d5s); err != nil {
return
}
kSec, err := ii.GetSection(CF_PRIVKEY)
if err != nil {
return
}
key, err := kSec.GetKey(CF_KEY)
if err != nil {
return
}
keyBytes, err := base64.StdEncoding.DecodeString(key.String())
if err != nil {
return
}
priv, err := UnmarshalPrivateKey(keyBytes)
if err != nil {
return
}
d5s.privateKey = priv
d5s.publicKey = priv.(stdcrypto.Signer).Public()
err = d5s.validate()
return
}
// public for external handler
func CreateServerConfigTemplate(file string, keyOpt string) (err error) {
var f *os.File
if file == NULL {
f = os.Stdout
} else {
f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600)
if err != nil {
return
}
defer f.Close()
}
defer f.Sync()
d5sConf := new(serverConf)
d5sConf.setDefaultValue()
// uppercase algo name
keyOpt = strings.ToUpper(keyOpt)
d5sConf.privateKey, err = GenerateDSAKey(keyOpt)
if err != nil {
return
}
ii := ini.Empty()
ds, _ := ii.NewSection(CF_SERVER)
ds.Comment = _SER_CONF_HEADER[1:]
err = ds.ReflectFrom(d5sConf)
if err != nil {
return
}
ks, _ := ii.NewSection(CF_PRIVKEY)
keyBytes := MarshalPrivateKey(d5sConf.privateKey)
ks.Comment = _SER_CONF_MIDDLE[1:]
ks.NewKey(CF_KEY, base64.StdEncoding.EncodeToString(keyBytes))
_, err = ii.WriteTo(f)
return
}
func (d *serverConf) generateConnInfoOfUser(ii *ini.File, user string) error {
u, err := d.AuthSys.UserInfo(user)
if err != nil {
return err
}
keyBytes, err := MarshalPublicKey(d.publicKey)
if err != nil {
return err
}
url := fmt.Sprintf("d5://%s:%s@%s/%s=%s/%s", u.Name, u.Pass, d.Listen, d.ServerName, NameOfKey(d.publicKey), d.Cipher)
sec, _ := ii.NewSection(CF_CREDENTIAL)
sec.NewKey(CF_URL, url)
sec.NewKey(CF_KEY, base64.StdEncoding.EncodeToString(keyBytes))
sec.Comment = _COMMENTED_PAC_SECTION
return nil
}
// set default values by field comment
// set recommended values by detecting
func (d *serverConf) setDefaultValue() {
setFieldsDefaultValue(d)
host, err := os.Hostname()
if err == nil {
host = regexp.MustCompile(`\W`).ReplaceAllString(host, "")
d.ServerName = strings.ToUpper(host)
}
if crypto.HasAESHardware() == 0 {
d.Cipher = "CHACHA12"
}
}
func setFieldsDefaultValue(str interface{}) {
typ := reflect.TypeOf(str)
val := reflect.ValueOf(str)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
ft := typ.Field(i)
fv := val.Field(i)
imp := ft.Tag.Get("importable")
if !ft.Anonymous && imp != NULL {
k := fv.Kind()
switch k {
case reflect.String:
fv.SetString(imp)
case reflect.Int:
intVal, err := strconv.ParseInt(imp, 10, 0)
if err == nil {
fv.SetInt(intVal)
}
default:
panic(fmt.Errorf("unsupported %v", k))
}
}
}
}
func findServerListenPort(addr string) int {
n, e := net.ResolveTCPAddr("tcp", addr)
if e != nil {
return 9008
}
return n.Port
}
func findFirstUnicastAddress() string {
nic, e := net.InterfaceAddrs()
if nic != nil && e == nil {
for _, v := range nic {
if i, _ := v.(*net.IPNet); i != nil {
if i.IP.IsGlobalUnicast() {
return i.IP.String()
}
}
}
}
return NULL
}
const _SER_CONF_HEADER = `
# ---------------------------------------------
# deblocus server configuration
# wiki: https://github.com/Lafeng/deblocus/wiki
# ---------------------------------------------
`
const _SER_CONF_MIDDLE = `
### Please take good care of this secret file during the server life cycle.
### DO NOT modify the following lines, unless you known what will happen.
`
const _CLT_CONF_HEADER = `
# ---------------------------------------------
# deblocus client configuration
# wiki: https://github.com/Lafeng/deblocus/wiki
# ---------------------------------------------
`
const _COMMENTED_PAC_SECTION = `# Optional
# [PAC.Server]
# File = mypac.js
`
const _NOTICE_MOD_ADDR = `
# +-----------------------------------------------------------------+
# May need to modify the "ADDR" to your public address.
# +-----------------------------------------------------------------+
`
| Lafeng/deblocus | tunnel/config.go | GO | mit | 14,293 |
module Fog
module OpenStack
class Compute
class Real
def get_server_details(server_id)
request(
:expects => [200, 203],
:method => 'GET',
:path => "servers/#{server_id}"
)
end
end
class Mock
def get_server_details(server_id)
response = Excon::Response.new
server = list_servers_detail.body['servers'].find { |srv| srv['id'] == server_id }
if server
response.status = [200, 203][rand(2)]
response.body = {'server' => server}
response
else
raise Fog::OpenStack::Compute::NotFound
end
end
end
end
end
end
| fog/fog-openstack | lib/fog/openstack/compute/requests/get_server_details.rb | Ruby | mit | 729 |
<?php
/*
File: class/class_api.php
Created: 11/10/2016 at 1:34PM Eastern Time
Info: Creates a class file to use as an API for modders
who don't wish to use the main game code!
Author: TheMasterGeneral
Website: https://github.com/MasterGeneral156/chivalry-engine
*/
if (!defined('MONO_ON')) {
exit;
}
class user
{
/*
Tests to see if specified user has at least the specified amount of money.
@param int user = User ID to test for.
@param text type = Currency type. [Ex. primary or secondary]
@param int money = Minimum money requied.
Returns true if user has more cash than required.
Returns false if user does not exist or does not have the minimum cash requred.
*/
function hasCurrency(int $user, string $type, int $minimum)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$minimum = (isset($minimum) && is_numeric($minimum)) ? abs(intval($minimum)) : 0;
$type = $db->escape(stripslashes(strtolower($type)));
$userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}"));
if ($userexist) {
if ($type == 'primary' || $type == 'secondary') {
$UserMoney = $db->fetch_single($db->query("SELECT `{$type}_currency` FROM `users` WHERE `userid` = {$user}"));
if ($UserMoney >= $minimum) {
return true;
}
}
}
}
/*
Gives the user the specified item and quantity
@param int user = User ID to test for.
@param int item = Item ID to give to the user.
@param int quantity = Quantity of item to give to the user.
Returns true if item successfully given to the user.
Returns false if item failed to be given to user.
*/
function giveItem(int $user, int $item, int $quantity)
{
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0;
$quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0;
if (addItem($user, $item, $quantity)) {
return true;
}
}
/*
Removes an item from the user specified
@param int user = User ID to test for.
@param int item = Item ID to take from the user.
@param int quantity = Quantity of item to remove from the user.
Returns true if item successfully taken from the user.
Returns false if item failed to be taken from user.
*/
function takeItem(int $user, int $item, int $quantity)
{
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0;
$quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0;
if (takeItem($user, $item, $quantity)) {
return true;
}
}
/*
Test to see whether or not the specified user has the item and optionally, an amount of the item.
@param int user = User to test on.
@param int item = Item ID to test for.
@param int qty = Quantity to test for. Optional. [Default: 1]
Returns true if the user has the item and requried quantity. False if otherwise.
*/
function hasItem(int $user, int $item, int $qty = 1)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0;
$qty = (isset($qty) && is_numeric($qty)) ? abs(intval($qty)) : 0;
if ($user > 0 || $item > 0 || $qty > 0) {
$i = $db->fetch_single($db->query("SELECT `inv_qty` FROM `inventory` WHERE `inv_userid` = {$user} && `inv_itemid` = {$item}"));
if ($qty == 1)
if ($i >= 1)
return true;
else
if ($i >= $qty)
return true;
}
}
/*
Function to fetch item count from a user's inventory.
@param int userid = User ID of the player to test inventory.
@param int itemid = Item ID to count.
Returns the count of Item ID found on the user.
*/
function countItem(int $userid, int $itemid)
{
global $db;
$userid = (isset($userid) && is_numeric($userid)) ? abs(intval($userid)) : 0;
$itemid = (isset($itemid) && is_numeric($itemid)) ? abs(intval($itemid)) : 0;
if (!empty($userid) || !empty($itemid)) {
$qty = $db->fetch_single($db->query("SELECT SUM(`inv_qty`) FROM `inventory` WHERE `inv_itemid` = {$itemid} AND `inv_userid` = {$userid}"));
return $qty;
}
}
/*
Gives user specified amount of currency type.
@param int user = User ID to give currency to.
@param int type = Currency type. [Ex. primary and secondary]
@param int money = Currency given.
Returns true if user has received currency.
Returns false if user does not receive currency.
*/
function giveCurrency(int $user, string $type, int $quantity)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$type = $db->escape(stripslashes(strtolower($type)));
$quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0;
$userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}"));
if ($userexist) {
if ($type == 'primary' || $type == 'secondary') {
$db->query("UPDATE `users` SET `{$type}_currency` = `{$type}_currency` + {$quantity} WHERE `userid` = {$user}");
return true;
}
}
}
/*
Takes qunatity of currency type from the user specified.
@param int user = User ID to give currency to.
@param int type = Currency type. [Ex. primary and secondary]
@param int money = Currency given.
Returns true if user has lost currency.
Returns false if user does not lose any currency.
*/
function takeCurrency(int $user, string $type, int $quantity)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$type = $db->escape(stripslashes(strtolower($type)));
$quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0;
$userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}"));
if ($userexist) {
if ($type == 'primary' || $type == 'secondary') {
$db->query("UPDATE `users` SET `{$type}_currency` = `{$type}_currency` - {$quantity} WHERE `userid` = {$user}");
$db->query("UPDATE `users` SET `{$type}_currency` = 0 WHERE `{$type}_currency` < 0");
return true;
}
}
}
/*
Tests to see what the user has equipped.
@param int user = User ID to test against.
@param int slot = Equipment slot to test. [Ex. Primary, Secondary, Armor]
@param int itemid = Item to test for. -1 = Any Item, 0 = No Item Equipped, >0 = Specific item
Returns true if user has item equipped
Returns false if user does not have item equipped.
*/
function itemEquipped(int $user, string $slot, int $itemid = -1)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$slot = $db->escape(stripslashes(strtolower($slot)));
if ($slot == 'primary' || $slot == 'secondary' || $slot == 'armor') {
//Any item equipped
if ($itemid == -1) {
$equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}"));
if ($equipped > 0) {
return true;
}
} //Specific item equipped
elseif ($itemid > 0) {
$itemid = (isset($itemid) && is_numeric($itemid)) ? abs(intval($itemid)) : 0;
$equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}"));
if ($equipped == $itemid) {
return true;
}
} //Nothing equipped
elseif ($itemid == 0) {
$equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}"));
if ($equipped == 0) {
return true;
}
}
}
}
/*
Tests the inputted user to see if they're in the infirmary
@param int user = User ID to test against.
Returns true if user is in the infirmary
Returns false if user is not in the infirmary
*/
function inInfirmary(int $user)
{
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
return userInInfirmary($user);
}
/*
Tests the inputted user to see if they're in the dungeon
@param int user = User ID to test against.
Returns true if user is in the dungeon.
Returns false if user is not in the dungeon.
*/
function inDungeon(int $user)
{
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
return userInDungeon($user);
}
/*
Places or removes infirmary time on the specified user.
@param int user = User ID to test against.
@param int time = Minutes user is in infirmary
@param text reason = Reason why user is in the infirmary
Returns true if user is placed in the infirmary, or is removed from it.
Returns false otherwise.
*/
function setInfirmary(int $user, int $time, string $reason)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$reason = $db->escape(stripslashes($reason));
if ($time >= 0) {
$time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0;
userPutInfirmary($user, $time, $reason);
return true;
} elseif ($time < 0) {
$time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0;
userRemoveInfirmary($user, $time);
return true;
}
}
/*
Places or removes dungeon/infirmary time on the specified user.
@param int user = User ID to test against.
@param int time = Minutes user is in dungeon.
@param text reason = Reason why user is in the dungeon.
Returns true if user is placed in the dungeon, or is removed from it.
Returns false otherwise.
*/
function setDungeon(int $user, int $time, string $reason)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$reason = $db->escape(stripslashes($reason));
if ($time >= 0) {
$time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0;
userPutDungeon($user, $time, $reason);
return true;
} elseif ($time < 0) {
$time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0;
userRemoveDungeon($user, $time);
return true;
}
}
/*
* Function to simulate a user training.
* @param int userid = User ID of the player you wish to simulate.
* @param text stat = Stat you wish for the user to train.
* @param int times = How much you wish the user to train.
* Returns stats gained.
*/
function train(int $userid, string $stat, int $times, int $multiplier = 1)
{
global $db;
$userid = (isset($userid) && is_numeric($userid)) ? abs(intval($userid)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
$times = (isset($times) && is_numeric($times)) ? abs(intval($times)) : 0;
$multiplier = (isset($multiplier) && is_numeric($multiplier)) ? abs(intval($multiplier)) : 1;
//Return empty if the call isn't complete.
if (empty($userid) || (empty($stat)) || (empty($times))) {
return 0;
}
$StatArray = array("strength", "agility", "guard", "labor", "iq");
if (!in_array($stat, $StatArray)) {
return -1;
}
$udq = $db->query("SELECT * FROM `users` WHERE `userid` = {$userid}");
$userdata = $db->fetch_row($udq);
$gain = 0;
//Do while value is less than the user's energy input, then add one to value.
for ($i = 0; $i < $times; $i++) {
//(1-4)/(600-1000)*(500-1000)*((User's Will+25)/175)
$gain +=
randomNumber(1, 4) / randomNumber(600, 1000) * randomNumber(500, 1000) * (($userdata['will'] + 25) / 175);
//Subtract a randomNumber number from user's will.
$userdata['will'] -= randomNumber(1, 3);
//User's will ends up negative, set to zero.
if ($userdata['will'] < 0) {
$userdata['will'] = 0;
}
}
//Add multiplier, if needed.
$gain *= $multiplier;
//Round the gained stats.
$gain = floor($gain);
//Update the user's stats.
$db->query("UPDATE `userstats`
SET `{$stat}` = `{$stat}` + {$gain}
WHERE `userid` = {$userid}");
//Update user's will and energy.
$db->query("UPDATE `users`
SET `will` = {$userdata['will']},
`energy` = `energy` - {$times}
WHERE `userid` = {$userid}");
return $gain;
}
/*
Get the user's member level. Can test for exact member level, or if user is above specified member level.
@param int user = User to test on.
@param text level = Member level to test for. [Valid: npc, member, web dev, forum moderator, assistant, admin]
@param boolean exact = Return true if ranked ONLY specified level. [Default: false]
Returns true if user is exactly or equal to/above specified member level. False if not.
*/
//This function needs refactored ASAP
function getStaffLevel(int $user, string $level, bool $exact = false)
{
global $db;
$level = $db->escape(stripslashes(strtolower($level)));
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
if ($user > 0) {
$userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$user}");
if ($db->num_rows($userexist) > 0) {
$ulevel = $db->fetch_single($db->query("SELECT `user_level` FROM `users` WHERE `userid` = {$user}"));
if ($exact == true) {
if ($level == $ulevel) {
return true;
}
} else {
if ($level == 'member') {
if ($ulevel == 'Member' || $ulevel == 'Forum Moderator' || $ulevel == 'Assistant'
|| $ulevel == 'Web Developer' || $ulevel == 'Admin'
) {
return true;
}
} elseif ($level == 'forum moderator') {
if ($ulevel == 'Forum Moderator' || $ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin') {
return true;
}
} elseif ($level == 'assistant') {
if ($ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin') {
return true;
}
} elseif ($level == 'web dev') {
if ($ulevel == 'Web Developer' || $ulevel == 'Admin') {
return true;
}
} elseif ($level == 'npc') {
if ($ulevel == 'Member' || $ulevel == 'NPC' || $ulevel == 'Forum Moderator' || $ulevel == 'Assistant'
|| $ulevel == 'Web Developer' || $ulevel == 'Admin'
) {
return true;
}
} elseif ($level == 'admin') {
if ($ulevel == 'Admin') {
return true;
}
}
}
}
}
}
/*
Set the specified user's stat to a value.
@param int user = User to test on.
@param text stat = User's table row to return.
@param int change = Numeric change (as a value)
Returns the value in the stat specified.
Throws E_ERROR if attempting to edit a sensitive field (Such as passwords)
*/
function setInfo(int $user, string $stat, int $change)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
$change = (isset($change) && is_numeric($change)) ? intval($change) : 0;
if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes')))
{
trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR);
}
else
{
$db->query("UPDATE users SET `{$stat}` = `{$stat}` + {$change} WHERE `userid` = {$user}");
$db->query("UPDATE users SET `{$stat}` = `max{$stat}` WHERE `{$stat}` > `max{$stat}`");
return true;
}
}
/*
Set the specified user's stat to a percent.
@param int user = User to test on.
@param text stat = User's table row to return.
@param int change = Numeric change (as percent)
Returns the value in the stat specified.
Throws E_ERROR if attempting to edit a sensitive field (Such as passwords)
*/
function setInfoPercent(int $user, string $stat, int $change)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
$change = (isset($change) && is_numeric($change)) ? intval($change) : 0;
if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes')))
{
trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR);
}
else
{
$maxstat = $db->fetch_single($db->query("SELECT `max{$stat}` FROM `users` WHERE `userid` = {$user}"));
$number = ($change / 100) * $maxstat;
$db->query("UPDATE users SET `{$stat}`=`{$stat}`+{$number} WHERE `{$stat}` < `max{$stat}`");
$db->query("UPDATE users SET `{$stat}` = `max{$stat}` WHERE `{$stat}` > `max{$stat}`");
return true;
}
}
/*
Returns the specified user's stat
@param int user = User to test on.
@param text stat = User's table row to return.
Returns the value in the stat specified.
Throws E_ERROR if attempting to edit a sensitive field (Such as passwords)
*/
function getInfo(int $user, string $stat)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes')))
{
trigger_error("You do not have permission to get the {$stat} on this user.", E_ERROR);
}
else
{
return $db->fetch_single($db->query("SELECT `{$stat}` FROM `users` WHERE `userid` = {$user}"));
}
}
/*
Returns the specified user's stat as a percent
@param int user = User to test on.
@param text stat = User's table row to return.
Returns the value in the stat specified.
Throws E_ERROR if attempting to edit a sensitive field (Such as passwords)
*/
function getInfoPercent(int $user, string $stat)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes')))
{
trigger_error("You do not have permission to get the {$stat} on this user.", E_ERROR);
}
else
{
$min = $db->fetch_single($db->query("SELECT `{$stat}` FROM `users` WHERE `userid` = {$user}"));
$max = $db->fetch_single($db->query("SELECT `max{$stat}` FROM `users` WHERE `userid` = {$user}"));
return round($min / $max * 100);
}
}
/*
Function to set a user's info a static value.
@param int user = User ID you wish to set a specific stat to.
@param text stat = Stat to alter.
@param int state = Value to set the stat to.
Returns true if the stat was updated, false otherwise.
Throws E_ERROR if attempting to edit a sensitive field (Such as passwords)
*/
function setInfoStatic(int $user, string $stat, int $state)
{
global $db, $api;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$stat = $db->escape(stripslashes(strtolower($stat)));
if (in_array($stat, array('password', 'email', 'lastip', 'loginip',
'registerip', 'personal_notes', 'staff_notes'))) {
trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR);
} else {
if (is_int($state)) {
$state = (isset($state) && is_numeric($state)) ? abs(intval($state)) : 0;
} else {
$state = $db->escape(stripslashes($state));
}
if ($user > 0) {
if (!($api->user->getNamefromID($user) == false)) {
$db->query("UPDATE `users` SET `{$stat}` = '{$state}' WHERE `userid` = '{$user}'");
return true;
}
}
}
}
/*
Adds a notification for the specified user.
@param int user = User ID to send notification to.
@param text text = Notification text.
Returns true always.
*/
function addNotification(int $user, string $text)
{
addNotification($user, $text);
return true;
}
/*
Adds an in-game message for the player specified.
@param int user = User ID message is sent to.
@param text subj = Message subject.
@param text msg = Message text.
@param int from = User ID message is from..
Returns true when message is sent. False if message fails.
*/
function addMail(int $user, string $subj, string $msg, int $from)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$from = (isset($from) && is_numeric($from)) ? abs(intval($from)) : 0;
$subj = $db->escape(stripslashes($subj));
$msg = $db->escape(stripslashes($msg));
$time = time();
$userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$user}");
if ($db->num_rows($userexist) > 0) {
$db->free_result($userexist);
$userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$from}");
if ($db->num_rows($userexist) > 0) {
$db->query("INSERT INTO `mail`
(`mail_to`, `mail_from`, `mail_status`, `mail_subject`, `mail_text`, `mail_time`)
VALUES
('{$user}', '{$from}', 'unread', '{$subj}', '{$msg}', '{$time}');");
return true;
}
}
}
/*
Returns the username of the user id specified.
@param int user = User's name we're trying to fetch.
On success, returns the user id's name, on failure, it returns false.
*/
function getNamefromID(int $user)
{
global $db;
$user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0;
$name = $db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}");
if ($db->num_rows($name) > 0) {
$username = $db->fetch_single($name);
return $username;
}
}
/*
Returns the userid of the username specified.
@param string name = User's ID we're trying to fetch.
On success, returns the user's id, on failure, it returns false.
*/
function getIDfromName(string $name)
{
global $db;
$name = $db->escape(stripslashes($name));
$id = $db->query("SELECT `userid` FROM `users` WHERE `username` = '{$name}'");
if ($db->num_rows($id) > 0) {
$usrid = $db->fetch_single($id);
return $usrid;
}
}
/*
Function to test if the inputted users share IPs at all.
@param int user1 = User ID of the first player.
@param int user2 = User ID of the second player.
Returns true if the users share an IP, false if not. Will also return false if both variables are equal.
*/
function checkIP(int $user1, int $user2)
{
global $db;
$user1 = (isset($user1) && is_numeric($user1)) ? abs(intval($user1)) : 0;
$user2 = (isset($user2) && is_numeric($user2)) ? abs(intval($user2)) : 0;
if (!empty($user1) || !empty($user2)) {
if ($user1 != $user2) {
$s = $db->fetch_row($db->query("SELECT `lastip`,`loginip`,`registerip` FROM `users` WHERE `userid` = {$user1}"));
$r = $db->fetch_row($db->query("SELECT `lastip`,`loginip`,`registerip` FROM `users` WHERE `userid` = {$user2}"));
if ($s['lastip'] == $r['lastip'] || $s['loginip'] == $r['loginip'] || $s['registerip'] == $r['registerip']) {
return true;
}
}
}
}
} | MasterGeneral156/chivalry-engine | upload/class/class_api_user.php | PHP | mit | 25,835 |
/**
* Service layer beans.
*/
package es.cesga.hadoop.service;
| javicacheiro/hadoop-on-demand-rest-jhipster | src/main/java/es/cesga/hadoop/service/package-info.java | Java | mit | 65 |
//
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var bust = require('gulp-buster');
var streamify = require('gulp-streamify');
var htmlreplace = require('gulp-html-replace');
var fs = require('fs');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
// Emit 'end' as the stream wouldn't do it itself.
// Without this, the gulp task won't end and the watch stops working.
this.emit('end');
}
gulp.task('libs', function () {
return browserify({debug: true})
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js', {debug: true})
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('scripts.js'))
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('css', function () {
return gulp.src('./styles/styles.css')
.pipe(gulp.dest('./dist/'))
.pipe(streamify(bust()))
.pipe(gulp.dest('.'));
});
gulp.task('icons', function () {
return gulp.src('./icons/**/*')
.pipe(gulp.dest('./dist/icons'));
});
gulp.task('favicons', function () {
return gulp.src('./favicons/**/*')
.pipe(gulp.dest('./dist/'));
});
gulp.task('html', function () {
var busters = JSON.parse(fs.readFileSync('busters.json'));
return gulp.src('index.html')
.pipe(htmlreplace({
'css': 'styles.css?v=' + busters['dist/styles.css'],
'js': [
'libs.js?v=' + busters['dist/libs.js'],
'scripts.js?v=' + busters['dist/scripts.js']
]
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
gulp.watch('styles/styles.css', ['css']);
gulp.watch('icons/**', ['icons']);
gulp.watch('favicons/**', ['favicons']);
gulp.watch(['busters.json', 'index.html'], ['html']);
});
gulp.task('default', ['libs', 'scripts', 'css', 'icons', 'favicons', 'html', 'watch']);
| pafalium/gd-web-env | gulpfile.js | JavaScript | mit | 2,513 |
#include "spritesheet.hpp"
//////////
// Code //
// Initializing the SpriteSheet sizes.
void SpriteSheet::init(int cols, int rows, int width, int height) {
this->cols = cols;
this->rows = rows;
this->width = width;
this->height = height;
}
// Making a SpriteSheet from an existing SDL_Texture.
SpriteSheet::SpriteSheet(SDL_Texture* tex,
int cols , int rows,
int width, int height) throw(HCException) {
this->sprite = new Sprite(tex);
init(cols, rows, width, height);
}
// Making a SpriteSheet from an SDL_Surface.
SpriteSheet::SpriteSheet(SDL_Renderer* renderer, SDL_Surface* surf,
int cols , int rows,
int width, int height) throw(HCException) {
this->sprite = new Sprite(renderer, surf);
init(cols, rows, width, height);
}
// Loading a SpriteSheet from a location on the disk.
SpriteSheet::SpriteSheet(SDL_Renderer* renderer, std::string path,
int cols , int rows,
int width, int height) throw(HCException) {
this->sprite = new Sprite(renderer, path);
init(cols, rows, width, height);
}
// The copy constructor.
SpriteSheet::SpriteSheet(const SpriteSheet& ss) {
this->sprite = ss.sprite;
init(ss.rows, ss.cols, ss.width, ss.height);
this->original = false;
}
// Destroying the SpriteSheet.
SpriteSheet::~SpriteSheet() {
if (this->original)
delete this->sprite;
}
// Blitting a specific tile.
void SpriteSheet::blit(Window& w, Rectangle dst, int x, int y) const {
Rectangle r(x * this->width, y * this->height,
this->width, this->height);
this->sprite->blit(w, dst, r);
}
// Accessors
int SpriteSheet::getCols() const { return this->cols; }
int SpriteSheet::getRows() const { return this->rows; }
| crockeo/hc | src/spritesheet.cpp | C++ | mit | 1,860 |
BrowserPolicy.content.allowOriginForAll("*.googleapis.com");
BrowserPolicy.content.allowOriginForAll("*.gstatic.com");
BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com");
BrowserPolicy.content.allowOriginForAll("*.geobytes.com");
BrowserPolicy.content.allowFontDataUrl();
| ameletyan/LeaveWithFriends | server/config/security.js | JavaScript | mit | 284 |
package blogr.vpm.fr.blogr.activity;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import blogr.vpm.fr.blogr.R;
import blogr.vpm.fr.blogr.format.AlignCenterTagsProvider;
import blogr.vpm.fr.blogr.format.AlignLeftTagsProvider;
import blogr.vpm.fr.blogr.format.AlignRightTagsProvider;
import blogr.vpm.fr.blogr.insertion.Inserter;
import blogr.vpm.fr.blogr.insertion.WikipediaLinkTagsProvider;
/**
* Created by vince on 11/05/15.
*/
public class PostContentEditionActions implements ActionMode.Callback {
private final Inserter inserter;
private final EditText editText;
public PostContentEditionActions(Inserter inserter, EditText editText) {
this.inserter = inserter;
this.editText = editText;
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.postcontentedition, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_wiki_link:
if (editText.getSelectionStart() < editText.getSelectionEnd()) {
String articleName = editText.getText().toString().substring(editText.getSelectionStart(), editText.getSelectionEnd());
inserter.insert(editText, new WikipediaLinkTagsProvider(articleName));
}
return true;
case R.id.action_align_left:
inserter.insert(editText, new AlignLeftTagsProvider());
return true;
case R.id.action_align_center:
inserter.insert(editText, new AlignCenterTagsProvider());
return true;
case R.id.action_align_right:
inserter.insert(editText, new AlignRightTagsProvider());
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
}
}
| vpmalley/tpblogr | app/src/main/java/blogr/vpm/fr/blogr/activity/PostContentEditionActions.java | Java | mit | 2,107 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataFactory::Mgmt::V2017_09_01_preview
module Models
#
# HBase server linked service.
#
class HBaseLinkedService < LinkedService
include MsRestAzure
def initialize
@type = "HBase"
end
attr_accessor :type
# @return The IP address or host name of the HBase server. (i.e.
# 192.168.222.160)
attr_accessor :host
# @return The TCP port that the HBase instance uses to listen for client
# connections. The default value is 9090.
attr_accessor :port
# @return The partial URL corresponding to the HBase server. (i.e.
# /gateway/sandbox/hbase/version)
attr_accessor :http_path
# @return [HBaseAuthenticationType] The authentication mechanism to use
# to connect to the HBase server. Possible values include: 'Anonymous',
# 'Basic'
attr_accessor :authentication_type
# @return The user name used to connect to the HBase instance.
attr_accessor :username
# @return [SecretBase] The password corresponding to the user name.
attr_accessor :password
# @return Specifies whether the connections to the server are encrypted
# using SSL. The default value is false.
attr_accessor :enable_ssl
# @return The full path of the .pem file containing trusted CA
# certificates for verifying the server when connecting over SSL. This
# property can only be set when using SSL on self-hosted IR. The default
# value is the cacerts.pem file installed with the IR.
attr_accessor :trusted_cert_path
# @return Specifies whether to require a CA-issued SSL certificate name
# to match the host name of the server when connecting over SSL. The
# default value is false.
attr_accessor :allow_host_name_cnmismatch
# @return Specifies whether to allow self-signed certificates from the
# server. The default value is false.
attr_accessor :allow_self_signed_server_cert
# @return The encrypted credential used for authentication. Credentials
# are encrypted using the integration runtime credential manager. Type:
# string (or Expression with resultType string).
attr_accessor :encrypted_credential
#
# Mapper for HBaseLinkedService class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'HBase',
type: {
name: 'Composite',
class_name: 'HBaseLinkedService',
model_properties: {
additional_properties: {
client_side_validation: true,
required: false,
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
connect_via: {
client_side_validation: true,
required: false,
serialized_name: 'connectVia',
type: {
name: 'Composite',
class_name: 'IntegrationRuntimeReference'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
parameters: {
client_side_validation: true,
required: false,
serialized_name: 'parameters',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterSpecificationElementType',
type: {
name: 'Composite',
class_name: 'ParameterSpecification'
}
}
}
},
annotations: {
client_side_validation: true,
required: false,
serialized_name: 'annotations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
type: {
client_side_validation: true,
required: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
host: {
client_side_validation: true,
required: true,
serialized_name: 'typeProperties.host',
type: {
name: 'Object'
}
},
port: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.port',
type: {
name: 'Object'
}
},
http_path: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.httpPath',
type: {
name: 'Object'
}
},
authentication_type: {
client_side_validation: true,
required: true,
serialized_name: 'typeProperties.authenticationType',
type: {
name: 'String'
}
},
username: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.username',
type: {
name: 'Object'
}
},
password: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.password',
type: {
name: 'Composite',
polymorphic_discriminator: 'type',
uber_parent: 'SecretBase',
class_name: 'SecretBase'
}
},
enable_ssl: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.enableSsl',
type: {
name: 'Object'
}
},
trusted_cert_path: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.trustedCertPath',
type: {
name: 'Object'
}
},
allow_host_name_cnmismatch: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.allowHostNameCNMismatch',
type: {
name: 'Object'
}
},
allow_self_signed_server_cert: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.allowSelfSignedServerCert',
type: {
name: 'Object'
}
},
encrypted_credential: {
client_side_validation: true,
required: false,
serialized_name: 'typeProperties.encryptedCredential',
type: {
name: 'Object'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_data_factory/lib/2017-09-01-preview/generated/azure_mgmt_data_factory/models/hbase_linked_service.rb | Ruby | mit | 8,440 |
module ResourceAuthentication
module TestCase
class MockRequest # :nodoc:
attr_accessor :controller
def initialize(controller)
self.controller = controller
end
def remote_ip
(controller && controller.respond_to?(:env) && controller.env.is_a?(Hash) && controller.env['REMOTE_ADDR']) || "1.1.1.1"
end
private
def method_missiing(*args, &block)
end
end
end
end | geetfun/Resource-Authentication | lib/resource_authentication/test_case/mock_request.rb | Ruby | mit | 458 |
<?php
/*
Template Name: WP Riddle Single Page
*/
?>
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php echo esc_attr(get_option('index_page_title')); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="stylesheet" href="<?php echo get_bloginfo('url') . '/wp-includes/css/buttons.min.css'; ?>">
<link rel="stylesheet" href="<?php echo get_bloginfo('url') . '/wp-admin/css/login.min.css'; ?>">
<link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__);?>../css/single.css">
<link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__);?>../css/index.css">
<link rel='stylesheet' id='open-sans-css' href='//fonts.useso.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&subset=latin%2Clatin-ext&ver=4.0' type='text/css' media='all' />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
</head>
<body class="login login-action-login wp-core-ui">
<ul id="pjax_nav">
<li class="left"><a href="<?php echo home_url(); ?>/" class="pjax"><?php echo esc_attr(get_option('index_page_heading')); ?></a></li>
<li class="right"><a href="<?php echo wp_logout_url(); ?>">Logout</a></li>
<li class="right"><?php
global $current_user;
get_currentuserinfo();
if (current_user_can("administrator"))
echo "<a href='wp-admin/'>" . $current_user->user_login . "</a>";
else
echo "<span id='username'>" . $current_user->user_login . "</span>";
?></li>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'pjax' ) ); ?>
</ul>
<div id="pjax_layer" class="fade-out"></div>
<div class="pjax_content">
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<a href="<?php echo home_url(); ?>/" class="pjax">Back</a>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<form id="loginform" name="keyform" method="post" action="<?php echo admin_url();?>admin-post.php">
<p>
<label for="key"><?php echo esc_attr(get_option('index_page_key_input')); ?><br/>
<input type="text" name="wpr_key" id="key" class="input" value="" placeholder="<?php echo get_option('index_page_input_placeholder'); ?>" autocomplete="off" /></label>
</p>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Submit" />
<input type="hidden" name="action" value="submit_key" />
</p>
</form>
</div><!-- #content -->
<p id="nav"><?php echo esc_attr(get_option('single_page_footer')); ?></p>
</div><!-- #primary -->
</div>
<script src="<?php echo plugin_dir_url(__FILE__);?>../js/push_state.js"></script>
</body>
</html>
| quietshu/wpriddle | template/wpr_single.php | PHP | mit | 3,458 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Memoria.Prime.Text;
namespace Memoria.Assets
{
public sealed class ExportFieldTags : FieldTags
{
private readonly KeyValuePair<Regex, String>[] _complexTags;
public ExportFieldTags()
{
_complexTags = GetComplexTags();
}
public String Replace(String str)
{
if (String.IsNullOrEmpty(str))
return str;
str = str.ReplaceAll(SimpleTags.Forward);
foreach (KeyValuePair<Regex, String> pair in _complexTags)
str = pair.Key.Replace(str, pair.Value);
return str;
}
private KeyValuePair<Regex, String>[] GetComplexTags()
{
return new Dictionary<Regex, String>
{
{new Regex(@"\[STRT=([0-9]+),([0-9]+)\]"), "{W$1H$2}"},
{new Regex(@"\[NUMB=([0-9]+)\]"), "{Variable $1}"},
{new Regex(@"\[ICON=([0-9]+)\]"), "{Icon $1}"},
{new Regex(@"\[PNEW=([0-9]+)\]"), "{Icon+ $1}"},
{new Regex(@"\[SPED=(-?[0-9]+)\]"), "{Speed $1}"},
{new Regex(@"\[TEXT=([^]]+)\]"), "{Text $1}"},
{new Regex(@"\[WDTH=([^]]+)\]"), "{Widths $1}"},
{new Regex(@"\[TIME=([^]]+)\]"), "{Time $1}"},
{new Regex(@"\[WAIT=([^]]+)\]"), "{Wait $1}"},
{new Regex(@"\[CENT=([^]]+)\]"), "{Center $1}"},
{new Regex(@"\[ITEM=([^]]+)\]"), "{Item $1}"},
{new Regex(@"\[PCHC=([^]]+)\]"), "{PreChoose $1}"},
{new Regex(@"\[PCHM=([^]]+)\]"), "{PreChooseMask $1}"},
{new Regex(@"\[MPOS=([^]]+)\]"), "{Position $1}"},
{new Regex(@"\[OFFT=([^]]+)\]"), "{Offset $1}"},
{new Regex(@"\[MOBI=([^]]+)\]"), "{Mobile $1}"},
{new Regex(@"\[YADD=([^]]+)\]"), "{y$1}"},
{new Regex(@"\[YSUB=([^]]+)\]"), "{y-$1}"},
{new Regex(@"\[FEED=([^]]+)\]"), "{f$1}"},
{new Regex(@"\[XTAB=([^]]+)\]"), "{x$1}"},
{new Regex(@"\[TBLE=([^]]+)\]"), "{Table $1}"}
}.ToArray();
}
}
} | Albeoris/Memoria | Assembly-CSharp/Memoria/Assets/Text/Export/Fields/ExportFieldTags.cs | C# | mit | 2,261 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolDB.Models
{
/// <summary>
///
/// </summary>
public class Major
{
public int MajorId { get; set; }
public string MajorName { get; set; }
public bool Active { get; set; }
}
}
| obrienmp15/dotnet | SchoolDB/SchoolDB/Models/Major.cs | C# | mit | 332 |
'use strict'
if (!process.addAsyncListener) require('async-listener')
var noop = function () {}
module.exports = function () {
return new AsyncState()
}
function AsyncState () {
var state = this
process.addAsyncListener({
create: asyncFunctionInitialized,
before: asyncCallbackBefore,
error: noop,
after: asyncCallbackAfter
})
// Record the state currently set on on the async-state object and return a
// snapshot of it. The returned object will later be passed as the `data`
// arg in the functions below.
function asyncFunctionInitialized () {
var data = {}
for (var key in state) {
data[key] = state[key]
}
return data
}
// We just returned from the event-loop: We'll now restore the state
// previously saved by `asyncFunctionInitialized`.
function asyncCallbackBefore (context, data) {
for (var key in data) {
state[key] = data[key]
}
}
// Clear the state so that it doesn't leak between isolated async stacks.
function asyncCallbackAfter (context, data) {
for (var key in state) {
delete state[key]
}
}
}
| watson/async-state | index.js | JavaScript | mit | 1,118 |
/**
Problem 9. Extract e-mails
Write a function for extracting all email addresses from given text.
All sub-strings that match the format @
should be recognized as emails.
Return the emails as array of strings.
*/
console.log('Problem 9. Extract e-mails');
var text='gosho@gmail.com bla bla bla pesho_peshev@yahoo.com bla bla gosho_geshev@outlook.com'
function extractEmails(text) {
var result=text.match(/[A-Z0-9._-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi);
return result;
}
console.log('Text: '+text);
console.log('E-mail: '+extractEmails(text));
console.log('#########################################');
| ztodorova/Telerik-Academy | JavaScript Fundamentals/Strings/scripts/9. Extract e-mails.js | JavaScript | mit | 605 |
# frozen_string_literal: true
require "rails_helper"
module Socializer
RSpec.describe People::ActivitiesController, type: :routing do
routes { Socializer::Engine.routes }
context "with routing" do
it "routes to #index" do
expect(get: "/people/1/activities")
.to route_to("socializer/people/activities#index", person_id: "1")
end
it "does not route to #new" do
expect(get: "/people/1/activities/new").not_to be_routable
end
it "does not route to #show" do
expect(get: "/people/1/activities/1/show").not_to be_routable
end
it "does not route to #edit" do
expect(get: "/people/1/activities/1/edit").not_to be_routable
end
it "does not route to #create" do
expect(post: "/people/1/activities").not_to be_routable
end
context "when specify does not route to #update" do
specify { expect(patch: "/people/1/activities/1").not_to be_routable }
specify { expect(put: "/people/1/activities/1").not_to be_routable }
end
it "does not route to #destroy" do
expect(delete: "/people/1/activities/1").not_to be_routable
end
end
end
end
| socializer/socializer | spec/routing/socializer/people/activities_routing_spec.rb | Ruby | mit | 1,203 |
/**
* Border Left Radius
*/
module.exports = function (decl, args) {
var radius = args[1] || '3px';
decl.replaceWith({
prop: 'border-bottom-left-radius',
value: radius,
source: decl.source
}, {
prop: 'border-top-left-radius',
value: radius,
source: decl.source
});
};
| ismamz/postcss-utilities | lib/border-left-radius.js | JavaScript | mit | 335 |
//=====================================================================
// This sample demonstrates using TeslaJS
//
// https://github.com/mseminatore/TeslaJS
//
// Copyright (c) 2016 Mark Seminatore
//
// Refer to included LICENSE file for usage rights and restrictions
//=====================================================================
"use strict";
require('colors');
var program = require('commander');
var framework = require('./sampleFramework.js');
//
//
//
program
.usage('[options]')
.option('-i, --index <n>', 'vehicle index (first car by default)', parseInt)
.option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)')
.parse(process.argv);
//
var sample = new framework.SampleFramework(program, sampleMain);
sample.run();
//
//
//
function sampleMain(tjs, options) {
var streamingOptions = {
vehicle_id: options.vehicle_id,
authToken: options.authToken
};
console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green);
console.log("\nStreaming starting...".cyan);
console.log("Columns: timestamp," + tjs.streamingColumns.toString());
tjs.startStreaming(streamingOptions, function (error, response, body) {
if (error) {
console.log(error);
return;
}
// display the streaming results
console.log(body);
console.log("...Streaming ended.".cyan);
});
}
| mseminatore/TeslaJS | samples/simpleStreaming.js | JavaScript | mit | 1,453 |
///<reference path="../node_modules/DefinitelyTyped/d3/d3.d.ts" />
interface PWInterpolatorFactory {
(oldScale: D3.Scale.LinearScale) : (t: number)=>powerfocusI;
}
/**
* A scale with polynomial zoom
* @class powerfocusI
* @extends D3.Scale.LinearScale
*/
interface powerfocusI extends D3.Scale.LinearScale {
(domain: number[], range: number[], interpolate: D3.Transition.Interpolate, focus: number, exponent: number, scaleInterpolate?: PWInterpolatorFactory) : powerfocusI;
focus: {
(): number;
(x: number): powerfocusI;
};
exponent: {
(): number;
(x: number): powerfocusI;
};
derivative(x:number): number;
invDerivAtFocus(): number;
scaleInterpolate: {
(): PWInterpolatorFactory;
(f: PWInterpolatorFactory): powerfocusI;
};
regionFocus(rstart:number, rend:number, proportion:number);
powerticks(m?): number[][];
copy(): powerfocusI;
}
declare var powerfocus: powerfocusI;
| chromolens/chromolens | src/powerfocus.d.ts | TypeScript | mit | 987 |
package net.server;
import java.net.Socket;
import net.client.SocketClientProtocol;
public abstract class SocketServerProtocol extends SocketClientProtocol {
/**
* Allow a sender to be added to the socket protocol's list of senders.
*
* This can be useful to send messages to clients which are not the current
* senders, though which are affected by the actions of the current sender.
*
* @param sender
* A Socket object which is tied to the sender object.
*/
public abstract void addSender(Socket sender);
/**
* Allow a sender to be removed from the socket protocol's list of senders.
*
* @param sender
* A Socket object which is tied to the sender object.
*/
public abstract void removeSender(Socket sender);
/**
* Get the maximum number of allowed client connections to this protocol.
*
* @return an integer representing the maximum number of allowed
* connections.
*/
public abstract int getMaxConnections();
/**
* Get the current number of clients connected to this protocol.
*
* @return an integer representing the current number of connections.
*/
public abstract int getNumConnections();
}
| awylie/carcassonne | src/main/java/net/andrewwylie/carcassonne/net/server/SocketServerProtocol.java | Java | mit | 1,236 |
module.exports = {
dist: {
files: {
'dist/geo.js': ['src/index.js'],
}
}
}; | javascriptHustler/geo | grunt/browserify.js | JavaScript | mit | 94 |
package com.onliquid.personalization;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import io.lqd.sdk.Liquid;
import java.util.HashMap;
public class MainActivity extends Activity {
private Liquid lqd;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
lqd = Liquid.getInstance();
}
public void enterSecondActivity(String username) {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("user", username);
startActivity(intent);
}
public void login(View view) {
String username = "";
HashMap attrs = new HashMap();
switch (view.getId()) {
case R.id.jack:
attrs.put("age", 23);
attrs.put("gender", "male");
username = "Jack";
break;
case R.id.jill:
attrs.put("age", 32);
attrs.put("gender", "female");
username = "Jill";
break;
case R.id.jonas:
attrs.put("age", 35);
attrs.put("gender", "male");
username = "Jonas";
}
lqd.identifyUser(username, attrs);
enterSecondActivity(username);
}
}
| lqd-io/android-examples | personalization/src/main/java/com/onliquid/personalization/MainActivity.java | Java | mit | 1,370 |
namespace Subsonic.Client
{
public struct SubsonicToken
{
public string Token { get; set; }
public string Salt { get; set; }
}
} | archrival/SubsonicSharp | Subsonic.Client/SubsonicToken.cs | C# | mit | 166 |
<?php
/**
* @author Ronald Vilbrandt <info@rvi-media.de>
* @copyright 2015 Ronald Vilbrandt, RVI-Media (www.rvi-media.de)
* @since 2015-08-13
*/
namespace Page\Home;
class HomeHtmlView extends \aRvi\View\View {
/**
* Runs the view
*
* @return string View content
*/
public function run() {
return "This is home. :)<br />Try <a href=\"" . $this->uriFetcher->fetch("page1?param1=¯\_(ツ)_/¯#jump") . "\">Page1</a> too!";
}
} | rvilbrandt/arvi | modules/Home/HomeHtmlView.php | PHP | mit | 482 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NavigationBarTitleSample.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("NavigationBarTitleSample.Droid")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| nuitsjp/PrimerOfPrismForms | NavigationBarTitleSample/NavigationBarTitleSample.Droid/Properties/AssemblyInfo.cs | C# | mit | 1,324 |
<?php
class Question
{
private $connection;
function __construct($mysqli)
{
$this->connection = $mysqli;
}
// Kõikide küsimustikude tõmbamine andmebaasist
function getAllQuestionnaires($email){
$stmt = $this->connection->prepare("SELECT tap_questionnaires.id, tap_questionnaires.name, tap_questionnaires.active, COUNT(tap_useranswers_ip.ip) FROM TAP_questionnaires LEFT JOIN TAP_useranswers_ip ON tap_questionnaires.id = tap_useranswers_ip.questionnaire_id WHERE author_email = ? GROUP BY tap_questionnaires.id, tap_questionnaires.name, tap_questionnaires.active;");
$stmt->bind_param("s", $email);
$stmt->bind_result($id, $name, $active, $count);
$stmt->execute();
$result = array();
while ($stmt->fetch()) {
$questionnaires = new StdClass();
$questionnaires->questionnaire_id= $id;
$questionnaires->questionnaire_name = $name;
$questionnaires->questionnaire_status = $active;
$questionnaires->questionnaire_answercount = $count;
array_push($result, $questionnaires);
}
$stmt->close();
return $result;
}
// Küsimustiku vaatamise jaoks admin panelis
function viewQuestionnaireAdmin($id){
$questionStmt = $this->connection->prepare("SELECT id, type, name FROM TAP_questions WHERE questionnaire_id=?;");
$questionStmt->bind_param("i", $id);
$questionStmt->bind_result($id, $type, $name);
$questionStmt->execute();
$result = array();
while ($questionStmt->fetch()) {
$questions = new StdClass();
$questions->question_id = $id;
$questions->question_type = $type;
$questions->question_name = $name;
array_push($result, $questions);
}
$questionStmt->close();
return $result;
}
// Küsimustiku kustutamine
function delQuestionnaire($id){
$stmt = $this->connection->prepare("DELETE FROM TAP_questionnaires WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
}
// Küsimustiku loomine
function createQuestionnaireWithNameAndEmail($name, $email, $questions){
$active = 1;
$stmt = $this->connection->prepare("INSERT INTO tap_questionnaires (name, author_email, active) VALUES (?, ?, ?);");
$stmt->bind_param("ssi", $name, $email, $active);
$stmt->execute();
$quizId = $stmt->insert_id;
$stmt->prepare("INSERT INTO tap_questions (questionnaire_id, type, name) VALUES(?, ?, ?)");
foreach($questions as $question){
if($question->type == "0"){
$stmt->bind_param('iis', $quizId, $question->type, $question->name);
$stmt->execute();
}elseif($question->type=="2"){
$stmt->bind_param('iis', $quizId, $question->type, $question->name);
$stmt->execute();
$questionId = $stmt->insert_id;
foreach($question->options as $opt){
$stmtOptions= $this->connection->prepare("INSERT INTO tap_options (question_id, options) VALUES (?,?)");
$stmtOptions->bind_param('is', $questionId, $opt);
$stmtOptions->execute();
$stmtOptions->close();
}
}
}
$stmt->close();
}
// Küsimustiku tõmbamine /quiz/index.php lehe jaoks et kontrollida, kas küsimustik on aktiivne või mitte
function loadQuestionnaireToAnswer($id){
$questionnaireStmt = $this->connection->prepare("SELECT name, active FROM TAP_questionnaires WHERE id=?;");
$questionnaireStmt->bind_param("i", $id);
$questionnaireStmt->bind_result($qu_name, $active);
$questionnaireStmt->execute();
while ($questionnaireStmt->fetch()){
$questionnaire = new StdClass();
$questionnaire->questionnaire_name = $qu_name;
$questionnaire->questionnaire_status = $active;
}
$questionnaireStmt->close();
return $questionnaire;
}
// Küsimustiku tõmbamine /quiz/index.php lehe jaoks et vastata
function viewQuestionnaireToAnswer($id)
{
$questionStmt = $this->connection->prepare("SELECT TAP_questions.id, TAP_questions.type, TAP_questions.name, TAP_options.id, TAP_options.options from TAP_questions LEFT JOIN TAP_options on TAP_questions.id=TAP_options.question_id WHERE TAP_questions.questionnaire_id = ?;");
$questionStmt->bind_param("i", $id);
$questionStmt->bind_result($question_id, $question_type, $question_name, $option_id, $option_name);
$questionStmt->execute();
$result = array();
while ($questionStmt->fetch()) {
$questions = new StdClass();
$questions->question_id = $question_id;
$questions->question_type = $question_type;
$questions->question_name = $question_name;
$questions->question_options = array();
if($question_type == 2){
$options = new StdClass();
$options->option_id = $option_id;
$options->option_name = $option_name;
array_push($questions->question_options, $options);
}
if(array_key_exists($question_id, $result) && isset($questions->question_options)){
array_push($result[$question_id]->question_options, $questions->question_options[0]);
} else {
$result[$question_id] = $questions;
}
}
$questionStmt->close();
$temp = array();
foreach ($result as $key => $value) {
array_push($temp, $value);
}
$result = $temp;
return $result;
}
// Checkboxiga (switch) küsimustiku staatuse muutmine admin panelil
function changeQuestionnaireStatus($id){
$stmt = $this->connection->prepare("SELECT active FROM TAP_questionnaires WHERE id=?;");
$stmt->bind_param("i",$id);
$stmt->bind_result($qu_status);
$stmt->execute();
while ($stmt->fetch()){
$questionnaire_status=$qu_status;
}
$stmt->close();
if($questionnaire_status==0){
$stmt2 = $this->connection->prepare("UPDATE TAP_questionnaires SET active=1 WHERE id=?;");
$stmt2->bind_param("i", $id);
$stmt2->execute();
$stmt2->close();
}else{
$stmt2 = $this->connection->prepare("UPDATE TAP_questionnaires SET active=0 WHERE id=?;");
$stmt2->bind_param("i", $id);
$stmt2->execute();
$stmt2->close();
}
}
// Kontroll, kas inimene juba vastas küsimusele või mitte
function hasUserAnsweredQuiz($quizId, $userIp){
$stmt = $this->connection->prepare("SELECT EXISTS(SELECT * FROM TAP_useranswers_ip WHERE questionnaire_id = ? AND ip = ?);");
$stmt->bind_param("is", $quizId, $userIp);
$stmt->bind_result($exists);
$stmt->execute();
$stmt->fetch();
$stmt->close();
return boolval($exists);
}
// Küsimustikule vastuste lisamine andmebaasi
function addAnswersToDb($quizId, $userIp, $answers){
$stmt = $this->connection->prepare("INSERT INTO tap_useranswers_ip (questionnaire_id, ip) VALUES (?, ?);");
$stmt->bind_param('is', $quizId, $userIp);
$stmt->execute();
$stmt->prepare("INSERT INTO tap_useranswers (questionnaire_id, question_id, answer) VALUES (?, ?, ?)");
foreach($answers as $answer){
$stmt->bind_param('iis', $quizId, $answer->id, $answer->value);
$stmt->execute();
}
$stmt->close();
}
}
| shxtov/TAP_kusitlused | app/class/Question.php | PHP | mit | 7,464 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Oakcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "merkleblock.h"
#include "hash.h"
#include "consensus/consensus.h"
#include "utilstrencodings.h"
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
header = block.GetBlockHeader();
std::vector<bool> vMatch;
std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const uint256& hash = block.vtx[i]->GetHash();
if (filter.IsRelevantAndUpdate(*block.vtx[i]))
{
vMatch.push_back(true);
vMatchedTxn.push_back(std::make_pair(i, hash));
}
else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
CMerkleBlock::CMerkleBlock(const CBlock& block, const std::set<uint256>& txids)
{
header = block.GetBlockHeader();
std::vector<bool> vMatch;
std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const uint256& hash = block.vtx[i]->GetHash();
if (txids.count(hash))
vMatch.push_back(true);
else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height-1, pos*2, vTxid), right;
// calculate right hash if not beyond the end of the array - copy left hash otherwise
if (pos*2+1 < CalcTreeWidth(height-1))
right = CalcHash(height-1, pos*2+1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
if (pos*2+1 < CalcTreeWidth(height-1))
TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return uint256();
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return uint256();
}
const uint256 &hash = vHash[nHashUsed++];
if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
vMatch.push_back(hash);
vnIndex.push_back(pos);
}
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
if (pos*2+1 < CalcTreeWidth(height-1)) {
right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
if (right == left) {
// The left and right branches should never be identical, as the transaction
// hashes covered by them must each be unique.
fBad = true;
}
} else {
right = left;
}
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return uint256();
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_BASE_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
return uint256();
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return uint256();
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return uint256();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
// verify that no problems occurred during the tree traversal
if (fBad)
return uint256();
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
return uint256();
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return uint256();
return hashMerkleRoot;
}
| stratton-oakcoin/oakcoin | src/merkleblock.cpp | C++ | mit | 6,736 |
var Model = require('./model');
var schema = {
name : String,
stuff: {
electronics: [{
type: String
}],
computing_dev: [{
type: String
}]
},
age:{
biological: Number
},
fruits: [
{
name: String,
fav: Boolean,
about: [{
type: String
}]
}
]
};
var person = function(data){
Model.call(this, schema, data);
}
person.prototype = Object.create(Model.prototype);
module.exports = person; | dpkshrma/NoSQL-Schema-Validator | demo/person.js | JavaScript | mit | 559 |
#include <cstdlib>
#include <iostream>
#include <vector>
#include <sys/time.h>
#include <omp.h>
#include <hbwmalloc.h>
using namespace std;
double drand() {
return double(rand()) / double(RAND_MAX);
}
double wctime() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}
const int n_task =2048;
const int n_time = 8192;
typedef double *double_ptr;
typedef double task_ar[n_task];
void compute (task_ar aar, task_ar bar, int n_time, int n_task) {
const int t_unroll=4;
for (int t = 0; t < n_time; t+=t_unroll) {
for(int t2=0;t2<t_unroll; ++t2) {
for (int i = 1; i < n_task-1; ++i) {
double l = aar[i-1];
double c = aar[i];
double r = aar[i+1];
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
bar[i] = c;
}
for (int i = 1; i < n_task-1; ++i) {
double l = bar[i-1];
double c = bar[i];
double r = bar[i+1];
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
c = 0.2*l+0.4*c+0.3*r+0.1;
l = 0.4*l+0.3*c+0.2*r+0.1;
r = 0.3*l+0.2*c+0.4*r+0.1;
aar[i] = c;
}
}
#pragma omp barrier
}
}
int main () {
const int n_thre = omp_get_max_threads();
cout << "n_thre " << n_thre << " " <<flush;
vector<double_ptr> ptra;
vector<double_ptr> ptrb;
for (int i=0;i<n_thre;++i) {
ptra.push_back((double*)hbw_malloc(sizeof(double) * n_task));
ptrb.push_back((double*)hbw_malloc(sizeof(double) * n_task));
for (int x=0;x<n_task;++x) {
ptra[i][x] = drand();
ptrb[i][x] = drand();
}
}
double time_begin = wctime();
#pragma omp parallel
{
int tid=omp_get_thread_num();
compute(ptra[tid], ptrb[tid], n_time, n_task);
}
double time_end = wctime();
double gflop = double(108)/1e9 * n_time * n_task * n_thre;
double sum = 0;
for (int i=0;i<n_thre;++i) {
for (int x=0;x<n_task;++x) {
sum += ptra[i][x];
}
}
cout << sum << "\tGflop " << gflop << "\ttime " << (time_end - time_begin)
<< "\tGflops " << gflop/(time_end - time_begin) << " n_barrier " << n_time << endl;
}
| nushio3/formura | attic/knl/tmp-04.cpp | C++ | mit | 2,420 |
import java.util.HashMap;
import java.util.Map;
public class LeetCode171 {
public int titleToNumber(String s) {
char[] chars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 1; i <= chars.length; i++) {
map.put(chars[i-1], i);
}
int result = 0;
for (int i = s.length() -1; i >= 0; i--) {
int num1 = map.get(s.charAt(i));
int pow = (int) Math.pow(26, s.length() -1 -i);
result += num1 * pow;
}
return result;
}
public static void main(String[] args) {
LeetCode171 leetCode171 = new LeetCode171();
System.out.println(leetCode171.titleToNumber("ZY"));
}
}
| rayjun/awesome-algorithm | leetcode/hashtable/LeetCode171.java | Java | mit | 817 |
// Depends on jsbn.js and rng.js
// Version 1.1: support utf-8 encoding in pkcs1pad2
// convert a (hex) string to a bignum object
function parseBigInt(str,r) {
return new BigInteger(str,r);
}
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N,E) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
function RSAEncryptB64(text) {
var h = this.encrypt(text);
if(h) return hex2b64(h); else return null;
}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
//my encrypt function, using fixed mudulus
var modulus = "BEB90F8AF5D8A7C7DA8CA74AC43E1EE8A48E6860C0D46A5D690BEA082E3A74E1"
+"571F2C58E94EE339862A49A811A31BB4A48F41B3BCDFD054C3443BB610B5418B"
+"3CBAFAE7936E1BE2AFD2E0DF865A6E59C2B8DF1E8D5702567D0A9650CB07A43D"
+"E39020969DF0997FCA587D9A8AE4627CF18477EC06765DF3AA8FB459DD4C9AF3";
var publicExponent = "10001";
function MyRSAEncryptB64(text)
{
var rsa = new RSAKey();
rsa.setPublic(modulus, publicExponent);
return rsa.encrypt_b64(text);
}
| Wolfrax/Traffic | B593js/RSA.js | JavaScript | mit | 3,146 |
<?php
declare(strict_types=1);
namespace DiContainerBenchmarks\Fixture\B;
class FixtureB792
{
}
| kocsismate/php-di-container-benchmarks | src/Fixture/B/FixtureB792.php | PHP | mit | 99 |
package com.anderspersson.xbmcwidget.remote;
import com.anderspersson.xbmcwidget.R;
import com.anderspersson.xbmcwidget.xbmc.XbmcService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
public class RemoteWidget extends AppWidgetProvider
{
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
RemoteViews remoteViews;
ComponentName remoteWidget;
remoteViews = new RemoteViews( context.getPackageName(), R.layout.remote_widget );
remoteWidget = new ComponentName( context, RemoteWidget.class );
Intent intent = new Intent(context, XbmcService.class);
context.startService(intent);
setupButton(context, remoteViews, XbmcService.PLAYPAUSE_ACTION, R.id.playpause);
setupButton(context, remoteViews, XbmcService.UP_ACTION, R.id.up);
setupButton(context, remoteViews, XbmcService.DOWN_ACTION, R.id.down);
setupButton(context, remoteViews, XbmcService.LEFT_ACTION, R.id.left);
setupButton(context, remoteViews, XbmcService.RIGHT_ACTION, R.id.right);
setupButton(context, remoteViews, XbmcService.SELECT_ACTION, R.id.select);
setupButton(context, remoteViews, XbmcService.BACK_ACTION, R.id.back);
setupButton(context, remoteViews, XbmcService.TOGGLE_FULLSCREEN_ACTION, R.id.togglefullscreen);
setupButton(context, remoteViews, XbmcService.TOGGLE_OSD_ACTION, R.id.toggleosd);
setupButton(context, remoteViews, XbmcService.HOME_ACTION, R.id.home);
setupButton(context, remoteViews, XbmcService.CONTEXT_ACTION, R.id.context);
appWidgetManager.updateAppWidget( remoteWidget, remoteViews );
}
private void setupButton(Context context, RemoteViews remoteViews, String action, int id) {
Intent playIntent = new Intent(context, XbmcService.class);
playIntent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, playIntent, 0);
remoteViews.setOnClickPendingIntent(id, pendingIntent);
}
}
| baluubas/XBMC-Widget | XBMCWidget/src/com/anderspersson/xbmcwidget/remote/RemoteWidget.java | Java | mit | 2,278 |
import prosper.datareader.exceptions
import prosper.datareader._version
| EVEprosper/ProsperDatareader | prosper/datareader/__init__.py | Python | mit | 72 |
<?php
/**
* Models from schema: ecofy version 0.1
* Code generated by TransformTask
*
*/
/**
* @todo: Copy this file to app/lang/<lang>/category.php
* Modify the values accordingly
*/
return array(
'_name' => 'category',
'_name_plural' => 'categorys',
'sid' => 'Sid',
'uuid' => 'Uuid',
'domain_sid' => 'Domain Sid',
'domain_id' => 'Domain Id',
'created_by' => 'Created By',
'created_dt' => 'Created Dt',
'updated_by' => 'Updated By',
'updated_dt' => 'Updated Dt',
'update_counter' => 'Update Counter',
'lang' => 'Lang',
'parent_sid' => 'Parent Sid',
'type' => 'Type',
'name' => 'Name',
'code' => 'Code',
'description' => 'Description',
'image_url' => 'Image Url',
'position' => 'Position',
'params_text' => 'Params Text',
);
| ysahnpark/pledgecontrol | vendor/altenia/ecofy/artifacts/codegen/output/category.schema.lara_lang.php | PHP | mit | 807 |
// Copyright (c) 2012-2014 The Moneta developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both monetad and moneta-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Tellurion");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/moneta/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
| moneta-project/moneta-2.0.1.0 | src/clientversion.cpp | C++ | mit | 3,984 |
using System.Linq;
using Android.Graphics;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using RoutingEffects = FormsCommunityToolkit.Effects;
using PlatformEffects = FormsCommunityToolkit.Effects.Droid;
[assembly: ExportEffect(typeof(PlatformEffects.LabelCustomFont), nameof(RoutingEffects.LabelCustomFont))]
namespace FormsCommunityToolkit.Effects.Droid
{
public class LabelCustomFont : PlatformEffect
{
protected override void OnAttached()
{
var control = Control as TextView;
if (control == null)
return;
var effect = (RoutingEffects.LabelCustomFont)Element.Effects.FirstOrDefault(item => item is RoutingEffects.LabelCustomFont);
if (effect != null && !string.IsNullOrWhiteSpace(effect.FontPath))
{
var font = Typeface.CreateFromAsset(Forms.Context.Assets, effect.FontPath);
control.Typeface = font;
}
}
protected override void OnDetached()
{
}
}
} | Depechie/FormsCommunityToolkit | src/Effects/Effects.Android/Effects/Label/LabelCustomFont.cs | C# | mit | 1,074 |
<!-- Bootstrap -->
<link href="<?php echo base_url() ?>plugins/Bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- select 2 -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/select2/select2.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- AdminLTE -->
<link rel="stylesheet" href="<?php echo base_url() ?>plugins/AdminLTE-2.3.6/css/AdminLTE.css">
<!-- AdminLTE Skins -->
<link rel="stylesheet" href="<?php echo base_url() ?>plugins/AdminLTE-2.3.6/css/skins/skin-blue.min.css">
<!-- Datatables -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/DataTables/datatables.min.css">
<!-- Morris -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/morris/morris.css">
<!-- datepicker -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/style.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/jquery.steps.css">
| Djoyulist/sisjadmcu | application/views/config/config_css.php | PHP | mit | 1,344 |
var ShaderTool = new (function ShaderTool(){
function catchReady(fn) {
var L = 'loading';
if (document.readyState != L){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != L){
fn();
}
});
}
}
this.VERSION = '0.01';
this.modules = {};
this.helpers = {};
this.classes = {};
var self = this;
catchReady(function(){
self.modules.GUIHelper.init();
self.modules.UniformControls.init();
self.modules.Editor.init();
self.modules.Rendering.init();
self.modules.SaveController.init();
self.modules.PopupManager.init();
document.documentElement.className = '_ready';
});
})();
// Utils
ShaderTool.Utils = {
trim: function( string ){
return string.replace(/^\s+|\s+$/g, '');
},
isSet: function( object ){
return typeof object != 'undefined' && object != null
},
isArray: function( object ){
var str = Object.prototype.toString.call(object);
return str == '[object Array]' || str == '[object Float32Array]';
// return Object.prototype.toString.call(object) === '[object Array]';
},
isArrayLike: function( object ){
if( this.isArray(object) ){
return true
}
if( typeof object.length == 'number' && typeof object[0] != 'undefined' && typeof object[object.length] != 'undefined'){
return true;
}
return false;
},
isArrayLike: function( object ){
if(this.isArray(object)){ return true; }
if(this.isObject(object) && this.isNumber(object.length) ){ return true; }
return false;
},
isNumber: function( object ){
return typeof object == 'number' && !isNaN(object);
},
isFunction: function( object ){
return typeof object == 'function';
},
isObject: function( object ){
return typeof object == 'object';
},
isString: function( object ){
return typeof object == 'string';
},
createNamedObject: function( name, props ){
return internals.createNamedObject( name, props );
},
testCallback: function( callback, applyArguments, context ){
if(this.isFunction(callback)){
return callback.apply(context, applyArguments || []);
}
return null;
},
copy: function( from, to ){
for(var i in from){ to[i] = from[i]; }
return to;
},
delegate: function( context, method ){
return function delegated(){
for(var argumentsLength = arguments.length, args = new Array(argumentsLength), k=0; k<argumentsLength; k++){
args[k] = arguments[k];
}
return method.apply( context, args );
}
},
debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate){
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow){
func.apply(context, args);
}
};
},
throttle: function(func, ms) {
var isThrottled = false, savedArgs, savedThis;
function wrapper() {
if (isThrottled) {
savedArgs = arguments;
savedThis = this;
return;
}
func.apply(this, arguments);
isThrottled = true;
setTimeout(function() {
isThrottled = false;
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
},
now: function(){
var P = 'performance';
if (window[P] && window[P]['now']) {
this.now = function(){ return window.performance.now() }
} else {
this.now = function(){ return +(new Date()) }
}
return this.now();
},
isFunction: function( object ){
return typeof object == 'function';
},
isNumberKey: function(e){
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
// if (charCode > 31 && (charCode < 48 || charCode > 57)){
if(charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8)){
if(charCode < 96 && charCode > 105){
return false;
}
}
}
return true;
},
toDecimalString: function( string ){
if(this.isNumber(string)){
return string;
}
if(string.substr(0,1) == '0'){
if(string.substr(1,1) != '.'){
string = '0.' + string.substr(1, string.length);
}
}
return string == '0.' ? '0' : string;
},
/*
hexToRgb: function(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
] : [];
}
*/
};
// Callback (Signal?)
ShaderTool.Utils.Callback = (function(){
// Callback == Signal ?
function Callback() {
this._handlers = [];
var self = this;
this.callShim = function(){
self.call.apply(self, arguments);
}
}
Callback.prototype = {
_throwError: function() {
throw new TypeError('Callback handler must be function!');
},
add: function(handler, context) {
if (typeof handler != 'function') {
this._throwError();
return;
}
this.remove(handler);
this._handlers.push({handler:handler, context: context});
},
remove: function(handler) {
if (typeof handler != 'function') {
this._throwError();
return;
}
var totalHandlers = this._handlers.length;
for (var k = 0; k < totalHandlers; k++) {
if (handler === this._handlers[k].handler) {
this._handlers.splice(k, 1);
return;
}
}
},
call: function() {
var totalHandlers = this._handlers.length;
for (var k = 0; k < totalHandlers; k++) {
var handlerData = this._handlers[k];
handlerData.handler.apply(handlerData.context || null, arguments);
}
}
};
return Callback;
})();
ShaderTool.Utils.Float32Array = (function(){
return typeof Float32Array === 'function' ? Float32Array : Array;
})();
ShaderTool.Utils.DOMUtils = (function(){
function addSingleEventListener(element, eventName, handler){
if (element.addEventListener) {
element.addEventListener(eventName, handler);
} else {
element.attachEvent('on' + eventName, function(e){
handler.apply(element,[e]);
});
}
}
var tempDiv = document.createElement('div');
function DOMUtils(){};
DOMUtils.prototype = {
addEventListener : function(element, eventName, handler){
if(ShaderTool.Utils.isArrayLike(element)){
var totalElements = element.length;
for(var k=0; k<totalElements; k++){
this.addEventListener(element[k], eventName, handler);
}
} else {
var eventName = ShaderTool.Utils.isArray(eventName) ? eventName : eventName.split(' ').join('|').split(',').join('|').split('|');
if(eventName.length > 1){
var totalEvents = eventName.length;
for(var k=0; k<totalEvents; k++){
addSingleEventListener(element, eventName[k], handler );
}
} else {
addSingleEventListener(element, eventName[0], handler);
}
}
},
addClass : function(element, className){
if (element.classList){
element.classList.add(className);
} else {
element.className += SPACE + className;
}
},
removeClass : function(element, className){
if (element.classList){
element.classList.remove(className);
} else{
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(SPACE).join('|') + '(\\b|$)', 'gi'), SPACE);
}
},
injectCSS: function( cssText ){
try{
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssText;
} else {
styleElement.appendChild(document.createTextNode(cssText));
}
document.getElementsByTagName('head')[0].appendChild(styleElement);
return true;
} catch( e ){
return false;
}
},
createFromHTML: function( html ){
tempDiv.innerHTML = html.trim();
var result = tempDiv.childNodes;
if(result.length > 1){
tempDiv.innerHTML = '<div>' + html.trim() + '<div/>'
result = tempDiv.childNodes;
}
return result[0];
}
}
return new DOMUtils();
})();
// Helpers
// LSHelper
ShaderTool.helpers.LSHelper = (function(){
var ALLOW_WORK = window.localStorage != null || window.sessionStorage != null;
function LSHelper(){
this._storage = window.localStorage || window.sessionStorage;
}
LSHelper.prototype = {
setItem: function( key, data ){
if( !ALLOW_WORK ){ return null }
var json = JSON.stringify(data)
this._storage.setItem( key, json );
return json;
},
getItem: function( key ){
if( !ALLOW_WORK ){ return null }
return JSON.parse(this._storage.getItem( key ))
},
clearItem: function( key ){
if( !ALLOW_WORK ){ return null }
this._storage.removeItem( key )
}
}
return new LSHelper();
})();
// FSHelper
ShaderTool.helpers.FSHelper = (function(){
function FSHelper(){};
FSHelper.prototype = {
request: function( element ){
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function(){
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
return new FSHelper();
})();
// Ticker
ShaderTool.helpers.Ticker = (function(){
var raf;
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame){
raf = function( callback ) {
var currTime = Utils.now();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout( function(){
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
} else {
raf = function( callback ){
return window.requestAnimationFrame( callback );
}
}
function Ticker(){
this.onTick = new ShaderTool.Utils.Callback();
var activeState = true;
var applyArgs = [];
var listeners = [];
var prevTime = ShaderTool.Utils.now();
var elapsedTime = 0;
var timeScale = 1;
var self = this;
var skippedFrames = 0;
var maxSkipFrames = 3;
this.stop = this.pause = this.sleep = function(){
activeState = false;
return this;
}
this.start = this.wake = function(){
activeState = true;
return this;
}
this.reset = function(){
elapsedTime = 0;
}
this.timeScale = function( value ){
if(ShaderTool.Utils.isSet(value)){ timeScale = value; }
return timeScale;
}
this.toggle = function(){
return (activeState ? this.stop() : this.start());
}
this.isActive = function(){
return activeState;
}
this.getTime = function(){
return elapsedTime;
}
function tickHandler( nowTime ){
var delta = (nowTime - prevTime) * timeScale;
prevTime = nowTime;
if(skippedFrames < maxSkipFrames){
skippedFrames++;
} else {
if(activeState){
elapsedTime += delta;
self.onTick.call(delta, elapsedTime)
}
}
raf( tickHandler );
}
raf( tickHandler );
};
return new Ticker();
})();
// Modules
// Future module
ShaderTool.modules.GUIHelper = (function(){
function GUIHelper(){}
GUIHelper.prototype = {
init: function(){
console.log('ShaderTool.modules.GUIHelper.init')
},
showError: function( message ){
console.error('GUIHelper: ' + message)
}
}
return new GUIHelper();
})();
// Editor
ShaderTool.modules.Editor = (function(){
function Editor(){}
Editor.prototype = {
init: function(){
console.log('ShaderTool.modules.Editor.init');
this._container = document.getElementById('st-editor');
this._editor = ace.edit(this._container);
this._editor.getSession().setMode('ace/mode/glsl');
// https://ace.c9.io/build/kitchen-sink.html
// this._editor.getSession().setTheme();
this._editor.$blockScrolling = Infinity;
this.onChange = new ShaderTool.Utils.Callback();
var self = this;
//this._editor.on('change', function(){
//self.onChange.call();
//});
this._editor.on('change', ShaderTool.Utils.throttle(function(){
if(!self._skipCallChange){
self.onChange.call();
}
}, 1000 / 60 * 10));
},
getData: function(){
return this._editor.getSession().getValue();
},
setData: function( value, skipCallChangeFlag ){
this._skipCallChange = skipCallChangeFlag;
this._editor.getSession().setValue( value );
this._skipCallChange = false;
if(!skipCallChangeFlag){
this.onChange.call();
}
},
clear: function(){
this.setValue('');
},
// future methods:
//lock: function(){},
//unlock: function(){},
//load: function( url ){}
}
return new Editor();
})();
ShaderTool.modules.Rendering = (function(){
var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}';
function Rendering(){}
Rendering.prototype = {
init: function(){
console.log('ShaderTool.modules.Rendering.init');
this._canvas = document.getElementById('st-canvas');
this._context = D3.createContextOnCanvas(this._canvas);
this._initSceneControls();
this.onChange = new ShaderTool.Utils.Callback();
// this._sourceChanged = true;
var fragmentSource = 'precision mediump float;\n';
fragmentSource += 'uniform sampler2D us2_source;\n';
fragmentSource += 'uniform float uf_time;\n';
fragmentSource += 'uniform vec2 uv2_resolution;\n';
fragmentSource += 'void main() {\n';
fragmentSource += '\tgl_FragColor = \n';
// fragmentSource += 'vec4(gl_FragCoord.xy / uv2_resolution, sin(uf_time), 1.);\n';
fragmentSource += '\t\ttexture2D(us2_source, gl_FragCoord.xy / uv2_resolution);\n';
fragmentSource += '}\n';
this._program = this._context.createProgram({
vertex: VERTEX_SOURCE,
fragment: fragmentSource
});
this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1]));
this._resolution = null;
this._texture = null;
this._framebuffer = null;
this._writePosition = 0;
this._source = {
program: this._program,
attributes: {
'av2_vtx': {
buffer: this._buffer,
size: 2,
type: this._context.AttribType.Float,
offset: 0
}
},
uniforms: {
'us2_source': this._context.UniformSampler(this._texture)
},
mode: this._context.Primitive.TriangleStrip,
count: 4
};
this._rasterizers = [];
this._rasterizers.push(new ShaderTool.classes.Rasterizer( this._context ));
// this._updateSource();
ShaderTool.modules.Editor.onChange.add(this._updateSource, this);
ShaderTool.modules.UniformControls.onChangeUniformList.add(this._updateSource, this);
ShaderTool.modules.UniformControls.onChangeUniformValue.add(this._updateUniforms, this);
ShaderTool.helpers.Ticker.onTick.add(this._render, this);
},
_updateSource: function( skipCallChangeFlag ){
var uniformSource = ShaderTool.modules.UniformControls.getUniformsCode();
var shaderSource = ShaderTool.modules.Editor.getData();
var fullSource = 'precision mediump float;\n\n' + uniformSource + '\n\n\n' + shaderSource;
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.updateSource(fullSource);
}
this._updateUniforms( skipCallChangeFlag );
},
_updateUniforms: function( skipCallChangeFlag ){
var uniforms = ShaderTool.modules.UniformControls.getUniformsData( this._context );
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.updateUniforms(uniforms);
}
if(!skipCallChangeFlag){
this.onChange.call();
}
},
_setResolution: function (width, height) {
if (!this._resolution) {
this._texture = [
this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height),
this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height)
];
framebuffer = [
this._context.createFramebuffer().attachColor(this._texture[1]),
this._context.createFramebuffer().attachColor(this._texture[0])
];
} else if (this._resolution[0] !== width || this._resolution[1] !== height) {
this._texture[0].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height);
this._texture[1].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height);
}
this._resolution = [width, height];
},
_initSceneControls: function(){
var self = this;
this.dom = {};
this.dom.playButton = document.getElementById('st-play');
this.dom.pauseButton = document.getElementById('st-pause');
this.dom.rewindButton = document.getElementById('st-rewind');
this.dom.fullscreenButton = document.getElementById('st-fullscreen');
this.dom.timescaleRange = document.getElementById('st-timescale');
this.dom.renderWidthLabel = document.getElementById('st-renderwidth');
this.dom.renderHeightLabel = document.getElementById('st-renderheight');
this.dom.sceneTimeLabel = document.getElementById('st-scenetime');
function setPlayingState( state ){
if(state){
ShaderTool.helpers.Ticker.start();
self.dom.playButton.style.display = 'none';
self.dom.pauseButton.style.display = '';
} else {
ShaderTool.helpers.Ticker.stop();
self.dom.playButton.style.display = '';
self.dom.pauseButton.style.display = 'none';
}
}
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.playButton, 'mousedown', function( e ){
e.preventDefault();
setPlayingState( true );
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.pauseButton, 'mousedown', function( e ){
e.preventDefault();
setPlayingState( false );
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.rewindButton, 'mousedown', function( e ){
e.preventDefault();
ShaderTool.helpers.Ticker.reset();
});
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.fullscreenButton, 'mousedown', function( e ){
e.preventDefault();
ShaderTool.helpers.FSHelper.request(self._canvas);
});
ShaderTool.Utils.DOMUtils.addEventListener(this._canvas, 'dblclick', function( e ){
e.preventDefault();
ShaderTool.helpers.FSHelper.exit();
});
this.dom.timescaleRange.setAttribute('step', '0.001');
this.dom.timescaleRange.setAttribute('min', '0.001');
this.dom.timescaleRange.setAttribute('max', '10');
this.dom.timescaleRange.setAttribute('value', '1');
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.timescaleRange, 'input change', function( e ){
ShaderTool.helpers.Ticker.timeScale( parseFloat(self.dom.timescaleRange.value) )
});
setPlayingState( true );
},
_render: function( delta, elapsedTime ){
// To seconds:
delta = delta * 0.001;
elapsedTime = elapsedTime * 0.001;
this.dom.sceneTimeLabel.innerHTML = elapsedTime.toFixed(2);;
if (this._canvas.clientWidth !== this._canvas.width ||
this._canvas.clientHeight !== this._canvas.height) {
var pixelRatio = window.devicePixelRatio || 1;
var cWidth = this._canvas.width = this._canvas.clientWidth * pixelRatio;
var cHeight = this._canvas.height = this._canvas.clientHeight * pixelRatio;
this._setResolution(cWidth, cHeight);
this.dom.renderWidthLabel.innerHTML = cWidth + 'px';
this.dom.renderHeightLabel.innerHTML = cHeight + 'px';
}
var previosFrame = this._texture[this._writePosition];
var resolution = this._resolution;
var destination = { framebuffer: framebuffer[this._writePosition] };
var totalRasterizers = this._rasterizers.length;
for(var k=0; k<totalRasterizers; k++){
var rasterizer = this._rasterizers[k];
rasterizer.render(elapsedTime, previosFrame, resolution, destination);
}
if (!this._resolution) {
return;
}
this._writePosition = (this._writePosition + 1) & 1;
this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime );
this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( this._resolution );
this._source.uniforms['us2_source'] = this._context.UniformSampler( this._texture[this._writePosition] );
this._context.rasterize(this._source);
},
getData: function(){
return {
uniforms: ShaderTool.modules.UniformControls.getData(),
source: ShaderTool.modules.Editor.getData()
}
},
setData: function( data, skipCallChangeFlag ){
ShaderTool.modules.UniformControls.setData( data.uniforms, true );
ShaderTool.modules.Editor.setData( data.source, true );
this._updateSource( skipCallChangeFlag );
ShaderTool.helpers.Ticker.reset();
if(!skipCallChangeFlag){
this.onChange.call();
}
}
}
return new Rendering();
})();
// Controls
ShaderTool.modules.UniformControls = (function(){
function UniformControls(){}
UniformControls.prototype = {
init: function(){
console.log('ShaderTool.modules.UniformControls.init');
this.onChangeUniformList = new ShaderTool.Utils.Callback();
this.onChangeUniformValue = new ShaderTool.Utils.Callback();
this._changed = true;
this._callChangeUniformList = function(){
this._changed = true;
this.onChangeUniformList.call();
}
this._callChangeUniformValue = function(){
this._changed = true;
this.onChangeUniformValue.call();
}
this._container = document.getElementById('st-uniforms-container');
this._controls = [];
this._uniforms = {};
this._createMethods = {};
this._createMethods[UniformControls.FLOAT] = this._createFloat;
this._createMethods[UniformControls.VEC2] = this._createVec2;
this._createMethods[UniformControls.VEC3] = this._createVec3;
this._createMethods[UniformControls.VEC4] = this._createVec4;
this._createMethods[UniformControls.COLOR3] = this._createColor3;
this._createMethods[UniformControls.COLOR4] = this._createColor4;
// Templates:
this._templates = {};
var totalTypes = UniformControls.TYPES.length;
for(var k=0; k<totalTypes; k++){
var type = UniformControls.TYPES[k]
var templateElement = document.getElementById('st-template-control-' + type);
if(templateElement){
this._templates[type] = templateElement.innerHTML;
templateElement.parentNode.removeChild(templateElement);
} else {
console.warn('No template html for ' + type + ' type!');
}
}
this._container.innerHTML = ''; // Clear container
// Tests:
/*
for(var k=0; k<totalTypes; k++){
this._createControl('myControl' + (k+1), UniformControls.TYPES[k], null, true );
}
//uniform float slide;
//uniform vec3 color1;
this._createControl('slide', UniformControls.FLOAT, [{max: 10, value: 10}], true );
// this._createControl('color1', UniformControls.COLOR3, null, true );
this._createControl('color1', UniformControls.VEC3, [{value:1},{},{}], true );
this._createControl('test', UniformControls.FLOAT, null, true );
this._createControl('test2', UniformControls.FLOAT, [{value: 1}], true );
this._createControl('test3', UniformControls.FLOAT, [{ value: 1 }], true );
//
//this._callChangeUniformList();
//this._callChangeUniformValue();
*/
this._initCreateControls();
},
/* Public methods */
getUniformsCode: function(){
var result = [];
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
result.push(this._controls[k].code);
}
return result.join('\n');
},
getUniformsData: function( context ){
if(!this._changed){
return this._uniforms;
}
this._changed = false;
this._uniforms = {};
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
var control = this._controls[k];
var value = control.getUniformValue();
if(control.type == UniformControls.FLOAT){
this._uniforms[control.name] = context.UniformFloat(value);
} else if(control.type == UniformControls.VEC2){
this._uniforms[control.name] = context.UniformVec2(value);
} else if(control.type == UniformControls.VEC3 || control.type == UniformControls.COLOR3){
this._uniforms[control.name] = context.UniformVec3(value);
} else if(control.type == UniformControls.VEC4 || control.type == UniformControls.COLOR4){
this._uniforms[control.name] = context.UniformVec4(value);
}
}
return this._uniforms;
},
getData: function(){
var uniforms = [];
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
var control = this._controls[k];
uniforms.push({
name: control.name,
type: control.type,
data: control.data
})
}
return uniforms;
},
setData: function( uniforms, skipCallChangeFlag){
this._clearControls( skipCallChangeFlag );
// TODO;
var totalUniforms = uniforms.length;
for(var k=0; k<totalUniforms; k++){
var uniformData = uniforms[k];
this._createControl(uniformData.name, uniformData.type, uniformData.data, true)
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
/* Private methods */
_checkNewUniformName: function( name ){
// TODO;
return name != '';
},
_initCreateControls: function(){
var addUniformNameInput = document.getElementById('st-add-uniform-name');
var addUniformTypeSelect = document.getElementById('st-add-uniform-type');
var addUniformSubmit = document.getElementById('st-add-uniform-submit');
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(addUniformSubmit, 'click', function( e ){
e.preventDefault();
var name = addUniformNameInput.value;
if( !self._checkNewUniformName(name) ){
// TODO: Show info about incorrect uniforn name?
addUniformNameInput.focus();
} else {
var type = addUniformTypeSelect.value;
self._createControl( name, type, null, false );
addUniformNameInput.value = '';
}
});
},
_createControl: function( name, type, initialData, skipCallChangeFlag ){
this._changed = true;
var self = this;
var control;
var elementTemplate = this._templates[type];
if( typeof elementTemplate == 'undefined' ){
console.error('No control template for type ' + type);
return;
}
var element = ShaderTool.Utils.DOMUtils.createFromHTML(elementTemplate);
var createMethod = this._createMethods[type];
if( createMethod ){
initialData = ShaderTool.Utils.isArray(initialData) ? initialData : [];
control = createMethod.apply(this, [name, element, initialData] );
} else {
throw new ShaderTool.Exception('Unknown uniform control type: ' + type);
return null;
}
control.name = name;
control.type = type;
control.element = element;
this._controls.push(control);
this._container.appendChild(element);
// name element
var nameElement = element.querySelector('[data-uniform-name]');
if(nameElement){
nameElement.setAttribute('title', 'Uniform ' + name + ' settings');
nameElement.innerHTML = name;
ShaderTool.Utils.DOMUtils.addEventListener(nameElement, 'dblclick', function( e ){
e.preventDefault();
alert('Show uniform rename dialog?')
});
}
// delete element
var deleteElement = element.querySelector('[data-uniform-delete]');
if(deleteElement){
ShaderTool.Utils.DOMUtils.addEventListener(deleteElement, 'click', function( e ){
e.preventDefault();
if (confirm('Delete uniform?')) {
self._removeControl( control );
}
});
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_removeControl: function( control, skipCallChangeFlag ){
var totalControls = this._controls.length;
for(var k=0; k<totalControls; k++){
if(this._controls[k] === control){
this._controls.splice(k, 1);
control.element.parentNode.removeChild( control.element );
break;
}
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_clearControls: function(skipCallChangeFlag){
var c = 0;
for(var k=0;k<this._controls.length; k++){
c++;
if(c > 100){
return;
}
this._removeControl( this._controls[k], true );
k--;
}
if(!skipCallChangeFlag){
this._callChangeUniformList();
}
},
_createFloat: function( name, element, initialData ){
var self = this;
var saveData = [ this._prepareRangeData( initialData[0]) ];
var uniformValue = saveData[0].value;
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue = saveData[0].value;
self._callChangeUniformValue();
});
return {
code: 'uniform float ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec2: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] )
];
var uniformValue = [saveData[0].value, saveData[1].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec2 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec3: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] ),
this._prepareRangeData( initialData[2] )
];
var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '3', saveData[2], function(){
uniformValue[2] = saveData[2].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec3 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createVec4: function( name, element, initialData ){
var self = this;
var saveData = [
this._prepareRangeData( initialData[0] ),
this._prepareRangeData( initialData[1] ),
this._prepareRangeData( initialData[2] ),
this._prepareRangeData( initialData[3] )
];
var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value, saveData[3].value];
this._initRangeElementGroup(element, '1', saveData[0], function(){
uniformValue[0] = saveData[0].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '2', saveData[1], function(){
uniformValue[1] = saveData[1].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '3', saveData[2], function(){
uniformValue[2] = saveData[2].value;
self._callChangeUniformValue();
});
this._initRangeElementGroup(element, '4', saveData[3], function(){
uniformValue[3] = saveData[3].value;
self._callChangeUniformValue();
});
return {
code: 'uniform vec4 ' + name + ';',
data: saveData,
getUniformValue: function(){
return uniformValue;
}
}
},
_createColor3: function( name, element, initialData ){
var self = this;
var saveData = this._prepareColorData(initialData, false)
this._initColorSelectElementGroup( element, false, saveData, function(){
self._callChangeUniformValue();
})
return {
code: 'uniform vec3 ' + name + ';',
data: saveData,
getUniformValue: function(){
return saveData;
}
}
},
_createColor4: function( name, element, initialData ){
var self = this;
var saveData = this._prepareColorData(initialData, true);
this._initColorSelectElementGroup( element, true, saveData, function(){
self._callChangeUniformValue();
})
return {
code: 'uniform vec4 ' + name + ';',
data: saveData,
getUniformValue: function(){
return saveData;
}
}
},
_prepareColorData: function( inputData, vec4Format ){
inputData = ShaderTool.Utils.isArray( inputData ) ? inputData : [];
var resultData = vec4Format ? [0,0,0,1] : [0,0,0];
var counter = vec4Format ? 4 : 3;
for(var k=0; k<counter;k++){
var inputComponent = inputData[k];
if( typeof inputComponent != 'undefined' ){
resultData[k] = inputComponent;
}
}
return resultData;
},
_prepareRangeData: function( inputData ){
inputData = typeof inputData == 'undefined' ? {} : inputData;
var resultData = { value: 0, min: 0, max: 1 };
for(var i in resultData){
if(typeof inputData[i] != 'undefined'){
resultData[i] = inputData[i];
}
}
return resultData;
},
_componentToHex: function(c){
var hex = c.toString(16);
return hex.length == 1 ? '0' + hex : hex;
},
_hexFromRGB: function(r, g, b){
return '#' + this._componentToHex(r) + this._componentToHex(g) + this._componentToHex(b);
},
_initColorSelectElementGroup: function( element, useAlpha, initialData, changeHandler ){
var colorElement = element.querySelector('[data-color]');
colorElement.value = this._hexFromRGB(initialData[0] * 256 << 0, initialData[1] * 256 << 0, initialData[2] * 256 << 0);
ShaderTool.Utils.DOMUtils.addEventListener(colorElement, 'change', function( e ){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(colorElement.value);
initialData[0] = parseInt( result[1], 16 ) / 256;
initialData[1] = parseInt( result[2], 16 ) / 256;
initialData[2] = parseInt( result[3], 16 ) / 256;
changeHandler();
});
if(useAlpha){
var rangeElement = element.querySelector('[data-range]');
rangeElement.setAttribute('min', '0');
rangeElement.setAttribute('max', '1');
rangeElement.setAttribute('step', '0.001');
rangeElement.setAttribute('value', initialData[3] );
ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){
initialData[3] = parseFloat(rangeElement.value);
changeHandler();
})
}
},
_initRangeElementGroup: function( element, attrIndex, initialData, changeHandler, stepValue ){
var minValue = initialData.min;
var maxValue = initialData.max;
var minElement = element.querySelector('[data-range-min-' + attrIndex + ']');// || document.createElement('input');
var maxElement = element.querySelector('[data-range-max-' + attrIndex + ']');// || document.createElement('input');
var rangeElement = element.querySelector('[data-range-' + attrIndex + ']');
var valueElement = element.querySelector('[data-range-value-' + attrIndex + ']') || document.createElement('div');
rangeElement.setAttribute('step', typeof stepValue != 'undefined' ? stepValue : '0.0001');
var prevMinValue;
var prevMaxValue;
minElement.setAttribute('title', 'Minimum value');
maxElement.setAttribute('title', 'Maximum value');
prevMinValue = minElement.value = valueElement.innerHTML = minValue;
prevMaxValue = maxElement.value = maxValue;
rangeElement.value = initialData.value;
ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){
if(minElement.value == ''){
minElement.value = prevMinValue;
}
if(maxElement.value == ''){
maxElement.value = prevMaxValue;
}
if(minValue > maxValue){
prevMinValue = minElement.value = maxValue;
prevMaxValue = maxElement.value = minValue;
}
valueElement.innerHTML = rangeElement.value;
initialData.min = minValue;
initialData.max = maxValue;
initialData.value = parseFloat(rangeElement.value);
changeHandler( initialData );
});
function updateRangeSettings(){
if(minElement.value == '' || maxElement.value == ''){
return;
}
prevMinValue = minElement.value;
prevMaxValue = maxElement.value;
minValue = ShaderTool.Utils.toDecimalString(minElement.value);
maxValue = ShaderTool.Utils.toDecimalString(maxElement.value);
var min = minValue = parseFloat(minValue);
var max = maxValue = parseFloat(maxValue);
if(min > max){
max = [min, min = max][0];
}
rangeElement.setAttribute('min', min);
rangeElement.setAttribute('max', max);
initialData.min = min;
initialData.max = max;
}
ShaderTool.Utils.DOMUtils.addEventListener([minElement, maxElement], 'keydown input change', function( e ){
if(!ShaderTool.Utils.isNumberKey( e )){
e.preventDefault();
return false;
}
updateRangeSettings();
});
updateRangeSettings();
}
}
UniformControls.FLOAT = 'float';
UniformControls.VEC2 = 'vec2';
UniformControls.VEC3 = 'vec3';
UniformControls.VEC4 = 'vec4';
UniformControls.COLOR3 = 'color3';
UniformControls.COLOR4 = 'color4';
UniformControls.TYPES = [UniformControls.FLOAT, UniformControls.VEC2, UniformControls.VEC3, UniformControls.VEC4, UniformControls.COLOR3, UniformControls.COLOR4];
return new UniformControls();
})();
// SaveController
ShaderTool.modules.SaveController = (function(){
var DEFAULT_CODE = '{"uniforms":[{"name":"bgcolor","type":"color3","data":[0.99609375,0.8046875,0.56640625]}],"source":"void main() {\\n gl_FragColor = vec4(bgcolor, 1.);\\n}"}';
function SaveController(){}
SaveController.prototype = {
init: function(){
console.log('ShaderTool.modules.SaveController.init');
var savedData = ShaderTool.helpers.LSHelper.getItem('lastShaderData');
if(savedData){
ShaderTool.modules.Rendering.setData(savedData, true);
} else {
ShaderTool.modules.Rendering.setData(JSON.parse(DEFAULT_CODE), true);
}
this._initSaveDialogs();
ShaderTool.modules.Rendering.onChange.add( this._saveLocalState, this);
this._saveLocalState();
},
_initSaveDialogs: function(){
this.dom = {};
this.dom.setCodeInput = document.getElementById('st-set-code-input');
this.dom.setCodeSubmit = document.getElementById('st-set-code-submit');
this.dom.getCodeInput = document.getElementById('st-get-code-input');
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.setCodeSubmit, 'click', function( e ){
var code = self.dom.setCodeInput.value;
if(code != ''){
ShaderTool.modules.Rendering.setData(JSON.parse(code), true)
}
})
},
_saveLocalState: function(){
var saveData = ShaderTool.modules.Rendering.getData();
ShaderTool.helpers.LSHelper.setItem('lastShaderData', saveData);
this.dom.getCodeInput.value = JSON.stringify(saveData);
}
}
return new SaveController();
})();
ShaderTool.modules.PopupManager = (function(){
var OPENED_CLASS_NAME = '_opened';
function PopupManager(){}
PopupManager.prototype = {
init: function(){
console.log('ShaderTool.modules.PopupManager.init');
this.dom = {};
this.dom.overlay = document.getElementById('st-popup-overlay');
this._opened = false;
var self = this;
ShaderTool.Utils.DOMUtils.addEventListener(this.dom.overlay, 'mousedown', function( e ){
if( e.target === self.dom.overlay ){
self.close();
}
})
var openers = document.querySelectorAll('[data-popup-opener]');
ShaderTool.Utils.DOMUtils.addEventListener(openers, 'click', function( e ){
self.open( this.getAttribute('data-popup-opener') )
})
},
open: function( popupName ){
this.close();
var popup = this.dom.overlay.querySelector(popupName);
if( popup ){
this._opened = true;
this._currentPopup = popup;
ShaderTool.Utils.DOMUtils.addClass(this._currentPopup, OPENED_CLASS_NAME);
ShaderTool.Utils.DOMUtils.addClass(this.dom.overlay, OPENED_CLASS_NAME);
} else {
// TODO;
}
},
close: function(){
if(!this._opened){
return;
}
this._opened = false;
ShaderTool.Utils.DOMUtils.removeClass(this.dom.overlay, OPENED_CLASS_NAME);
ShaderTool.Utils.DOMUtils.removeClass(this._currentPopup, OPENED_CLASS_NAME);
}
}
return new PopupManager();
})();
// classes
ShaderTool.classes.Rasterizer = (function(){
var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}';
function Rasterizer( context ){
this._context = context;
this._program = null;
this._prevProgram = null;
this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1]));
this._source = {
program: this._program,
attributes: {
'av2_vtx': {
buffer: this._buffer,
size: 2,
type: this._context.AttribType.Float,
offset: 0
}
},
uniforms: {},
mode: this._context.Primitive.TriangleStrip,
count: 4
};
}
Rasterizer.prototype = {
updateSource: function (fragmentSource) {
var savePrevProgramFlag = true;
try{
var newProgram = this._context.createProgram({
vertex: VERTEX_SOURCE,
fragment: fragmentSource
});
this._source.program = newProgram;
} catch( e ){
console.warn('Error updating Rasterizer fragmentSource: ' + e.message);
savePrevProgramFlag = false;
if(this._prevProgram){
this._source.program = this._prevProgram;
}
}
if(savePrevProgramFlag){
this._prevProgram = newProgram;
}
},
updateUniforms: function(uniforms){
this._source.uniforms = uniforms;
},
render: function ( elapsedTime, frame, resolution, destination ) {
this._source.uniforms['us2_frame'] = this._context.UniformSampler( frame );
this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( resolution );
this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime);
this._context.rasterize(this._source, null, destination);
}
}
return Rasterizer;
})();
| w23/tool.gl | front/js/shadertool.js | JavaScript | mit | 52,669 |
import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link";
import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next }) => (
<div className={styles.postNav}>
{prev && (
<Link to={`/${prev.fields.slug}`}>
上一篇:
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={`/${next.fields.slug}`}>
下一篇:
{next.frontmatter.title}
</Link>
)}
</div>
);
export default class Post extends PureComponent {
componentDidMount() {
ScrollReveal().reveal(".article-header>h1", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "top",
distance: "120px"
});
ScrollReveal().reveal(".article-content", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "bottom",
distance: "120px"
});
}
componentWillUnmount() {
ScrollReveal().destroy();
}
render() {
const post = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
<PostNav prev={prev} next={next} />
</Layout>
);
}
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`;
| EvKylin/Kylin | Example/blog/src/templates/post.js | JavaScript | mit | 1,886 |
package com.jikken2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
@SuppressLint("NewApi")
public class ConnectDB_PP extends AsyncTask<Void, Void, String> {
private static String URL = "172.29.139.104/db_group_a";
private static String USER = "group_a";
private static String PASS = "m4we6baq";
private static int TIMEOUT = 5;
private Activity act = null;
private String sql = "";
private ProgressDialog dialog;
private ResultSet rs = null;
private String sta = "";
private double longi;
private double lati;
private AsyncTaskCallback callback = null;;
public interface AsyncTaskCallback {
void preExecute();
void postExecute(String result);
void progressUpdate(int progress);
void cancel();
}
public ConnectDB_PP(Activity act) {
this.act = act;
}
public ConnectDB_PP(Activity act, String sql) {
this.act = act;
this.sql = sql;
}
public ConnectDB_PP(Activity act, String sql, AsyncTaskCallback _callback) {
this.act = act;
this.sql = sql;
this.callback = _callback;
}
public String getSta() {
return sta;
}
public double getLati() {
return lati;
}
public double getLongi() {
return longi;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
callback.preExecute();
this.dialog = new ProgressDialog(this.act);
this.dialog.setMessage("Connecting...");
this.dialog.show();
}
@Override
protected String doInBackground(Void... arg0) {
String text = "";
try {
// JDBC load
Class.forName("com.mysql.jdbc.Driver");
// time out
DriverManager.setLoginTimeout(TIMEOUT);
// connect to DB
Connection con = DriverManager.getConnection("jdbc:mysql://" + URL,
USER, PASS);
Statement stmt = con.createStatement();
// execute query
rs = stmt.executeQuery(sql);
while (rs.next()) {
sta += rs.getString("station");
lati += rs.getDouble("latitude");
longi += rs.getDouble("longitude");
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
// text = e.getMessage();
text = "螟ア謨�";
sta = "螟ア謨�";
}
return text;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
callback.postExecute(result);
if (this.dialog != null && this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
} | 000ubird/JikkenII | src/com/jikken2/ConnectDB_PP.java | Java | mit | 2,503 |
import * as React from 'react';
import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';
import { composeRef } from 'rc-util/lib/ref';
import { ConfigContext } from '../config-provider';
import devWarning from '../_util/devWarning';
import { Breakpoint, responsiveArray } from '../_util/responsiveObserve';
import useBreakpoint from '../grid/hooks/useBreakpoint';
import SizeContext, { AvatarSize } from './SizeContext';
export interface AvatarProps {
/** Shape of avatar, options:`circle`, `square` */
shape?: 'circle' | 'square';
/*
* Size of avatar, options: `large`, `small`, `default`
* or a custom number size
* */
size?: AvatarSize;
gap?: number;
/** Src of image avatar */
src?: React.ReactNode;
/** Srcset of image avatar */
srcSet?: string;
draggable?: boolean;
/** Icon to be used in avatar */
icon?: React.ReactNode;
style?: React.CSSProperties;
prefixCls?: string;
className?: string;
children?: React.ReactNode;
alt?: string;
/* callback when img load error */
/* return false to prevent Avatar show default fallback behavior, then you can do fallback by your self */
onError?: () => boolean;
}
const InternalAvatar: React.ForwardRefRenderFunction<unknown, AvatarProps> = (props, ref) => {
const groupSize = React.useContext(SizeContext);
const [scale, setScale] = React.useState(1);
const [mounted, setMounted] = React.useState(false);
const [isImgExist, setIsImgExist] = React.useState(true);
const avatarNodeRef = React.useRef<HTMLElement>();
const avatarChildrenRef = React.useRef<HTMLElement>();
const avatarNodeMergeRef = composeRef(ref, avatarNodeRef);
const { getPrefixCls } = React.useContext(ConfigContext);
const setScaleParam = () => {
if (!avatarChildrenRef.current || !avatarNodeRef.current) {
return;
}
const childrenWidth = avatarChildrenRef.current.offsetWidth; // offsetWidth avoid affecting be transform scale
const nodeWidth = avatarNodeRef.current.offsetWidth;
// denominator is 0 is no meaning
if (childrenWidth !== 0 && nodeWidth !== 0) {
const { gap = 4 } = props;
if (gap * 2 < nodeWidth) {
setScale(nodeWidth - gap * 2 < childrenWidth ? (nodeWidth - gap * 2) / childrenWidth : 1);
}
}
};
React.useEffect(() => {
setMounted(true);
}, []);
React.useEffect(() => {
setIsImgExist(true);
setScale(1);
}, [props.src]);
React.useEffect(() => {
setScaleParam();
}, [props.gap]);
const handleImgLoadError = () => {
const { onError } = props;
const errorFlag = onError ? onError() : undefined;
if (errorFlag !== false) {
setIsImgExist(false);
}
};
const {
prefixCls: customizePrefixCls,
shape,
size: customSize,
src,
srcSet,
icon,
className,
alt,
draggable,
children,
...others
} = props;
const size = customSize === 'default' ? groupSize : customSize;
const screens = useBreakpoint();
const responsiveSizeStyle: React.CSSProperties = React.useMemo(() => {
if (typeof size !== 'object') {
return {};
}
const currentBreakpoint: Breakpoint = responsiveArray.find(screen => screens[screen])!;
const currentSize = size[currentBreakpoint];
return currentSize
? {
width: currentSize,
height: currentSize,
lineHeight: `${currentSize}px`,
fontSize: icon ? currentSize / 2 : 18,
}
: {};
}, [screens, size]);
devWarning(
!(typeof icon === 'string' && icon.length > 2),
'Avatar',
`\`icon\` is using ReactNode instead of string naming in v4. Please check \`${icon}\` at https://ant.design/components/icon`,
);
const prefixCls = getPrefixCls('avatar', customizePrefixCls);
const sizeCls = classNames({
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
});
const hasImageElement = React.isValidElement(src);
const classString = classNames(
prefixCls,
sizeCls,
{
[`${prefixCls}-${shape}`]: shape,
[`${prefixCls}-image`]: hasImageElement || (src && isImgExist),
[`${prefixCls}-icon`]: icon,
},
className,
);
const sizeStyle: React.CSSProperties =
typeof size === 'number'
? {
width: size,
height: size,
lineHeight: `${size}px`,
fontSize: icon ? size / 2 : 18,
}
: {};
let childrenToRender;
if (typeof src === 'string' && isImgExist) {
childrenToRender = (
<img src={src} draggable={draggable} srcSet={srcSet} onError={handleImgLoadError} alt={alt} />
);
} else if (hasImageElement) {
childrenToRender = src;
} else if (icon) {
childrenToRender = icon;
} else if (mounted || scale !== 1) {
const transformString = `scale(${scale}) translateX(-50%)`;
const childrenStyle: React.CSSProperties = {
msTransform: transformString,
WebkitTransform: transformString,
transform: transformString,
};
const sizeChildrenStyle: React.CSSProperties =
typeof size === 'number'
? {
lineHeight: `${size}px`,
}
: {};
childrenToRender = (
<ResizeObserver onResize={setScaleParam}>
<span
className={`${prefixCls}-string`}
ref={(node: HTMLElement) => {
avatarChildrenRef.current = node;
}}
style={{ ...sizeChildrenStyle, ...childrenStyle }}
>
{children}
</span>
</ResizeObserver>
);
} else {
childrenToRender = (
<span
className={`${prefixCls}-string`}
style={{ opacity: 0 }}
ref={(node: HTMLElement) => {
avatarChildrenRef.current = node;
}}
>
{children}
</span>
);
}
// The event is triggered twice from bubbling up the DOM tree.
// see https://codesandbox.io/s/kind-snow-9lidz
delete others.onError;
delete others.gap;
return (
<span
{...others}
style={{ ...sizeStyle, ...responsiveSizeStyle, ...others.style }}
className={classString}
ref={avatarNodeMergeRef as any}
>
{childrenToRender}
</span>
);
};
const Avatar = React.forwardRef<unknown, AvatarProps>(InternalAvatar);
Avatar.displayName = 'Avatar';
Avatar.defaultProps = {
shape: 'circle' as AvatarProps['shape'],
size: 'default' as AvatarProps['size'],
};
export default Avatar;
| icaife/ant-design | components/avatar/avatar.tsx | TypeScript | mit | 6,437 |
import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props);
this.styles = styleConstructor(props.theme);
}
shouldComponentUpdate(nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
let changed = true;
if (!r1 && !r2) {
changed = false;
} else if (r1 && r2) {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reservation) {
changed = false;
} else if (r1.reservation && r2.reservation) {
if ((!r1.date && !r2.date) || (r1.date && r2.date)) {
changed = this.props.rowHasChanged(r1.reservation, r2.reservation);
}
}
}
return changed;
}
renderDate(date, item) {
if (this.props.renderDay) {
return this.props.renderDay(date ? xdateToData(date) : undefined, item);
}
const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined;
if (date) {
return (
<View style={this.styles.day}>
<Text style={[this.styles.dayNum, today]}>{date.getDate()}</Text>
<Text style={[this.styles.dayText, today]}>{XDate.locales[XDate.defaultLocale].dayNamesShort[date.getDay()]}</Text>
</View>
);
} else {
return (
<View style={this.styles.day}/>
);
}
}
render() {
const {reservation, date} = this.props.item;
let content;
if (reservation) {
const firstItem = date ? true : false;
content = this.props.renderItem(reservation, firstItem);
} else {
content = this.props.renderEmptyDate(date);
}
return (
<View style={this.styles.container}>
{this.renderDate(date, reservation)}
<View style={{flex:1}}>
{content}
</View>
</View>
);
}
}
export default ReservationListItem; | eals/react-native-calender-pn-wix-extended | src/agenda/reservation-list/reservation.js | JavaScript | mit | 2,094 |
<?php
namespace O876\MVC\Adapter;
/**
* Adapteur
* Interface permettant la création d'une classe gérant la connexion à une base de données
* @author raphael.marandet
*
*/
interface Intf {
/**
* Permet de définir les paramètre de connexion à une base de données
* serveur, identifiant, mot de passe, encodage...
* @param array $aConf
*/
public function setConfiguration(array $aConf);
/**
* Envoie une requête à la base de donnée.
* @param string $sQuery requête
* @return array résultat de requête
*/
public function query($sQuery);
/**
* Renvoie le dernier identifiant auto incrément généré par un insert
* @return int
*/
public function getLastInsertId();
} | Laboralphy/h5-raycaster-lab | dynamics/o876-php/MVC/Adapter/Intf.php | PHP | mit | 716 |
"""
Visualization module.
"""
import numpy as np
from matplotlib import animation
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from pca import create_handles
import warnings
warnings.filterwarnings('ignore')
def get_temp_markers(year, attacks):
"""
Gives all the information about the markers needed for the
year passed in argument.
"""
data_given_year = attacks[attacks['Year'] == year].reset_index()
num_markers = data_given_year.shape[0]
markers = np.zeros(num_markers, dtype=[('Longitude', float, 1),
('Latitude', float, 1),
('Size', float, 1),
('Color', float, 1)])
killed = data_given_year['Killed']
_MIN, _MAX, _MEDIAN = killed.min(), killed.max(), killed.median()
markers['Longitude'] = data_given_year['Longitude']
markers['Latitude'] = data_given_year['Latitude']
markers['Size'] = 10* np.abs(killed - _MEDIAN) + 1
markers['Color'] = (killed - _MIN)/(_MAX - _MIN)
return markers, _MAX
def world_view(attacks):
"""
Creates an animation where we see the evolution of the worldwide terrorist attacks
among the available years.
"""
fig = plt.figure(figsize=(10, 10))
cmap = plt.get_cmap('inferno')
# create the map
map = Basemap(projection='cyl')
map.drawmapboundary()
map.fillcontinents(color='lightgray', zorder=0)
# define the frame values (as 1993 is not contained in the database
# we have to remove it, otherwise we will have an empty frame)
frames = np.append(np.arange(1970, 1993), np.arange(1994, 2017))
# create the plot structure
temp_markers, _MAX = get_temp_markers(frames[0], attacks)
xs, ys = map(temp_markers['Longitude'], temp_markers['Latitude'])
scat = map.scatter(xs, ys, s=temp_markers['Size'], c=temp_markers['Color'], cmap=cmap, marker='o',
alpha=0.3, zorder=10)
year_text = plt.text(-170, 80, str(frames[0]),fontsize=15)
cbar = map.colorbar(scat, location='bottom')
cbar.set_label('number of killed people 0.0 = min [0] 1.0 = max [{}]' .format(_MAX))
plt.title('Activity of terrorism attacks from 1970 to 2016')
plt.savefig('world_view.pdf', bbox_inches='tight')
plt.show()
def update(year):
"""
Updates the content of each frame during the animation for
the year passed in argument.
"""
# retrieve necessary information from the markers
temp_markers, _MAX = get_temp_markers(year, attacks)
# update the map content
xs, ys = map(temp_markers['Longitude'], temp_markers['Latitude'])
scat.set_offsets(np.hstack((xs[:,np.newaxis], ys[:, np.newaxis])))
scat.set_color(cmap(temp_markers['Color']))
scat.set_sizes(temp_markers['Size'])
year_text.set_text(str(year))
cbar.set_label('number of killed people 0.0 = min [0] 1.0 = max [{}]' .format(_MAX))
return scat,
# create animation
ani = animation.FuncAnimation(fig, update, interval=1000, frames=frames, blit=True)
ani.save('visualization.mp4', writer = 'ffmpeg', fps=1, bitrate=-1)
plt.show()
def get_group_markers(attacks, group):
"""
Gives all the information about the markers for the
group passed in argument.
"""
data_given_group = attacks[attacks['Group'] == group]
num_markers = data_given_group.shape[0]
markers = np.zeros(num_markers, dtype=[('Longitude', float, 1),
('Latitude', float, 1),
('Size', float, 1),
('Color', float, 1)])
killed = data_given_group['Killed']
_MIN, _MAX, _MEDIAN = killed.min(), killed.max(), killed.median()
markers['Longitude'] = data_given_group['Longitude']
markers['Latitude'] = data_given_group['Latitude']
markers['Size'] = 10* np.abs(killed - _MEDIAN) + 1
markers['Color'] = (killed - _MIN)/(_MAX - _MIN)
return markers, _MAX
def zoom_taliban_intensity(attacks):
"""
Zooms in the particular location of the attacks perpetrated by the Taliban group
showing the intensity of the attacks.
"""
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111)
cmap = plt.get_cmap('inferno')
plt.title('Intensity of attacks perpetrated by the Taliban group\n')
# create the map
map = Basemap(projection='cyl',lat_0=0, lon_0=0)
map.drawmapboundary()
map.fillcontinents(color='lightgray', zorder=0)
# create the plot structure
temp_markers, _MAX = get_group_markers(attacks, 'Taliban')
xs, ys = map(temp_markers['Longitude'], temp_markers['Latitude'])
scat = map.scatter(xs, ys, s=temp_markers['Size'], c=temp_markers['Color'], cmap=cmap, marker='o',
alpha=0.3, zorder=10)
axins = zoomed_inset_axes(ax, 9, loc=2)
axins.set_xlim(25, 40)
axins.set_ylim(60, 75)
plt.xticks(visible=False)
plt.yticks(visible=False)
map2 = Basemap(llcrnrlon=55,llcrnrlat=25,urcrnrlon=75,urcrnrlat=40, ax=axins)
map2.drawmapboundary()
map2.fillcontinents(color='lightgray', zorder=0)
map2.drawcoastlines()
map2.drawcountries()
map2.scatter(xs, ys, s=temp_markers['Size']/5., c=cmap(temp_markers['Color']), alpha=0.5)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.savefig('taliban_zoom_intensity.pdf', bbox_inches='tight')
plt.show()
def get_group_attack_types_markers(attacks, group):
"""
Gives the description of the attack types about the markers for the
group passed in argument.
"""
data_given_year = attacks[attacks['Group'] == group]
list_attack_type_unique = data_given_year['Attack_type'].unique().tolist()
list_attack_type = data_given_year['Attack_type'].tolist()
# assign each attack to the corresponding color
colors_attack_type = plt.cm.tab20(list(range(1,len(list_attack_type_unique)+1)))
label_color_dict_attack_type = dict(zip(list_attack_type_unique, colors_attack_type))
cvec_attack_type = [label_color_dict_attack_type[label] for label in list_attack_type]
num_markers = data_given_year.shape[0]
markers = np.zeros(num_markers, dtype=[('Longitude', float, 1),
('Latitude', float, 1),
('Size', float, 1),
('Color', float, 4)])
killed = data_given_year['Killed']
_MIN, _MAX, _MEDIAN = killed.min(), killed.max(), killed.median()
markers['Longitude'] = data_given_year['Longitude']
markers['Latitude'] = data_given_year['Latitude']
markers['Size'] = 100
markers['Color'] = np.array(cvec_attack_type)
return markers, label_color_dict_attack_type
def zoom_taliban_attack_types(attacks):
"""
Zooms in the particular location of the attacks perpetrated by the Taliban group
showing the different attack types.
"""
group = 'Taliban'
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(111)
cmap = plt.get_cmap('inferno')
plt.title('Attack types perpetrated by the Taliban group\n')
# create the map
map = Basemap(projection='cyl',lat_0=0, lon_0=0)
map.drawmapboundary()
map.fillcontinents(color='lightgray', zorder=0)
# create the plot structure
temp_markers, _MAX = get_group_markers(attacks, group)
xs, ys = map(temp_markers['Longitude'], temp_markers['Latitude'])
scat = map.scatter(xs, ys, s=temp_markers['Size'], c=temp_markers['Color'], cmap=cmap, marker='o',
alpha=0.5, zorder=10)
axins = zoomed_inset_axes(ax, 9, loc=2)
axins.set_xlim(25, 40)
axins.set_ylim(60, 75)
plt.xticks(visible=False)
plt.yticks(visible=False)
map2 = Basemap(llcrnrlon=55,llcrnrlat=25,urcrnrlon=75,urcrnrlat=40, ax=axins)
map2.drawmapboundary()
map2.fillcontinents(color='lightgray', zorder=0)
map2.drawcoastlines()
map2.drawcountries()
temp_markers, label_color_dict_attack_type = get_group_attack_types_markers(attacks, group)
map2.scatter(xs, ys, s=temp_markers['Size']/5., c=temp_markers['Color'], alpha=0.5)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
handles = create_handles(label_color_dict_attack_type, ax)
labels = [h.get_label() for h in handles]
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), handles=handles, labels=labels)
plt.savefig('taliban_zoom_attack_types.pdf', bbox_inches='tight')
plt.show()
| mdeff/ntds_2017 | projects/reports/terrorist_attacks/project/visualization.py | Python | mit | 8,333 |
export declare const skills_en: string;
| YoungLeeNENU/younglee | dist/info/skills.en.d.ts | TypeScript | mit | 41 |
/*
* Copyright (c) 2011 Ayan Dave http://daveayan.com
* 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:
*
* 1) The above copyright notice and this permission notice shall be included without any changes or alterations
* in all copies or substantial portions of the Software.
* 2) The copyright notice part of the org.json package and its classes shall be honored.
* 3) This software shall be used for Good, not Evil.
* portions of the Software.
*
* The copyright notice part of the org.json package and its classes shall be honored.
* This software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.daveayan.rjson.utils;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.daveayan.json.JSONArray;
import com.daveayan.json.JSONException;
import com.daveayan.json.JSONObject;
import com.daveayan.json.JSONTokener;
import com.daveayan.rjson.Rjson;
import com.daveayan.rjson.transformer.BaseTransformer;
public class RjsonUtil {
private static Log log = LogFactory.getLog(BaseTransformer.class);
public static Object getJsonObject(String json) throws JSONException {
log.debug("getJsonObject for " + json);
if(StringUtils.isEmpty(json)) {
return "";
}
JSONTokener tokener = new JSONTokener(json);
char firstChar = tokener.nextClean();
if (firstChar == '\"') {
return tokener.nextString('\"');
}
if (firstChar == '{') {
tokener.back();
return new JSONObject(tokener);
}
if (firstChar == '[') {
tokener.back();
return new JSONArray(tokener);
}
if (Character.isDigit(firstChar)) {
tokener.back();
return tokener.nextValue();
}
tokener.back();
return tokener.nextValue();
}
public static String reformat(String inputJson) {
String outputJson = new String(inputJson);
try {
JSONObject jo = new JSONObject(inputJson.toString());
outputJson = jo.toString(2);
} catch (JSONException e) {
}
return outputJson;
}
public static Object fileAsObject(String filename) throws IOException {
return Rjson.newInstance().toObject(fileAsString(filename));
}
public static String fileAsString(String file) throws IOException {
return FileUtils.readFileToString(new File(file)).replaceAll("\\r\\n", "\n");
}
public static Rjson completeSerializer() {
return Rjson.newInstance().with(new NullifyDateTransformer()).andRecordAllModifiers();
}
public static Rjson pointInTimeSerializer() {
return Rjson.newInstance().andRecordAllModifiers().andRecordFinal().andDoNotFormatJson();
}
public static void recordJsonToFile(Object object, String absolutePath) {
recordJsonToFile(object, absolutePath, RjsonUtil.completeSerializer());
}
public static void recordJsonToFile(Object object, String absolutePath, Rjson rjson) {
try {
FileUtils.writeStringToFile(new File(absolutePath), rjson.toJson(object));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String escapeJsonCharactersIn(String string) {
String newString = StringUtils.replace(string, "\"", "");
newString = StringUtils.replace(newString, "[", "\\[");
newString = StringUtils.replace(newString, "]", "\\]");
newString = StringUtils.replace(newString, "{", "\\{");
newString = StringUtils.replace(newString, "}", "\\}");
return newString;
}
public static String unEscapeJsonCharactersIn(String string) {
String newString = StringUtils.replace(string, "\"", "");
newString = StringUtils.replace(newString, "\\[", "[");
newString = StringUtils.replace(newString, "\\]", "]");
newString = StringUtils.replace(newString, "\\{", "{");
newString = StringUtils.replace(newString, "\\}", "}");
return newString;
}
} | daveayan/rjson | src/main/java/com/daveayan/rjson/utils/RjsonUtil.java | Java | mit | 4,825 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Taskling.Blocks.RangeBlocks;
using Taskling.InfrastructureContracts.Blocks.CommonRequests;
namespace Taskling.InfrastructureContracts.Blocks
{
public interface IRangeBlockRepository
{
Task ChangeStatusAsync(BlockExecutionChangeStatusRequest changeStatusRequest);
Task<RangeBlock> GetLastRangeBlockAsync(LastBlockRequest lastRangeBlockRequest);
}
}
| Vanlightly/Taskling.NET | src/Taskling/InfrastructureContracts/Blocks/IRangeBlockRepository.cs | C# | mit | 502 |
namespace LSLib.LS.Enums
{
public enum CompressionLevel
{
FastCompression,
DefaultCompression,
MaxCompression
};
} | Norbyte/lslib | LSLib/LS/Enums/CompressionLevel.cs | C# | mit | 161 |
version https://git-lfs.github.com/spec/v1
oid sha256:2566f139073c240a090aee1fb4254ec2b799a9402dd6494447afbe4e12c97654
size 6184
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.5.1/matrix/matrix-min.js | JavaScript | mit | 129 |
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
Klauskpm\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
Klauskpm\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
Klauskpm\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| klauskpm/klauskpm | bootstrap/app.php | PHP | mit | 1,617 |
namespace DataBoss.Linq
{
public static class Collection
{
public static EmptyCollection<T> Empty<T>() => new();
}
} | drunkcod/DataBoss | Source/DataBoss.Linq/Collection.cs | C# | mit | 127 |
package de.tum.in.www1.artemis.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;
/**
* Spring Data JPA repository for the ModelingSubmission entity.
*/
@SuppressWarnings("unused")
@Repository
public interface ModelingSubmissionRepository extends JpaRepository<ModelingSubmission, Long> {
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.assessor where submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findByIdWithEagerResult(@Param("submissionId") Long submissionId);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.feedbacks left join fetch r.assessor where submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findByIdWithEagerResultAndFeedback(@Param("submissionId") Long submissionId);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.participation p left join fetch submission.result r left join fetch r.feedbacks where p.exercise.id = :#{#exerciseId} and r.assessmentType = 'MANUAL'")
List<ModelingSubmission> findByExerciseIdWithEagerResultsWithManualAssessment(@Param("exerciseId") Long exerciseId);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.feedbacks where submission.exampleSubmission = true and submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findExampleSubmissionByIdWithEagerResult(@Param("submissionId") Long submissionId);
/**
* @param courseId the course we are interested in
* @param submitted boolean to check if an exercise has been submitted or not
* @return number of submissions belonging to courseId with submitted status
*/
long countByParticipation_Exercise_Course_IdAndSubmitted(Long courseId, boolean submitted);
/**
* @param courseId the course id we are interested in
* @return the number of submissions belonging to the course id, which have the submitted flag set to true and the submission date before the exercise due date, or no exercise
* due date at all
*/
@Query("SELECT COUNT (DISTINCT submission) FROM ModelingSubmission submission WHERE submission.participation.exercise.course.id = :#{#courseId} AND submission.submitted = TRUE AND (submission.submissionDate < submission.participation.exercise.dueDate OR submission.participation.exercise.dueDate IS NULL)")
long countByCourseIdSubmittedBeforeDueDate(@Param("courseId") Long courseId);
/**
* @param exerciseId the exercise id we are interested in
* @return the number of submissions belonging to the exercise id, which have the submitted flag set to true and the submission date before the exercise due date, or no
* exercise due date at all
*/
@Query("SELECT COUNT (DISTINCT submission) FROM ModelingSubmission submission WHERE submission.participation.exercise.id = :#{#exerciseId} AND submission.submitted = TRUE AND (submission.submissionDate < submission.participation.exercise.dueDate OR submission.participation.exercise.dueDate IS NULL)")
long countByExerciseIdSubmittedBeforeDueDate(@Param("exerciseId") Long exerciseId);
}
| ls1intum/ArTEMiS | src/main/java/de/tum/in/www1/artemis/repository/ModelingSubmissionRepository.java | Java | mit | 3,605 |
/*
* Qt4 facoin GUI.
*
* W.J. van der Laan 2011-2012
* The Facoin Developers 2011-2012
*/
#include "facoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "facoinunits.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "wallet.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QFileDialog>
#include <QDesktopServices>
#include <QTimer>
#include <QDragEnterEvent>
#include <QUrl>
#include <QStyle>
#include <iostream>
extern CWallet* pwalletMain;
extern int64_t nLastCoinStakeSearchInterval;
double GetPoSKernelPS();
FacoinGUI::FacoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
unlockWalletAction(0),
lockWalletAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0),
nWeight(0)
{
resize(850, 550);
setWindowTitle(tr("FACOIN") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/facoin"));
setWindowIcon(QIcon(":icons/facoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create the tray icon (or setup the dock icon)
createTrayIcon();
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
signVerifyMessageDialog = new SignVerifyMessageDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelStakingIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelStakingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
if (GetBoolArg("-staking", true))
{
QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
timerStakingIcon->start(30 * 1000);
updateStakingIcon();
}
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = qApp->style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Clicking on "Verify Message" in the address book sends you to the verify message tab
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
gotoOverviewPage();
}
FacoinGUI::~FacoinGUI()
{
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
#endif
}
void FacoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setToolTip(tr("Show general overview of wallet"));
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a FACOIN address"));
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setToolTip(tr("Browse transaction history"));
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setToolTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/facoin"), tr("&About FACOIN"), this);
aboutAction->setToolTip(tr("Show information about FACOIN"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setToolTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for FACOIN"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/facoin"), tr("&Show / Hide"), this);
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setToolTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(QIcon(":/icons/lock_open"), tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Lock Wallet"), this);
lockWalletAction->setToolTip(tr("Lock wallet"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export the data in the current tab to a file"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered()), this, SLOT(unlockWallet()));
connect(lockWalletAction, SIGNAL(triggered()), this, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void FacoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(exportAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void FacoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
}
void FacoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/facoin_testnet"));
setWindowIcon(QIcon(":icons/facoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/facoin_testnet"));
#endif
if(trayIcon)
{
trayIcon->setToolTip(tr("FACOIN client") + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
rpcConsole->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void FacoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if(walletModel)
{
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus(walletModel->getEncryptionStatus());
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void FacoinGUI::createTrayIcon()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip(tr("FACOIN client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
notificator = new Notificator(qApp->applicationName(), trayIcon);
}
#ifndef Q_OS_MAC
void FacoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void FacoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void FacoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void FacoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to FACOIN network", "", count));
}
void FacoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// don't show / hide progress bar and its label if we have no connection to the network
if (!clientModel || clientModel->getNumConnections() == 0)
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
return;
}
QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
QString tooltip;
if(count < nTotalBlocks)
{
int nRemainingBlocks = nTotalBlocks - count;
float nPercentageDone = count / (nTotalBlocks * 0.01f);
if (strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(tr("Synchronizing with network..."));
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
progressBar->setMaximum(nTotalBlocks);
progressBar->setValue(count);
progressBar->setVisible(true);
}
tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
}
else
{
if (strStatusBarWarnings.isEmpty())
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
}
// Override progressBarLabel text and hide progress bar, when we have warnings to display
if (!strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(strStatusBarWarnings);
progressBarLabel->setVisible(true);
progressBar->setVisible(false);
}
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
QString text;
// Represent time from last generated block in human readable text
if(secs <= 0)
{
// Fully up to date. Leave text empty.
}
else if(secs < 60)
{
text = tr("%n second(s) ago","",secs);
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
overviewPage->showOutOfSyncWarning(false);
}
else
{
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
syncIconMovie->start();
overviewPage->showOutOfSyncWarning(true);
}
if(!text.isEmpty())
{
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1.").arg(text);
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void FacoinGUI::error(const QString &title, const QString &message, bool modal)
{
// Report errors from network/worker thread
if(modal)
{
QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
} else {
notificator->notify(Notificator::Critical, title, message);
}
}
void FacoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void FacoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void FacoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(
FacoinUnits::formatWithUnit(FacoinUnits::FAC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void FacoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
if(!walletModel || !clientModel)
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On new transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
TransactionTableModel::ToAddress, parent)
.data(Qt::DecorationRole));
notificator->notify(Notificator::Information,
(amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(FacoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
.arg(type)
.arg(address), icon);
}
}
void FacoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void FacoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void FacoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void FacoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void FacoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void FacoinGUI::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void FacoinGUI::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
void FacoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void FacoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (sendCoinsPage->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
gotoSendCoinsPage();
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid FACOIN address or malformed URI parameters."));
}
event->acceptProposedAction();
}
void FacoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
showNormalIfMinimized();
gotoSendCoinsPage();
}
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid FACOIN address or malformed URI parameters."));
}
void FacoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void FacoinGUI::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus(walletModel->getEncryptionStatus());
}
void FacoinGUI::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if(!filename.isEmpty()) {
if(!walletModel->backupWallet(filename)) {
QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
}
}
}
void FacoinGUI::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void FacoinGUI::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if(walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog::Mode mode = sender() == unlockWalletAction ?
AskPassphraseDialog::UnlockStaking : AskPassphraseDialog::Unlock;
AskPassphraseDialog dlg(mode, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void FacoinGUI::lockWallet()
{
if(!walletModel)
return;
walletModel->setWalletLocked(true);
}
void FacoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void FacoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void FacoinGUI::updateWeight()
{
if (!pwalletMain)
return;
TRY_LOCK(cs_main, lockMain);
if (!lockMain)
return;
TRY_LOCK(pwalletMain->cs_wallet, lockWallet);
if (!lockWallet)
return;
uint64_t nMinWeight = 0, nMaxWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
}
void FacoinGUI::updateStakingIcon()
{
updateWeight();
if (nLastCoinStakeSearchInterval && nWeight)
{
uint64_t nNetworkWeight = GetPoSKernelPS();
unsigned nEstimateTime = nTargetSpacing * nNetworkWeight / nWeight;
QString text;
if (nEstimateTime < 60)
{
text = tr("%n second(s)", "", nEstimateTime);
}
else if (nEstimateTime < 60*60)
{
text = tr("%n minute(s)", "", nEstimateTime/60);
}
else if (nEstimateTime < 24*60*60)
{
text = tr("%n hour(s)", "", nEstimateTime/(60*60));
}
else
{
text = tr("%n day(s)", "", nEstimateTime/(60*60*24));
}
labelStakingIcon->setPixmap(QIcon(":/icons/staking_on").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3").arg(nWeight).arg(nNetworkWeight).arg(text));
}
else
{
labelStakingIcon->setPixmap(QIcon(":/icons/staking_off").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
if (pwalletMain && pwalletMain->IsLocked())
labelStakingIcon->setToolTip(tr("Not staking because wallet is locked"));
else if (vNodes.empty())
labelStakingIcon->setToolTip(tr("Not staking because wallet is offline"));
else if (IsInitialBlockDownload())
labelStakingIcon->setToolTip(tr("Not staking because wallet is syncing"));
else if (!nWeight)
labelStakingIcon->setToolTip(tr("Not staking because you don't have mature coins"));
else
labelStakingIcon->setToolTip(tr("Not staking"));
}
}
| facash/facoin | src/qt/facoingui.cpp | C++ | mit | 35,491 |
class MoviesController < ApplicationController
def index
@movies = Movie.all.sort { |a,b| a.title <=> b.title }
end
def show
@movie = Movie.find(params[:id])
@roles = @movie.roles.sort { |a,b| a.actor.name <=> b.actor.name }
@suckr = ImageSuckr::GoogleSuckr.new
end
def new
@movie = Movie.new
end
def create
@movie = Movie.create(movie_params)
redirect_to movie_path(@movie.id)
end
private
def movie_params
params.require(:movie).permit(:title, :year)
end
end
| cjord01/imdb_clone | imdb/app/controllers/movies_controller.rb | Ruby | mit | 491 |
package edu.psu.compbio.seqcode.gse.ewok.nouns;
import java.util.Vector;
import edu.psu.compbio.seqcode.gse.datasets.species.Gene;
public class GeneDomainTimeSeries {
public static final int window = 30000;
private Gene gene;
private Vector<GeneDomainData> data;
public GeneDomainTimeSeries(Gene g, int tps) {
gene = g;
data = new Vector<GeneDomainData>();
for(int i = 0; i < tps; i++) {
data.add(new GeneDomainData(gene, window));
}
}
public void addDomain(SimpleDomain sd, int tp) {
data.get(tp).addDomain(sd);
}
public boolean isCovered(int tp) {
return data.get(tp).isTSSCovered();
}
public String getBitString() {
String str = "";
for(int i = 0; i < data.size(); i++) {
str += isCovered(i) ? "1" : "0";
}
return str;
}
public String toString() { return gene.getID() + " " + getBitString(); }
}
| shaunmahony/seqcode | src/edu/psu/compbio/seqcode/gse/ewok/nouns/GeneDomainTimeSeries.java | Java | mit | 897 |
import React from 'react'
export default class NoteItem extends React.Component {
render () {
return (
<div>
<p>Category = {this.props.note.category}</p>
<p>The Note = {this.props.note.noteText}</p>
<hr />
</div>
)
}
} | josedigital/koala-app | src/components/Note/NoteItem.js | JavaScript | mit | 276 |
<?php
/*
* This file is part of ImgCache.
*
* (c) Igor Lazarev <strider2038@rambler.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Strider2038\ImgCache\Enum;
use MyCLabs\Enum\Enum;
/**
* @author Igor Lazarev <strider2038@rambler.ru>
*/
class HttpProtocolVersionEnum extends Enum
{
public const V1_0 = '1.0';
public const V1_1 = '1.1';
}
| strider2038/imgcache-service | src/Enum/HttpProtocolVersionEnum.php | PHP | mit | 454 |
<?php
namespace Translations\Test\App\Controller;
use Cake\Controller\Controller;
class UsersController extends Controller
{
/**
* Simple users login action
*
* @return void
*/
public function login(): void
{
}
}
| QoboLtd/cakephp-translations | tests/App/Controller/UsersController.php | PHP | mit | 251 |
///<reference path="./otmword.ts" />
///<reference path="./wmmodules.ts" />
///<reference path="./wgenerator.ts" />
///<reference path="./ntdialog.ts" />
/**
* 単語作成部で使用するViewModel
*/
class WordDisplayVM {
/**
* コンストラクタ
* @param el バインディングを適用するタグのid
* @param dict OTM形式辞書クラス
* @param createSetting 単語文字列作成に使用する設定
*/
constructor(el, dict, createSetting, equivalent) {
this.el = el;
this.data = {
dictionary: dict,
isDisabled: false,
createSetting: createSetting,
id: 1,
equivalent: equivalent,
};
this.initMethods();
}
/**
* VMで使用するメソッドを定義するメソッド
*/
initMethods() {
this.methods = {
/**
* 単語文字列を作成するメソッド
*/
create: function _create() {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add("");
this.dictionary.add(word);
},
/**
* 設定されている全ての訳語に対して単語を作成するメソッド
*/
createAll: function _createAll() {
this.equivalent.equivalentsList.data.forEach((x) => {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add(x.equivalents.join(","));
this.dictionary.add(word);
});
},
/**
* 作成した全ての単語を削除するメソッド
*/
removeAll: function _removeAll() {
this.dictionary.removeAll();
// idを初期値にする
this.id = 1;
},
/**
* 作成した単語一覧をOTM-JSON形式で出力するメソッド
*/
outputOtmJSON: function _outputOtmJSON() {
// idを振り直す
let id = 1;
this.dictionary.words.forEach((x) => {
x.entry.id = id++;
});
WMModules.exportJSON(this.dictionary, "dict.json");
// 引き続き作成する場合を考えてidを更新する
this.id = id;
},
// 個々で使用する部分
/**
* 訳語選択ダイアログを呼び出すメソッド
* @param 訳語を設定する単語クラス
*/
showEquivalentDialog: function _showEquivalentDialog(word) {
this.equivalent.selectedWordId = word.entry.id.toString();
WMModules.equivalentDialog.show();
},
/**
* 単語を削除するメソッド
* @param 削除する単語クラス
*/
remove: function _remove(word) {
this.dictionary.remove(word.entry.id);
},
/**
* 単語の区切りの","で文字列を区切って配列にするためのメソッド
* @param 単語の訳語(カンマ区切り)
* @return カンマを区切り文字として分割した結果の文字列配列
*/
splitter: function _splitter(value) {
return value.split(",").map(function (x) { return x.trim(); });
},
};
}
}
//# sourceMappingURL=worddisplayvm.js.map | Nobuyuki-Tokuchi/wordmaker_web | scripts/worddisplayvm.js | JavaScript | mit | 5,118 |
var CategoryLevel = function(){
'use strict';
var categorys = {};
this.addCategory = function(_name) {
categorys[_name] = [];
};
this.addDataToLastCategory = function(_categoryName, _lineData, _className) {
var category = categorys[_categoryName];
};
};
| russellmt/PortfolioProject | app/js/categoryLevel.js | JavaScript | mit | 298 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowBasis.Crypto
{
public enum DigestType
{
SHA1 = 0,
MD5 = 1
}
}
| calebdoise/flowbasis | src/FlowBasis/FlowBasis.Crypto/DigestType.cs | C# | mit | 224 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Display Debug backtrace
|--------------------------------------------------------------------------
|
| If set to TRUE, a backtrace will be displayed along with php errors. If
| error_reporting is disabled, the backtrace will not display, regardless
| of this setting
|
*/
defined('SHOW_DEBUG_BACKTRACE') OR define('SHOW_DEBUG_BACKTRACE', TRUE);
/*
|--------------------------------------------------------------------------
| File and Directory Modes
|--------------------------------------------------------------------------
|
| These prefs are used when checking and setting modes when working
| with the file system. The defaults are fine on servers with proper
| security, but you may wish (or even need) to change the values in
| certain environments (Apache running a separate process for each
| user, PHP under CGI with Apache suEXEC, etc.). Octal values should
| always be used to set the mode correctly.
|
*/
defined('FILE_READ_MODE') OR define('FILE_READ_MODE', 0644);
defined('FILE_WRITE_MODE') OR define('FILE_WRITE_MODE', 0666);
defined('DIR_READ_MODE') OR define('DIR_READ_MODE', 0755);
defined('DIR_WRITE_MODE') OR define('DIR_WRITE_MODE', 0755);
/*
|--------------------------------------------------------------------------
| File Stream Modes
|--------------------------------------------------------------------------
|
| These modes are used when working with fopen()/popen()
|
*/
defined('FOPEN_READ') OR define('FOPEN_READ', 'rb');
defined('FOPEN_READ_WRITE') OR define('FOPEN_READ_WRITE', 'r+b');
defined('FOPEN_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
defined('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
defined('FOPEN_WRITE_CREATE') OR define('FOPEN_WRITE_CREATE', 'ab');
defined('FOPEN_READ_WRITE_CREATE') OR define('FOPEN_READ_WRITE_CREATE', 'a+b');
defined('FOPEN_WRITE_CREATE_STRICT') OR define('FOPEN_WRITE_CREATE_STRICT', 'xb');
defined('FOPEN_READ_WRITE_CREATE_STRICT') OR define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
/*
|--------------------------------------------------------------------------
| Exit Status Codes
|--------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') OR define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') OR define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') OR define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') OR define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') OR define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') OR define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') OR define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') OR define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') OR define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') OR define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
define('PWKEY', '!@#$%^&*'); //密码加密密钥
define('BUYTYPE', ['1' => '6HC', '2' => '双色', '3' => '赛车']);
| samuelamam/GameBling | application/config/constants.php | PHP | mit | 4,442 |
package solutions.digamma.damas.common;
/**
* Exception occurs in case of incompatibility between DMS items. For example
* this exception should be thrown when an identifier of existing but
* incompatible item is passed to a method.
*
* @author Ahmad Shahwan
*/
public class CompatibilityException extends MisuseException {
public CompatibilityException() {
super();
}
public CompatibilityException(String message) {
super(message);
}
public CompatibilityException(Exception e) {
super(e);
}
public CompatibilityException(String message, Exception e) {
super(message, e);
}
}
| digammas/damas | solutions.digamma.damas.api/src/main/java/solutions/digamma/damas/common/CompatibilityException.java | Java | mit | 651 |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using AutoMapper;
using BellTowerEscape.Commands;
using BellTowerEscape.Utility;
namespace BellTowerEscape.Server
{
public class Game
{
private static int _MAXID = 0;
public static int START_DELAY = 5000; // 5 seconds
public static int TURN_DURATION = 2000; // 2 seconds
public static int SERVER_PROCESSING = 2000; // 2 seconds
public int totalTimeProcessing = TURN_DURATION + SERVER_PROCESSING;
public static int TIME_TO_WAIT_FOR_SECOND_PLAYER = 60000; // 1 minute
public static int MAX_TURN = 500;
public static bool IsRunningLocally = HttpContext.Current.Request.IsLocal;
private static int _NUMBER_OF_ELEVATORS = 4;
public static int NUMBER_OF_FLOORS = 12;
private static int _MAX_PEOPLE_TO_ADD_PER_FLOOR = 2;
private HighFrequencyTimer _gameLoop = null;
public ConcurrentDictionary<string, Player> Players = new ConcurrentDictionary<string, Player>();
private ConcurrentDictionary<string, Player> _authTokens = new ConcurrentDictionary<string, Player>();
public int Seed { get; set; }
public Random Random { get; set; }
public int Id { get; set; }
public bool Processing { get; set; }
public int Turn { get; set; }
public bool GameOver { get; set; }
private bool _started { get; set; }
public bool Waiting { get; set; }
public bool _processingComplete { get; set; }
private object synclock = new object();
private long elapsedWaitTime = 0;
private long elapsedTotalTurn = 0;
private long elapsedServerTime = 0;
private long gameStartCountdown = START_DELAY;
public ConcurrentDictionary<int, Elevator> Elevators { get; set;}
public ConcurrentDictionary<int, Floor> Floors { get; set; }
public bool Running { get; set; }
public Game(int? seed, int? id) : base()
{
if (seed != null && seed.HasValue)
{
Random = new Random(seed.Value);
}
if (id != null && id.HasValue)
{
Id = id.Value;
}
}
public Game()
{
if (Random == null)
{
Random = new Random();
}
Id = _MAXID++;
Elevators = new ConcurrentDictionary<int, Elevator>();
// dirty filthy hacks
var evenElevators = Random.Next(NUMBER_OF_FLOORS);
var oddElevators = Random.Next(NUMBER_OF_FLOORS);
for (int i = 0; i < _NUMBER_OF_ELEVATORS; i++)
{
Elevators.GetOrAdd(i, new Elevator(){Id = i, Floor = (i % 2 == 0) ? evenElevators : oddElevators, Meeples = new List<Meeple>()});
}
Floors = new ConcurrentDictionary<int, Floor>();
for (int i = 0; i < NUMBER_OF_FLOORS; i++)
{
Floors.GetOrAdd(i, new Floor() {Meeples = new List<Meeple>(), Number = i});
}
AddMeepleToFloors();
Turn = 0;
Running = false;
_started = false;
_gameLoop = new HighFrequencyTimer(60, this.Update);
}
private void AddMeepleToFloors()
{
Floors[Random.Next(NUMBER_OF_FLOORS)].SpawnMeeple(this, Random.Next(_MAX_PEOPLE_TO_ADD_PER_FLOOR));
}
/// <summary>
/// Logs player with a certain name into the game and returns an authorization token
/// </summary>
/// <param name="playerName"></param>
/// <returns></returns>
public LogonResult LogonPlayer(string playerName)
{
var result = new LogonResult();
if (!Players.ContainsKey(playerName))
{
var newPlayer = new Player()
{
AuthToken = System.Guid.NewGuid().ToString(),
PlayerName = playerName
};
var success = Players.TryAdd(playerName, newPlayer);
var success2 = _authTokens.TryAdd(newPlayer.AuthToken, newPlayer);
if (success && success2)
{
System.Diagnostics.Debug.WriteLine("Player logon [{0}]:[{1}]", newPlayer.PlayerName,
newPlayer.AuthToken);
}
_allocateElevators(newPlayer.AuthToken);
result.AuthToken = newPlayer.AuthToken;
result.GameId = Id;
result.GameStart = (int) this.gameStartCountdown;
}
else
{
System.Diagnostics.Debug.WriteLine("Player {0} already logged on!", playerName);
}
result.GameId = Id;
return result;
}
public void StartDemoAgent(LogonResult demoResult, string playerName)
{
var agentTask = Task.Factory.StartNew(() =>
{
string endpoint = "";
if (IsRunningLocally)
{
endpoint = "http://localhost:3193";
}
else {
endpoint = "http://elevators.azurewebsites.net";
}
AgentBase sweetDemoAgent = new AgentBase(playerName, endpoint);
sweetDemoAgent.Start(demoResult).Wait();
});
}
public List<ElevatorLite> GetElevatorsForPlayer(string token)
{
return this.Elevators.Values.Where(e => e.PlayerToken == token).Select(Mapper.Map<ElevatorLite>).ToList();
}
public List<ElevatorLite> GetElevatorsForOtherPlayer(string token)
{
return this.Elevators.Values.Where(e => e.PlayerToken != token).Select(Mapper.Map<ElevatorLite>).ToList();
}
public int GetEnemyDelivered(string token)
{
return this._authTokens.Values.Where(e => e.AuthToken != token).First().Score;
}
private void _allocateElevators(string token)
{
lock (synclock)
{
var count = _NUMBER_OF_ELEVATORS/2;
foreach (var elevator in Elevators.Values)
{
if (count <= 0) break;
if(string.IsNullOrEmpty(elevator.PlayerToken))
{
count--;
elevator.PlayerToken = token;
}
}
}
}
public StatusResult GetStatus(StatusCommand command)
{
var status = "Initializing";
if (!this._started)
{
status = "Game waiting for Logons";
}
if (this.Waiting)
{
status = "Waiting for another player to join...";
}
if (this.GameOver)
{
if (this.Waiting) {
status = "Other players never joined";
}
else if (this._authTokens.Values.GroupBy(e => e.Score).First().Count() == this.Players.Count())
{
status = "Game Over - It's a TIE!";
}
else
{
var winningPlayer = this._authTokens.Values.OrderByDescending(e => e.Score).First().PlayerName;
status = "Game Over - " + winningPlayer + " wins!";
}
}
if (this.Running)
{
status = "Game Running";
}
return new StatusResult()
{
EnemyElevators = GetElevatorsForOtherPlayer(command.AuthToken),
MyElevators = GetElevatorsForPlayer(command.AuthToken),
TimeUntilNextTurn = (int) (_started ?
(SERVER_PROCESSING + TURN_DURATION - this.elapsedTotalTurn - this.elapsedServerTime) : Waiting ? SERVER_PROCESSING + TURN_DURATION : this.gameStartCountdown),
Delivered = _authTokens[command.AuthToken].Score,
EnemyDelivered = this.Waiting ? 0 : GetEnemyDelivered(command.AuthToken),
Floors = Floors.Values.Select(Mapper.Map<FloorLite>).ToList(),
Id = this.Id,
Turn = this.Turn,
IsGameOver = this.GameOver,
Status = status
};
}
public MoveResult MoveElevator(MoveCommand command)
{
var result = new MoveResult();
//var token = command.AuthToken;
var id = command.ElevatorId;
Elevator elevator;
var exists = Elevators.TryGetValue(id, out elevator);
var error = _validateMoveElevatorErrors(command);
if (error == null && elevator != null)
{
elevator.Done = true;
// we have validated control and existance of the elevator
if (command.Direction.ToLower() == "up")
{
elevator.Floor = Math.Min(elevator.Floor + 1, NUMBER_OF_FLOORS - 1);
elevator.IsStopped = false;
result.Message = string.Format("Moved elevator {0} up successfully", command.ElevatorId);
}
else if (command.Direction.ToLower() == "down")
{
elevator.Floor = Math.Max(elevator.Floor - 1, 0);
elevator.IsStopped = false;
result.Message = string.Format("Moved elevator {0} down successfully", command.ElevatorId);
}
else if (command.Direction.ToLower() == "stop")
{
elevator.IsStopped = true;
result.Message = string.Format("Stopped elevator {0} successfully", command.ElevatorId);
}
result.Success = true;
}
else
{
System.Diagnostics.Debug.WriteLine(error.Message);
return error;
}
return result;
}
private MoveResult _validateMoveElevatorErrors(MoveCommand command)
{
var token = command.AuthToken;
var id = command.ElevatorId;
Elevator elevator;
var exists = Elevators.TryGetValue(id, out elevator);
if (!exists)
{
return new MoveResult()
{
Success = false,
Message = string.Format("Elevator for id {0} does not exist", id)
};
}
if (string.IsNullOrEmpty(command.Direction))
{
return new MoveResult()
{
Success = false,
Message = string.Format("Could not move elevator on empty direction")
};
}
if (command.Direction.ToLower() != "up" &&
command.Direction.ToLower() != "down" &&
command.Direction.ToLower() != "stop")
{
return new MoveResult()
{
Success = false,
Message = string.Format("Could not move elevator on invalid direction {0}", command.Direction)
};
}
if (elevator.PlayerToken != token)
{
return new MoveResult()
{
Success = false,
Message = string.Format("Can't move elevators you don't own ;) ID: {0}", command.ElevatorId)
};
}
if (elevator.Done)
{
return new MoveResult()
{
Success = false,
Message = string.Format("Elevator has already been moved")
};
}
if (Processing)
{
return new MoveResult()
{
Success = false,
Message = string.Format("Server is processing, please try again soon")
};
}
return null;
}
public void Update(long delta)
{
if (this.Waiting)
{
elapsedWaitTime += delta;
if (elapsedWaitTime > TIME_TO_WAIT_FOR_SECOND_PLAYER)
{
GameOver = true;
this.Stop();
}
return;
}
if (!_started)
{
this.gameStartCountdown -= delta;
if (this.gameStartCountdown <= 0)
{
_started = true;
}
return;
}
if (GameOver)
{
this.Stop();
return;
}
this.elapsedTotalTurn += delta;
if (!Processing && this.elapsedTotalTurn >= TURN_DURATION)
{
Processing = true;
}
if (this.elapsedTotalTurn >= SERVER_PROCESSING + TURN_DURATION)
{
Processing = false;
_processingComplete = false;
this.elapsedTotalTurn = 0;
Turn++;
// publish viz update every turn
ClientManager.UpdateClientGame(this);
}
if (Processing && !_processingComplete)
{
// score meeples
foreach (var elevator in Elevators.Values.ToList())
{
foreach (var meeple in elevator.Meeples.ToList())
{
if (elevator.Floor == meeple.Destination && elevator.IsStopped)
{
if (meeple.Patience >= 0)
{
elevator.Meeples.Remove(meeple);
_authTokens[elevator.PlayerToken].Score++;
}
}
}
}
// for each floor
for (int i = 0; i < Floors.Count; i++)
{
// let's just not bother when there are no meeples
if (Floors[i].Meeples.Count <= 0) { continue; }
// get all stopped elevators based on capacity
List<Elevator> elevatorsStoppedOnFloor = Elevators.Values.Where(e => e.IsStopped && e.Floor == i).ToList();
// ensure "fairness" by shuffling
elevatorsStoppedOnFloor.Shuffle(this);
// sort ascnedingly
elevatorsStoppedOnFloor = elevatorsStoppedOnFloor.OrderByDescending(e => e.FreeSpace).ToList();
var elevatorGroups = elevatorsStoppedOnFloor.GroupBy(e => e.FreeSpace);
// each group should have the same amount of free space
foreach (var eGroup in elevatorGroups)
{
// SHUFFLE IT AGAIN!
var eGroupShuffled = eGroup.ToList();
eGroupShuffled.Shuffle(this);
// just kill it, then again max of 4 elevators, possibly not worth it. BUT bell tower is expandable!
if (Floors[i].Meeples.Count <= 0) { break; }
// keep going for the amount of free space in the elevator
for (int j = eGroup.Key; j > 0; j--)
{
// add 1 meeple to the elevator at a time
foreach (Elevator elevator in eGroupShuffled)
{
if (Floors[i].Meeples.Count > 0 && elevator.FreeSpace > 0)
{
Meeple meeple = Floors[i].Meeples[0];
Floors[i].Meeples.Remove(meeple);
elevator.Meeples.Add(meeple);
meeple.InElevator = true;
}
}
}
}
}
// for each elevator check Meeple frustration
foreach (var elevator in Elevators.Values.ToList())
{
foreach (var meeple in elevator.Meeples.ToList())
{
meeple.Update();
if (meeple.Patience < 0 && elevator.IsStopped)
{
// GET OFF. If the meeple is on the floor it wanted, you still get negative points.
if (meeple.Destination != elevator.Floor)
{
// TODO: It may or may not be worth having that meeple be frustrated to the point where they don't want to get back on your elevators
meeple.FrustratedAtPlayer = elevator.PlayerToken;
Floor floor;
Floors.TryGetValue(elevator.Floor, out floor);
meeple.ResetMeeple(elevator.Floor);
floor.Meeples.Add(meeple);
_authTokens[elevator.PlayerToken].Score--;
}
elevator.Meeples.Remove(meeple);
}
}
}
// add new Meeples
AddMeepleToFloors();
// clear state variables
foreach (var elevator in Elevators.Values)
{
elevator.IsStopped = false; //so, if your AI skips a turn, you can't fake a "stopped" elevator ploy
elevator.Done = false;
}
_processingComplete = true;
}
if (Turn >= MAX_TURN)
{
this.GameOver = true;
}
}
public void Start()
{
Running = true;
_gameLoop.Start();
}
public void Stop()
{
Running = false;
_gameLoop.Stop();
}
}
} | eonarheim/BellTowerEscape | BellTowerEscape/Server/Game.cs | C# | mit | 19,303 |
begin
require File.expand_path('../../ripper', __FILE__)
require 'test/unit'
ripper_test = true
module TestRipper; end
rescue LoadError
p $!
end
class TestRipper::Ripper < Test::Unit::TestCase
def setup
@ripper = Ripper.new '1 + 1'
end
def test_column
assert_nil @ripper.column
end
def test_encoding
assert_equal Encoding::UTF_8, @ripper.encoding
end
def test_end_seen_eh
refute @ripper.end_seen?
end
def test_filename
assert_equal '(ripper)', @ripper.filename
end
def test_lineno
assert_nil @ripper.lineno
end
def test_parse
refute @ripper.parse
end
def test_yydebug
refute @ripper.yydebug
end
def test_yydebug_equals
@ripper.yydebug = true
assert @ripper.yydebug
end
end if ripper_test
| ngty/ripper-pure | src/ripper/test/ripper/test_ripper.rb | Ruby | mit | 786 |
module HelperMethods
# Find and click the 'submit' button.
# Should be used +within+ a form's scope.
def submit
find("[type='submit']").click
end
# Reload the current page
def reload_page
visit page.current_url
end
# Shortcut for accessing localizations
def t(*args)
I18n.t(*args)
end
end
RSpec.configuration.include HelperMethods, :type => :feature
| jazen/static | spec/acceptance/support/helpers.rb | Ruby | mit | 386 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storage.generated;
import com.azure.core.util.Context;
/** Samples for Table Create. */
public final class TableCreateSamples {
/*
* x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2021-08-01/examples/TableOperationPut.json
*/
/**
* Sample code: TableOperationPut.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void tableOperationPut(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.storageAccounts()
.manager()
.serviceClient()
.getTables()
.createWithResponse("res3376", "sto328", "table6185", Context.NONE);
}
}
| Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java | Java | mit | 925 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Ricardo Ribeiro"
__credits__ = ["Ricardo Ribeiro"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
__status__ = "Development"
import time
from datetime import datetime, timedelta
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
time_elapsed = datetime(1,1,1) + timedelta(seconds=(te-ts) )
print("%s: %d:%d:%d:%d;%d" % (method.__name__, time_elapsed.day-1, time_elapsed.hour, time_elapsed.minute, time_elapsed.second, time_elapsed.microsecond))
return result
return timed | sunj1/my_pyforms | pyforms/Utils/timeit.py | Python | mit | 694 |
<?php session_start(); include "secure/connectstring.php";?>
<DIV id="requesttabcontent" class="tab-content">
<DIV class="tab-pane fade in" id="open">
<BR>
<table class = 'table table-hover table-condensed '>
<THEAD>
<TR>
<TD class = 'td_scholar_10 column_name'>
REQUEST DATE
</TD>
<TD class = 'td_scholar_5 column_name'>
ID #
</TD>
<TD class = 'td_scholar_15 column_name'>
SCHOLAR
</TD>
<TD class = 'td_scholar_10 column_name'>
CATEGORY
</TD>
<TD class = 'td_scholar_20 column_name'>
DETAILS
</TD>
<TD class = 'td_scholar_5 column_name'>
AMOUNT REQUESTED
</TD>
<TD class = 'td_scholar_20 column_name'>
AMOUNT APPROVED
</TD>
<TD class = 'td_scholar_15 column_name'>
AVAILABLE ACTIONS
</TD>
</TR>
</THEAD>
<TBODY>
<?php
include 'secure/connectstring.php';
$curr_user_id = $_SESSION['user_id'];
$query_open = "Select * FROM tb_request_info, tb_scholar_info, tb_config_listing, tb_config_listing_request_category WHERE tb_request_info.req_cat = tb_config_listing_request_category.id AND tb_request_info.req_type = tb_config_listing.id AND (tb_config_listing.category = 'request_type') AND tb_scholar_info.scholar_id = tb_request_info.req_scholar_id AND req_status = 'COMPLETED' AND req_ac_id = $curr_user_id ORDER BY req_id DESC, req_item_id DESC";
$result_open = mysql_query($query_open) or die(mysql_error());
while ($row_open = mysql_fetch_object($result_open))
{
$button_value = "h" . $row_open->req_id . "i" . $row_open->req_item_id . "e";
echo "<TR>";
echo "<TD>";
echo $row_open->req_date_requested;
echo "</TD>";
echo "<TD>";
echo $row_open->req_id;
echo "-";
echo $row_open->req_item_id;
echo "</TD>";
echo "<TD>";
echo $row_open->scholar_first_name;
echo " ";
echo $row_open->scholar_last_name;
echo "</TD>";
echo "<TD>";
echo $row_open->category;
echo "</TD>";
echo "<TD>";
echo "<span class='note_text'>";
echo $row_open->option;
echo "</span>";
echo "<BR>";
if ($row_open->req_description != '')
{
echo "<BR>";
echo "<span class='note_text'>Extra Comment: ";
echo $row_open->req_description;
echo "</span>";
}
if ($row_open->req_rejection_reason != '')
{
echo "<BR>";
echo "<span class='note_text'>Rejection Reason: ";
echo $row_open->req_rejection_reason;
echo "</span>";
}
echo "</TD>";
echo "<TD>";
echo $row_open->req_amount_requested;
echo "</TD>";
echo "<TD>";
echo $row_open->req_amount_approved;
echo "</TD>";
echo "<TD>
<button type='button' id='button_request_action' class='btn btn-warning button_history' value='" . $button_value . "' data-toggle='modal' data-target='#historymodal'>
view history
</button>
</TD>";
echo "</TR>";
}
?>
</TBODY>
</TABLE>
</DIV>
</DIV>
| ivanlanuza/reallife | AC_request_view_completed_process.php | PHP | mit | 3,363 |
<?php
namespace Enqueue\Redis\Tests\Functional;
use Enqueue\Redis\RedisContext;
use Enqueue\Test\RedisExtension;
use PHPUnit\Framework\TestCase;
/**
* @group functional
*/
class PhpRedisCommonUseCasesTest extends TestCase
{
use CommonUseCasesTrait;
use RedisExtension;
/**
* @var RedisContext
*/
private $context;
protected function setUp(): void
{
$this->context = $this->buildPhpRedisContext();
$this->context->deleteQueue($this->context->createQueue('enqueue.test_queue'));
$this->context->deleteTopic($this->context->createTopic('enqueue.test_topic'));
}
protected function tearDown(): void
{
$this->context->close();
}
/**
* {@inheritdoc}
*/
protected function getContext()
{
return $this->context;
}
}
| php-enqueue/enqueue-dev | pkg/redis/Tests/Functional/PhpRedisCommonUseCasesTest.php | PHP | mit | 834 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.mod.mixin.api.text.title;
import com.google.common.base.Optional;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S45PacketTitle;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.title.Title;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.mod.text.SpongeText;
import org.spongepowered.mod.text.title.SpongeTitle;
import java.util.Arrays;
@Mixin(value = Title.class, remap = false)
public abstract class MixinTitle implements SpongeTitle {
@Shadow protected Optional<Text> title;
@Shadow protected Optional<Text> subtitle;
@Shadow protected Optional<Integer> fadeIn;
@Shadow protected Optional<Integer> stay;
@Shadow protected Optional<Integer> fadeOut;
@Shadow protected boolean clear;
@Shadow protected boolean reset;
private S45PacketTitle[] packets;
public boolean isFlowerPot() {
return false;
}
@Override
public void send(EntityPlayerMP player) {
if (this.packets == null) {
S45PacketTitle[] packets = new S45PacketTitle[5];
int i = 0;
if (this.clear) {
packets[i++] = new S45PacketTitle(S45PacketTitle.Type.CLEAR, null);
}
if (this.reset) {
packets[i++] = new S45PacketTitle(S45PacketTitle.Type.RESET, null);
}
if (this.fadeIn.isPresent() || this.stay.isPresent() || this.fadeOut.isPresent()) {
packets[i++] = new S45PacketTitle(this.fadeIn.or(20), this.stay.or(60), this.fadeOut.or(20));
}
if (this.subtitle.isPresent()) {
packets[i++] = new S45PacketTitle(S45PacketTitle.Type.SUBTITLE, ((SpongeText) this.subtitle.get()).toComponent());
}
if (this.title.isPresent()) {
packets[i++] = new S45PacketTitle(S45PacketTitle.Type.TITLE, ((SpongeText) this.title.get()).toComponent());
}
this.packets = i == packets.length ? packets : Arrays.copyOf(packets, i);
}
for (S45PacketTitle packet : this.packets) {
player.playerNetServerHandler.sendPacket(packet);
}
}
}
| SpongeHistory/Sponge-History | src/main/java/org/spongepowered/mod/mixin/api/text/title/MixinTitle.java | Java | mit | 3,524 |
package com.uberverse.arkcraft.common.item.ranged;
public class ItemSlingshot {
}
| tom5454/ARKCraft | src/main/java/com/uberverse/arkcraft/common/item/ranged/ItemSlingshot.java | Java | mit | 84 |
package fr.unice.spinefm.MSPLModel.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import fr.unice.spinefm.roassaltracer.RoassalTracer;
public class DEAssociationEndImplDelegate extends DEAssociationEndImpl {
private static int counter = 0;
public DEAssociationEndImplDelegate() {
super();
if (this.getId() == null || this.getId().equals("")) {
this.setId("DEAEnd_"+(counter++));
}
}
public void roassalTrace(Map<String, List<String>> buffer) {
if (this.getId() == null || this.getId().equals("")) {
this.setId("DEAEnd_"+(counter++));
}
if (!buffer.containsKey(RoassalTracer.ROASSAL_DEAEND))
buffer.put(RoassalTracer.ROASSAL_DEAEND, new ArrayList<String>());
RoassalTracer.callRoassalTracer(this.getLinkMultiplicity(), buffer);
String trace = RoassalTracer.ROASSAL_DEAEND+" id=\""+this.id+"\" apply_on=["+this.apply_on.getId()+"] linkMultiplicity=["+this.linkMultiplicity.getId()+"]";
buffer.get(RoassalTracer.ROASSAL_DEAEND).add(trace);
}
@Override
public String toString() {
return "DEAEnd "+this.getId();
}
}
| surli/spinefm | spinefm-eclipseplugins-root/spinefm-core/src/fr/unice/spinefm/MSPLModel/impl/DEAssociationEndImplDelegate.java | Java | mit | 1,094 |
export * from './themes';
| sinnerschrader/patternplate | components/next-generation/themes/src/index.ts | TypeScript | mit | 26 |
<?php
namespace Tasks\TaskBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class StatusType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Tasks\TaskBundle\Entity\Status'
));
}
public function getName()
{
return 'tasks_taskbundle_statustype';
}
}
| szilagyikinga/tasks_v2 | src/Tasks/TaskBundle/Form/StatusType.php | PHP | mit | 666 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG'),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://localhost',
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY', 'SomeRandomString'),
'cipher' => MCRYPT_RIJNDAEL_128,
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => 'daily',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
'Illuminate\Bus\BusServiceProvider',
'Illuminate\Cache\CacheServiceProvider',
'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
'Illuminate\Routing\ControllerServiceProvider',
'Illuminate\Cookie\CookieServiceProvider',
'Illuminate\Database\DatabaseServiceProvider',
'Illuminate\Encryption\EncryptionServiceProvider',
'Illuminate\Filesystem\FilesystemServiceProvider',
'Illuminate\Foundation\Providers\FoundationServiceProvider',
'Illuminate\Hashing\HashServiceProvider',
'Illuminate\Mail\MailServiceProvider',
'Illuminate\Pagination\PaginationServiceProvider',
'Illuminate\Pipeline\PipelineServiceProvider',
'Illuminate\Queue\QueueServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'Illuminate\Auth\Passwords\PasswordResetServiceProvider',
'Illuminate\Session\SessionServiceProvider',
'Illuminate\Translation\TranslationServiceProvider',
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Html\HtmlServiceProvider',
/*
* Application Service Providers...
*/
'App\Providers\AppServiceProvider',
'App\Providers\BusServiceProvider',
'App\Providers\ConfigServiceProvider',
'App\Providers\EventServiceProvider',
'App\Providers\RouteServiceProvider',
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => 'Illuminate\Support\Facades\App',
'Artisan' => 'Illuminate\Support\Facades\Artisan',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Blade' => 'Illuminate\Support\Facades\Blade',
'Bus' => 'Illuminate\Support\Facades\Bus',
'Cache' => 'Illuminate\Support\Facades\Cache',
'Config' => 'Illuminate\Support\Facades\Config',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'DB' => 'Illuminate\Support\Facades\DB',
'Eloquent' => 'Illuminate\Database\Eloquent\Model',
'Event' => 'Illuminate\Support\Facades\Event',
'File' => 'Illuminate\Support\Facades\File',
'Hash' => 'Illuminate\Support\Facades\Hash',
'Input' => 'Illuminate\Support\Facades\Input',
'Inspiring' => 'Illuminate\Foundation\Inspiring',
'Lang' => 'Illuminate\Support\Facades\Lang',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Password' => 'Illuminate\Support\Facades\Password',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Redirect' => 'Illuminate\Support\Facades\Redirect',
'Redis' => 'Illuminate\Support\Facades\Redis',
'Request' => 'Illuminate\Support\Facades\Request',
'Response' => 'Illuminate\Support\Facades\Response',
'Route' => 'Illuminate\Support\Facades\Route',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Session' => 'Illuminate\Support\Facades\Session',
'Storage' => 'Illuminate\Support\Facades\Storage',
'URL' => 'Illuminate\Support\Facades\URL',
'Validator' => 'Illuminate\Support\Facades\Validator',
'View' => 'Illuminate\Support\Facades\View',
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',
],
];
| SalvadorP/pacasas | config/app.php | PHP | mit | 7,233 |
module Dumpdb
class Db
DEFAULT_VALUE = ''.freeze
def initialize(dump_file_name = nil, values = nil)
dump_file_name = dump_file_name || 'dump.output'
@values = dumpdb_symbolize_keys(values)
[:host, :port, :user, :pw, :db, :output_root].each do |key|
@values[key] ||= DEFAULT_VALUE
end
@values[:output_dir] = dumpdb_build_output_dir(
self.output_root,
self.host,
self.db
)
@values[:dump_file] = File.join(self.output_dir, dump_file_name)
end
def to_hash; @values; end
def method_missing(meth, *args, &block)
if @values.has_key?(meth.to_sym)
@values[meth.to_sym]
else
super
end
end
def respond_to?(meth)
@values.has_key?(meth.to_sym) || super
end
private
def dumpdb_build_output_dir(output_root, host, database)
dir_name = dumpdb_build_output_dir_name(host, database)
if output_root && !output_root.to_s.empty?
File.join(output_root, dir_name)
else
dir_name
end
end
def dumpdb_build_output_dir_name(host, database)
[host, database, Time.now.to_f].map(&:to_s).reject(&:empty?).join("__")
end
def dumpdb_symbolize_keys(values)
(values || {}).inject({}) do |h, (k, v)|
h.merge(k.to_sym => v)
end
end
end
end
| redding/dumpdb | lib/dumpdb/db.rb | Ruby | mit | 1,367 |
module My
module Github
module Projects
VERSION = "1.0.0"
end
end
end
| drnic/my_github_projects | lib/my_github_projects/version.rb | Ruby | mit | 88 |