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 clusterconf
import (
"encoding/json"
"fmt"
"math/rand"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/cerana/cerana/acomm"
"github.com/cerana/cerana/pkg/errors"
)
const bundlesPrefix string = "bundles"
// BundleDatasetType is the type of dataset to be used in a bundle.
type BundleDatasetType int
// Valid bundle dataset types
const (
RWZFS = iota
TempZFS
RAMDisk
)
// Bundle is information about a bundle of services.
type Bundle struct {
c *ClusterConf
ID uint64 `json:"id"`
Datasets map[string]BundleDataset `json:"datasets"`
Services map[string]BundleService `json:"services"`
Redundancy uint64 `json:"redundancy"`
Ports BundlePorts `json:"ports"`
// ModIndex should be treated as opaque, but passed back on updates.
ModIndex uint64 `json:"modIndex"`
}
// BundlePorts is a map of port numbers to port information.
type BundlePorts map[int]BundlePort
// MarshalJSON marshals BundlePorts into a JSON map, converting int keys to
// strings.
func (p BundlePorts) MarshalJSON() ([]byte, error) {
ports := make(map[string]BundlePort)
for port, value := range p {
ports[strconv.Itoa(port)] = value
}
j, err := json.Marshal(ports)
return j, errors.Wrap(err)
}
// UnmarshalJSON unmarshals JSON into a BundlePorts, converting string keys to
// ints.
func (p BundlePorts) UnmarshalJSON(data []byte) error {
ports := make(map[string]BundlePort)
if err := json.Unmarshal(data, &ports); err != nil {
return errors.Wrapv(err, map[string]interface{}{"json": string(data)})
}
p = make(BundlePorts)
for port, value := range ports {
portI, err := strconv.Atoi(port)
if err != nil {
return errors.Wrapv(err, map[string]interface{}{"port": port})
}
p[portI] = value
}
return nil
}
// BundleDataset is configuration for a dataset associated with a bundle.
type BundleDataset struct {
Name string `json:"name"`
ID string `json:"id"`
Type BundleDatasetType `json:"type"`
Quota uint64 `json:"type"`
}
func (d BundleDataset) overlayOn(base *Dataset) (BundleDataset, error) {
if d.ID != base.ID {
return d, errors.Newv("dataset ids do not match", map[string]interface{}{
"bundleDatasetID": d.ID,
"datasetID": base.ID,
})
}
// overlay data
if d.Quota <= 0 {
d.Quota = base.Quota
}
return d, nil
}
// BundleService is configuration overrides for a service of a bundle and
// associated bundles.
type BundleService struct {
ServiceConf
Datasets map[string]ServiceDataset `json:"datasets"`
}
func (s BundleService) overlayOn(base *Service) (BundleService, error) {
if s.ID != base.ID {
return s, errors.Newv("service ids do not match", map[string]interface{}{
"bundleServiceID": s.ID,
"serviceID": base.ID,
})
}
// maps are pointers, so need to be duplicated separately.
result := s
result.Datasets = make(map[string]ServiceDataset)
for k, v := range s.Datasets {
result.Datasets[k] = v
}
result.HealthChecks = make(map[string]HealthCheck)
for k, v := range s.HealthChecks {
result.HealthChecks[k] = v
}
result.Env = make(map[string]string)
for k, v := range s.Env {
result.Env[k] = v
}
// overlay data
if result.Dataset == "" {
result.Dataset = base.Dataset
}
if result.Limits.CPU <= 0 {
result.Limits.CPU = base.Limits.CPU
}
if result.Limits.Memory <= 0 {
result.Limits.Memory = base.Limits.Memory
}
if result.Limits.Processes <= 0 {
result.Limits.Processes = base.Limits.Processes
}
for id, hc := range base.HealthChecks {
_, ok := result.HealthChecks[id]
if !ok {
result.HealthChecks[id] = hc
continue
}
}
for key, val := range base.Env {
_, ok := result.Env[key]
if !ok {
result.Env[key] = val
}
}
if result.Cmd == nil {
result.Cmd = base.Cmd
}
return result, nil
}
// ServiceDataset is configuration for mounting a dataset for a bundle service.
type ServiceDataset struct {
Name string `json:"name"`
MountPoint string `json:"mountPoint"`
ReadOnly bool `json:"readOnly"`
}
// BundlePort is configuration for a port associated with a bundle.
type BundlePort struct {
Port int `json:"port"`
Public bool `json:"public"`
ConnectedBundles []string `json:"connectedBundles"`
ExternalPort int `json:"externalPort"`
}
// DeleteBundleArgs are args for bundle delete task.
type DeleteBundleArgs struct {
ID uint64 `json:"id"`
}
// GetBundleArgs are args for retrieving a bundle.
type GetBundleArgs struct {
ID uint64 `json:"id"`
CombinedOverlay bool `json:"overlay"`
}
// ListBundleArgs are args for retrieving a bundle list.
type ListBundleArgs struct {
CombinedOverlay bool `json:"overlay"`
}
// BundlePayload can be used for task args or result when a bundle object needs
// to be sent.
type BundlePayload struct {
Bundle *Bundle `json:"bundle"`
}
// BundleListResult is the result from listing bundles.
type BundleListResult struct {
Bundles []*Bundle `json:"bundles"`
}
// GetBundle retrieves a bundle.
func (c *ClusterConf) GetBundle(req *acomm.Request) (interface{}, *url.URL, error) {
var args GetBundleArgs
if err := req.UnmarshalArgs(&args); err != nil {
return nil, nil, err
}
if args.ID == 0 {
return nil, nil, errors.Newv("missing arg: id", map[string]interface{}{"args": args})
}
bundle, err := c.getBundle(args.ID)
if err != nil {
return nil, nil, err
}
if args.CombinedOverlay {
bundle, err = bundle.combinedOverlay()
if err != nil {
return nil, nil, err
}
}
return &BundlePayload{bundle}, nil, nil
}
// ListBundles retrieves a list of all bundles.
func (c *ClusterConf) ListBundles(req *acomm.Request) (interface{}, *url.URL, error) {
var args ListBundleArgs
if err := req.UnmarshalArgs(&args); err != nil {
return nil, nil, err
}
keys, err := c.kvKeys(bundlesPrefix)
if err != nil {
return nil, nil, err
}
// extract and deduplicate the bundle ids
ids := make(map[uint64]bool)
keyFormat := filepath.Join(bundlesPrefix, "%d")
for _, key := range keys {
var id uint64
_, err := fmt.Sscanf(key, keyFormat, &id)
if err != nil {
return nil, nil, errors.Newv("failed to extract valid bundle id", map[string]interface{}{"key": key, "keyFormat": keyFormat})
}
ids[id] = true
}
var wg sync.WaitGroup
bundleChan := make(chan *Bundle, len(ids))
errChan := make(chan error, len(ids))
for id := range ids {
wg.Add(1)
go func(id uint64) {
defer wg.Done()
bundle, err := c.getBundle(id)
if err != nil {
errChan <- err
return
}
if args.CombinedOverlay {
bundle, err = bundle.combinedOverlay()
if err != nil {
errChan <- err
return
}
}
bundleChan <- bundle
}(id)
}
wg.Wait()
close(bundleChan)
close(errChan)
if len(errChan) > 0 {
err := <-errChan
return nil, nil, err
}
bundles := make([]*Bundle, 0, len(bundleChan))
for bundle := range bundleChan {
bundles = append(bundles, bundle)
}
return &BundleListResult{
Bundles: bundles,
}, nil, nil
}
// UpdateBundle creates or updates a bundle config. When updating, a Get should first be performed and the modified Bundle passed back.
func (c *ClusterConf) UpdateBundle(req *acomm.Request) (interface{}, *url.URL, error) {
var args BundlePayload
if err := req.UnmarshalArgs(&args); err != nil {
return nil, nil, err
}
if args.Bundle == nil {
return nil, nil, errors.Newv("missing arg: bundle", map[string]interface{}{"args": args})
}
args.Bundle.c = c
if args.Bundle.ID == 0 {
rand.Seed(time.Now().UnixNano())
args.Bundle.ID = uint64(rand.Int63())
}
if err := args.Bundle.update(); err != nil {
return nil, nil, err
}
return &BundlePayload{args.Bundle}, nil, nil
}
// DeleteBundle deletes a bundle config.
func (c *ClusterConf) DeleteBundle(req *acomm.Request) (interface{}, *url.URL, error) {
var args DeleteBundleArgs
if err := req.UnmarshalArgs(&args); err != nil {
return nil, nil, err
}
if args.ID == 0 {
return nil, nil, errors.Newv("missing arg: id", map[string]interface{}{"args": args})
}
bundle, err := c.getBundle(args.ID)
if err != nil {
if strings.Contains(err.Error(), "bundle config not found") {
return nil, nil, nil
}
return nil, nil, err
}
return nil, nil, bundle.delete()
}
func (c *ClusterConf) getBundle(id uint64) (*Bundle, error) {
bundle := &Bundle{
c: c,
ID: id,
}
if err := bundle.reload(); err != nil {
return nil, err
}
return bundle, nil
}
func (b *Bundle) reload() error {
var err error
key := path.Join(bundlesPrefix, strconv.FormatUint(b.ID, 10), "config")
value, err := b.c.kvGet(key)
if err != nil {
if strings.Contains(err.Error(), "key not found") {
err = errors.Newv("bundle config not found", map[string]interface{}{"bundleID": b.ID})
}
return err
}
if err = json.Unmarshal(value.Data, &b); err != nil {
return errors.Wrapv(err, map[string]interface{}{"json": string(value.Data)})
}
b.ModIndex = value.Index
return nil
}
func (b *Bundle) delete() error {
key := path.Join(bundlesPrefix, strconv.FormatUint(b.ID, 10))
return errors.Wrapv(b.c.kvDelete(key, b.ModIndex), map[string]interface{}{"bundleID": b.ID})
}
// update saves the core bundle config.
func (b *Bundle) update() error {
key := path.Join(bundlesPrefix, strconv.FormatUint(b.ID, 10), "config")
index, err := b.c.kvUpdate(key, b, b.ModIndex)
if err != nil {
return errors.Wrapv(err, map[string]interface{}{"bundleID": b.ID})
}
b.ModIndex = index
return nil
}
// combinedOverlay will create a new *Bundle object containing the base configurations of datasets and services with the bundle values overlayed on top.
// Note: Attempting to save a combined overlay bundle will result in an error.
func (b *Bundle) combinedOverlay() (*Bundle, error) {
var wg sync.WaitGroup
errorChan := make(chan error, len(b.Datasets)+len(b.Services))
defer close(errorChan)
// duplicate bundle using json to also duplicate the map field values
var result Bundle
tmp, err := json.Marshal(b)
if err != nil {
return nil, errors.Wrapv(err, map[string]interface{}{"bundle": b}, "failed to marshal bundle")
}
if err := json.Unmarshal(tmp, &result); err != nil {
return nil, errors.Wrapv(err, map[string]interface{}{"bundle": b, "json": string(tmp)}, "failed to unmarshal bundle")
}
result.Datasets = make(map[string]BundleDataset)
for k, v := range b.Datasets {
result.Datasets[k] = v
}
result.Services = make(map[string]BundleService)
for k, v := range b.Services {
result.Services[k] = v
}
result.Ports = make(BundlePorts)
for k, v := range b.Ports {
result.Ports[k] = v
}
for i, d := range b.Datasets {
wg.Add(1)
go func(id string, bd BundleDataset) {
defer wg.Done()
dataset, err := b.c.getDataset(id)
if err != nil {
errorChan <- err
return
}
combined, err := bd.overlayOn(dataset)
if err != nil {
errorChan <- err
return
}
result.Datasets[id] = combined
}(i, d)
}
for i, s := range b.Services {
wg.Add(1)
go func(id string, bs BundleService) {
defer wg.Done()
service, err := b.c.getService(id)
if err != nil {
errorChan <- err
return
}
combined, err := bs.overlayOn(service)
if err != nil {
errorChan <- err
return
}
result.Services[id] = combined
}(i, s)
}
wg.Wait()
if len(errorChan) == 0 {
return &result, nil
}
errs := make([]error, len(errorChan))
Loop:
for {
select {
case err := <-errorChan:
errs = append(errs, err)
default:
break Loop
}
}
return nil, errors.Newv("bundle overlay failed", map[string]interface{}{"bundleID": b.ID, "errors": errs})
}
| cerana/cerana | providers/clusterconf/bundle.go | GO | mit | 11,671 |
/* global expect */
describe('outputFormat', () => {
describe('when given a format', () => {
it('decides the output that will be used for serializing errors', () => {
expect(
function () {
const clonedExpect = expect.clone().outputFormat('html');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
htmlMessage:
'<div style="font-family: monospace; white-space: nowrap">' +
'<div><span style="color: red; font-weight: bold">expected</span> <span style="color: #0086b3">42</span> <span style="color: red; font-weight: bold">to equal</span> <span style="color: #0086b3">24</span></div>' +
'</div>',
}
);
expect(
function () {
const clonedExpect = expect.clone().outputFormat('ansi');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
message:
'\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24\n',
}
);
});
});
});
| unexpectedjs/unexpected | test/api/outputFormat.spec.js | JavaScript | mit | 1,096 |
require 'json'
require 'net/http'
require 'open-uri'
require 'uri'
require 'ostruct'
module DismalTony # :nodoc:
# Umbrella module for all mixins for Directives
module DirectiveHelpers
# Basic template , adds the inheritence methods through metaprogramming so
# that n-children inherit class methods and instance methods apropriately.
module HelperTemplate
# Special case, only includes the class methods here.
def self.included(base)
base.extend(ClassMethods)
end
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# Adds the inclusion method to the class this class is included on,
# So that its n-children inherit class methods
def included(base)
base.send(:include, const_get(:InstanceMethods))
base.extend const_get(:ClassMethods)
end
end
end
# Basic helpers that make the Directives function
module CoreHelpers
include HelperTemplate
# Basic helpers that make the Directives function
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# DSL function, sets the Directives +name+ to +param+
def set_name(param)
@name = param
end
# DSL function, sets the Directives +group+ to +param+
def set_group(param)
@group = param
end
# DSL function, adds a new entry to the +parameters+ hash keyed by +param+ and given a value of +initial+.
def add_param(param, initial = nil)
@default_params ||= {}
@default_params[param.to_sym] = initial
end
# DSL function, takes each key-value pair in +inputpar+ and adds a new entry to
# the +parameters+ hash keyed by +param+ and given a value of +initial+.
def add_params(inputpar)
inputpar.each do |ki, va|
@default_params[ki] = va
end
end
# Yields the +criteria+ array, and uses the +block+ to add its results to
# +match_criteria+ afterwards, allowing you to add new MatchLogic objects using the DSL.
def add_criteria
crit = []
yield crit
@match_criteria ||= []
@match_criteria += crit
end
# Returns an Errored directive, using +qry+ and +vi+ to construct the new Directive
def error(qry, vi)
me = new(qry, vi)
me.query.complete(self, HandledResponse.error)
end
end
# Basic helpers that make the Directives function
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
end
end
# Utility functions to help construct responses easier.
module ConversationHelpers
include HelperTemplate
# Utility functions to help construct responses easier.
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# Takes in Hash<Regexp, Array<String>> and adds them to the synonyms
def add_synonyms # :yields: synonyms
new_syns = {}
yield new_syns
synonyms.merge!(new_syns)
end
# The array of synonyms available for using #synonym_for
def synonyms
@synonyms ||= {
/^awesome$/i => %w[great excellent cool awesome splendid],
/^okay$/i => %w[okay great alright],
/^hello$/i => %w[hello hi greetings],
/^yes$/i => %w[yes affirmative definitely correct certainly],
/^no$/i => %w[no negative incorrect false],
/^update$/i => %w[update change modify revise alter edit adjust],
/^updated$/i => %w[updated changed modified revised altered edited adjusted],
/^add$/i => %w[add create],
/^added$/i => %w[added created],
/^what|how$/i => %w[how what]
}
end
end
# Utility functions to help construct responses easier.
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
# Given a string, scans through the synonym array for any potential synonyms.
def synonym_for(word)
resp = nil
synonyms.each do |reg, syns|
resp = word =~ reg ? syns.sample : nil
return resp if resp
end
word
end
# Instance hook for the class method
def synonyms
@synonyms ||= self.class.synonyms
@synonyms
end
end
end
# Assists with emoji selection
module EmojiHelpers
include HelperTemplate
# Assists with emoji selection
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
# Chooses randomly from +moj+, or if no arguments are passed randomly from all emoji.
def random_emoji(*moj)
if moj.length.zero?
DismalTony::EmojiDictionary.emoji_table.keys.sample
else
moj.sample
end
end
# Returns randomly from a predefined set of positiveemoji
def positive_emoji
%w[100 checkbox star thumbsup rocket].sample
end
# Returns randomly from a predefined set of negative emoji
def negative_emoji
%w[cancel caution frown thumbsdown siren].sample
end
# Returns randomly from a predefined set of face emoji
def random_face_emoji
%w[cool goofy monocle sly smile think].sample
end
# Returns randomly from a predefined set of time emoji
def time_emoji
%w[clockface hourglass alarmclock stopwatch watch].sample
end
end
end
# Mixin for JSON-based web APIs.
module JSONAPIHelpers
include HelperTemplate
# Mixin for JSON-based web APIs.
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# Takes in a block +blk+ and calculates it later to ensure late ENV access
def set_api_defaults(&blk)
@api_defaults_proc = blk
end
# Retrieves the block from #set_api_defaults and calls it.
def get_api_defaults
res = {}
@api_defaults_proc.call(res)
res
end
# Gets the api_defaults
def api_defaults
@api_defaults ||= get_api_defaults
end
# Sets the api_defaults
def api_defaults=(newval)
@api_defaults = newval
end
# Gets the api_url
def api_url
@api_url
end
# Sets the api_url
def api_url=(newval)
@api_url = newval
end
# DSL method for setting the api_url
def set_api_url(url)
@api_url = url
end
end
# Mixin for JSON-based web APIs.
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
# Instance hook for the api_url
def api_url
@api_url ||= self.class.api_url
@api_url
end
# Sets the api_url
def api_url=(new_value)
@api_url = new_value
end
# Generates an API request from the provided data to this mixin.
# Parses and returns the JSON body of a request, intelligently merging
# given arguments in +input_args+ and the #api_defaults
def api_request(input_args)
addr = URI(api_url)
parms = input_args.clone
parms = api_defaults.merge(parms)
addr.query = URI.encode_www_form(parms)
JSON.parse(Net::HTTP.get(addr))
end
# Instance hook for api_defaults
def api_defaults
@api_defaults ||= self.class.api_defaults
@api_defaults
end
# Sets api_defaults
def api_defaults=(new_value)
@api_defaults = new_value
end
end
end
# Provides simpler access to DataStore#directive_data, and streamlines
# defining and creating structs to put in it.
module DataStructHelpers
include HelperTemplate
# Provides simpler access to DataStore#directive_data, and streamlines
# defining and creating structs to put in it.
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# Takes in a block returning a Struct, where user schema is defined.
def define_data_struct
@data_struct_template = yield
end
# Gets data_struct_template
def data_struct_template
@data_struct_template
end
# Sets data_struct_template
def data_struct_template=(newval)
@data_struct_template = newval
end
end
# Provides simpler access to DataStore#directive_data, and streamlines
# defining and creating structs to put in it.
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
# Uses the Directive's name, and any passed values to dig into the directive data
def get_stored_data(*ky)
vi.data_store.read_data(name, *ky)
end
# In this Directive's storage, stores +ky+ with a value of +v+.
# If a block is given, passes it to #data_struct and uses that as the value.
def store_data(ky, v = nil, &block)
if block_given?
vi.data_store.store_data(directive: name, key: ky, value: data_struct(&block))
else
vi.data_store.store_data(directive: name, key: ky, value: v)
end
end
# Takes in arguments to create a new struct. If no #data_struct_template is defined,
# It creates an OpenStruct instead. Otherwise, correctly maps values to the struct.
def data_struct # :yields: arguments
ud_args = {}
yield ud_args
if data_struct_template.nil?
OpenStruct.new(ud_args)
else
args_list = data_struct_template.members.map { |a| ud_args[a] }
data_struct_template.new(*args_list)
end
end
# Instance hook for the data struct template
def data_struct_template
@data_struct_template ||= self.class.data_struct_template
@data_struct_template
end
# Sets the data struct template
def data_struct_template=(newval)
@data_struct_template = newval
end
end
end
# Provides a mechanism to return rich values from responses
module DataRepresentationHelpers
include HelperTemplate
# Provides a mechanism to return rich values from responses
# Contains the Class methods of the helper, which are added on inclusion
module ClassMethods
# Defines a default data representation
def define_data_representation
@data_representation = yield
end
# Gets data_representation
def data_representation
@data_representation
end
# Sets data_representation to +new_val+
def data_representation=(new_val)
@data_representation = new_val
end
end
# Provides a mechanism to return rich values from responses
# Contains the Instance methods of the helper, which are added on inclusion
module InstanceMethods
# Instance hook for data_representation
def data_representation
@data_representation ||= self.class.data_representation
@data_representation ||= parameters
@data_representation ||= OpenStruct.new
@data_representation
end
# Sets data_representation to +new_val+
def data_representation=(new_val)
@data_representation = new_val
end
# DSL method, overwrites data representation
def return_data(data)
@data_representation = data
end
end
end
end
end
| jtp184/DismalTony | lib/dismaltony/directive_helpers.rb | Ruby | mit | 12,093 |
'use strict';
const fs = require('fs');
const remote = require('electron').remote;
const mainProcess = remote.require('./main');
module.exports = {
template: `
<v-list dense class="pt-0">
<v-list-tile to="recent-projects" :router="true">
<v-list-tile-action>
<v-icon>list</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="recent-projects">Recent projects</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="existingProject">
<v-list-tile-action>
<v-icon>folder_open</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-project">Add existing project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="create-project" :router="true">
<v-list-tile-action>
<v-icon>create_new_folder</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="create-project">Create new project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="globalProject" v-if="globalComposerFileExists">
<v-list-tile-action>
<v-icon>public</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="global-composer">Global composer</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="settings" :router="true">
<v-list-tile-action>
<v-icon>settings</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-settings">Settings</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
`,
computed: {
globalComposerFileExists() {
return fs.existsSync(remote.app.getPath('home') + '/.composer');
}
},
methods: {
existingProject: () => {
mainProcess.openDirectory();
},
globalProject: () => {
mainProcess.openProject(remote.app.getPath('home') + '/.composer');
},
}
}
| mglaman/conductor | src/components/MainNavigation.js | JavaScript | mit | 1,947 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sl_SI" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About AmeroX</source>
<translation>O AmeroX</translation>
</message>
<message>
<location line="+39"/>
<source><b>AmeroX</b> version</source>
<translation><b>AmeroX</b> verzija</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The AmeroX developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
To je poizkusen softver.
Distribuiran pod MIT/X11 softversko licenco, glej priloženo datoteko COPYING ali http://www.opensource.org/licenses/mit-license.php.
Ta proizvod vključuje softver razvit s strani projekta OpenSSL za uporabo v OpenSSL Toolkit (http://www.openssl.org/) in kriptografski softver, ki ga je napisal Eric Young (eay@cryptsoft.com), ter UPnP softver, ki ga je napisal Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Imenik</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dvakrat kliknite za urejanje naslovov ali oznak</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Ustvari nov naslov</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopiraj trenutno izbrani naslov v odložišče</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nov naslov</translation>
</message>
<message>
<location line="-46"/>
<source>These are your AmeroX addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>To so vaši AmeroX naslovi za prejemanje plačil. Priporočeno je da vsakemu pošiljatelju namenite drugega in tako dobite večji pregled nad svojimi nakazili.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Kopiraj naslov</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Prikaži &QR kodo</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a AmeroX address</source>
<translation>Podpišite sporočilo, kot dokazilo lastništva AmeroX naslova</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Podpiši &sporočilo</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Izbriši izbran naslov iz seznama</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified AmeroX address</source>
<translation>Potrdi sporočilo, da zagotovite, da je bilo podpisano z izbranim AmeroX naslovom</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Potrdi sporočilo</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Izbriši</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Kopiraj &oznako</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Uredi</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Izvozi podatke imenika</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Datoteka s podatki, ločenimi z vejico (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Napaka pri izvozu datoteke</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Napaka pri pisanju na datoteko %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Oznaka</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Naslov</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ni oznake)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Poziv gesla</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Vnesite geslo</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Novo geslo</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Ponovite novo geslo</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Služi kot onemogočenje pošiljanja prostega denarja, v primerih okužbe operacijskega sistema. Ne ponuja prave zaščite.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Samo za staking.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Vnesite novo geslo za vstop v denarnico.<br/>Prosimo, da geslo sestavite iz <b> 10 ali več naključnih znakov</b> oz. <b>osem ali več besed</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Šifriraj denarnico</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>To dejanje zahteva geslo za odklepanje vaše denarnice.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Odkleni denarnico</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>To dejanje zahteva geslo za dešifriranje vaše denarnice.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dešifriraj denarnico</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Zamenjaj geslo</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Vnesite staro in novo geslo denarnice.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Potrdi šifriranje denarnice</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Opozorilo: Če šifrirate svojo denarnico in izgubite svoje geslo, boste <b> IZGUBILI VSE SVOJE KOVANCE</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ali ste prepričani, da želite šifrirati vašo denarnico?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>POMEMBNO: Vsaka predhodna varnostna kopija datoteke denarnice mora biti nadomeščena z novo datoteko šifrirane denarnice. Zaradi varnostnih razlogov bodo namreč prejšnje varnostne kopije datoteke nešifrirane denarnice postale neuporabne takoj ko boste pričeli uporabljati novo, šifrirano denarnico.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Opozorilo: imate prižgan Cap Lock</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Denarnica šifrirana</translation>
</message>
<message>
<location line="-58"/>
<source>AmeroX will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>AmeroX se bo sedaj zaprl, da dokonča proces šifriranje. Pomnite, da tudi šifriranje vaše denarnice ne more v celoti zaščititi vaših kovancev pred krajo z zlonamernimi programi in računalniškimi virusi, če ti okužijo vaš računalnik.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Šifriranje denarnice je spodletelo</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Šifriranje denarnice spodletelo je zaradi notranje napake. Vaša denarnica ni šifrirana.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Vnešeno geslo se ne ujema</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Odklep denarnice spodletel</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Geslo za dešifriranje denarnice, ki ste ga vnesli, ni pravilno.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dešifriranje denarnice je spodletelo</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Geslo denarnice je bilo uspešno spremenjeno.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Podpiši &sporočilo ...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Sinhroniziranje z omrežjem ...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Pregled</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Pokaži splošen pregled denarnice</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transakcije</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Brskaj po zgodovini transakcij</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Imenik</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Uredi seznam shranjenih naslovov in oznak</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Prejmi kovance</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Prikaži seznam naslovov za prejemanje plačil. </translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&Pošlji kovance</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>I&zhod</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Izhod iz aplikacije</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about AmeroX</source>
<translation>Pokaži informacije o AmeroX</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>O &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Prikaži informacije o Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Možnosti ...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Šifriraj denarnico ...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Ustvari varnostno kopijo denarnice ...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Spremeni geslo ...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>Ostaja ~%n bloka </numerusform><numerusform>Ostaja ~%n blokov</numerusform><numerusform>Ostaja ~%n blokov</numerusform><numerusform>Ostaja ~%n blokov </numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Prenešen %1 od %2 blokov transakcijske zgodovine (%3% opravljeno).</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>&Izvozi...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a AmeroX address</source>
<translation>Pošlji kovance na AmeroX naslov</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for AmeroX</source>
<translation>Spremeni nastavitve za AmeroX</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Izvozi podatke v izbranem zavihku v datoteko</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Šifriraj ali dešifriraj denarnico</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Napravi varnostno kopijo denarnice na drugo lokacijo</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Spremeni šifrirno geslo denarnice</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Razhroščevalno okno</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Odpri razhroščevalno in diagnostično konzolo</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>%Potrdi sporočilo ...</translation>
</message>
<message>
<location line="-202"/>
<source>AmeroX</source>
<translation>AmeroX</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Denarnica</translation>
</message>
<message>
<location line="+180"/>
<source>&About AmeroX</source>
<translation>&O AmeroX</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Prikaži / Skrij</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>Odkleni denarnico</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Zakleni denarnico</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Zakleni denarnico</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Datoteka</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Nastavitve</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Pomoč</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Orodna vrstica zavihkov</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Orodna vrsticai</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>AmeroX client</source>
<translation>AmeroX program</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to AmeroX network</source>
<translation><numerusform>%n aktivne povezave na AmeroX omrežje</numerusform><numerusform>%n aktivnih povezav na AmeroX omrežje</numerusform><numerusform>%n aktivnih povezav na AmeroX omrežje</numerusform><numerusform>%n aktivnih povezav na AmeroX omrežje</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Prenešenih %1 blokov transakcijske zgodovine.</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Deležeje [Staking].<br>Teža vašega deleženja je %1<br>Teža celotne mreže deleženja je %2<br>Pričakovan čas do prejema nagrade %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Ne deležite ker je denarnica zakljenjena</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Ne deležite ker denarnica ni povezana</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Ne deležite ker se denarnica sinhronizira z omrežjem</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Ne deležite ker nimate zrelih kovancev. </translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>pred %n sekundo</numerusform><numerusform>pred %n sekundama</numerusform><numerusform>pred %n sekundami</numerusform><numerusform>pred %n sekundami </numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About AmeroX card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about AmeroX card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>&Odkleni denarnico...</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>Pred %n minuto</numerusform><numerusform>Pred %n minutama</numerusform><numerusform>Pred %n minutami</numerusform><numerusform>Pred %n minutami</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>Pred %n uro.</numerusform><numerusform>Pred %n urama.</numerusform><numerusform>Pred %n urami.</numerusform><numerusform>Pred %n urami.</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>Pred %n dnevom.</numerusform><numerusform>Pred %n dnevoma.</numerusform><numerusform>Pred %n dnevi.</numerusform><numerusform>Pred %n dnevi.</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Posodobljeno</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Pridobivanje ...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Zadnji prejeti blok je bil ustvarjen %1.</translation>
</message>
<message>
<location line="+59"/>
<source>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?</source>
<translation>Ta transakcija je prekoračila limit. Še vedno jo lahko pošljete za plačilo %1 transakcije, ki je plačano vsem delom omrežja kot deležnina in pomaga zagotavljati njegovo varnost. Ali želite plačati provizijo?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Potrdi transakcijsko provizijo</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Odlivi</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Prilivi</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Količina: %2
Vrsta: %3
Naslov: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>Rokovanje z URI</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid AmeroX address or malformed URI parameters.</source>
<translation>URI ne more biti razčlenjen! To se lahko zgodi zaradi neveljavnega AmeroX naslova ali slabih parametrov URI.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Denarnica je <b>šifrirana</b> in trenutno <b>odklenjena</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Denarnica je <b>šifrirana</b> in trenutno <b>zaklenjena</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Napravi varnostno kopijo denarnice</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Datoteka denarnice (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Ustvarjanje varnostne kopije je spodeltelo </translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Prišlo je do napake ob poskušanju shranjevanja datoteke denarnice na novo lokacijo.</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n sekundo</numerusform><numerusform>%n sekundama</numerusform><numerusform>%n sekund</numerusform><numerusform>%n sekund</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minuto</numerusform><numerusform>%n minutama</numerusform><numerusform>%n minut</numerusform><numerusform>%n minut</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ura</numerusform><numerusform>%n uri</numerusform><numerusform>%n ure</numerusform><numerusform>%n ura</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dan</numerusform><numerusform>%n dneva</numerusform><numerusform>%n dnevi</numerusform><numerusform>%n dni</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>Ne deležite</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. AmeroX can no longer continue safely and will quit.</source>
<translation>Prišlo je do usodne napake. Program AmeroX se ne more več varno nadaljevati in se bo zato zaprl. </translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Omrežno Opozorilo</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Kontrola kovancev</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Količina:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Biti:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Količina:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prednostno mesto:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Provizija:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Nizek output:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>ne</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Po proviziji:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Sprememba:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>od/obkljukaj vse</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Drevo</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Seznam</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Količina</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Oznaka</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Naslov</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Potrdila</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Potrjeno</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prednostno mesto</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Kopiraj naslov</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopiraj oznako</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopiraj količino</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopiraj ID transakcije</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopiraj količino</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopiraj provizijo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopiraj po proviziji</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopiraj bite</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopiraj prednostno mesto</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopiraj nizek output:</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopiraj spremembo</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>najvišja</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>visoka</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>srednje visoka</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>srednje</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>srednje nizka</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>nizka</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>najnižja</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>PRAH</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>da</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Ta oznakla se obarva rdeče, če je transakcija večja od 10000 bajtov.
To pomeni, da je zahtevana provizija vsaj %1 na kb.
Lahko variira +/- 1 Bajt na vnos.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Transakcije z višjo prioriteto imajo višjo verjetnost, da so vključene v blok.
Ta oznaka se obarva rdeče, če je prioriteta manjša kot "srednja".
To pomeni, da je zahtevana provizija vsaj %1 na kb.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Ta oznaka se obarva rdeče, če prejemnik dobi količino manjšo od %1.
To pomeni, da je potrebna vsaj %2 provizija.
Zneski pod 0.546 krat minimalna transakcijska provizija so prikazani kot PRAH.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Ta oznakla se obarva rdeče, če je sprememba manjša od %1.
To pomeni, da je zahtevana provizija vsaj %2.</translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(ni oznake)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>spremeni iz %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(spremeni)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Uredi naslov</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Oznaka</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Oznaka povezana s tem vnosom v imeniku</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Naslov</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Naslov povezan s tem vnosom v imeniku. Spremenite ga lahko le za naslove odlivov.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nov naslov za prilive</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nov naslov za odlive</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Uredi naslov za prilive</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Uredi naslov za odlive</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Vnešeni naslov "&1" je že v imeniku.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid AmeroX address.</source>
<translation>Vneseni naslov "%1" ni veljaven AmeroX naslov.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Denarnice ni bilo mogoče odkleniti.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Ustvarjanje novega ključa je spodletelo.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>AmeroX-Qt</source>
<translation>AmeroX-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>različica</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uporaba:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>možnosti ukazne vrstice</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>možnosti uporabniškega vmesnika</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nastavi jezik, npr. "sl_SI" (privzeto: jezikovna oznaka sistema)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Zaženi pomanjšano</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Prikaži splash screen ob zagonu (default: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Možnosti</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Glavno</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Izbirne transakcijske provizije za kB, ki pomagajo pri tem, da so vaše transakcije procesirane hitreje. Večina transakcij je velikih 1 kB. Priporočena je provizija 0.01.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Nakazilo plačila & provizija</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Rezervirana količina ne deleži in je tako na voljo za potrošnjo.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Rezerva</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start AmeroX after logging in to the system.</source>
<translation>Avtomatično zaženi AmeroX ob zagonu sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start AmeroX on system login</source>
<translation>&Zaženi AmeroX ob prijavi v sistem</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Loči podatkovne baze blokov in naslovov ob zaustavitvi. To pomeni da jih lahko prenesete na drugo lokacijo, a upočasni zaustavitev. Denarnica je vedno ločena. </translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>&Loči podatkovne baze ob zaustavitvi</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Omrežje</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the AmeroX client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Avtomatično odpri vrata na routerju za AmeroX program. To deluje le če vaš router podpira UPnP in je ta omogočen. </translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Začrtaj vrata z &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the AmeroX network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Poveži se na AmeroX omrežje skozi SOCKS proxy (npr. ko se povezujete prek Tora)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Poveži se skozi SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP naslov proxy strežnika (npr. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Vrata:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Vrata strežnika (npr.: 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &različica:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS različica proxya (npr.: 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Okno</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Ob pomanjšanju okna prikaži le ikono v odlagališču.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Pomanjšaj v odlagališče namesto v opravilno vrstico</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Pomanjšaj aplikacijo, ko je okno zaprto. Ko je omogočena ta možnost lahko aplikacijo zaprete le tako, da izberete Izhod v meniju.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>P&omanjšaj ko zapreš</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Prikaz</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Uporabniški vmesnik &jezik:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting AmeroX.</source>
<translation>Tu lahko nastavite jezik uporabniškega vmesnika. Nastavitve bodo pričele delovati ob ponovnem zagonu AmeroX aplikacije. </translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enota prikaza količin:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Izberite privzeto delitev enot, ki naj bodo prikazane v vmesniku ob pošiljanju kovancev.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show AmeroX addresses in the transaction list or not.</source>
<translation>Izbira prikaza AmeroX naslovov v seznamu transakcij.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Prikaz naslovov v seznamu transakcij</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Izbira prikaza lastnosti kontrole kovancev.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Prikaži lastnosti &kontrole kovancev (samo za strokovnjake!)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Potrdi</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Prekini</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Uporabi</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>privzeto</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Opozorilo</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting AmeroX.</source>
<translation>Ta nastavitev bo pričela delovati ob ponovnem zagonu AmeroX aplikacije</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Podan naslov proxy strežnika je neveljaven.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Oblika</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the AmeroX network after a connection is established, but this process has not completed yet.</source>
<translation>Prikazane informacije so morda zastarele. Vaša denarnica se avtomatično sinhronizira z AmeroX omrežjem, ko je vzpostavljena povezava, toda ta proces še ni bil zaključen.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>Deleženje:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nepotrjeni:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Denarnica</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Razpoložljivi:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Vaše trenutno razpoložljivo stanje</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Nezreli:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Z deleženjem pridobljeni kovanci, ki še niso dozoreli.</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Skupaj:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Vaše trenutno skupno stanje</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Pogoste transakcije</></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Znesek transakcij, ki še niso bile potrjene in se še ne upoštevajo v trenutnem stanju na računu.</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Znesek kovancev, ki so bili v deleženju in se še ne upoštevajo v trenutnem stanju na računu.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>nesinhronizirano</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR koda </translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Zahtevaj plačilo</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Znesek:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Oznaka:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Sporočilo:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Shrani kot...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Napaka pri šifriranju URI v QR kodo.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Vnesen znesek je neveljaven, prosimo preverite vnos.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI predolg, skušajte zmanjšati besedilo oznake/sporočila.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Shrani QR kodo</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG slike (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Ime odjemalca</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Neznano</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Različica odjemalca</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informacije</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>OpenSSL različica v rabi</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Čas zagona</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Omrežje</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Število povezav</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Na testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>veriga blokov</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Trenutno število blokov</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Ocena vseh blokov</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Čas zadnjega bloka</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Odpri</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Možnosti ukazne vrstice.</translation>
</message>
<message>
<location line="+7"/>
<source>Show the AmeroX-Qt help message to get a list with possible AmeroX command-line options.</source>
<translation>Prikaži AmeroX-Qt sporočilo za pomoč , ki prikaže vse možnosti ukazne vrstice AmeroX aplikacije</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Prikaži</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konzola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Datum izgradnje</translation>
</message>
<message>
<location line="-104"/>
<source>AmeroX - Debug window</source>
<translation>AmeroX - okno za odpravljanje napak</translation>
</message>
<message>
<location line="+25"/>
<source>AmeroX Core</source>
<translation>AmeroX jedro</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Razhroščevalna dnevniška datoteka</translation>
</message>
<message>
<location line="+7"/>
<source>Open the AmeroX debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Odpri AmeroX datoteko zapisov odpravljanja napak iz trenutnega direktorija podatkov. Če so datoteke zapisov velike, to lahko traja nekaj sekund.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Počisti konzolo</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the AmeroX RPC console.</source>
<translation>Dobrodošli v AmeroX RPC konzoli.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Za navigiranje po zgodovini uporabite puščici gor in dol, in <b>Ctrl-L</b> za izpraznjenje zaslona.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Vtipkaj <b>pomoč</b> za vpogled v razpožljive ukaze.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Pošlji kovance</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Funkcije kontrole kovancev</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Vnosi...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>samodejno izbran</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Premalo sredstev!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Količina:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Biti:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Znesek:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 hack</source>
<translation>123.456 hack {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prednostno mesto:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>srednje</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Provizija:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Nizek output:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>ne</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Po proviziji:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Sprememba</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>izbira spremembe naslova</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Pošlji več prejemnikom hkrati</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Dodaj &prejemnika</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Odstrani vsa polja transakcij</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Počisti &vse</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Dobroimetje:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 hack</source>
<translation>123.456 hack</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Potrdi odlivno dejanje</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>P&ošlji</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a AmeroX address (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Vnesite AmeroX naslov (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopiraj količino</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiraj količino</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopiraj provizijo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopiraj po proviziji</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopiraj bite</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopiraj prednostno mesto</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopiraj nizek output</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopiraj spremembo</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Potrdi odliv kovancev </translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ali ste prepričani, da želite poslati %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>in</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Prejemnikov naslov ni veljaven, prosimo če ga ponovno preverite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Količina za plačilo mora biti večja od 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Količina presega vaše dobroimetje</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Seštevek presega vaše stanje na računu ko je vključen %1 provizije na transakcijo. </translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Najdena kopija naslova, možnost pošiljanja na vsakega izmed naslov le enkrat ob pošiljanju.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Napaka: Ustvarjanje transakcije spodletelo</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Napaka: Transakcija je bila zavrnjena. To se je lahko zgodilo, če so bili kovanci v vaši denarnici že zapravljeni, na primer če ste uporabili kopijo wallet.dat in so bili kovanci zapravljeni v kopiji, a tu še niso bili označeni kot zapravljeni.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid AmeroX address</source>
<translation>OPOZORILO: Neveljaven AmeroX naslov</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(ni oznake)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>OPOZORILO: neznana sprememba naslova</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Oblika</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>K&oličina:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Prejemnik &plačila:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Vnesite oznako za ta naslov, ki bo shranjena v imenik</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Oznaka:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Naslov kamor želite poslati plačilo (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Izberite naslov iz imenika</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Prilepi naslov iz odložišča</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Odstrani tega prejemnika</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a AmeroX address (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Vnesite AmeroX naslov (npr. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Podpisi - Podpiši/potrdi sporočilo</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Podpiši sporočilo</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Sporočila lahko podpišete s svojim naslovom, da dokažete lastništvo. Bodite previdni, saj vas lahko phishing napadi skušajo pretentati v to, da jim prepišete svojo identiteto. Podpisujte le jasne in razločne izjave, s katerimi se strinjate.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Naslov s katerim želite podpisati sporočilo (npr. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Izberite naslov iz imenika</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Prilepi naslov iz odložišča</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Vnesite sporočilo, ki ga želite podpisati</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopiraj trenutno izbrani naslov v odložišče</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this AmeroX address</source>
<translation>Podpišite sporočilo, kot dokazilo lastništva AmeroX naslova</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Ponastavite vse polja sporočila s podpisom</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Počisti &vse </translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Potrdi sporočilo</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Vnesite naslov za podpis, sporočilo (poskribte da točno skopirate presledke med vrsticami, črkami, itd.) in podpis spodaj, da potrdite sporočilo Da se ognete napadom posrednika, bodite pozorni, da ne boste v podpisu ugledali več, kot je v podpisanemu sporočilu samem.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Naslov s katerim je bilo podpisano sporočilo (npr. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified AmeroX address</source>
<translation>Potrdite sporočilo, da zagotovite, da je bilo podpisano z izbranim AmeroX naslovom</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Ponastavite vse polja sporočila potrditve</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a AmeroX address (e.g. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Vnesite AmeroX naslov (npr. AmeroXfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Kliknite "Podpiši sporočilo" za ustvaritev podpisa</translation>
</message>
<message>
<location line="+3"/>
<source>Enter AmeroX signature</source>
<translation>Vnesite AmeroX podpis</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Vnešeni naslov ni veljaven.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Prosimo preverite naslov in poizkusite znova.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Vnešen naslov se ne nanaša na ključ.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Odklepanje denarnice je bilo prekinjeno.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Zasebni ključ vnešenega naslov ni na voljo.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Podpisovanje sporočila spodletelo.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Sporočilo podpisano.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Ni bilo mogoče dešifrirati podpisa.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Prosimo preverite podpis in poizkusite znova.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Podpis se ni ujemal s povzetkom sporočila.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Pregledovanje sporočila spodletelo.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Sporočilo pregledano.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Odpri enoto %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Odprt za %n blok</numerusform><numerusform>Odprt za %n bloka</numerusform><numerusform>Odprt za %n blokov</numerusform><numerusform>Odprt za %n blokov</numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>sporen</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepotrjeno</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 potrdil</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Stanje</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, predvajanje skozi %n vozlišče</numerusform><numerusform>, predvajanje skozi %n vozlišči</numerusform><numerusform>, predvajanje skozi %n vozlišč</numerusform><numerusform>, predvajanje skozi %n vozlišč</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Izvor</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generirano</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Pošiljatelj</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Prejemnik</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>lasten naslov</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>oznaka</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>dozori čez %n blok</numerusform><numerusform>dozori čez %n bloka</numerusform><numerusform>dozori čez %n blokov</numerusform><numerusform>dozori čez %n blokov</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ni bilo sprejeto</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Dolg</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Provizija transakcije</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Neto količina</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Sporočilo</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Opomba</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID transakcije</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Ustvarjeni kovanci morajo zoreti 510 blokov preden so lahko potrošeni. Ko ustvarite ta blok, je predvajan po mreži in nanizan v verigo blokov. Če mu priključitev na verigo spodleti, se bo njegovo stanje spremenilo v "ni sprejet" in ne bo razpoložljiv. To se lahko občasno zgodi, če drugo vozlišče ustvari blok par sekund pred vami. </translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Razhroščevalna informacija</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transakcija</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Vnosi</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Količina</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>pravilno</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>nepravilno</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, še ni bil uspešno predvajan</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>neznano</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Podrobnosti transakcije</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>To podokno prikazuje podroben opis transakcije</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Vrsta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Naslov</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Količina</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Odpri enoto %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Potrjeno (%1 potrdil)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Odprt še %n blok</numerusform><numerusform>Odprt še %n bloka</numerusform><numerusform>Odprt še %n blokov</numerusform><numerusform>Odprt še %n blokov</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Nepovezan</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Nepotrjeno</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Potrjuje (%1 od %2 priporočenih potrditev)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Sporen</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Nezrel (%1 potrditev, na voljo bo po %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ta blok ni prejelo še nobeno vozlišče. Najverjetneje ne bo sprejet!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generirano, toda ne sprejeto</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Prejeto z</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Prejeto od</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Poslano</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Izplačilo sebi</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minirano</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(ni na voljo)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Stanje transakcije. Zapeljite z miško čez to polje za prikaz števila potrdil. </translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum in čas, ko je transakcija bila prejeta.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Vrsta transakcije.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Naslov prejemnika transakcije.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Količina odlita ali prilita dobroimetju.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Vse</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Danes</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Ta teden</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Ta mesec</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Prejšnji mesec</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>To leto</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Območje ...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Prejeto z</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Poslano</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Samemu sebi</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minirano</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Drugo</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Vnesite naslov ali oznako za iskanje</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimalna količina</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiraj naslov</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopiraj oznako</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiraj količino</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopiraj ID transakcije</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Uredi oznako</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Prikaži podrobnosti transakcije</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Izvozi podatke transakcij</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Datoteka s podatki, ločenimi z vejico (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Potrjeno</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Vrsta</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Oznaka</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Naslov</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Količina</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Napaka pri izvažanju podatkov</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Napaka pri pisanju na datoteko %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Območje:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>za</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Pošiljanje...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>AmeroX version</source>
<translation>AmeroX različica</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Uporaba:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or AmeroXd</source>
<translation>Pošlji ukaz na -server ali blackoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Prikaži ukaze</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Prikaži pomoč za ukaz</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Možnosti:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: AmeroX.conf)</source>
<translation>Določi konfiguracijsko datoteko (privzeto: AmeroX.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: AmeroXd.pid)</source>
<translation>Določi pid datoteko (privzeto: AmeroX.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Določi datoteko denarnice (znotraj imenika s podatki)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Določi podatkovni imenik</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Nastavi pomnilnik podatkovne zbirke v megabajtih (privzeto: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Nastavi velikost zapisa podatkovne baze na disku v megabajtih (privzeto: 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Sprejmi povezave na <port> (privzeta vrata: 15714 ali testnet: 25714) </translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Obdrži maksimalno število <n> povezav (privzeto: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Poveži se na vozlišče da pridobiš naslove soležnikov in prekini povezavo</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Določite vaš lasten javni naslov</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Naveži na dani naslov. Uporabi [host]:port ukaz za IPv6</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>Deleži svoje kovance za podporo omrežja in pridobi nagrado (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Prag za prekinitev povezav s slabimi odjemalci (privzeto: 1000)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Število sekund preden se ponovno povežejo neodzivni soležniki (privzeto: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Prišlo je do napake pri nastavljanju RPC porta %u za vhodne povezave na IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Loči podatkovne baze blokov in naslovov. Podaljša čas zaustavitve (privzeto: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Napaka: Transakcija je bila zavrnjena. To se je lahko zgodilo, če so bili kovanci v vaši denarnici že zapravljeni, na primer če ste uporabili kopijo wallet.dat in so bili kovanci zapravljeni v kopiji, a tu še niso bili označeni kot zapravljeni.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Napaka: Ta transakcija zahteva transakcijsko provizijo vsaj %s zaradi svoje količine, kompleksnosti ali uporabo sredstev, ki ste jih prejeli pred kratkim. </translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Sprejmi povezave na <port> (privzeta vrata: 15714 ali testnet: 25714) </translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Sprejmi ukaze iz ukazne vrstice in JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Napaka: Ustvarjanje transakcije spodletelo</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Napaka: Zaklenjena denarnica, ni mogoče opraviti transakcije</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Uvažanje blockchain podatkovne datoteke.</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Uvažanje podatkovne datoteke verige blokov.</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Teci v ozadju in sprejemaj ukaze</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Uporabi testno omrežje</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Sprejmi zunanje povezave (privzeto: 1 če ni nastavljen -proxy ali -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Prišlo je do napake pri nastavljanju RPC porta %u za vhodne povezave na IPv6: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Napaka pri zagonu podatkovne baze okolja %s! Za popravilo, NAPRAVITE VARNOSTNO KOPIJO IMENIKA, in iz njega odstranite vse razen datoteke wallet.dat</translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Nastavi maksimalno velikost visoke-prioritete/nizke-provizije transakcij v bajtih (privzeto: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Opozorilo: -paytxfee je nastavljen zelo visoko! To je transakcijska provizija, ki jo boste plačali ob pošiljanju transakcije.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong AmeroX will not work properly.</source>
<translation>Opozorilo: Prosimo preverite svoj datum in čas svojega računalnika! Če je vaša ura nastavljena napačno AmeroX ne bo deloval.</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Opozorilo: napaka pri branju wallet.dat! Vsi ključi so bili pravilno prebrani, podatki o transakciji ali imenik vnešenih naslovov so morda izgubljeni ali nepravilni.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Opozorilo: wallet.dat je pokvarjena, podatki rešeni! Originalna wallet.dat je bila shranjena kot denarnica. {timestamp}.bak v %s; če imate napačno prikazano stanje na računu ali v transakcijah prenovite datoteko z varnostno kopijo. </translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Poizkusi rešiti zasebni ključ iz pokvarjene wallet.dat </translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Možnosti ustvarjanja blokov:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Poveži se samo na določena vozlišče(a)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Odkrij svoj IP naslov (privzeto: 1 ob poslušanju, ko ni aktiviran -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Poslušanje za vrata je spodletelo. Če želite lahko uporabite ukaz -listen=0.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Najdi soležnike z uporabno DNS vpogleda (privzeto: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Sinhronizacija načina točk preverjanja (privzeto: strogo)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Neveljaven -tor naslov: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Neveljavni znesek za -reservebalance=<amount></translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Največji sprejemni medpomnilnik glede na povezavo, <n>*1000 bytov (privzeto: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Največji oddajni medpomnilnik glede na povezavo, <n>*1000 bytov (privzeto: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Poveži se samo z vozlišči v omrežju <net> (IPv4, IPv6 in Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output dodatnih informacij razhroščevanja. Obsega vse druge -debug* možnosti.</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output dodatnih informacij razhroščevanja omrežja. </translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Opremi output rahroščevanja s časovnim žigom. </translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL možnosti: (glejte Bitcoin Wiki za navodla, kako nastaviti SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Izberi verzijo socks proxya za uporabo (4-5, privzeto: 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Pošlji sledilne/razhroščevalne informacije v konzolo namesto jih shraniti v debug.log datoteko</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Pošlji sledilne/razhroščevalne informacije v razhroščevalnik</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Nastavi največjo velikost bloka v bajtih (privzeto: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Nastavi najmanjšo velikost bloka v bajtih (privzeto: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Skrči debug.log datoteko ob zagonu aplikacije (privzeto: 1 ko ni aktiviran -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Določi čas pavze povezovanja v milisekundah (privzeto: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>Ni bilo mogoče vpisati točke preverjanja, napačen ključ za točko preverjanja?
</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Uporabi UPnP za mapiranje vrat poslušanja (privzeto: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Uporabi UPnP za mapiranje vrat poslušanja (privzeto: 1 med poslušanjem)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Uporabi proxy za povezavo s skritimi storitvami tora (privzeto: isto kot -proxy) </translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Uporabniško ime za JSON-RPC povezave</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Potrdite neoporečnost baze podatkov...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>OPOZORILO: zaznana je bila kršitev s sinhronizirami točkami preverjanja, a je bila izpuščena.</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Opozorilo: Malo prostora na disku!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Opozorilo: ta različica je zastarela, potrebna je nadgradnja!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat poškodovana, neuspešna obnova</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Geslo za JSON-RPC povezave</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=AmeroXrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "AmeroX Alert" admin@foo.com
</source>
<translation>%s, nastaviti morate rpcgeslo v konfiguracijski datoteki:
%s
Priporočeno je, da uporabite naslednje naključno geslo:
rpcuser=AmeroXrpc
rpcpassword=%s
(tega gesla si vam ni potrebno zapomniti)
Uporabniško ime in geslo NE SMETA biti ista.
Če datoteka ne obstaja, jo ustvarite z lastniškimi dovoljenji za datoteke.
Prav tako je priporočeno, da nastavite alernotify, tkako da vas opozori na probleme;
na primer: alertnotify=echo %%s | mail -s "AmeroX Alarm" admin@foo.com
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Najdi soležnike prek irca (privzeto: 0)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Sinhroniziraj čas z drugimi vozlišči. Onemogoči, če je čas na vašem sistemu točno nastavljen, npr. sinhroniziranje z NTP (privzeto: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Ob ustvarjanju transakcij, prezri vnose z manjšo vrednostjo kot (privzeto: 0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Dovoli JSON-RPC povezave z določenega IP naslova</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Pošlji ukaze vozlišču na <ip> (privzet: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Izvrši ukaz, ko se najboljši blok spremeni (%s je v cmd programu nadomeščen z zgoščenimi bloki).</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Izvedi ukaz, ko bo transakcija denarnice se spremenila (V cmd je bil TxID zamenjan za %s)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Zahtevaj potrditve za spremembo (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>Zahtevaj da transakcijske skripte uporabljajo operatorje canonical PUSH (privzeto: 1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Izvrši ukaz, ko je prejet relevanten alarm (%s je v cmd programu nadomeščen s sporočilom)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Posodobi denarnico v najnovejši zapis</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Nastavi velikost ključa bazena na <n> (privzeto: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Ponovno preglej verigo blokov za manjkajoče transakcije denarnice</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Koliko blokov naj preveri ob zagonu aplikacije (privzeto: 2500, 0 = vse)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Kako temeljito naj bo preverjanje blokov (0-6, privzeto: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Uvozi bloke iz zunanje blk000?.dat datoteke</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Uporabi OpenSSL (https) za JSON-RPC povezave</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Datoteka potrdila strežnika (privzeta: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Zasebni ključ strežnika (privzet: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Dovoljeni kodirniki (privzeti: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>OPOZORILO: Najdene so bile neveljavne točke preverjanja! Prikazane transakcije so morda napačne! Poiščite novo različico aplikacije ali pa obvestite razvijalce.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>To sporočilo pomoči</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Denarnica %s se nahaja zunaj datotečnega imenika %s.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. AmeroX is probably already running.</source>
<translation>Ni bilo mogoče najti podatkovnega imenika %s. Aplikacija AmeroX je verjetno že zagnana.</translation>
</message>
<message>
<location line="-98"/>
<source>AmeroX</source>
<translation>AmeroX</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Na tem računalniku je bilo nemogoče vezati na %s (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Poveži se skozi socks proxy</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Omogoči DNS povezave za -addnode, -seednode in -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Nalaganje naslovov ...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Napaka pri nalaganju blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Napaka pri nalaganju wallet.dat: denarnica pokvarjena</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of AmeroX</source>
<translation>Napaka pri nalaganju wallet.dat: denarnica zahteva novejšo verzijo AmeroX</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart AmeroX to complete</source>
<translation>Denarnica mora biti prepisana: ponovno odprite AmeroX za dokončanje</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Napaka pri nalaganju wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Neveljaven -proxy naslov: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Neznano omrežje določeno v -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Zahtevana neznana -socks proxy različica: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Ni mogoče določiti -bind naslova: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Ni mogoče določiti -externalip naslova: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Neveljavni znesek za -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Napaka: ni mogoče zagnati vozlišča</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Pošiljanje...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Neveljavna količina</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Premalo sredstev</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Nalaganje indeksa blokov ...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Dodaj vozlišče za povezavo nanj in skušaj le to obdržati odprto</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. AmeroX is probably already running.</source>
<translation>Navezava v %s na tem računalniku ni mogoča AmeroX aplikacija je verjetno že zagnana.</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Provizija na KB ki jo morate dodati transakcijam, ki jih pošiljate</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Neveljavni znesek za -miniput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Nalaganje denarnice ...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Ne morem </translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Ni mogoče zagnati keypoola</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Ni mogoče zapisati privzetega naslova</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Ponovno pregledovanje ...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Nalaganje končano</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Za uporabo %s opcije</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Napaka</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Nastaviti morate rpcpassword=<password> v konfiguracijski datoteki:
%s
Če datoteka ne obstaja, jo ustvarite z lastniškimi dovoljenji za datoteke.</translation>
</message>
</context>
</TS> | ameroxcoin/AmeroX | src/qt/locale/bitcoin_sl_SI.ts | TypeScript | mit | 130,618 |
// **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerUtils.java,v $
// $RCSfile: ImageServerUtils.java,v $
// $Revision: 1.10 $
// $Date: 2006/02/16 16:22:49 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.image;
import java.awt.Color;
import java.awt.Paint;
import java.awt.geom.Point2D;
import java.util.Properties;
import com.bbn.openmap.omGraphics.OMColor;
import com.bbn.openmap.proj.Proj;
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.ProjectionFactory;
import com.bbn.openmap.util.Debug;
import com.bbn.openmap.util.PropUtils;
/**
* A class to contain convenience functions for parsing web image requests.
*/
public class ImageServerUtils implements ImageServerConstants {
/**
* Create an OpenMap projection from the values stored in a Properties
* object. The properties inside should be parsed out from a map request,
* with the keywords being those defined in the ImageServerConstants
* interface. Assumes that the shared instance of the ProjectionFactory has
* been initialized with the expected Projections.
*/
public static Proj createOMProjection(Properties props,
Projection defaultProj) {
float scale = PropUtils.floatFromProperties(props,
SCALE,
defaultProj.getScale());
int height = PropUtils.intFromProperties(props,
HEIGHT,
defaultProj.getHeight());
int width = PropUtils.intFromProperties(props,
WIDTH,
defaultProj.getWidth());
Point2D llp = defaultProj.getCenter();
float longitude = PropUtils.floatFromProperties(props,
LON,
(float) llp.getX());
float latitude = PropUtils.floatFromProperties(props,
LAT,
(float) llp.getY());
Class<? extends Projection> projClass = null;
String projType = props.getProperty(PROJTYPE);
ProjectionFactory projFactory = ProjectionFactory.loadDefaultProjections();
if (projType != null) {
projClass = projFactory.getProjClassForName(projType);
}
if (projClass == null) {
projClass = defaultProj.getClass();
}
if (Debug.debugging("imageserver")) {
Debug.output("ImageServerUtils.createOMProjection: projection "
+ projClass.getName() + ", with HEIGHT = " + height
+ ", WIDTH = " + width + ", lat = " + latitude + ", lon = "
+ longitude + ", scale = " + scale);
}
Proj proj = (Proj) projFactory.makeProjection(projClass,
new Point2D.Float(longitude, latitude),
scale,
width,
height);
return (Proj) proj;
}
/**
* Create a Color object from the properties TRANSPARENT and BGCOLOR
* properties. Default color returned is white.
*
* @param props the Properties containing background color information.
* @return Color object for background.
*/
public static Color getBackground(Properties props) {
return (Color) getBackground(props, Color.white);
}
/**
* Create a Color object from the properties TRANSPARENT and BGCOLOR
* properties. Default color returned is white.
*
* @param props the Properties containing background color information.
* @param defPaint the default Paint to use in case the color isn't defined
* in the properties.
* @return Color object for background.
*/
public static Paint getBackground(Properties props, Paint defPaint) {
boolean transparent = PropUtils.booleanFromProperties(props,
TRANSPARENT,
false);
Paint backgroundColor = PropUtils.parseColorFromProperties(props,
BGCOLOR,
defPaint);
if (backgroundColor == null) {
backgroundColor = Color.white;
}
if (transparent) {
if (backgroundColor instanceof Color) {
Color bgc = (Color) backgroundColor;
backgroundColor = new Color(bgc.getRed(), bgc.getGreen(), bgc.getBlue(), 0x00);
} else {
backgroundColor = OMColor.clear;
}
}
if (Debug.debugging("imageserver")) {
Debug.output("ImageServerUtils.createOMProjection: projection color: "
+ (backgroundColor instanceof Color ? Integer.toHexString(((Color) backgroundColor).getRGB())
: backgroundColor.toString())
+ ", transparent("
+ transparent + ")");
}
return backgroundColor;
}
} | d2fn/passage | src/main/java/com/bbn/openmap/image/ImageServerUtils.java | Java | mit | 5,229 |
/*
* Copyright (C) 2013-2018 The Project Lombok Authors.
*
* 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 lombok.javac;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCAssert;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCContinue;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCErroneous;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCSkip;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCSwitch;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCWildcard;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.JCTree.TypeBoundKind;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import lombok.permit.Permit;
public class JavacTreeMaker {
private final TreeMaker tm;
public JavacTreeMaker(TreeMaker tm) {
this.tm = tm;
}
public TreeMaker getUnderlyingTreeMaker() {
return tm;
}
public JavacTreeMaker at(int pos) {
tm.at(pos);
return this;
}
private static class MethodId<J> {
private final Class<?> owner;
private final String name;
private final Class<J> returnType;
private final Class<?>[] paramTypes;
MethodId(Class<?> owner, String name, Class<J> returnType, Class<?>... types) {
this.owner = owner;
this.name = name;
this.paramTypes = types;
this.returnType = returnType;
}
@Override public String toString() {
StringBuilder out = new StringBuilder();
out.append(returnType.getName()).append(" ").append(owner.getName()).append(".").append(name).append("(");
boolean f = true;
for (Class<?> p : paramTypes) {
if (f) f = false;
else out.append(", ");
out.append(p.getName());
}
return out.append(")").toString();
}
}
private static class SchroedingerType {
final Object value;
private SchroedingerType(Object value) {
this.value = value;
}
@Override public int hashCode() {
return value == null ? -1 : value.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof SchroedingerType) {
Object other = ((SchroedingerType) obj).value;
return value == null ? other == null : value.equals(other);
}
return false;
}
static Object getFieldCached(ConcurrentMap<String, Object> cache, String className, String fieldName) {
Object value = cache.get(fieldName);
if (value != null) return value;
try {
value = Permit.getField(Class.forName(className), fieldName).get(null);
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
} catch (ClassNotFoundException e) {
throw Javac.sneakyThrow(e);
}
cache.putIfAbsent(fieldName, value);
return value;
}
private static Field NOSUCHFIELDEX_MARKER;
static {
try {
NOSUCHFIELDEX_MARKER = Permit.getField(SchroedingerType.class, "NOSUCHFIELDEX_MARKER");
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
}
}
static Object getFieldCached(ConcurrentMap<Class<?>, Field> cache, Object ref, String fieldName) throws NoSuchFieldException {
Class<?> c = ref.getClass();
Field field = cache.get(c);
if (field == null) {
try {
field = Permit.getField(c, fieldName);
} catch (NoSuchFieldException e) {
cache.putIfAbsent(c, NOSUCHFIELDEX_MARKER);
throw Javac.sneakyThrow(e);
}
Permit.setAccessible(field);
Field old = cache.putIfAbsent(c, field);
if (old != null) field = old;
}
if (field == NOSUCHFIELDEX_MARKER) throw new NoSuchFieldException(fieldName);
try {
return field.get(ref);
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
}
}
}
public static class TypeTag extends SchroedingerType {
private static final ConcurrentMap<String, Object> TYPE_TAG_CACHE = new ConcurrentHashMap<String, Object>();
private static final ConcurrentMap<Class<?>, Field> FIELD_CACHE = new ConcurrentHashMap<Class<?>, Field>();
private static final Method TYPE_TYPETAG_METHOD;
static {
Method m = null;
try {
m = Permit.getMethod(Type.class, "getTag");
} catch (NoSuchMethodException e) {}
TYPE_TYPETAG_METHOD = m;
}
private TypeTag(Object value) {
super(value);
}
public static TypeTag typeTag(JCTree o) {
try {
return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag"));
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
}
}
public static TypeTag typeTag(Type t) {
if (t == null) return Javac.CTC_VOID;
try {
return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag"));
} catch (NoSuchFieldException e) {
if (TYPE_TYPETAG_METHOD == null) throw new IllegalStateException("Type " + t.getClass() + " has neither 'tag' nor getTag()");
try {
return new TypeTag(TYPE_TYPETAG_METHOD.invoke(t));
} catch (IllegalAccessException ex) {
throw Javac.sneakyThrow(ex);
} catch (InvocationTargetException ex) {
throw Javac.sneakyThrow(ex.getCause());
}
}
}
public static TypeTag typeTag(String identifier) {
return new TypeTag(getFieldCached(TYPE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.code.TypeTags" : "com.sun.tools.javac.code.TypeTag", identifier));
}
}
public static class TreeTag extends SchroedingerType {
private static final ConcurrentMap<String, Object> TREE_TAG_CACHE = new ConcurrentHashMap<String, Object>();
private static final Field TAG_FIELD;
private static final Method TAG_METHOD;
private static final MethodId<Integer> OP_PREC = MethodId(TreeInfo.class, "opPrec", int.class, TreeTag.class);
static {
Method m = null;
try {
m = Permit.getMethod(JCTree.class, "getTag");
} catch (NoSuchMethodException e) {}
if (m != null) {
TAG_FIELD = null;
TAG_METHOD = m;
} else {
Field f = null;
try {
f = Permit.getField(JCTree.class, "tag");
} catch (NoSuchFieldException e) {}
TAG_FIELD = f;
TAG_METHOD = null;
}
}
private TreeTag(Object value) {
super(value);
}
public static TreeTag treeTag(JCTree o) {
try {
if (TAG_METHOD != null) return new TreeTag(TAG_METHOD.invoke(o));
else return new TreeTag(TAG_FIELD.get(o));
} catch (InvocationTargetException e) {
throw Javac.sneakyThrow(e.getCause());
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
}
}
public static TreeTag treeTag(String identifier) {
return new TreeTag(getFieldCached(TREE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier));
}
public int getOperatorPrecedenceLevel() {
return invokeAny(null, OP_PREC, value);
}
public boolean isPrefixUnaryOp() {
return Javac.CTC_NEG.equals(this) || Javac.CTC_POS.equals(this) || Javac.CTC_NOT.equals(this) || Javac.CTC_COMPL.equals(this) || Javac.CTC_PREDEC.equals(this) || Javac.CTC_PREINC.equals(this);
}
}
static <J> MethodId<J> MethodId(Class<?> owner, String name, Class<J> returnType, Class<?>... types) {
return new MethodId<J>(owner, name, returnType, types);
}
/**
* Creates a new method ID based on the name of the method to invoke, the return type of that method, and the types of the parameters.
*
* A method matches if the return type matches, and for each parameter the following holds:
*
* Either (A) the type listed here is the same as, or a subtype of, the type of the method in javac's TreeMaker, or
* (B) the type listed here is a subtype of SchroedingerType.
*/
static <J> MethodId<J> MethodId(String name, Class<J> returnType, Class<?>... types) {
return new MethodId<J>(TreeMaker.class, name, returnType, types);
}
/**
* Creates a new method ID based on the name of a method in this class, assuming the name of the method to invoke in TreeMaker has the same name,
* the same return type, and the same parameters (under the same rules as the other MethodId method).
*/
static <J> MethodId<J> MethodId(String name) {
for (Method m : JavacTreeMaker.class.getDeclaredMethods()) {
if (m.getName().equals(name)) {
@SuppressWarnings("unchecked") Class<J> r = (Class<J>) m.getReturnType();
Class<?>[] p = m.getParameterTypes();
return new MethodId<J>(TreeMaker.class, name, r, p);
}
}
throw new InternalError("Not found: " + name);
}
private static final Object METHOD_NOT_FOUND = new Object[0];
private static final Object METHOD_MULTIPLE_FOUND = new Object[0];
private static final ConcurrentHashMap<MethodId<?>, Object> METHOD_CACHE = new ConcurrentHashMap<MethodId<?>, Object>();
private <J> J invoke(MethodId<J> m, Object... args) {
return invokeAny(tm, m, args);
}
@SuppressWarnings("unchecked") private static <J> J invokeAny(Object owner, MethodId<J> m, Object... args) {
Method method = getFromCache(m);
try {
if (m.returnType.isPrimitive()) {
Object res = method.invoke(owner, args);
String sn = res.getClass().getSimpleName().toLowerCase();
if (!sn.startsWith(m.returnType.getSimpleName())) throw new ClassCastException(res.getClass() + " to " + m.returnType);
return (J) res;
}
return m.returnType.cast(method.invoke(owner, args));
} catch (InvocationTargetException e) {
throw Javac.sneakyThrow(e.getCause());
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
} catch (IllegalArgumentException e) {
System.err.println(method);
throw Javac.sneakyThrow(e);
}
}
private static boolean tryResolve(MethodId<?> m) {
Object s = METHOD_CACHE.get(m);
if (s == null) s = addToCache(m);
if (s instanceof Method) return true;
return false;
}
private static Method getFromCache(MethodId<?> m) {
Object s = METHOD_CACHE.get(m);
if (s == null) s = addToCache(m);
if (s == METHOD_MULTIPLE_FOUND) throw new IllegalStateException("Lombok TreeMaker frontend issue: multiple matches when looking for method: " + m);
if (s == METHOD_NOT_FOUND) throw new IllegalStateException("Lombok TreeMaker frontend issue: no match when looking for method: " + m);
return (Method) s;
}
private static Object addToCache(MethodId<?> m) {
Method found = null;
outer:
for (Method method : m.owner.getDeclaredMethods()) {
if (!m.name.equals(method.getName())) continue;
Class<?>[] t = method.getParameterTypes();
if (t.length != m.paramTypes.length) continue;
for (int i = 0; i < t.length; i++) {
if (Symbol.class.isAssignableFrom(t[i])) continue outer;
if (!SchroedingerType.class.isAssignableFrom(m.paramTypes[i])) {
if (t[i].isPrimitive()) {
if (t[i] != m.paramTypes[i]) continue outer;
} else {
if (!t[i].isAssignableFrom(m.paramTypes[i])) continue outer;
}
}
}
if (found == null) found = method;
else {
METHOD_CACHE.putIfAbsent(m, METHOD_MULTIPLE_FOUND);
return METHOD_MULTIPLE_FOUND;
}
}
if (found == null) {
METHOD_CACHE.putIfAbsent(m, METHOD_NOT_FOUND);
return METHOD_NOT_FOUND;
}
Permit.setAccessible(found);
Object marker = METHOD_CACHE.putIfAbsent(m, found);
if (marker == null) return found;
return marker;
}
//javac versions: 6-8
private static final MethodId<JCCompilationUnit> TopLevel = MethodId("TopLevel");
public JCCompilationUnit TopLevel(List<JCAnnotation> packageAnnotations, JCExpression pid, List<JCTree> defs) {
return invoke(TopLevel, packageAnnotations, pid, defs);
}
//javac versions: 6-8
private static final MethodId<JCImport> Import = MethodId("Import");
public JCImport Import(JCTree qualid, boolean staticImport) {
return invoke(Import, qualid, staticImport);
}
//javac versions: 6-8
private static final MethodId<JCClassDecl> ClassDef = MethodId("ClassDef");
public JCClassDecl ClassDef(JCModifiers mods, Name name, List<JCTypeParameter> typarams, JCExpression extending, List<JCExpression> implementing, List<JCTree> defs) {
return invoke(ClassDef, mods, name, typarams, extending, implementing, defs);
}
//javac versions: 6-8
private static final MethodId<JCMethodDecl> MethodDef = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, List.class, List.class, JCBlock.class, JCExpression.class);
public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List<JCTypeParameter> typarams, List<JCVariableDecl> params, List<JCExpression> thrown, JCBlock body, JCExpression defaultValue) {
return invoke(MethodDef, mods, name, resType, typarams, params, thrown, body, defaultValue);
}
//javac versions: 8
private static final MethodId<JCMethodDecl> MethodDefWithRecvParam = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, JCVariableDecl.class, List.class, List.class, JCBlock.class, JCExpression.class);
public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List<JCTypeParameter> typarams, JCVariableDecl recvparam, List<JCVariableDecl> params, List<JCExpression> thrown, JCBlock body, JCExpression defaultValue) {
return invoke(MethodDefWithRecvParam, mods, name, resType, recvparam, typarams, params, thrown, body, defaultValue);
}
//javac versions: 6-8
private static final MethodId<JCVariableDecl> VarDef = MethodId("VarDef");
public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) {
JCVariableDecl varDef = invoke(VarDef, mods, name, vartype, init);
// We use 'position of the type is -1' as indicator in delombok that the original node was written using JDK10's 'var' feature, because javac desugars 'var' to the real type and doesn't leave any markers other than the
// node position to indicate that it did so. Unfortunately, that means vardecls we generate look like 'var' to delombok. Adjust the position to avoid this.
if (varDef.vartype != null && varDef.vartype.pos == -1) varDef.vartype.pos = 0;
return varDef;
}
//javac versions: 8
private static final MethodId<JCVariableDecl> ReceiverVarDef = MethodId("ReceiverVarDef");
public JCVariableDecl ReceiverVarDef(JCModifiers mods, JCExpression name, JCExpression vartype) {
return invoke(ReceiverVarDef, mods, name, vartype);
}
//javac versions: 6-8
private static final MethodId<JCSkip> Skip = MethodId("Skip");
public JCSkip Skip() {
return invoke(Skip);
}
//javac versions: 6-8
private static final MethodId<JCBlock> Block = MethodId("Block");
public JCBlock Block(long flags, List<JCStatement> stats) {
return invoke(Block, flags, stats);
}
//javac versions: 6-8
private static final MethodId<JCDoWhileLoop> DoLoop = MethodId("DoLoop");
public JCDoWhileLoop DoLoop(JCStatement body, JCExpression cond) {
return invoke(DoLoop, body, cond);
}
//javac versions: 6-8
private static final MethodId<JCWhileLoop> WhileLoop = MethodId("WhileLoop");
public JCWhileLoop WhileLoop(JCExpression cond, JCStatement body) {
return invoke(WhileLoop, cond, body);
}
//javac versions: 6-8
private static final MethodId<JCForLoop> ForLoop = MethodId("ForLoop");
public JCForLoop ForLoop(List<JCStatement> init, JCExpression cond, List<JCExpressionStatement> step, JCStatement body) {
return invoke(ForLoop, init, cond, step, body);
}
//javac versions: 6-8
private static final MethodId<JCEnhancedForLoop> ForeachLoop = MethodId("ForeachLoop");
public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) {
return invoke(ForeachLoop, var, expr, body);
}
//javac versions: 6-8
private static final MethodId<JCLabeledStatement> Labelled = MethodId("Labelled");
public JCLabeledStatement Labelled(Name label, JCStatement body) {
return invoke(Labelled, label, body);
}
//javac versions: 6-8
private static final MethodId<JCSwitch> Switch = MethodId("Switch");
public JCSwitch Switch(JCExpression selector, List<JCCase> cases) {
return invoke(Switch, selector, cases);
}
//javac versions: 6-11
private static final MethodId<JCCase> Case11 = MethodId("Case", JCCase.class, JCExpression.class, com.sun.tools.javac.util.List.class);
//javac version: 12+
public static class Case12 {
private static final Class<?> CASE_KIND_CLASS = classForName(TreeMaker.class, "com.sun.source.tree.CaseTree$CaseKind");
static final MethodId<JCCase> Case12 = MethodId("Case", JCCase.class, CASE_KIND_CLASS, com.sun.tools.javac.util.List.class, com.sun.tools.javac.util.List.class, JCTree.class);
static final Object CASE_KIND_STATEMENT = CASE_KIND_CLASS.getEnumConstants()[0];
}
static Class<?> classForName(Class<?> context, String name) {
try {
return context.getClassLoader().loadClass(name);
} catch (ClassNotFoundException e) {
Error x = new NoClassDefFoundError(e.getMessage());
x.setStackTrace(e.getStackTrace());
throw x;
}
}
public JCCase Case(JCExpression pat, List<JCStatement> stats) {
if (tryResolve(Case11)) return invoke(Case11, pat, stats);
return invoke(Case12.Case12, Case12.CASE_KIND_STATEMENT, pat == null ? com.sun.tools.javac.util.List.nil() : com.sun.tools.javac.util.List.of(pat), stats, null);
}
//javac versions: 6-8
private static final MethodId<JCSynchronized> Synchronized = MethodId("Synchronized");
public JCSynchronized Synchronized(JCExpression lock, JCBlock body) {
return invoke(Synchronized, lock, body);
}
//javac versions: 6-8
private static final MethodId<JCTry> Try = MethodId("Try", JCTry.class, JCBlock.class, List.class, JCBlock.class);
public JCTry Try(JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
return invoke(Try, body, catchers, finalizer);
}
//javac versions: 7-8
private static final MethodId<JCTry> TryWithResources = MethodId("Try", JCTry.class, List.class, JCBlock.class, List.class, JCBlock.class);
public JCTry Try(List<JCTree> resources, JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
return invoke(TryWithResources, resources, body, catchers, finalizer);
}
//javac versions: 6-8
private static final MethodId<JCCatch> Catch = MethodId("Catch");
public JCCatch Catch(JCVariableDecl param, JCBlock body) {
return invoke(Catch, param, body);
}
//javac versions: 6-8
private static final MethodId<JCConditional> Conditional = MethodId("Conditional");
public JCConditional Conditional(JCExpression cond, JCExpression thenpart, JCExpression elsepart) {
return invoke(Conditional, cond, thenpart, elsepart);
}
//javac versions: 6-8
private static final MethodId<JCIf> If = MethodId("If");
public JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart) {
return invoke(If, cond, thenpart, elsepart);
}
//javac versions: 6-8
private static final MethodId<JCExpressionStatement> Exec = MethodId("Exec");
public JCExpressionStatement Exec(JCExpression expr) {
return invoke(Exec, expr);
}
//javac version: 6-11
private static final MethodId<JCBreak> Break11 = MethodId("Break", JCBreak.class, Name.class);
//javac version: 12+
private static final MethodId<JCBreak> Break12 = MethodId("Break", JCBreak.class, JCExpression.class);
public JCBreak Break(Name label) {
if (tryResolve(Break11)) return invoke(Break11, label);
return invoke(Break12, label != null ? Ident(label) : null);
}
//javac versions: 6-8
private static final MethodId<JCContinue> Continue = MethodId("Continue");
public JCContinue Continue(Name label) {
return invoke(Continue, label);
}
//javac versions: 6-8
private static final MethodId<JCReturn> Return = MethodId("Return");
public JCReturn Return(JCExpression expr) {
return invoke(Return, expr);
}
//javac versions: 6-8
private static final MethodId<JCThrow> Throw = MethodId("Throw");
public JCThrow Throw(JCExpression expr) {
return invoke(Throw, expr);
}
//javac versions: 6-8
private static final MethodId<JCAssert> Assert = MethodId("Assert");
public JCAssert Assert(JCExpression cond, JCExpression detail) {
return invoke(Assert, cond, detail);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> Apply = MethodId("Apply");
public JCMethodInvocation Apply(List<JCExpression> typeargs, JCExpression fn, List<JCExpression> args) {
return invoke(Apply, typeargs, fn, args);
}
//javac versions: 6-8
private static final MethodId<JCNewClass> NewClass = MethodId("NewClass");
public JCNewClass NewClass(JCExpression encl, List<JCExpression> typeargs, JCExpression clazz, List<JCExpression> args, JCClassDecl def) {
return invoke(NewClass, encl, typeargs, clazz, args, def);
}
//javac versions: 6-8
private static final MethodId<JCNewArray> NewArray = MethodId("NewArray");
public JCNewArray NewArray(JCExpression elemtype, List<JCExpression> dims, List<JCExpression> elems) {
return invoke(NewArray, elemtype, dims, elems);
}
//javac versions: 8
// private static final MethodId<JCLambda> Lambda = MethodId("Lambda");
// public JCLambda Lambda(List<JCVariableDecl> params, JCTree body) {
// return invoke(Lambda, params, body);
// }
//javac versions: 6-8
private static final MethodId<JCParens> Parens = MethodId("Parens");
public JCParens Parens(JCExpression expr) {
return invoke(Parens, expr);
}
//javac versions: 6-8
private static final MethodId<JCAssign> Assign = MethodId("Assign");
public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
return invoke(Assign, lhs, rhs);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCAssignOp> Assignop = MethodId("Assignop");
public JCAssignOp Assignop(TreeTag opcode, JCTree lhs, JCTree rhs) {
return invoke(Assignop, opcode.value, lhs, rhs);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCUnary> Unary = MethodId("Unary");
public JCUnary Unary(TreeTag opcode, JCExpression arg) {
return invoke(Unary, opcode.value, arg);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCBinary> Binary = MethodId("Binary");
public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) {
return invoke(Binary, opcode.value, lhs, rhs);
}
//javac versions: 6-8
private static final MethodId<JCTypeCast> TypeCast = MethodId("TypeCast");
public JCTypeCast TypeCast(JCTree expr, JCExpression type) {
return invoke(TypeCast, expr, type);
}
//javac versions: 6-8
private static final MethodId<JCInstanceOf> TypeTest = MethodId("TypeTest");
public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) {
return invoke(TypeTest, expr, clazz);
}
//javac versions: 6-8
private static final MethodId<JCArrayAccess> Indexed = MethodId("Indexed");
public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) {
return invoke(Indexed, indexed, index);
}
//javac versions: 6-8
private static final MethodId<JCFieldAccess> Select = MethodId("Select");
public JCFieldAccess Select(JCExpression selected, Name selector) {
return invoke(Select, selected, selector);
}
//javac versions: 8
// private static final MethodId<JCMemberReference> Reference = MethodId("Reference");
// public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name, JCExpression expr, List<JCExpression> typeargs) {
// return invoke(Reference, mode, name, expr, typeargs);
// }
//javac versions: 6-8
private static final MethodId<JCIdent> Ident = MethodId("Ident", JCIdent.class, Name.class);
public JCIdent Ident(Name idname) {
return invoke(Ident, idname);
}
//javac versions: 6-8
//tag = [6-7] int [8] TypeTag
private static final MethodId<JCLiteral> Literal = MethodId("Literal", JCLiteral.class, TypeTag.class, Object.class);
public JCLiteral Literal(TypeTag tag, Object value) {
return invoke(Literal, tag.value, value);
}
//javac versions: 6-8
//typetag = [6-7] int [8] TypeTag
private static final MethodId<JCPrimitiveTypeTree> TypeIdent = MethodId("TypeIdent");
public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) {
return invoke(TypeIdent, typetag.value);
}
//javac versions: 6-8
private static final MethodId<JCArrayTypeTree> TypeArray = MethodId("TypeArray");
public JCArrayTypeTree TypeArray(JCExpression elemtype) {
return invoke(TypeArray, elemtype);
}
//javac versions: 6-8
private static final MethodId<JCTypeApply> TypeApply = MethodId("TypeApply");
public JCTypeApply TypeApply(JCExpression clazz, List<JCExpression> arguments) {
return invoke(TypeApply, clazz, arguments);
}
//javac versions: 7-8
// private static final MethodId<JCTypeUnion> TypeUnion = MethodId("TypeUnion");
// public JCTypeUnion TypeUnion(List<JCExpression> components) {
// return invoke(TypeUnion, compoonents);
// }
//javac versions: 8
// private static final MethodId<JCTypeIntersection> TypeIntersection = MethodId("TypeIntersection");
// public JCTypeIntersection TypeIntersection(List<JCExpression> components) {
// return invoke(TypeIntersection, components);
// }
//javac versions: 6-8
private static final MethodId<JCTypeParameter> TypeParameter = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class);
public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds) {
return invoke(TypeParameter, name, bounds);
}
//javac versions: 8
private static final MethodId<JCTypeParameter> TypeParameterWithAnnos = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class, List.class);
public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds, List<JCAnnotation> annos) {
return invoke(TypeParameterWithAnnos, name, bounds, annos);
}
//javac versions: 6-8
private static final MethodId<JCWildcard> Wildcard = MethodId("Wildcard");
public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) {
return invoke(Wildcard, kind, type);
}
//javac versions: 6-8
private static final MethodId<TypeBoundKind> TypeBoundKind = MethodId("TypeBoundKind");
public TypeBoundKind TypeBoundKind(BoundKind kind) {
return invoke(TypeBoundKind, kind);
}
//javac versions: 6-8
private static final MethodId<JCAnnotation> Annotation = MethodId("Annotation", JCAnnotation.class, JCTree.class, List.class);
public JCAnnotation Annotation(JCTree annotationType, List<JCExpression> args) {
return invoke(Annotation, annotationType, args);
}
//javac versions: 8
private static final MethodId<JCAnnotation> TypeAnnotation = MethodId("TypeAnnotation", JCAnnotation.class, JCTree.class, List.class);
public JCAnnotation TypeAnnotation(JCTree annotationType, List<JCExpression> args) {
return invoke(TypeAnnotation, annotationType, args);
}
//javac versions: 6-8
private static final MethodId<JCModifiers> ModifiersWithAnnotations = MethodId("Modifiers", JCModifiers.class, long.class, List.class);
public JCModifiers Modifiers(long flags, List<JCAnnotation> annotations) {
return invoke(ModifiersWithAnnotations, flags, annotations);
}
//javac versions: 6-8
private static final MethodId<JCModifiers> Modifiers = MethodId("Modifiers", JCModifiers.class, long.class);
public JCModifiers Modifiers(long flags) {
return invoke(Modifiers, flags);
}
//javac versions: 8
// private static final MethodId<JCAnnotatedType> AnnotatedType = MethodId("AnnotatedType");
// public JCAnnotatedType AnnotatedType(List<JCAnnotation> annotations, JCExpression underlyingType) {
// return invoke(AnnotatedType, annotations, underlyingType);
// }
//javac versions: 6-8
private static final MethodId<JCErroneous> Erroneous = MethodId("Erroneous", JCErroneous.class);
public JCErroneous Erroneous() {
return invoke(Erroneous);
}
//javac versions: 6-8
private static final MethodId<JCErroneous> ErroneousWithErrs = MethodId("Erroneous", JCErroneous.class, List.class);
public JCErroneous Erroneous(List<? extends JCTree> errs) {
return invoke(ErroneousWithErrs, errs);
}
//javac versions: 6-8
private static final MethodId<LetExpr> LetExpr = MethodId("LetExpr", LetExpr.class, List.class, JCTree.class);
public LetExpr LetExpr(List<JCVariableDecl> defs, JCTree expr) {
return invoke(LetExpr, defs, expr);
}
//javac versions: 6-8
private static final MethodId<JCClassDecl> AnonymousClassDef = MethodId("AnonymousClassDef");
public JCClassDecl AnonymousClassDef(JCModifiers mods, List<JCTree> defs) {
return invoke(AnonymousClassDef, mods, defs);
}
//javac versions: 6-8
private static final MethodId<LetExpr> LetExprSingle = MethodId("LetExpr", LetExpr.class, JCVariableDecl.class, JCTree.class);
public LetExpr LetExpr(JCVariableDecl def, JCTree expr) {
return invoke(LetExprSingle, def, expr);
}
//javac versions: 6-8
private static final MethodId<JCIdent> IdentVarDecl = MethodId("Ident", JCIdent.class, JCVariableDecl.class);
public JCExpression Ident(JCVariableDecl param) {
return invoke(IdentVarDecl, param);
}
//javac versions: 6-8
private static final MethodId<List<JCExpression>> Idents = MethodId("Idents");
public List<JCExpression> Idents(List<JCVariableDecl> params) {
return invoke(Idents, params);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> App2 = MethodId("App", JCMethodInvocation.class, JCExpression.class, List.class);
public JCMethodInvocation App(JCExpression meth, List<JCExpression> args) {
return invoke(App2, meth, args);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> App1 = MethodId("App", JCMethodInvocation.class, JCExpression.class);
public JCMethodInvocation App(JCExpression meth) {
return invoke(App1, meth);
}
//javac versions: 6-8
private static final MethodId<List<JCAnnotation>> Annotations = MethodId("Annotations");
public List<JCAnnotation> Annotations(List<Attribute.Compound> attributes) {
return invoke(Annotations, attributes);
}
//javac versions: 6-8
private static final MethodId<JCLiteral> LiteralWithValue = MethodId("Literal", JCLiteral.class, Object.class);
public JCLiteral Literal(Object value) {
return invoke(LiteralWithValue, value);
}
//javac versions: 6-8
private static final MethodId<JCAnnotation> AnnotationWithAttributeOnly = MethodId("Annotation", JCAnnotation.class, Attribute.class);
public JCAnnotation Annotation(Attribute a) {
return invoke(AnnotationWithAttributeOnly, a);
}
//javac versions: 8
private static final MethodId<JCAnnotation> TypeAnnotationWithAttributeOnly = MethodId("TypeAnnotation", JCAnnotation.class, Attribute.class);
public JCAnnotation TypeAnnotation(Attribute a) {
return invoke(TypeAnnotationWithAttributeOnly, a);
}
//javac versions: 6-8
private static final MethodId<JCStatement> Call = MethodId("Call");
public JCStatement Call(JCExpression apply) {
return invoke(Call, apply);
}
//javac versions: 6-8
private static final MethodId<JCExpression> Type = MethodId("Type");
public JCExpression Type(Type type) {
return invoke(Type, type);
}
} | Lekanich/lombok | src/utils/lombok/javac/JavacTreeMaker.java | Java | mit | 34,532 |
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url"),
filesys = require("fs");
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
filesys.readFile(full_path, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else{
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
});
}).listen(8080);
sys.puts("Server Running on 8080");
| mark-hahn/node-ide | test.js | JavaScript | mit | 914 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BreakoutGL
{
public class Program
{
public static void Main(string[] args)
{
using (Game game = new Game())
{
game.Run();
}
}
}
}
| minalear/Breakout | src/BreakoutGL/Program.cs | C# | mit | 348 |
# -*- coding: utf-8 -*-
""" Sahana Eden Common Alerting Protocol (CAP) Model
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
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.
"""
__all__ = ("S3CAPModel",
"cap_info_labels",
"cap_alert_is_template",
"cap_rheader",
"cap_alert_list_layout",
#"cap_gis_location_xml_post_parse",
#"cap_gis_location_xml_post_render",
)
import datetime
import urllib2 # Needed for quoting & error handling on fetch
try:
from cStringIO import StringIO # Faster, where available
except:
from StringIO import StringIO
from gluon import *
from gluon.storage import Storage
from gluon.tools import fetch
from ..s3 import *
# =============================================================================
class S3CAPModel(S3Model):
"""
CAP: Common Alerting Protocol
- this module is a non-functional stub
http://eden.sahanafoundation.org/wiki/BluePrint/Messaging#CAP
"""
names = ("cap_alert",
"cap_alert_represent",
"cap_warning_priority",
"cap_info",
"cap_info_represent",
"cap_resource",
"cap_area",
"cap_area_represent",
"cap_area_location",
"cap_area_tag",
"cap_info_category_opts",
)
def model(self):
T = current.T
db = current.db
settings = current.deployment_settings
add_components = self.add_components
configure = self.configure
crud_strings = current.response.s3.crud_strings
define_table = self.define_table
# ---------------------------------------------------------------------
# List of Incident Categories -- copied from irs module <--
# @ToDo: Switch to using event_incident_type
#
# The keys are based on the Canadian ems.incident hierarchy, with a
# few extra general versions added to 'other'
# The values are meant for end-users, so can be customised as-required
# NB It is important that the meaning of these entries is not changed
# as otherwise this hurts our ability to do synchronisation
# Entries can be hidden from user view in the controller.
# Additional sets of 'translations' can be added to the tuples.
cap_incident_type_opts = {
"animalHealth.animalDieOff": T("Animal Die Off"),
"animalHealth.animalFeed": T("Animal Feed"),
"aviation.aircraftCrash": T("Aircraft Crash"),
"aviation.aircraftHijacking": T("Aircraft Hijacking"),
"aviation.airportClosure": T("Airport Closure"),
"aviation.airspaceClosure": T("Airspace Closure"),
"aviation.noticeToAirmen": T("Notice to Airmen"),
"aviation.spaceDebris": T("Space Debris"),
"civil.demonstrations": T("Demonstrations"),
"civil.dignitaryVisit": T("Dignitary Visit"),
"civil.displacedPopulations": T("Displaced Populations"),
"civil.emergency": T("Civil Emergency"),
"civil.looting": T("Looting"),
"civil.publicEvent": T("Public Event"),
"civil.riot": T("Riot"),
"civil.volunteerRequest": T("Volunteer Request"),
"crime": T("Crime"),
"crime.bomb": T("Bomb"),
"crime.bombExplosion": T("Bomb Explosion"),
"crime.bombThreat": T("Bomb Threat"),
"crime.dangerousPerson": T("Dangerous Person"),
"crime.drugs": T("Drugs"),
"crime.homeCrime": T("Home Crime"),
"crime.illegalImmigrant": T("Illegal Immigrant"),
"crime.industrialCrime": T("Industrial Crime"),
"crime.poisoning": T("Poisoning"),
"crime.retailCrime": T("Retail Crime"),
"crime.shooting": T("Shooting"),
"crime.stowaway": T("Stowaway"),
"crime.terrorism": T("Terrorism"),
"crime.vehicleCrime": T("Vehicle Crime"),
"fire": T("Fire"),
"fire.forestFire": T("Forest Fire"),
"fire.hotSpot": T("Hot Spot"),
"fire.industryFire": T("Industry Fire"),
"fire.smoke": T("Smoke"),
"fire.urbanFire": T("Urban Fire"),
"fire.wildFire": T("Wild Fire"),
"flood": T("Flood"),
"flood.damOverflow": T("Dam Overflow"),
"flood.flashFlood": T("Flash Flood"),
"flood.highWater": T("High Water"),
"flood.overlandFlowFlood": T("Overland Flow Flood"),
"flood.tsunami": T("Tsunami"),
"geophysical.avalanche": T("Avalanche"),
"geophysical.earthquake": T("Earthquake"),
"geophysical.lahar": T("Lahar"),
"geophysical.landslide": T("Landslide"),
"geophysical.magneticStorm": T("Magnetic Storm"),
"geophysical.meteorite": T("Meteorite"),
"geophysical.pyroclasticFlow": T("Pyroclastic Flow"),
"geophysical.pyroclasticSurge": T("Pyroclastic Surge"),
"geophysical.volcanicAshCloud": T("Volcanic Ash Cloud"),
"geophysical.volcanicEvent": T("Volcanic Event"),
"hazardousMaterial": T("Hazardous Material"),
"hazardousMaterial.biologicalHazard": T("Biological Hazard"),
"hazardousMaterial.chemicalHazard": T("Chemical Hazard"),
"hazardousMaterial.explosiveHazard": T("Explosive Hazard"),
"hazardousMaterial.fallingObjectHazard": T("Falling Object Hazard"),
"hazardousMaterial.infectiousDisease": T("Infectious Disease (Hazardous Material)"),
"hazardousMaterial.poisonousGas": T("Poisonous Gas"),
"hazardousMaterial.radiologicalHazard": T("Radiological Hazard"),
"health.infectiousDisease": T("Infectious Disease"),
"health.infestation": T("Infestation"),
"ice.iceberg": T("Iceberg"),
"ice.icePressure": T("Ice Pressure"),
"ice.rapidCloseLead": T("Rapid Close Lead"),
"ice.specialIce": T("Special Ice"),
"marine.marineSecurity": T("Marine Security"),
"marine.nauticalAccident": T("Nautical Accident"),
"marine.nauticalHijacking": T("Nautical Hijacking"),
"marine.portClosure": T("Port Closure"),
"marine.specialMarine": T("Special Marine"),
"meteorological.blizzard": T("Blizzard"),
"meteorological.blowingSnow": T("Blowing Snow"),
"meteorological.drought": T("Drought"),
"meteorological.dustStorm": T("Dust Storm"),
"meteorological.fog": T("Fog"),
"meteorological.freezingDrizzle": T("Freezing Drizzle"),
"meteorological.freezingRain": T("Freezing Rain"),
"meteorological.freezingSpray": T("Freezing Spray"),
"meteorological.hail": T("Hail"),
"meteorological.hurricane": T("Hurricane"),
"meteorological.rainFall": T("Rain Fall"),
"meteorological.snowFall": T("Snow Fall"),
"meteorological.snowSquall": T("Snow Squall"),
"meteorological.squall": T("Squall"),
"meteorological.stormSurge": T("Storm Surge"),
"meteorological.thunderstorm": T("Thunderstorm"),
"meteorological.tornado": T("Tornado"),
"meteorological.tropicalStorm": T("Tropical Storm"),
"meteorological.waterspout": T("Waterspout"),
"meteorological.winterStorm": T("Winter Storm"),
"missingPerson": T("Missing Person"),
# http://en.wikipedia.org/wiki/Amber_Alert
"missingPerson.amberAlert": T("Child Abduction Emergency"),
"missingPerson.missingVulnerablePerson": T("Missing Vulnerable Person"),
# http://en.wikipedia.org/wiki/Silver_Alert
"missingPerson.silver": T("Missing Senior Citizen"),
"publicService.emergencySupportFacility": T("Emergency Support Facility"),
"publicService.emergencySupportService": T("Emergency Support Service"),
"publicService.schoolClosure": T("School Closure"),
"publicService.schoolLockdown": T("School Lockdown"),
"publicService.serviceOrFacility": T("Service or Facility"),
"publicService.transit": T("Transit"),
"railway.railwayAccident": T("Railway Accident"),
"railway.railwayHijacking": T("Railway Hijacking"),
"roadway.bridgeClosure": T("Bridge Closed"),
"roadway.hazardousRoadConditions": T("Hazardous Road Conditions"),
"roadway.roadwayAccident": T("Road Accident"),
"roadway.roadwayClosure": T("Road Closed"),
"roadway.roadwayDelay": T("Road Delay"),
"roadway.roadwayHijacking": T("Road Hijacking"),
"roadway.roadwayUsageCondition": T("Road Usage Condition"),
"roadway.trafficReport": T("Traffic Report"),
"temperature.arcticOutflow": T("Arctic Outflow"),
"temperature.coldWave": T("Cold Wave"),
"temperature.flashFreeze": T("Flash Freeze"),
"temperature.frost": T("Frost"),
"temperature.heatAndHumidity": T("Heat and Humidity"),
"temperature.heatWave": T("Heat Wave"),
"temperature.windChill": T("Wind Chill"),
"wind.galeWind": T("Gale Wind"),
"wind.hurricaneForceWind": T("Hurricane Force Wind"),
"wind.stormForceWind": T("Storm Force Wind"),
"wind.strongWind": T("Strong Wind"),
"other.buildingCollapsed": T("Building Collapsed"),
"other.peopleTrapped": T("People Trapped"),
"other.powerFailure": T("Power Failure"),
}
# ---------------------------------------------------------------------
# CAP alerts
#
# CAP alert Status Code (status)
cap_alert_status_code_opts = OrderedDict([
("Actual", T("Actual - actionable by all targeted recipients")),
("Exercise", T("Exercise - only for designated participants (decribed in note)")),
("System", T("System - for internal functions")),
("Test", T("Test - testing, all recipients disregard")),
("Draft", T("Draft - not actionable in its current form")),
])
# CAP alert message type (msgType)
cap_alert_msgType_code_opts = OrderedDict([
("Alert", T("Alert: Initial information requiring attention by targeted recipients")),
("Update", T("Update: Update and supercede earlier message(s)")),
("Cancel", T("Cancel: Cancel earlier message(s)")),
("Ack", T("Ack: Acknowledge receipt and acceptance of the message(s)")),
("Error", T("Error: Indicate rejection of the message(s)")),
])
# CAP alert scope
cap_alert_scope_code_opts = OrderedDict([
("Public", T("Public - unrestricted audiences")),
("Restricted", T("Restricted - to users with a known operational requirement (described in restriction)")),
("Private", T("Private - only to specified addresses (mentioned as recipients)"))
])
# CAP info categories
cap_info_category_opts = OrderedDict([
("Geo", T("Geophysical (inc. landslide)")),
("Met", T("Meteorological (inc. flood)")),
("Safety", T("General emergency and public safety")),
("Security", T("Law enforcement, military, homeland and local/private security")),
("Rescue", T("Rescue and recovery")),
("Fire", T("Fire suppression and rescue")),
("Health", T("Medical and public health")),
("Env", T("Pollution and other environmental")),
("Transport", T("Public and private transportation")),
("Infra", T("Utility, telecommunication, other non-transport infrastructure")),
("CBRNE", T("Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack")),
("Other", T("Other events")),
])
tablename = "cap_alert"
define_table(tablename,
Field("is_template", "boolean",
readable = False,
writable = True,
),
Field("template_id", "reference cap_alert",
label = T("Template"),
ondelete = "RESTRICT",
represent = self.template_represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cap_alert.id",
self.template_represent,
filterby="is_template",
filter_opts=(True,)
)),
comment = T("Apply a template"),
),
Field("template_title",
label = T("Template Title"),
),
Field("template_settings", "text",
default = "{}",
readable = False,
),
Field("identifier", unique=True, length=128,
default = self.generate_identifier,
label = T("Identifier"),
),
Field("sender",
label = T("Sender"),
default = self.generate_sender,
# @todo: can not be empty in alerts (validator!)
),
s3_datetime("sent",
default = "now",
writable = False,
),
Field("status",
default = "Draft",
label = T("Status"),
requires = IS_IN_SET(cap_alert_status_code_opts),
),
Field("msg_type",
label = T("Message Type"),
requires = IS_EMPTY_OR(
IS_IN_SET(cap_alert_msgType_code_opts)
),
),
Field("source",
label = T("Source"),
default = self.generate_source,
),
Field("scope",
label = T("Scope"),
requires = IS_EMPTY_OR(
IS_IN_SET(cap_alert_scope_code_opts)
),
),
# Text describing the restriction for scope=restricted
Field("restriction", "text",
label = T("Restriction"),
),
Field("addresses", "list:string",
label = T("Recipients"),
represent = self.list_string_represent,
#@ToDo: provide a better way to add multiple addresses,
# do not ask the user to delimit it themselves
# this should eventually use the CAP contacts
#widget = S3CAPAddressesWidget,
),
Field("codes", "text",
default = settings.get_cap_codes(),
label = T("Codes"),
represent = S3KeyValueWidget.represent,
widget = S3KeyValueWidget(),
),
Field("note", "text",
label = T("Note"),
),
Field("reference", "list:reference cap_alert",
label = T("Reference"),
represent = S3Represent(lookup = tablename,
fields = ["msg_type", "sent", "sender"],
field_sep = " - ",
multiple = True,
),
# @ToDo: This should not be manually entered,
# needs a widget
#widget = S3ReferenceWidget(table,
# one_to_many=True,
# allow_create=False),
),
# @ToDo: Switch to using event_incident_type_id
Field("incidents", "list:string",
label = T("Incidents"),
represent = S3Represent(options = cap_incident_type_opts,
multiple = True),
requires = IS_EMPTY_OR(
IS_IN_SET(cap_incident_type_opts,
multiple = True,
sort = True,
)),
widget = S3MultiSelectWidget(),
),
# approved_on field for recording when the alert was approved
s3_datetime("approved_on",
readable = False,
writable = False,
),
*s3_meta_fields())
filter_widgets = [
S3TextFilter(["identifier",
"sender",
"incidents",
"cap_info.headline",
"cap_info.event_type_id",
],
label = T("Search"),
comment = T("Search for an Alert by sender, incident, headline or event."),
),
S3OptionsFilter("info.category",
label = T("Category"),
options = cap_info_category_opts,
),
S3LocationFilter("location.location_id",
label = T("Location(s)"),
# options = gis.get_countries().keys(),
),
S3OptionsFilter("info.language",
label = T("Language"),
),
]
configure(tablename,
context = {"location": "location.location_id",
},
filter_widgets = filter_widgets,
list_layout = cap_alert_list_layout,
list_orderby = "cap_info.expires desc",
onvalidation = self.cap_alert_form_validation,
# update the approved_on field on approve of the alert
onapprove = self.cap_alert_approve,
)
# Components
add_components(tablename,
cap_area = "alert_id",
cap_area_location = {"name": "location",
"joinby": "alert_id",
},
cap_info = "alert_id",
cap_resource = "alert_id",
)
self.set_method("cap", "alert",
method = "import_feed",
action = CAPImportFeed())
if crud_strings["cap_template"]:
crud_strings[tablename] = crud_strings["cap_template"]
else:
ADD_ALERT = T("Create Alert")
crud_strings[tablename] = Storage(
label_create = ADD_ALERT,
title_display = T("Alert Details"),
title_list = T("Alerts"),
# If already-published, this should create a new "Update"
# alert instead of modifying the original
title_update = T("Edit Alert"),
title_upload = T("Import Alerts"),
label_list_button = T("List Alerts"),
label_delete_button = T("Delete Alert"),
msg_record_created = T("Alert created"),
msg_record_modified = T("Alert modified"),
msg_record_deleted = T("Alert deleted"),
msg_list_empty = T("No alerts to show"))
alert_represent = S3Represent(lookup = tablename,
fields = ["msg_type", "sent", "sender"],
field_sep = " - ")
alert_id = S3ReusableField("alert_id", "reference %s" % tablename,
comment = T("The alert message containing this information"),
label = T("Alert"),
ondelete = "CASCADE",
represent = alert_represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cap_alert.id",
alert_represent)),
)
# ---------------------------------------------------------------------
# CAP info segments
#
cap_info_responseType_opts = OrderedDict([
("Shelter", T("Shelter - Take shelter in place or per instruction")),
("Evacuate", T("Evacuate - Relocate as instructed in the instruction")),
("Prepare", T("Prepare - Make preparations per the instruction")),
("Execute", T("Execute - Execute a pre-planned activity identified in instruction")),
("Avoid", T("Avoid - Avoid the subject event as per the instruction")),
("Monitor", T("Monitor - Attend to information sources as described in instruction")),
("Assess", T("Assess - Evaluate the information in this message.")),
("AllClear", T("AllClear - The subject event no longer poses a threat")),
("None", T("None - No action recommended")),
])
cap_info_urgency_opts = OrderedDict([
("Immediate", T("Response action should be taken immediately")),
("Expected", T("Response action should be taken soon (within next hour)")),
("Future", T("Responsive action should be taken in the near future")),
("Past", T("Responsive action is no longer required")),
("Unknown", T("Unknown")),
])
cap_info_severity_opts = OrderedDict([
("Extreme", T("Extraordinary threat to life or property")),
("Severe", T("Significant threat to life or property")),
("Moderate", T("Possible threat to life or property")),
("Minor", T("Minimal to no known threat to life or property")),
("Unknown", T("Severity unknown")),
])
cap_info_certainty_opts = OrderedDict([
("Observed", T("Observed: determined to have occurred or to be ongoing")),
("Likely", T("Likely (p > ~50%)")),
("Possible", T("Possible but not likely (p <= ~50%)")),
("Unlikely", T("Not expected to occur (p ~ 0)")),
("Unknown", T("Certainty unknown")),
])
# ---------------------------------------------------------------------
# Warning Priorities for CAP
tablename = "cap_warning_priority"
define_table(tablename,
Field("priority_rank", "integer",
label = T("Priority Rank"),
length = 2,
),
Field("event_code",
label = T("Event Code"),
),
Field("name", notnull = True, length = 64,
label = T("Name"),
),
Field("event_type",
label = T("Event Type"),
),
Field("urgency",
label = T("Urgency"),
requires = IS_IN_SET(cap_info_urgency_opts),
),
Field("severity",
label = T("Severity"),
requires = IS_IN_SET(cap_info_severity_opts),
),
Field("certainty",
label = T("Certainty"),
requires = IS_IN_SET(cap_info_certainty_opts),
),
Field("color_code",
label = T("Color Code"),
),
*s3_meta_fields())
priority_represent = S3Represent(lookup = tablename)
crud_strings[tablename] = Storage(
label_create = T("Create Warning Priority"),
title_display = T("Warning Priority Details"),
title_list = T("Warning Priorities"),
title_update = T("Edit Warning Priority"),
title_upload = T("Import Warning Priorities"),
label_list_button = T("List Warning Priorities"),
label_delete_button = T("Delete Warning Priority"),
msg_record_created = T("Warning Priority added"),
msg_record_modified = T("Warning Priority updated"),
msg_record_deleted = T("Warning Priority removed"),
msg_list_empty = T("No Warning Priorities currently registered")
)
# ---------------------------------------------------------------------
# CAP info priority
# @ToDo: i18n: Need label=T("")
tablename = "cap_info"
define_table(tablename,
alert_id(),
Field("is_template", "boolean",
default = False,
readable = False,
writable = False,
),
Field("template_info_id", "reference cap_info",
ondelete = "RESTRICT",
readable = False,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cap_info.id",
self.template_represent,
filterby="is_template",
filter_opts=(True,)
)),
widget = S3HiddenWidget(),
),
Field("template_settings", "text",
readable = False,
),
Field("language",
default = "en",
requires = IS_EMPTY_OR(
IS_IN_SET(settings.get_cap_languages())
),
),
Field("category", "list:string",
represent = S3Represent(options = cap_info_category_opts,
multiple = True,
),
required = True,
requires = IS_IN_SET(cap_info_category_opts,
multiple = True,
),
widget = S3MultiSelectWidget(),
), # 1 or more allowed
self.event_type_id(empty = False,
script = '''
$.filterOptionsS3({
'trigger':'event_type_id',
'target':'priority',
'lookupURL':S3.Ap.concat('/cap/priority_get/'),
'lookupResource':'event_type'
})'''
),
Field("response_type", "list:string",
represent = S3Represent(options = cap_info_responseType_opts,
multiple = True,
),
requires = IS_IN_SET(cap_info_responseType_opts,
multiple = True),
widget = S3MultiSelectWidget(),
), # 0 or more allowed
Field("priority",
represent = priority_represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(
db, "cap_warning_priority.id",
priority_represent
),
),
),
Field("urgency",
required = True,
requires = IS_IN_SET(cap_info_urgency_opts),
),
Field("severity",
required = True,
requires = IS_IN_SET(cap_info_severity_opts),
),
Field("certainty",
required = True,
requires = IS_IN_SET(cap_info_certainty_opts),
),
Field("audience", "text"),
Field("event_code", "text",
default = settings.get_cap_event_codes(),
represent = S3KeyValueWidget.represent,
widget = S3KeyValueWidget(),
),
s3_datetime("effective",
default = "now",
),
s3_datetime("onset"),
s3_datetime("expires",
past = 0,
),
Field("sender_name"),
Field("headline"),
Field("description", "text"),
Field("instruction", "text"),
Field("contact", "text"),
Field("web",
requires = IS_EMPTY_OR(IS_URL()),
),
Field("parameter", "text",
default = settings.get_cap_parameters(),
label = T("Parameters"),
represent = S3KeyValueWidget.represent,
widget = S3KeyValueWidget(),
),
*s3_meta_fields())
# @ToDo: Move labels into main define_table (can then be lazy & performs better anyway)
info_labels = cap_info_labels()
for field in info_labels:
db.cap_info[field].label = info_labels[field]
if crud_strings["cap_template_info"]:
crud_strings[tablename] = crud_strings["cap_template_info"]
else:
ADD_INFO = T("Add alert information")
crud_strings[tablename] = Storage(
label_create = ADD_INFO,
title_display = T("Alert information"),
title_list = T("Information entries"),
title_update = T("Update alert information"), # this will create a new "Update" alert?
title_upload = T("Import alert information"),
subtitle_list = T("Listing of alert information items"),
label_list_button = T("List information entries"),
label_delete_button = T("Delete Information"),
msg_record_created = T("Alert information created"),
msg_record_modified = T("Alert information modified"),
msg_record_deleted = T("Alert information deleted"),
msg_list_empty = T("No alert information to show"))
info_represent = S3Represent(lookup = tablename,
fields = ["language", "headline"],
field_sep = " - ")
info_id = S3ReusableField("info_id", "reference %s" % tablename,
label = T("Information Segment"),
ondelete = "CASCADE",
represent = info_represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cap_info.id",
info_represent)
),
sortby = "identifier",
)
configure(tablename,
#create_next = URL(f="info", args=["[id]", "area"]),
onaccept = self.info_onaccept,
)
# Components
add_components(tablename,
cap_resource = "info_id",
cap_area = "info_id",
)
# ---------------------------------------------------------------------
# CAP Resource segments
#
# Resource elements sit inside the Info segment of the export XML
# - however in most cases these would be common across all Infos, so in
# our internal UI we link these primarily to the Alert but still
# allow the option to differentiate by Info
#
tablename = "cap_resource"
define_table(tablename,
alert_id(writable = False,
),
info_id(),
self.super_link("doc_id", "doc_entity"),
Field("resource_desc",
requires = IS_NOT_EMPTY(),
),
Field("mime_type",
requires = IS_NOT_EMPTY(),
),
Field("size", "integer",
writable = False,
),
Field("uri",
# needs a special validation
writable = False,
),
#Field("file", "upload"),
Field("deref_uri", "text",
readable = False,
writable = False,
),
Field("digest",
writable = False,
),
*s3_meta_fields())
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Resource"),
title_display = T("Alert Resource"),
title_list = T("Resources"),
title_update = T("Edit Resource"),
subtitle_list = T("List Resources"),
label_list_button = T("List Resources"),
label_delete_button = T("Delete Resource"),
msg_record_created = T("Resource added"),
msg_record_modified = T("Resource updated"),
msg_record_deleted = T("Resource deleted"),
msg_list_empty = T("No resources currently defined for this alert"))
# @todo: complete custom form
crud_form = S3SQLCustomForm(#"name",
"info_id",
"resource_desc",
S3SQLInlineComponent("image",
label=T("Image"),
fields=["file",
],
),
S3SQLInlineComponent("document",
label=T("Document"),
fields=["file",
],
),
)
configure(tablename,
super_entity = "doc_entity",
crud_form = crud_form,
# Shouldn't be required if all UI actions go through alert controller & XSLT configured appropriately
create_onaccept = update_alert_id(tablename),
)
# ---------------------------------------------------------------------
# CAP Area segments
#
# Area elements sit inside the Info segment of the export XML
# - however in most cases these would be common across all Infos, so in
# our internal UI we link these primarily to the Alert but still
# allow the option to differentiate by Info
#
# Each <area> can have multiple elements which are one of <polygon>,
# <circle>, or <geocode>.
# <polygon> and <circle> are explicit geometry elements.
# <geocode> is a key-value pair in which the key is a standard
# geocoding system like SAME, FIPS, ZIP, and the value is a defined
# value in that system. The region described by the <area> is the
# union of the areas described by the individual elements, but the
# CAP spec advises that, if geocodes are included, the concrete
# geometry elements should outline the area specified by the geocodes,
# as not all recipients will have access to the meanings of the
# geocodes. However, since geocodes are a compact way to describe an
# area, it may be that they will be used without accompanying geometry,
# so we should not count on having <polygon> or <circle>.
#
# Geometry elements are each represented by a gis_location record, and
# linked to the cap_area record via the cap_area_location link table.
# For the moment, <circle> objects are stored with the center in the
# gis_location's lat, lon, and radius (in km) as a tag "radius" and
# value. ToDo: Later, we will add CIRCLESTRING WKT.
#
# Geocode elements are currently stored as key value pairs in the
# cap_area record.
#
# <area> can also specify a minimum altitude and maximum altitude
# ("ceiling"). These are stored in explicit fields for now, but could
# be replaced by key value pairs, if it is found that they are rarely
# used.
#
# (An alternative would be to have cap_area link to a gis_location_group
# record. In that case, the geocode tags could be stored in the
# gis_location_group's overall gis_location element's tags. The altitude
# could be stored in the overall gis_location's elevation, with ceiling
# stored in a tag. We could consider adding a maximum elevation field.)
tablename = "cap_area"
define_table(tablename,
alert_id(writable = False,
),
info_id(),
Field("name",
label = T("Area description"),
required = True,
),
Field("altitude", "integer"), # Feet above Sea-level in WGS84 (Specific or Minimum is using a range)
Field("ceiling", "integer"), # Feet above Sea-level in WGS84 (Maximum)
*s3_meta_fields())
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Area"),
title_display = T("Alert Area"),
title_list = T("Areas"),
title_update = T("Edit Area"),
subtitle_list = T("List Areas"),
label_list_button = T("List Areas"),
label_delete_button = T("Delete Area"),
msg_record_created = T("Area added"),
msg_record_modified = T("Area updated"),
msg_record_deleted = T("Area deleted"),
msg_list_empty = T("No areas currently defined for this alert"))
crud_form = S3SQLCustomForm("name",
"info_id",
# Not yet working with default formstyle or multiple=True
#S3SQLInlineComponent("location",
# name = "location",
# label = "",
# multiple = False,
# fields = [("", "location_id")],
# ),
S3SQLInlineComponent("tag",
name = "tag",
label = "",
fields = ["tag",
"value",
],
),
"altitude",
"ceiling",
)
area_represent = S3Represent(lookup=tablename)
configure(tablename,
#create_next = URL(f="area", args=["[id]", "location"]),
# Shouldn't be required if all UI actions go through alert controller & XSLT configured appropriately
create_onaccept = update_alert_id(tablename),
crud_form = crud_form,
)
# Components
add_components(tablename,
cap_area_location = {"name": "location",
"joinby": "area_id",
},
cap_area_tag = {"name": "tag",
"joinby": "area_id",
},
)
area_id = S3ReusableField("area_id", "reference %s" % tablename,
label = T("Area"),
ondelete = "CASCADE",
represent = area_represent,
requires = IS_ONE_OF(db, "cap_area.id",
area_represent),
)
# ToDo: Use a widget tailored to entering <polygon> and <circle>.
# Want to be able to enter them by drawing on the map.
# Also want to allow selecting existing locations that have
# geometry, maybe with some filtering so the list isn't cluttered
# with irrelevant locations.
tablename = "cap_area_location"
define_table(tablename,
alert_id(readable = False,
writable = False,
),
area_id(),
self.gis_location_id(
widget = S3LocationSelector(points = False,
polygons = True,
show_map = True,
catalog_layers = True,
show_address = False,
show_postcode = False,
),
),
)
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Add Location"),
title_display = T("Alert Location"),
title_list = T("Locations"),
title_update = T("Edit Location"),
subtitle_list = T("List Locations"),
label_list_button = T("List Locations"),
label_delete_button = T("Delete Location"),
msg_record_created = T("Location added"),
msg_record_modified = T("Location updated"),
msg_record_deleted = T("Location deleted"),
msg_list_empty = T("No locations currently defined for this alert"))
configure(tablename,
# Shouldn't be required if all UI actions go through alert controller & XSLT configured appropriately
create_onaccept = update_alert_id(tablename),
)
# ---------------------------------------------------------------------
# Area Tags
# - Key-Value extensions
# - Used to hold for geocodes: key is the geocode system name, and
# value is the specific value for this area.
# - Could store other values here as well, to avoid dedicated fields
# in cap_area for rarely-used items like altitude and ceiling, but
# would have to distinguish those from geocodes.
#
# ToDo: Provide a mechanism for pre-loading geocodes that are not tied
# to individual areas.
# ToDo: Allow sharing the key-value pairs. Cf. Ruby on Rails tagging
# systems such as acts-as-taggable-on, which has a single table of tags
# used by all classes. Each tag record has the class and field that the
# tag belongs to, as well as the tag string. We'd want tag and value,
# but the idea is the same: There would be a table with tag / value
# pairs, and individual cap_area, event_event, org_whatever records
# would link to records in the tag table. So we actually would not have
# duplicate tag value records as we do now.
tablename = "cap_area_tag"
define_table(tablename,
area_id(),
# ToDo: Allow selecting from a dropdown list of pre-defined
# geocode system names.
Field("tag",
label = T("Geocode Name"),
),
# ToDo: Once the geocode system is selected, fetch a list
# of current values for that geocode system. Allow adding
# new values, e.g. with combo box menu.
Field("value",
label = T("Value"),
),
s3_comments(),
*s3_meta_fields())
#configure(tablename,
# deduplicate = self.cap_area_tag_deduplicate,
# )
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
return dict(cap_alert_id = alert_id,
cap_alert_represent = alert_represent,
cap_area_represent = area_represent,
cap_info_represent = info_represent,
cap_info_category_opts = cap_info_category_opts
)
# -------------------------------------------------------------------------
@staticmethod
def generate_identifier():
"""
Generate an identifier for a new form
"""
db = current.db
table = db.cap_alert
r = db().select(table.id,
limitby=(0, 1),
orderby=~table.id).first()
_time = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d")
if r:
next_id = int(r.id) + 1
else:
next_id = 1
# Format: prefix-time+-timezone+sequence-suffix
settings = current.deployment_settings
prefix = settings.get_cap_identifier_prefix() or current.xml.domain
oid = settings.get_cap_identifier_oid()
suffix = settings.get_cap_identifier_suffix()
return "%s-%s-%s-%03d%s%s" % \
(prefix, oid, _time, next_id, ["", "-"][bool(suffix)], suffix)
# -------------------------------------------------------------------------
@staticmethod
def generate_sender():
"""
Generate a sender for a new form
"""
try:
user_id = current.auth.user.id
except AttributeError:
return ""
return "%s/%d" % (current.xml.domain, user_id)
# -------------------------------------------------------------------------
@staticmethod
def generate_source():
"""
Generate a source for CAP alert
"""
return "%s@%s" % (current.xml.domain,
current.deployment_settings.get_base_public_url())
# -------------------------------------------------------------------------
@staticmethod
def template_represent(id, row=None):
"""
Represent an alert template concisely
"""
if row:
id = row.id
elif not id:
return current.messages["NONE"]
else:
db = current.db
table = db.cap_alert
row = db(table.id == id).select(table.is_template,
table.template_title,
# left = table.on(table.id == table.parent_item_category_id), Doesn't work
limitby=(0, 1)).first()
try:
# @ToDo: Should get headline from "info"?
if row.is_template:
return row.template_title
else:
return s3db.cap_alert_represent(id)
except:
return current.messages.UNKNOWN_OPT
# -------------------------------------------------------------------------
@staticmethod
def list_string_represent(string, fmt=lambda v: v):
try:
if isinstance(string, list):
return ", ".join([fmt(i) for i in string])
elif isinstance(string, basestring):
return ", ".join([fmt(i) for i in string[1:-1].split("|")])
except IndexError:
return current.messages.UNKNOWN_OPT
return ""
# -------------------------------------------------------------------------
@staticmethod
def cap_alert_form_validation(form):
"""
On Validation for CAP alert form
"""
form_vars = form.vars
if form_vars.get("scope") == "Private" and not form_vars.get("addresses"):
form.errors["addresses"] = \
current.T("'Recipients' field mandatory in case of 'Private' scope")
return
# -------------------------------------------------------------------------
@staticmethod
def info_onaccept(form):
"""
After DB I/O
"""
if "vars" in form:
form_vars = form.vars
elif "id" in form:
form_vars = form
elif hasattr(form, "vars"):
form_vars = form.vars
else:
form_vars = form
info_id = form_vars.id
if not info_id:
return
db = current.db
atable = db.cap_alert
itable = db.cap_info
info = db(itable.id == info_id).select(itable.alert_id,
limitby=(0, 1)).first()
if info:
alert_id = info.alert_id
if alert_id and cap_alert_is_template(alert_id):
db(itable.id == info_id).update(is_template = True)
return True
# -------------------------------------------------------------------------
@staticmethod
def cap_alert_approve(record=None):
"""
Update the approved_on field when alert gets approved
"""
if not record:
return
alert_id = record["id"]
# Update approved_on at the time the alert is approved
if alert_id:
db = current.db
approved_on = record["approved_on"]
db(db.cap_alert.id == alert_id).update(approved_on = current.request.utcnow)
# =============================================================================
def cap_info_labels():
"""
Labels for CAP info segments
"""
T = current.T
return dict(language=T("Language"),
category=T("Category"),
event_type_id=T("Event"),
response_type=T("Response type"),
urgency=T("Urgency"),
severity=T("Severity"),
certainty=T("Certainty"),
audience=T("Audience"),
event_code=T("Event code"),
effective=T("Effective"),
onset=T("Onset"),
expires=T("Expires at"),
sender_name=T("Sender's name"),
headline=T("Headline"),
description=T("Description"),
instruction=T("Instruction"),
web=T("URL"),
contact=T("Contact information"),
parameter=T("Parameters")
)
# =============================================================================
def cap_alert_is_template(alert_id):
"""
Tell whether an alert entry is a template
"""
if not alert_id:
return False
table = current.s3db.cap_alert
query = (table.id == alert_id)
r = current.db(query).select(table.is_template,
limitby=(0, 1)).first()
return r and r.is_template
# =============================================================================
def cap_rheader(r):
""" Resource Header for CAP module """
rheader = None
if r.representation == "html":
record = r.record
if record:
T = current.T
s3db = current.s3db
tablename = r.tablename
if tablename == "cap_alert":
record_id = record.id
table = s3db.cap_info
query = (table.alert_id == record_id)
row = current.db(query).select(table.id,
limitby=(0, 1)).first()
if record.is_template:
if not (row and row.id):
error = DIV(T("An alert needs to contain at least one info item."),
_class="error")
else:
error = ""
tabs = [(T("Template"), None),
(T("Information template"), "info"),
#(T("Area"), "area"),
#(T("Resource Files"), "resource"),
]
rheader_tabs = s3_rheader_tabs(r, tabs)
rheader = DIV(TABLE(TR(TH("%s: " % T("Template")),
TD(A(S3CAPModel.template_represent(record_id, record),
_href=URL(c="cap", f="template",
args=[record_id, "update"]))),
),
),
rheader_tabs,
error
)
else:
if not (row and row.id):
error = DIV(T("You need to create at least one alert information item in order to be able to broadcast this alert!"),
_class="error")
export_btn = ""
else:
error = ""
export_btn = A(DIV(_class="export_cap_large"),
_href=URL(c="cap", f="alert", args=["%s.cap" % record_id]),
_target="_blank",
)
auth = current.auth
# Display 'Submit for Approval' based on permission
# and deployment settings
if not r.record.approved_by and \
current.deployment_settings.get_cap_authorisation() and \
auth.s3_has_permission("update", "cap_alert", record_id=r.id):
# Get the user ids for the role alert_approver
db = current.db
agtable = db.auth_group
rows = db(agtable.role == "Alert Approver")._select(agtable.id)
group_rows = db(agtable.id.belongs(rows)).select(agtable.id)
if group_rows:
for group_row in group_rows:
group_id = group_row.id
user_ids = auth.s3_group_members(group_id) # List of user_ids
pe_ids = [] # List of pe_ids
for user_id in user_ids:
pe_ids.append(auth.s3_user_pe_id(int(user_id)))
submit_btn = A(T("Submit for Approval"),
_href = URL(f = "compose",
vars = {"cap_alert.id": record.id,
"pe_ids": pe_ids,
},
),
_class = "action-btn"
)
else:
submit_btn = None
else:
submit_btn = None
table = s3db.cap_area
query = (table.alert_id == record_id)
row = current.db(query).select(table.id,
limitby=(0, 1)).first()
if row:
# We have an Area, so we can add Locations
location_tab = (T("Location"), "location")
else:
location_tab = ""
tabs = [(T("Alert Details"), None),
(T("Information"), "info"),
(T("Area"), "area"),
location_tab,
(T("Resource Files"), "resource"),
]
rheader_tabs = s3_rheader_tabs(r, tabs)
rheader = DIV(TABLE(TR(TH("%s: " % T("Alert")),
TD(A(s3db.cap_alert_represent(record_id, record),
_href=URL(c="cap", f="alert",
args=[record_id, "update"]))),
),
TR(export_btn)
),
rheader_tabs,
error
)
if submit_btn:
rheader.insert(1, TR(submit_btn))
elif tablename == "cap_area":
# Shouldn't ever be called
tabs = [(T("Area"), None),
(T("Locations"), "location"),
#(T("Geocodes"), "tag"),
]
rheader_tabs = s3_rheader_tabs(r, tabs)
rheader = DIV(TABLE(TR(TH("%s: " % T("Alert")),
TD(A(s3db.cap_alert_represent(record.alert_id),
_href=URL(c="cap", f="alert",
args=[record.id, "update"])))
),
TR(TH("%s: " % T("Information")),
TD(A(s3db.cap_info_represent(record.info_id),
_href=URL(c="cap", f="info",
args=[record.info_id, "update"]))),
),
TR(TH("%s: " % T("Area")),
TD(A(s3db.cap_area_represent(record.id, record),
_href=URL(c="cap", f="area",
args=[record.id, "update"]))),
),
),
rheader_tabs
)
elif tablename == "cap_area_location":
# Shouldn't ever be called
# We need the rheader only for the link back to the area.
rheader = DIV(TABLE(TR(TH("%s: " % T("Area")),
TD(A(s3db.cap_area_represent(record.area_id),
_href=URL(c="cap", f="area",
args=[record.area_id, "update"]))),
),
))
elif tablename == "cap_info":
# Shouldn't ever be called
tabs = [(T("Information"), None),
(T("Resource Files"), "resource"),
]
if cap_alert_is_template(record.alert_id):
rheader_tabs = s3_rheader_tabs(r, tabs)
table = r.table
rheader = DIV(TABLE(TR(TH("%s: " % T("Template")),
TD(A(S3CAPModel.template_represent(record.alert_id),
_href=URL(c="cap", f="template",
args=[record.alert_id, "update"]))),
),
TR(TH("%s: " % T("Info template")),
TD(A(s3db.cap_info_represent(record.id, record),
_href=URL(c="cap", f="info",
args=[record.id, "update"]))),
)
),
rheader_tabs,
_class="cap_info_template_form"
)
current.response.s3.js_global.append('''i18n.cap_locked="%s"''' % T("Locked"))
else:
tabs.insert(1, (T("Areas"), "area"))
rheader_tabs = s3_rheader_tabs(r, tabs)
table = r.table
rheader = DIV(TABLE(TR(TH("%s: " % T("Alert")),
TD(A(s3db.cap_alert_represent(record.alert_id),
_href=URL(c="cap", f="alert",
args=[record.alert_id, "update"]))),
),
TR(TH("%s: " % T("Information")),
TD(A(s3db.cap_info_represent(record.id, record),
_href=URL(c="cap", f="info",
args=[record.id, "update"]))),
)
),
rheader_tabs
)
return rheader
# =============================================================================
def update_alert_id(tablename):
""" On-accept for area and resource records """
def func(form):
if "vars" in form:
form_vars = form.vars
elif "id" in form:
form_vars = form
elif hasattr(form, "vars"):
form_vars = form.vars
else:
form_vars = form
if form_vars.get("alert_id", None):
# Nothing to do
return
# Look up from the info/area
_id = form_vars.id
if not _id:
return
db = current.db
table = db[tablename]
if tablename == "cap_area_location":
area_id = form_vars.get("area_id", None)
if not area_id:
# Get the full record
item = db(table.id == _id).select(table.alert_id,
table.area_id,
limitby=(0, 1)).first()
try:
alert_id = item.alert_id
area_id = item.area_id
except:
# Nothing we can do
return
if alert_id:
# Nothing to do
return
atable = db.cap_area
area = db(atable.id == area_id).select(atable.alert_id,
limitby=(0, 1)).first()
try:
alert_id = area.alert_id
except:
# Nothing we can do
return
else:
info_id = form_vars.get("info_id", None)
if not info_id:
# Get the full record
item = db(table.id == _id).select(table.alert_id,
table.info_id,
limitby=(0, 1)).first()
try:
alert_id = item.alert_id
info_id = item.info_id
except:
# Nothing we can do
return
if alert_id:
# Nothing to do
return
itable = db.cap_info
info = db(itable.id == info_id).select(itable.alert_id,
limitby=(0, 1)).first()
try:
alert_id = info.alert_id
except:
# Nothing we can do
return
db(table.id == _id).update(alert_id = alert_id)
return func
# =============================================================================
def cap_gis_location_xml_post_parse(element, record):
"""
UNUSED - done in XSLT
Convert CAP polygon representation to WKT; extract circle lat lon.
Latitude and longitude in CAP are expressed as signed decimal values in
coordinate pairs:
latitude,longitude
The circle text consists of:
latitude,longitude radius
where the radius is in km.
Polygon text consists of a space separated sequence of at least 4
coordinate pairs where the first and last are the same.
lat1,lon1 lat2,lon2 lat3,lon3 ... lat1,lon1
"""
# @ToDo: Extract altitude and ceiling from the enclosing <area>, and
# compute an elevation value to apply to all enclosed gis_locations.
cap_polygons = element.xpath("cap_polygon")
if cap_polygons:
cap_polygon_text = cap_polygons[0].text
# CAP polygons and WKT have opposite separator conventions:
# CAP has spaces between coordinate pairs and within pairs the
# coordinates are separated by comma, and vice versa for WKT.
# Unfortunately, CAP and WKT (as we use it) also have opposite
# orders of lat and lon. CAP has lat lon, WKT has lon lat.
# Both close the polygon by repeating the first point.
cap_points_text = cap_polygon_text.split()
cap_points = [cpoint.split(",") for cpoint in cap_points_text]
# @ToDo: Should we try interpreting all the points as decimal numbers,
# and failing validation if they're wrong?
wkt_points = ["%s %s" % (cpoint[1], cpoint[0]) for cpoint in cap_points]
wkt_polygon_text = "POLYGON ((%s))" % ", ".join(wkt_points)
record.wkt = wkt_polygon_text
return
cap_circle_values = element.xpath("resource[@name='gis_location_tag']/data[@field='tag' and text()='cap_circle']/../data[@field='value']")
if cap_circle_values:
cap_circle_text = cap_circle_values[0].text
coords, radius = cap_circle_text.split()
lat, lon = coords.split(",")
try:
# If any of these fail to interpret as numbers, the circle was
# badly formatted. For now, we don't try to fail validation,
# but just don't set the lat, lon.
lat = float(lat)
lon = float(lon)
radius = float(radius)
except ValueError:
return
record.lat = lat
record.lon = lon
# Add a bounding box for the given radius, if it is not zero.
if radius > 0.0:
bbox = current.gis.get_bounds_from_radius(lat, lon, radius)
record.lat_min = bbox["lat_min"]
record.lon_min = bbox["lon_min"]
record.lat_max = bbox["lat_max"]
record.lon_max = bbox["lon_max"]
# =============================================================================
def cap_gis_location_xml_post_render(element, record):
"""
UNUSED - done in XSLT
Convert Eden WKT polygon (and eventually circle) representation to
CAP format and provide them in the rendered s3xml.
Not all internal formats have a parallel in CAP, but an effort is made
to provide a resonable substitute:
Polygons are supported.
Circles that were read in from CAP (and thus carry the original CAP
circle data) are supported.
Multipolygons are currently rendered as their bounding box.
Points are rendered as zero radius circles.
Latitude and longitude in CAP are expressed as signed decimal values in
coordinate pairs:
latitude,longitude
The circle text consists of:
latitude,longitude radius
where the radius is in km.
Polygon text consists of a space separated sequence of at least 4
coordinate pairs where the first and last are the same.
lat1,lon1 lat2,lon2 lat3,lon3 ... lat1,lon1
"""
# @ToDo: Can we rely on gis_feature_type == 3 to tell if the location is a
# polygon, or is it better to look for POLYGON in the wkt? For now, check
# both.
# @ToDo: CAP does not support multipolygons. Do we want to extract their
# outer polygon if passed MULTIPOLYGON wkt? For now, these are exported
# with their bounding box as the polygon.
# @ToDo: What if a point (gis_feature_type == 1) that is not a CAP circle
# has a non-point bounding box? Should it be rendered as a polygon for
# the bounding box?
try:
from lxml import etree
except:
# This won't fail, since we're in the middle of processing xml.
return
SubElement = etree.SubElement
s3xml = current.xml
TAG = s3xml.TAG
RESOURCE = TAG["resource"]
DATA = TAG["data"]
ATTRIBUTE = s3xml.ATTRIBUTE
NAME = ATTRIBUTE["name"]
FIELD = ATTRIBUTE["field"]
VALUE = ATTRIBUTE["value"]
loc_tablename = "gis_location"
tag_tablename = "gis_location_tag"
tag_fieldname = "tag"
val_fieldname = "value"
polygon_tag = "cap_polygon"
circle_tag = "cap_circle"
fallback_polygon_tag = "cap_polygon_fallback"
fallback_circle_tag = "cap_circle_fallback"
def __cap_gis_location_add_polygon(element, cap_polygon_text, fallback=False):
"""
Helper for cap_gis_location_xml_post_render that adds the CAP polygon
data to the current element in a gis_location_tag element.
"""
# Make a gis_location_tag.
tag_resource = SubElement(element, RESOURCE)
tag_resource.set(NAME, tag_tablename)
tag_field = SubElement(tag_resource, DATA)
# Add tag and value children.
tag_field.set(FIELD, tag_fieldname)
if fallback:
tag_field.text = fallback_polygon_tag
else:
tag_field.text = polygon_tag
val_field = SubElement(tag_resource, DATA)
val_field.set(FIELD, val_fieldname)
val_field.text = cap_polygon_text
def __cap_gis_location_add_circle(element, lat, lon, radius, fallback=False):
"""
Helper for cap_gis_location_xml_post_render that adds CAP circle
data to the current element in a gis_location_tag element.
"""
# Make a gis_location_tag.
tag_resource = SubElement(element, RESOURCE)
tag_resource.set(NAME, tag_tablename)
tag_field = SubElement(tag_resource, DATA)
# Add tag and value children.
tag_field.set(FIELD, tag_fieldname)
if fallback:
tag_field.text = fallback_circle_tag
else:
tag_field.text = circle_tag
val_field = SubElement(tag_resource, DATA)
val_field.set(FIELD, val_fieldname)
# Construct a CAP circle string: latitude,longitude radius
cap_circle_text = "%s,%s %s" % (lat, lon, radius)
val_field.text = cap_circle_text
# Sort out the geometry case by wkt, CAP tags, gis_feature_type, bounds,...
# Check the two cases for CAP-specific locations first, as those will have
# definite export values. For others, we'll attempt to produce either a
# circle or polygon: Locations with a bounding box will get a box polygon,
# points will get a zero-radius circle.
# Currently wkt is stripped out of gis_location records right here:
# https://github.com/flavour/eden/blob/master/modules/s3/s3resource.py#L1332
# https://github.com/flavour/eden/blob/master/modules/s3/s3resource.py#L1426
# https://github.com/flavour/eden/blob/master/modules/s3/s3resource.py#L3152
# Until we provide a way to configure that choice, this will not work for
# polygons.
wkt = record.get("wkt", None)
# WKT POLYGON: Although there is no WKT spec, according to every reference
# that deals with nested polygons, the outer, enclosing, polygon must be
# listed first. Hence, we extract only the first polygon, as CAP has no
# provision for nesting.
if wkt and wkt.startswith("POLYGON"):
# ToDo: Is it sufficient to test for adjacent (( to find the start of
# the polygon, or might there be whitespace between them?
start = wkt.find("((")
end = wkt.find(")")
if start >=0 and end >=0:
polygon_text = wkt[start + 2 : end]
points_text = polygon_text.split(",")
points = [p.split() for p in points_text]
cap_points_text = ["%s,%s" % (point[1], point[0]) for point in points]
cap_polygon_text = " ".join(cap_points_text)
__cap_gis_location_add_polygon(element, cap_polygon_text)
return
# Fall through if the wkt string was mal-formed.
# CAP circle stored in a gis_location_tag with tag = cap_circle.
# If there is a cap_circle tag, we don't need to do anything further, as
# export.xsl will use it. However, we don't know if there is a cap_circle
# tag...
#
# @ToDo: The export calls xml_post_render after processing a resource's
# fields, but before its components are added as children in the xml tree.
# If this were delayed til after the components were added, we could look
# there for the cap_circle gis_location_tag record. Since xml_post_parse
# isn't in use yet (except for this), maybe we could look at moving it til
# after the components?
#
# For now, with the xml_post_render before components: We could do a db
# query to check for a real cap_circle tag record, and not bother with
# creating fallbacks from bounding box or point...but we don't have to.
# Instead, just go ahead and add the fallbacks under different tag names,
# and let the export.xsl sort them out. This only wastes a little time
# compared to a db query.
# ToDo: MULTIPOLYGON -- Can stitch together the outer polygons in the
# multipolygon, but would need to assure all were the same handedness.
# The remaining cases are for locations that don't have either polygon wkt
# or a cap_circle tag.
# Bounding box: Make a four-vertex polygon from the bounding box.
# This is a fallback, as if there is a circle tag, we'll use that.
lon_min = record.get("lon_min", None)
lon_max = record.get("lon_max", None)
lat_min = record.get("lat_min", None)
lat_max = record.get("lat_max", None)
if lon_min and lon_max and lat_min and lat_max and \
(lon_min != lon_max) and (lat_min != lat_max):
# Although there is no WKT requirement, arrange the points in
# counterclockwise order. Recall format is:
# lat1,lon1 lat2,lon2 ... latN,lonN, lat1,lon1
cap_polygon_text = \
"%(lat_min)s,%(lon_min)s %(lat_min)s,%(lon_max)s %(lat_max)s,%(lon_max)s %(lat_max)s,%(lon_min)s %(lat_min)s,%(lon_min)s" \
% {"lon_min": lon_min,
"lon_max": lon_max,
"lat_min": lat_min,
"lat_max": lat_max}
__cap_gis_location_add_polygon(element, cap_polygon_text, fallback=True)
return
# WKT POINT or location with lat, lon: This can be rendered as a
# zero-radius circle.
# Q: Do we put bounding boxes around POINT locations, and are they
# meaningful?
lat = record.get("lat", None)
lon = record.get("lon", None)
if not lat or not lon:
# Look for POINT.
if wkt and wkt.startswith("POINT"):
start = wkt.find("(")
end = wkt.find(")")
if start >=0 and end >=0:
point_text = wkt[start + 2 : end]
point = point_text.split()
try:
lon = float(point[0])
lat = float(point[1])
except ValueError:
pass
if lat and lon:
# Add a (fallback) circle with zero radius.
__cap_gis_location_add_circle(element, lat, lon, 0, True)
return
# ToDo: Other WKT.
# Did not find anything to use. Presumably the area has a text description.
return
# =============================================================================
def cap_alert_list_layout(list_id, item_id, resource, rfields, record):
"""
Default dataList item renderer for CAP Alerts on the Home page.
@param list_id: the HTML ID of the list
@param item_id: the HTML ID of the item
@param resource: the S3Resource to render
@param rfields: the S3ResourceFields to render
@param record: the record as dict
"""
record_id = record["cap_alert.id"]
item_class = "thumbnail"
#raw = record._row
headline = record["cap_info.headline"]
location = record["cap_area.name"]
description = record["cap_info.description"]
sender = record["cap_info.sender_name"]
headline = A(headline,
# @ToDo: Link to nicely-formatted version of Display page
_href = URL(c="cap", f="alert", args=record_id),
)
headline = DIV(headline,
current.T("in %(location)s") % dict(location=location)
)
item = DIV(headline,
P(description),
P(sender, style="bold"),
_class=item_class,
_id=item_id,
)
return item
# =============================================================================
class CAPImportFeed(S3Method):
"""
Import CAP alerts from a URL
"""
# -------------------------------------------------------------------------
@staticmethod
def apply_method(r, **attr):
"""
Apply method.
@param r: the S3Request
@param attr: controller options for this request
"""
if r.representation == "html":
T = current.T
request = current.request
response = current.response
title = T("Import from Feed URL")
# @ToDo: use Formstyle
form = FORM(
TABLE(
TR(TD(DIV(B("%s:" % T("URL")),
SPAN(" *", _class="req"))),
TD(INPUT(_type="text", _name="url",
_id="url", _value="")),
TD(),
),
TR(TD(B("%s: " % T("User"))),
TD(INPUT(_type="text", _name="user",
_id="user", _value="")),
TD(),
),
TR(TD(B("%s: " % T("Password"))),
TD(INPUT(_type="text", _name="password",
_id="password", _value="")),
TD(),
),
TR(TD(B("%s: " % T("Ignore Errors?"))),
TD(INPUT(_type="checkbox", _name="ignore_errors",
_id="ignore_errors")),
TD(),
),
TR(TD(),
TD(INPUT(_type="submit", _value=T("Import"))),
TD(),
)
)
)
response.view = "create.html"
output = dict(title=title,
form=form)
if form.accepts(request.vars, current.session):
form_vars = form.vars
url = form_vars.get("url", None)
if not url:
response.error = T("URL is required")
return output
# @ToDo:
username = form_vars.get("username", None)
password = form_vars.get("password", None)
try:
file = fetch(url)
except urllib2.URLError:
response.error = str(sys.exc_info()[1])
return output
except urllib2.HTTPError:
response.error = str(sys.exc_info()[1])
return output
File = StringIO(file)
stylesheet = os.path.join(request.folder, "static", "formats",
"cap", "import.xsl")
xml = current.xml
tree = xml.parse(File)
resource = current.s3db.resource("cap_alert")
s3xml = xml.transform(tree, stylesheet_path=stylesheet,
name=resource.name)
try:
resource.import_xml(s3xml,
ignore_errors=form_vars.get("ignore_errors", None))
except:
response.error = str(sys.exc_info()[1])
else:
import_count = resource.import_count
if import_count:
response.confirmation = "%s %s" % \
(import_count,
T("Alerts successfully imported."))
else:
response.information = T("No Alerts available.")
return output
else:
raise HTTP(501, current.ERROR.BAD_METHOD)
# END =========================================================================
| michaelhowden/eden | modules/s3db/cap.py | Python | mit | 86,498 |
using System.Data.Entity;
using LauraAndChad.Models;
namespace LauraAndChad
{
public class LauraAndChadContext : DbContext
{
public LauraAndChadContext() : base("name=LauraAndChadContext")
{
}
public DbSet<Rsvp> Rsvps { get; set; }
}
}
| chad-ramos/laura-and-chad | LauraAndChad/LauraAndChadContext.cs | C# | mit | 285 |
var path = require('path');
var fs = require('fs');
var Writer = require('broccoli-writer');
var Handlebars = require('handlebars');
var walkSync = require('walk-sync');
var RSVP = require('rsvp');
var helpers = require('broccoli-kitchen-sink-helpers');
var mkdirp = require('mkdirp');
var Promise = RSVP.Promise;
var EXTENSIONS_REGEX = new RegExp('.(hbs|handlebars)');
var HandlebarsWriter = function (inputTree, files, options) {
if (!(this instanceof HandlebarsWriter)) {
return new HandlebarsWriter(inputTree, files, options);
}
this.inputTree = inputTree;
this.files = files;
this.options = options || {};
this.context = this.options.context || {};
this.destFile = this.options.destFile || function (filename) {
return filename.replace(/(hbs|handlebars)$/, 'html');
};
this.handlebars = this.options.handlebars || Handlebars;
this.loadPartials();
this.loadHelpers();
};
HandlebarsWriter.prototype = Object.create(Writer.prototype);
HandlebarsWriter.prototype.constructor = HandlebarsWriter;
HandlebarsWriter.prototype.loadHelpers = function () {
var helpers = this.options.helpers;
if (!helpers) return;
if ('function' === typeof helpers) helpers = helpers();
if ('object' !== typeof helpers) {
throw Error('options.helpers must be an object or a function that returns an object');
}
this.handlebars.registerHelper(helpers);
};
HandlebarsWriter.prototype.loadPartials = function () {
var partials = this.options.partials;
var partialsPath;
var partialFiles;
if (!partials) return;
if ('string' !== typeof partials) {
throw Error('options.partials must be a string');
}
partialsPath = path.join(process.cwd(), partials);
partialFiles = walkSync(partialsPath).filter(EXTENSIONS_REGEX.test.bind(EXTENSIONS_REGEX));
partialFiles.forEach(function (file) {
var key = file.replace(partialsPath, '').replace(EXTENSIONS_REGEX, '');
var filePath = path.join(partialsPath, file);
this.handlebars.registerPartial(key, fs.readFileSync(filePath).toString());
}, this);
};
HandlebarsWriter.prototype.write = function (readTree, destDir) {
var self = this;
this.loadPartials();
this.loadHelpers();
return readTree(this.inputTree).then(function (sourceDir) {
var targetFiles = helpers.multiGlob(self.files, {cwd: sourceDir});
return RSVP.all(targetFiles.map(function (targetFile) {
function write (output) {
var destFilepath = path.join(destDir, self.destFile(targetFile));
mkdirp.sync(path.dirname(destFilepath));
var str = fs.readFileSync(path.join(sourceDir, targetFile)).toString();
var template = self.handlebars.compile(str);
fs.writeFileSync(destFilepath, template(output));
}
var output = ('function' !== typeof self.context) ? self.context : self.context(targetFile);
return Promise.resolve(output).then(write);
}));
});
};
module.exports = HandlebarsWriter; | michaellopez/broccoli-handlebars | index.js | JavaScript | mit | 2,973 |
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import RequestContext
# Create your views here.
from django.views.generic import ListView, DetailView
from .models import Category, Product
from cart.forms import CartAddProductForm
def category_list(request):
return render(request, "shop/category_list.html",
{'nodes': Category.objects.all()})
'''
class CategoryList(ListView):
model = Category
template_name = "category_list.html"
'''
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, "shop/product_list.html",
{'category': category,
'nodes': categories,
'products': products,})
'''
class ProductList(ListView):
model = DesignProduct
template_name = "shop/product_list.html"
'''
def product_detail(request, id, slug):
categories = Category.objects.all()
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
cart_product_form = CartAddProductForm()
return render(request,
'shop/product_detail.html',
{'product': product,
'nodes': categories,
'cart_product_form': cart_product_form}) | sunlaiqi/fundiy | src/shop/views.py | Python | mit | 1,636 |
class ::Numeric
include GlobalizeNumeric::CoreExtensions::Numeric
end
class ::String
include GlobalizeNumeric::CoreExtensions::String
end
#class ::Locale
# include GlobalizeNumeric::Locale
#end
#Locale.class_eval do
# include GlobalizeNumeric::Locale
#end
| yeameen/globalize_numeric | lib/core_ext_hook.rb | Ruby | mit | 266 |
var _a;
import app from './app';
import toHTML from './vdom-to-html';
import { _createEventTests, _createStateTests } from './apprun-dev-tools-tests';
app['debug'] = true;
window['_apprun-help'] = ['', () => {
Object.keys(window).forEach(cmd => {
if (cmd.startsWith('_apprun-')) {
cmd === '_apprun-help' ?
console.log('AppRun Commands:') :
console.log(`* ${cmd.substring(8)}: ${window[cmd][0]}`);
}
});
}];
function newWin(html) {
const win = window.open('', '_apprun_debug', 'toolbar=0');
win.document.write(`<html>
<title>AppRun Analyzer | ${document.location.href}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI" }
li { margin-left: 80px; }
</style>
<body>
<div id="main">${html}</div>
</script>
</body>
</html>`);
win.document.close();
}
const get_components = () => {
const o = { components: {} };
app.run('get-components', o);
const { components } = o;
return components;
};
const viewElement = element => app.h("div", null,
element.tagName.toLowerCase(),
element.id ? '#' + element.id : '',
' ',
element.className && element.className.split(' ').map(c => '.' + c).join());
const viewComponents = state => {
const Events = ({ events }) => app.h("ul", null, events && events.filter(event => event.name !== '.').map(event => app.h("li", null, event.name)));
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name),
app.h(Events, { events: component['_actions'] }))));
return app.h("ul", null, state.map(({ element, comps }) => app.h("li", null,
app.h("div", null, viewElement(element)),
app.h(Components, { components: comps }))));
};
const viewEvents = state => {
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name))));
const Events = ({ events, global }) => app.h("ul", null, events && events
.filter(event => event.global === global && event.event !== '.')
.map(({ event, components }) => app.h("li", null,
app.h("div", null, event),
app.h(Components, { components: components }))));
return app.h("div", null,
app.h("div", null, "GLOBAL EVENTS"),
app.h(Events, { events: state, global: true }),
app.h("div", null, "LOCAL EVENTS"),
app.h(Events, { events: state, global: false }));
};
const _events = (print) => {
const global_events = app['_events'];
const events = {};
const cache = get_components();
const add_component = component => component['_actions'].forEach(event => {
events[event.name] = events[event.name] || [];
events[event.name].push(component);
});
if (cache instanceof Map) {
for (let [key, comps] of cache) {
comps.forEach(add_component);
}
}
else {
Object.keys(cache).forEach(el => cache[el].forEach(add_component));
}
const data = [];
Object.keys(events).forEach(event => {
data.push({ event, components: events[event], global: global_events[event] ? true : false });
});
data.sort(((a, b) => a.event > b.event ? 1 : -1)).map(e => e.event);
if (print) {
const vdom = viewEvents(data);
newWin(toHTML(vdom));
}
else {
console.log('=== GLOBAL EVENTS ===');
data.filter(event => event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
console.log('=== LOCAL EVENTS ===');
data.filter(event => !event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
}
};
const _components = (print) => {
const components = get_components();
const data = [];
if (components instanceof Map) {
for (let [key, comps] of components) {
const element = typeof key === 'string' ? document.getElementById(key) : key;
data.push({ element, comps });
}
}
else {
Object.keys(components).forEach(el => {
const element = typeof el === 'string' ? document.getElementById(el) : el;
data.push({ element, comps: components[el] });
});
}
if (print) {
const vdom = viewComponents(data);
newWin(toHTML(vdom));
}
else {
data.forEach(({ element, comps }) => console.log(element, comps));
}
};
let debugging = Number((_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.getItem('__apprun_debugging__')) || 0;
app.on('debug', p => {
if (debugging & 1 && p.event)
console.log(p);
if (debugging & 2 && p.vdom)
console.log(p);
});
window['_apprun-components'] = ['components [print]', (p) => {
_components(p === 'print');
}];
window['_apprun-events'] = ['events [print]', (p) => {
_events(p === 'print');
}];
window['_apprun-log'] = ['log [event|view] on|off', (a1, a2) => {
var _a;
if (a1 === 'on') {
debugging = 3;
}
else if (a1 === 'off') {
debugging = 0;
}
else if (a1 === 'event') {
if (a2 === 'on') {
debugging |= 1;
}
else if (a2 === 'off') {
debugging &= ~1;
}
}
else if (a1 === 'view') {
if (a2 === 'on') {
debugging |= 2;
}
else if (a2 === 'off') {
debugging &= ~2;
}
}
console.log(`* log ${a1} ${a2 || ''}`);
(_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.setItem('__apprun_debugging__', `${debugging}`);
}];
window['_apprun-create-event-tests'] = ['create-event-tests',
() => _createEventTests()
];
window['_apprun-create-state-tests'] = ['create-state-tests <start|stop>',
(p) => _createStateTests(p)
];
window['_apprun'] = (strings) => {
const [cmd, ...p] = strings[0].split(' ').filter(c => !!c);
const command = window[`_apprun-${cmd}`];
if (command)
command[1](...p);
else
window['_apprun-help'][1]();
};
console.info('AppRun DevTools 2.27: type "_apprun `help`" to list all available commands.');
const reduxExt = window['__REDUX_DEVTOOLS_EXTENSION__'];
if (reduxExt) {
let devTools_running = false;
const devTools = window['__REDUX_DEVTOOLS_EXTENSION__'].connect();
if (devTools) {
const hash = location.hash || '#';
devTools.send(hash, '');
const buf = [{ component: null, state: '' }];
console.info('Connected to the Redux DevTools');
devTools.subscribe((message) => {
if (message.type === 'START')
devTools_running = true;
else if (message.type === 'STOP')
devTools_running = false;
else if (message.type === 'DISPATCH') {
// console.log('From Redux DevTools: ', message);
const idx = message.payload.index;
if (idx === 0) {
app.run(hash);
}
else {
const { component, state } = buf[idx];
component === null || component === void 0 ? void 0 : component.setState(state);
}
}
});
const send = (component, action, state) => {
if (state == null)
return;
buf.push({ component, state });
devTools.send(action, state);
};
app.on('debug', p => {
if (devTools_running && p.event) {
const state = p.newState;
const type = p.event;
const payload = p.p;
const action = { type, payload };
const component = p.component;
if (state instanceof Promise) {
state.then(s => send(component, action, s));
}
else {
send(component, action, state);
}
}
});
}
}
//# sourceMappingURL=apprun-dev-tools.js.map | yysun/apprun | esm/apprun-dev-tools.js | JavaScript | mit | 8,440 |
using AdfToArm.Core.Models.LinkedServices.LinkedServiceTypeProperties;
using Newtonsoft.Json;
namespace AdfToArm.Core.Models.LinkedServices
{
[JsonObject]
public class AzureSqlDatabase : LinkedService
{
public AzureSqlDatabase()
{
Properties = new LinkedServiceProperties
{
Type = LinkedServiceType.AzureSqlDatabase,
TypeProperties = new AzureSqlDatabaseTypeProperties()
};
}
public AzureSqlDatabase(string name) : this()
{
Name = name;
}
}
}
| deepnetworkgmbh/adfToArm | src/AdfToArm.Core/Models/LinkedServices/AzureSqlDatabase.cs | C# | mit | 615 |
module Blorgh::Concerns::Models::Post
extend ActiveSupport::Concern
# 'included do' causes the included code to be evaluated in the
# context where it is included (post.rb), rather than being
# executed in the module's context (blorgh/concerns/models/post).
included do
attr_accessor :author_name
belongs_to :author, class_name: "User"
before_save :set_author
private
def set_author
self.author = User.find_or_create_by(name: author_name)
end
end
def summary
"#{title}"
end
module ClassMethods
def some_class_method
'some class method string'
end
end
end | juanortizthirdwave/ruby_guides_engine | lib/concerns/models/post.rb | Ruby | mit | 638 |
import './index.css';
import React, {Component} from 'react';
import { postToggleDevice } from '../ajax';
export default class SocketDevice extends Component {
constructor() {
super();
this.state = {clicked: false, device: {}};
this.clicked = this.clicked.bind(this);
}
componentWillMount() {
var device = this.props.device;
if (device.enabled) {
this.setState({clicked: true});
}
this.setState({device: device});
}
clicked() {
var nextState = !this.state.clicked;
var id = this.state.device.id;
if (this.props.valueControl) {
this.props.valueControl(id, 'enabled', nextState);
this.setState({clicked: nextState});
} else {
this.toggle(id);
}
}
toggle() {
var id = this.state.device.id;
postToggleDevice(id, function (device) {
this.setState({clicked: device.enabled, device: device});
}.bind(this));
}
render() {
var name = this.state.device.name;
var classes = 'icon-tinted' + (this.state.clicked ? ' active' : '');
return (<div className="m-t-1">
<h4>
<a className={classes} onClick={this.clicked}><i className="fa fa-plug fa-lg"/></a> {name}
</h4>
</div>);
}
}
SocketDevice.propTypes = {
device: React.PropTypes.object.isRequired,
valueControl: React.PropTypes.func.isRequired
};
| aspic/wemo-control | src/SocketDevice/index.js | JavaScript | mit | 1,491 |
package com.jsoniter.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonIgnore {
boolean ignoreDecoding() default true;
boolean ignoreEncoding() default true;
}
| json-iterator/java | src/main/java/com/jsoniter/annotation/JsonIgnore.java | Java | mit | 452 |
var config = {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
ceo = {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg"
},
cto = {
parent: ceo,
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg"
},
cbo = {
parent: ceo,
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg"
},
cdo = {
parent: ceo,
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg"
},
cio = {
parent: cto,
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
ciso = {
parent: cto,
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: {val: "we@aregreat.com", href: "mailto:we@aregreat.com"}
},
image: "../headshots/9.jpg"
},
cio2 = {
parent: cdo,
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
},
ciso2 = {
parent: cbo,
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
ciso3 = {
parent: cbo,
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
ciso4 = {
parent: cbo,
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
chart_config = [
config,
ceo,
cto,
cbo,
cdo,
cio,
ciso,
cio2,
ciso2,
ciso3,
ciso4
];
// Another approach, same result
// JSON approach
/*
var chart_config = {
chart: {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
nodeStructure: {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg",
children: [
{
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg",
children: [
{
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
{
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: "we@aregreat.com"
},
image: "../headshots/9.jpg"
}
]
},
{
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg",
children: [
{
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
{
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
{
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
]
},
{
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg",
children: [
{
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
}
]
}
]
}
};
*/ | fperucic/treant-js | examples/basic-example/basic-example.js | JavaScript | mit | 6,298 |
require 'spec_helper'
describe User do
before do
@user = User.new(name: "Example User", email: "user@example.com",
password: "foobar800", password_confirmation: "foobar800")
end
subject {@user}
it {should respond_to(:name)}
it {should respond_to(:email)}
it {should respond_to(:password_digest)}
it {should respond_to(:password)}
it {should respond_to(:password_confirmation)}
it {should respond_to(:remember_token)}
it {should respond_to(:authenticate)}
it {should respond_to(:admin)}
it {should be_valid}
it {should_not be_admin}
describe "with admin attribute set to 'true'" do
before do
@user.save!
@user.toggle!(:admin)
end
it {should be_admin}
end
describe "when name is not present" do
before { @user.name =" "}
it {should_not be_valid}
end
describe "when email is not present" do
before {@user.email = " "}
it {should_not be_valid}
end
describe "when name is too long" do
before{ @user.name = "a" * 51}
it {should_not be_valid}
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.
foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@user.email = invalid_address
expect(@user).not_to be_valid
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
addresses.each do |valid_address|
@user.email = valid_address
expect(@user).to be_valid
end
end
end
describe "email address with mixed case" do
let(:mixed_case_email) {"Foo@ExAMpLe.CoM"}
it "should be saved as all lower case" do
@user.email = mixed_case_email
@user.save
expect(@user.reload.email).to eq mixed_case_email.downcase
end
end
describe "when email address is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it {should_not be_valid}
end
describe "when password is not present" do
before do
@user = User.new(name: "Example User", email: "user@example.com",
password: " ", password_confirmation: " ")
end
it {should_not be_valid}
end
describe "when password doesn't match confirmation" do
before { @user.password_confirmation = "mismatch"}
it {should_not be_valid}
end
describe "with a password that's too short" do
before {@user.password = @user.password_confirmation = "a"*5}
it {should be_invalid}
end
describe "return value of authenticate method" do
before {@user.save}
let(:found_user){User.find_by(email: @user.email)}
describe "with valid password" do
it {should eq found_user.authenticate(@user.password)}
end
describe "with invalid password" do
let(:user_for_invalid_password) {found_user.authenticate("invalid")}
it {should_not eq user_for_invalid_password}
specify {expect(user_for_invalid_password).to be_false}
end
end
describe "remember token" do
before { @user.save }
its(:remember_token){should_not be_blank}
end
end
| mbreecher/task_app | spec/models/user_spec.rb | Ruby | mit | 3,092 |
# -*- encoding: utf-8 -*-
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Mugshot::Storage do
it "should convert an id to path with 6 levels of directories" do
@fs = Mugshot::Storage.new
@fs.send(:id_to_path, "a9657a30c7df012c736512313b021ce1").should == "a9/65/7a/30/c7/df/012c736512313b021ce1"
end
end
| globocom/mugshot | spec/mugshot/storage_spec.rb | Ruby | mit | 347 |
# 005_cleaner.py
#####################################################################
##################################
# Import des modules et ajout du path de travail pour import relatif
import sys
sys.path.insert(0 , 'C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/')
from voca import AddLog , StringFormatter , OutFileCreate , OdditiesFinder
##################################
# Init des paths et noms de fichiers
missionName = '005'
AddLog('title' , '{} : Début du nettoyage du fichier'.format(missionName))
work_dir = 'C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/raw/{}_raw/'.format(missionName)
# Nom du fichier source
raw_file = 'src'
##################################
# retreiving raw string
raw_string_with_tabs = open(work_dir + raw_file , 'r').read()
# replacing tabs with carriage return
raw_string_with_cr = raw_string_with_tabs.replace( '\t', '\n' )
# turning the string into a list
raw_list = raw_string_with_cr.splitlines()
# going through oddities finder
AddLog('subtitle' , 'Début de la fonction OdditiesFinder')
list_without_oddities = OdditiesFinder( raw_list )
# going through string formatter
ref_list = []
AddLog('subtitle' , 'Début de la fonction StringFormatter')
for line in list_without_oddities:
ref_list.append( StringFormatter( line ) )
##################################
# Enregistrement des fichiers sortie
AddLog('subtitle' , 'Début de la fonction OutFileCreate')
OutFileCreate('C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/out/','{}_src'.format(missionName),ref_list,'prenoms masculins italiens')
| sighill/shade_app | apis/raw/005_raw/005_cleaner.py | Python | mit | 1,625 |
#Attr Methods
# I worked on this challenge by myself.
# I spent [#] hours on this challenge.
# Pseudocode
# Input:
# Output:
# Steps:
class NameData
end
class Greetings
end
# Release 1
#What are these methods doing?
# These methods set a name, age, and occupation, then they allow those instance variables to change by calling a new method to update the value of those instance variables.
#How are they modifying or returning the value of instance variables?
## They pass an argument into a new method that updates the value of the instance variables.
# Release 2
# What changed between the last release and this release?
## Now the @age variable is readable without needing to explicitly write a method that exposes it.
#What was replaced?
## The what_is_age() method was replaced with attr_reader.
#Is this code simpler than the last?
## Yes because now you can call class.age to return the age of the person.
# Release 3
#What changed between the last release and this release?
## Now the @age variable can be writeable without needing to explicitly write a method that allows it to be changed. If you set it equal to a new value, it'll change.
#What was replaced?
## The change_my_age method is no longer necessary.
#Is this code simpler than the last?
## Sure is. Now we can just set the age equal to a new value and it'll change.
# Release 4
## see release_4.rb
# Release 5
##
class NameData
attr_accessor :name
def initialize
@name = 'Ryan'
end
def print_name
"#{name}"
end
end
class Greetings
def hello
namedata = NameData.new
name = namedata.print_name
puts "Hello #{name}! How wonderful to see you today."
end
end
greet = Greetings.new
greet.hello # puts "Hello Student! How wonderful to see you today."
# Reflection
##What is a reader method?
## It allows you to access the value of a variable from outside the class
##What is a writer method?
## It allows you to update the value of a variable from outside the class
#What do the attr methods do for you?
## It's a shorthand way of letting you update the method from elsewhere
#Should you always use an accessor to cover your bases? Why or why not?
## Not necessarily because you don't always want to let other methods and classes update the value of your objects
#What is confusing to you about these methods?
## The shorthand notation took some getting used to. | ryanfs/phase-0 | week-6/attr/my_solution.rb | Ruby | mit | 2,388 |
require( ['build/index'] );
| pixelsnow/arkanoid-uni | scripts/index.js | JavaScript | mit | 28 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will try guess the protocol, domain
| and path to your installation. However, you should always configure this
| explicitly and never rely on auto-guessing, especially in production
| environments.
|
*/
$config['base_url'] = '';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = 'dA3ncryptionK3y';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 1200; //*** 1200 secondes -> 20 minutes ***
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| cyrilBezel/application_tex | application/config/config.php | PHP | mit | 17,766 |
<?php
namespace Gwa\Remote;
/**
* @brief Loads a remote resource using curl.
* @class RemoteResource
*/
class RemoteResource
{
private $_url;
private $_errno;
private $_errmsg;
private $_content;
private $_header;
private $_options;
/**
* @brief The constructor.
* @param string $url
*/
public function __construct( $url )
{
$this->_url = $url;
// set standard options
$this->_options = array(
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_SSL_VERIFYPEER => false
);
if (!ini_get('open_basedir')) {
$this->_options[CURLOPT_FOLLOWLOCATION] = 1;
$this->_options[CURLOPT_MAXREDIRS] = 2;
}
}
/**
* @brief Fetches the resource.
* @return bool success?
*/
public function fetch()
{
$ch = curl_init();
// set options
curl_setopt($ch, CURLOPT_URL, $this->_url);
foreach ($this->_options as $opt=>$value) {
curl_setopt($ch, $opt, $value);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->_content = curl_exec($ch);
$this->_errno = curl_errno($ch);
$this->_errmsg = curl_error($ch);
$this->_header = curl_getinfo($ch);
curl_close($ch);
return $this->_errno==0 ? true : false;
}
/**
* @brief Sets a CURL option
* @link http://www.php.net/manual/en/function.curl-setopt.php
*
* @param string $opt
* @param string $value
*/
public function setOption( $opt, $value )
{
$this->_options[$opt] = $value;
}
/**
* @brief Sets username and password to be passed on fetch.
* @param string $user
* @param string $password
*/
public function setUserPassword( $user, $password )
{
$this->setOption(CURLOPT_USERPWD, $user.':'.$password);
}
/**
* @return string
*/
public function getErrorNumber()
{
return $this->_errno;
}
/**
* @return string
*/
public function getError()
{
return $this->_errmsg;
}
/**
* @return array
*/
public function getHeaders()
{
return $this->_header;
}
/**
* @return string
*/
public function getHTTPCode()
{
return $this->_header['http_code'];
}
/**
* @brief Returns the content.
* @return string
*/
public function getContent()
{
return $this->_content;
}
/**
* @brief Returns the title of a HTML page.
* @return string
*/
public function getTitle()
{
$pattern = '/<title>(.*)<\/title>/i';
if (preg_match($pattern, $this->_content, $match)) {
return $match[1];
}
return '';
}
}
| gwa/gwRemoteResource | src/Gwa/Remote/RemoteResource.php | PHP | mit | 2,909 |
package com.fteams.siftrain.entities;
import com.fteams.siftrain.util.SongUtils;
public class SimpleNotesInfo implements Comparable<SimpleNotesInfo>{
public Double timing_sec;
public Integer effect;
public Double effect_value;
public Integer position;
@Override
public int compareTo(SimpleNotesInfo o) {
if (!o.timing_sec.equals(timing_sec))
return Double.compare(timing_sec, o.timing_sec);
return SongUtils.compare(position, o.position);
}
}
| kbz/SIFTrain | core/src/com/fteams/siftrain/entities/SimpleNotesInfo.java | Java | mit | 503 |
const app = require('../server');
const readline = require('readline');
const {
User,
Role,
RoleMapping,
} = app.models;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
Role.findOne({ where: { name: 'admin' } })
.then((role) => {
if (!role) {
console.log('No admin role found. Create fixtures first.');
process.exit();
}
const admin = {};
const fields = ['username', 'password'];
let field = fields.shift();
console.log(`${field}: `);
rl.on('line', (line) => {
admin[field] = line;
field = fields.shift();
if (!field) {
process.stdout.write('Creating the user... ');
User.create(admin)
.then(user =>
RoleMapping.create({
UserId: user.id,
RoleId: role.id,
})
)
.then(() => {
console.log('Done!\n');
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
return;
}
process.stdout.write(`${field}: \n`);
});
});
| oamaok/kinko | server/scripts/create-admin.js | JavaScript | mit | 1,056 |
/*Owner & Copyrights: Vance King Saxbe. A.*//*Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/
$stream = file_get_contents('USDMOPLAST.txt');
$avgp = "8.03";
$high = "8.03";
$low = "8.03";
echo "&L=".$stream."&N=USDMOP&";
$temp = file_get_contents("USDMOPTEMP.txt", "r");
if ($stream != $temp ) {
$mhigh = ($avgp + $high)/2;
$mlow = ($avgp + $low)/2;
$llow = ($low - (($avgp - $low)/2));
$hhigh = ($high + (($high - $avgp)/2));
$diff = $stream - $temp;
$diff = number_format($diff, 2, '.', '');
$avgp = number_format($avgp, 2, '.', '');
if ( $stream > $temp ) {
if ( ($stream > $mhigh ) && ($stream < $high)) { echo "&sign=au" ; }
if ( ($stream < $mlow ) && ($stream > $low)) { echo "&sign=ad" ; }
if ( $stream < $llow ) { echo "&sign=as" ; }
if ( $stream > $hhigh ) { echo "&sign=al" ; }
if ( ($stream < $hhigh) && ($stream > $high)) { echo "&sign=auu" ; }
if ( ($stream > $llow) && ($stream < $low)) { echo "&sign=add" ; }
//else { echo "&sign=a" ; }
$filedish = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$write = fputs($filedish, "USDMOP:Macau Pataca:".$stream. ":Moving up:"."\r\n");
fclose( $filedish );}
if ( $stream < $temp ) {
if ( ($stream >$mhigh) && ($stream < $high)) { echo "&sign=bu" ; }
if ( ($stream < $mlow) && ($stream > $low)) { echo "&sign=bd" ; }
if ( $stream < $llow ) { echo "&sign=bs" ; }
if ( $stream > $hhigh ) { echo "&sign=bl" ; }
if ( ($stream < $hhigh) && ($stream > $high)) { echo "&sign=buu" ; }
if ( ($stream > $llow) && ($stream < $low)) { echo "&sign=bdd" ; }
// else { echo "&sign=b" ; }
$filedish = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$write = fputs($filedish, "USDMOP:Macau Pataca:".$stream. ":Moving down:"."\r\n");
fclose( $filedish );}
$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filename= 'USDMOP.txt';
$file = fopen($filename, "a+" );
fwrite( $file, $stream.":".$time."\r\n" );
fclose( $file );
if (($stream > $mhigh ) && ($temp<= $mhigh ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$risk = ($stream - $low) * (200000/$stream);
$risk = (int)$risk;
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Approaching:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream < $mhigh ) && ($temp>= $mhigh ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $stream) * (200000/$stream);
$risk = (int)$risk;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Moving Down:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream > $mlow ) && ($temp<= $mlow ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$risk = ($stream - $low) * (200000/$stream);
$risk = (int)$risk;
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Moving Up:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream < $mlow ) && ($temp>= $mlow ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $stream) * (200000/$stream);
$risk = (int)$risk;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Approaching:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream > $high ) && ($temp<= $high ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$risk = ($stream - $low) * (200000/$stream);
$risk = (int)$risk;
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Breaking:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream > $hhigh ) && ($temp<= $hhigh ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$risk = ($stream - $low) * (200000/$stream);
$risk = (int)$risk;
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Moving Beyond:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream < $hhigh ) && ($temp>= $hhigh ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream. ":Coming near:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream < $high ) && ($temp>= $high ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream. ":Retracing:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($stream < $llow ) && ($temp>= $llow ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $stream) * (200000/$stream);
$risk = (int)$risk;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Breaking Beyond:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream < $low ) && ($temp>= $low ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $stream) * (200000/$stream);
$risk = (int)$risk;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Breaking:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream > $llow ) && ($temp<= $llow ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Coming near:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream > $low ) && ($temp<= $low ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:". $stream.":Retracing:PLOW:"."\r\n");
fclose( $filedash );
}
if (($stream > $avgp ) && ($temp<= $avgp ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($stream - $low) * (200000/$stream);
$risk = (int)$risk;
$avgp = number_format($avgp, 2, '.', '');
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Sliding up:PAVG:"."\r\n");
fclose( $filedash );
}
if (($stream < $avgp ) && ($temp>= $avgp ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $stream) * (200000/$stream);
$risk = (int)$risk;
$avgp = number_format($avgp, 2, '.', '');
$time = date('h:i:s',$new_time);
$filedash = fopen("C:\wamp\www\charity\hu\bloomberg\indices\malert.txt", "a+");
$wrote = fputs($filedash, "USDMOP:Macau Pataca:".$stream. ":Sliding down:PAVG:"."\r\n");
fclose( $filedash );
}
}
$filedash = fopen("USDMOPTEMP.txt", "w");
$wrote = fputs($filedash, $stream);
fclose( $filedash );
//echo "&chg=".$json_output['cp']."&";
?>
/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/ | VanceKingSaxbeA/FOREX-Engine | App/USDMOP.php | PHP | mit | 9,398 |
<?php
namespace JeroenNoten\LaravelAdminLte\Menu;
use Illuminate\Support\Arr;
use JeroenNoten\LaravelAdminLte\Helpers\MenuItemHelper;
class Builder
{
protected const ADD_AFTER = 0;
protected const ADD_BEFORE = 1;
protected const ADD_INSIDE = 2;
/**
* The set of menu items.
*
* @var array
*/
public $menu = [];
/**
* The set of filters applied to menu items.
*
* @var array
*/
private $filters;
/**
* Constructor.
*
* @param array $filters
*/
public function __construct(array $filters = [])
{
$this->filters = $filters;
}
/**
* Add new items at the end of the menu.
*
* @param mixed $newItems Items to be added
*/
public function add(...$newItems)
{
$items = $this->transformItems($newItems);
if (! empty($items)) {
array_push($this->menu, ...$items);
}
}
/**
* Add new items after a specific menu item.
*
* @param mixed $itemKey The key that represents the specific menu item
* @param mixed $newItems Items to be added
*/
public function addAfter($itemKey, ...$newItems)
{
$this->addItem($itemKey, self::ADD_AFTER, ...$newItems);
}
/**
* Add new items before a specific menu item.
*
* @param mixed $itemKey The key that represents the specific menu item
* @param mixed $newItems Items to be added
*/
public function addBefore($itemKey, ...$newItems)
{
$this->addItem($itemKey, self::ADD_BEFORE, ...$newItems);
}
/**
* Add new submenu items inside a specific menu item.
*
* @param mixed $itemKey The key that represents the specific menu item
* @param mixed $newItems Items to be added
*/
public function addIn($itemKey, ...$newItems)
{
$this->addItem($itemKey, self::ADD_INSIDE, ...$newItems);
}
/**
* Remove a specific menu item.
*
* @param mixed $itemKey The key of the menu item to remove
*/
public function remove($itemKey)
{
// Find the specific menu item. Return if not found.
if (! ($itemPath = $this->findItem($itemKey, $this->menu))) {
return;
}
// Remove the item.
Arr::forget($this->menu, implode('.', $itemPath));
// Normalize the menu (remove holes in the numeric indexes).
$holedArrPath = implode('.', array_slice($itemPath, 0, -1)) ?: null;
$holedArr = Arr::get($this->menu, $holedArrPath, $this->menu);
Arr::set($this->menu, $holedArrPath, array_values($holedArr));
}
/**
* Check if exists a menu item with the specified key.
*
* @param mixed $itemKey The key of the menu item to check for
* @return bool
*/
public function itemKeyExists($itemKey)
{
return (bool) $this->findItem($itemKey, $this->menu);
}
/**
* Transform the items by applying the filters.
*
* @param array $items An array with items to be transformed
* @return array Array with the new transformed items
*/
protected function transformItems($items)
{
return array_filter(
array_map([$this, 'applyFilters'], $items),
[MenuItemHelper::class, 'isAllowed']
);
}
/**
* Find a menu item by the item key and return the path to it.
*
* @param mixed $itemKey The key of the item to find
* @param array $items The array to look up for the item
* @return mixed Array with the path sequence, or empty array if not found
*/
protected function findItem($itemKey, $items)
{
// Look up on all the items.
foreach ($items as $key => $item) {
if (isset($item['key']) && $item['key'] === $itemKey) {
return [$key];
} elseif (MenuItemHelper::isSubmenu($item)) {
// Do the recursive call to search on submenu. If we found the
// item, merge the path with the current one.
if ($subPath = $this->findItem($itemKey, $item['submenu'])) {
return array_merge([$key, 'submenu'], $subPath);
}
}
}
// Return empty array when the item is not found.
return [];
}
/**
* Apply all the available filters to a menu item.
*
* @param mixed $item A menu item
* @return mixed A new item with all the filters applied
*/
protected function applyFilters($item)
{
// Filters are only applied to array type menu items.
if (! is_array($item)) {
return $item;
}
// If the item is a submenu, transform all the submenu items first.
// These items need to be transformed first because some of the submenu
// filters (like the ActiveFilter) depends on these results.
if (MenuItemHelper::isSubmenu($item)) {
$item['submenu'] = $this->transformItems($item['submenu']);
}
// Now, apply all the filters on the item.
foreach ($this->filters as $filter) {
// If the item is not allowed to be shown, there is no sense to
// continue applying the filters.
if (! MenuItemHelper::isAllowed($item)) {
return $item;
}
$item = $filter->transform($item);
}
return $item;
}
/**
* Add new items to the menu in a particular place, relative to a
* specific menu item.
*
* @param mixed $itemKey The key that represents the specific menu item
* @param int $where Where to add the new items
* @param mixed $items Items to be added
*/
protected function addItem($itemKey, $where, ...$items)
{
// Find the specific menu item. Return if not found.
if (! ($itemPath = $this->findItem($itemKey, $this->menu))) {
return;
}
// Get the target array and add the new items there.
$itemKeyIdx = end($itemPath);
reset($itemPath);
if ($where === self::ADD_INSIDE) {
$targetPath = implode('.', array_merge($itemPath, ['submenu']));
$targetArr = Arr::get($this->menu, $targetPath, []);
array_push($targetArr, ...$items);
} else {
$targetPath = implode('.', array_slice($itemPath, 0, -1)) ?: null;
$targetArr = Arr::get($this->menu, $targetPath, $this->menu);
$offset = ($where === self::ADD_AFTER) ? 1 : 0;
array_splice($targetArr, $itemKeyIdx + $offset, 0, $items);
}
Arr::set($this->menu, $targetPath, $targetArr);
// Apply the filters because the menu now have new items.
$this->menu = $this->transformItems($this->menu);
}
}
| JeroenNoten/Laravel-AdminLTE | src/Menu/Builder.php | PHP | mit | 6,853 |
<?php
namespace Bonsai\Mapper\Converter;
use \Bonsai\Module\Tools;
class LocalizeUrl implements Converter
{
public function convert($output)
{
return Tools::localizeURL($output);
}
}
| TheCargoAgency/BonsaiPHP | src/Mapper/Converter/LocalizeUrl.php | PHP | mit | 208 |
package org.nww.core.data.filter;
import java.util.List;
/**
* A simple filter criteria implementation checking the existence of a string
* inside a list of strings. Does only match if the list contains a totally
* equal string like the context one.
*
* @author MGA
*/
public class StringInListFilterCriteria implements FilterCriteria<List<String>, String> {
/**
* Checks whether the passed list contains the context string.
*
* @param toCheck list of string where to find the context in
* @param context the context string to be found
* @return true if the context is found inside the list of strings
*/
@Override
public boolean match(List<String> toCheck, String context) {
if (toCheck.isEmpty()) {
return true;
}
return toCheck.contains(context);
}
}
| NetzwerkWohnen/NWW | src/main/java/org/nww/core/data/filter/StringInListFilterCriteria.java | Java | mit | 877 |
declare module "diagram-js/lib/features/global-connect/GlobalConnect" {
import EventBus from "diagram-js/lib/core/EventBus";
import { Base } from "diagram-js/lib/model";
import Canvas from "diagram-js/lib/core/Canvas";
import Dragging from "diagram-js/lib/features/dragging/Dragging";
export default class GlobalConnect {
public _dragging: Dragging;
constructor(eventBus: EventBus, dragging: {}, connect: {}, canvas: Canvas, toolManager: {});
public registerProvider(provider: IGlobalConnectProvider): void;
public isActive(): boolean;
public toggle(): void;
/**
* Initiates tool activity.
*/
public start(): void;
/**
* Check if source shape can initiate connection.
*
* @param {Base} startTarget
* @return {Boolean}
*/
public canStartConnect(startTarget: Base): boolean;
}
export interface IGlobalConnectProvider {
/**
* Check if source shape can initiate connection.
*
* @param {Base} startTarget
* @return {Boolean}
*/
canStartConnect(startTarget: Base): boolean;
}
}
| ProcessHub/processhub-sdk | src/process/types/diagram-js/lib/features/global-connect/globalconnect.d.ts | TypeScript | mit | 1,101 |
#!/usr/bin/python
"""
title : testtermopi.py
description : This program runs the termopi.py
: Displays the status of the resources (cpu load and memory usage) consumed by a Raspberry Pi
computer and the resources consumed by one or more containers instantiated in the Pi.
source :
author : Carlos Molina-Jimenez (Carlos.Molina@cl.cam.ac.uk)
date : 27 Mar 2017
institution : Computer Laboratory, University of Cambridge
version : 1.0
usage :
notes :
compile and run : % python termopi.py
: It imports pidict.py, dockerctl.py and picheck.py which are found in
: ./modules.
: You need to include "./modules" in the PYTHONPATH environment variable to
: indicate python where to find the pidict.py, dockerctl.py and picheck.py.
: For example, in a bash shell, you need to include the following lines
: in your .bash_profile file located in you home directory (you can see it with
: (# ls -la).
:
: PYTHONPATH="./modules"
: export PYTHONPATH
python_version : Python 2.7.12
====================================================
"""
from modules.tools.termopi import termopi # class with dictionary data structure
# Threshold of cpu exhaustion
cpuUsageThreshold= 50
cpuLoadThreshold= 3
termo= termopi()
termo.prt_pi_resources()
termo.create_jsonfile_with_pi_status()
#termo.check_pi_resource_status(cpuUsageThreshold)
| AdL1398/PiCasso | source/modules/tester/testtermopi.py | Python | mit | 1,603 |
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.addColumn("troop_type", "production_cost", "int", callback);
};
exports.down = function(db, callback) {
};
| Codes-With-Eagles-SWE2014/Server | web_server/migrations/20141116202453-troopcost.js | JavaScript | mit | 210 |
<?php
/*
* This file is part of the Zephir.
*
* (c) Zephir Team <team@zephir-lang.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Zephir\Optimizers\FunctionCall;
use function Zephir\add_slashes;
use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Compiler;
use Zephir\Optimizers\OptimizerAbstract;
/**
* MemnstrOptimizer.
*
* Like 'strpos' but it returns a boolean value
*/
class MemstrOptimizer extends OptimizerAbstract
{
/**
* @param array $expression
* @param Call $call
* @param CompilationContext $context
*
* @return bool|CompiledExpression|mixed
*/
public function optimize(array $expression, Call $call, CompilationContext $context)
{
if (!isset($expression['parameters'])) {
return false;
}
if (2 != \count($expression['parameters'])) {
return false;
}
if ('string' == $expression['parameters'][1]['parameter']['type']) {
$str = add_slashes($expression['parameters'][1]['parameter']['value']);
unset($expression['parameters'][1]);
}
$resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);
$context->headersManager->add('kernel/string');
if (isset($str)) {
return new CompiledExpression('bool', 'zephir_memnstr_str('.$resolvedParams[0].', SL("'.$str.'"), "'.Compiler::getShortUserPath($expression['file']).'", '.$expression['line'].')', $expression);
}
return new CompiledExpression('bool', 'zephir_memnstr('.$resolvedParams[0].', '.$resolvedParams[1].', "'.Compiler::getShortUserPath($expression['file']).'", '.$expression['line'].')', $expression);
}
}
| dreamsxin/zephir | Library/Optimizers/FunctionCall/MemstrOptimizer.php | PHP | mit | 1,887 |
import { Inject, Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/operator/mergeMap';
import 'rxjs/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
@Injectable()
export class Sandbox3Service {
data: string = 'this data comes from the sandbox3 service';
getSynchronousData() {
return this.data;
}
getSynchronousDataArg(arg: number) {
return arg;
}
}
| dav793/angular2-seed | app/components/sandbox/sandbox3/sandbox3.service.ts | TypeScript | mit | 524 |
'use strict';
// you have to require the utils module and call adapter function
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
// include node-ssdp and node-upnp-subscription
const {Client, Server} = require('node-ssdp');
const Subscription = require('./lib/upnp-subscription');
const parseString = require('xml2js').parseString;
const DOMParser = require('xmldom').DOMParser;
const request = require('request');
const nodeSchedule = require('node-schedule');
let adapter;
let client = new Client();
const tasks = [];
let taskRunning = false;
const actions = {}; // scheduled actions
const crons = {};
const checked = {}; // store checked objects for polling
let discoveredDevices = [];
let sidPromise; // Read SIDs promise
let globalCb; // callback for last processTasks
function startCronJob(cron) {
console.log('Start cron JOB: ' + cron);
crons[cron] = nodeSchedule.scheduleJob(cron, () => pollActions(cron));
}
function stopCronJob(cron) {
if (crons[cron]) {
crons[cron].cancel();
delete crons[cron];
}
}
function pollActions(cron) {
Object.keys(actions).forEach(id =>
actions[id].cron === cron && addTask({name: 'sendCommand', id}));
processTasks();
}
function reschedule(changedId, deletedCron) {
const schedules = {};
if (changedId) {
if (!deletedCron) {
Object.keys(actions).forEach(_id => {
if (_id !== changedId) {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
}
});
if (!schedules[actions[changedId].cron]) {
// start cron job
startCronJob(actions[changedId].cron);
}
} else {
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
if (schedules[deletedCron] === 1 && crons[deletedCron]) {
// stop cron job
stopCronJob(deletedCron);
}
}
} else {
// first
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
Object.keys(schedules).forEach(cron => startCronJob(cron));
}
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName, strictObjectChecks: false});
adapter = new utils.Adapter(options);
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', callback => {
try {
server.stop(); // advertise shutting down and stop listening
adapter.log.info('cleaned everything up...');
clearAliveAndSIDStates(callback);
} catch (e) {
callback();
}
});
adapter.on('objectChange', (id, obj) => {
if (obj && obj.common && obj.common.custom &&
obj.common.custom[adapter.namespace] &&
obj.common.custom[adapter.namespace].enabled &&
obj.native && obj.native.request
) {
if (!actions[id]) {
adapter.log.info(`enabled polling of ${id} with schedule ${obj.common.custom[adapter.namespace].schedule}`);
setImmediate(() => reschedule(id));
}
actions[id] = {cron: obj.common.custom[adapter.namespace].schedule};
} else if (actions[id]) {
adapter.log.debug('Removed polling for ' + id);
setImmediate((id, cron) => reschedule(id, cron), id, actions[id].cron);
delete actions[id];
}
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
if (!state || state.ack) {
return;
}
// Subscribe to an service when its state Alive is true
if (id.match(/\.request$/)) {
// Control a device when a related object changes its value
if (checked[id] !== undefined) {
checked[id] && sendCommand(id);
} else {
adapter.getObject(id, (err, obj) => {
if (obj && obj.native && obj.native.request) {
checked[id] = true;
sendCommand(id);
} else {
checked[id] = false;
}
});
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', () => {
main();
});
// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', obj => {
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
adapter.log.info('send command');
// Send response in callback if required
obj.callback && adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
}
}
});
return adapter;
}
function getValueFromArray(value) {
if (typeof value === 'object' && value instanceof Array && value[0] !== undefined) {
return value[0] !== null ? value[0].toString() : '';
} else {
return value !== null && value !== undefined ? value.toString() : '';
}
}
let foundIPs = []; // Array for the caught broadcast answers
function sendBroadcast() {
// adapter.log.debug('Send Broadcast');
// Sends a Broadcast and catch the URL with xml device description file
client.on('response', (headers, _statusCode, _rinfo) => {
let answer = (headers || {}).LOCATION;
if (answer && foundIPs.indexOf(answer) === -1) {
foundIPs.push(answer);
if (answer !== answer.match(/.*dummy.xml/g)) {
setTimeout(() => firstDevLookup(answer), 1000);
}
}
});
client.search('ssdp:all');
}
// Read the xml device description file of each upnp device the first time
function firstDevLookup(strLocation, cb) {
const originalStrLocation = strLocation;
adapter.log.debug('firstDevLookup for ' + strLocation);
request(strLocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
adapter.log.debug('Positive answer for request of the XML file for ' + strLocation);
try {
const xmlStringSerialized = new DOMParser().parseFromString((body || '').toString(), 'text/xml');
parseString(xmlStringSerialized, {explicitArray: true, mergeAttrs: true}, (err, result) => {
let path;
let xmlDeviceType;
let xmlTypeOfDevice;
let xmlUDN;
let xmlManufacturer;
adapter.log.debug('Parsing the XML file for ' + strLocation);
if (err) {
adapter.log.warn('Error: ' + err);
} else {
adapter.log.debug('Creating objects for ' + strLocation);
let i;
if (!result || !result.root || !result.root.device) {
adapter.log.debug('Error by parsing of ' + strLocation + ': Cannot find deviceType');
return;
}
path = result.root.device[0];
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceType);
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug('TypeOfDevice ' + xmlTypeOfDevice);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the port
let strPort = strLocation.replace(/\bhttp:\/\/.*\d:/ig, '');
strPort = strPort.replace(/\/.*/g, '');
if (strPort.match(/http:/ig)) {
strPort = '';
} else {
strPort = parseInt(strPort, 10);
}
// Looking for the IP of a device
strLocation = strLocation.replace(/http:\/\/|"/g, '').replace(/:\d*\/.*/ig, '');
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.UDN).replace(/"/g, '').replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${strLocation}`);
xmlUDN = '';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug('Can not read manufacturer of ' + strLocation);
xmlManufacturer = '';
}
// Extract the path to the device icon that is delivered by the device
// let i_icons = 0;
let xmlIconURL;
let xmlFN;
let xmlManufacturerURL;
let xmlModelNumber;
let xmlModelDescription;
let xmlModelName;
let xmlModelURL;
try {
// i_icons = path.iconList[0].icon.length;
xmlIconURL = getValueFromArray(path.iconList[0].icon[0].url).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not find a icon for ${strLocation}`);
xmlIconURL = '';
}
//Looking for the friendlyName of a device
try {
xmlFN = nameFilter(getValueFromArray(path.friendlyName));
} catch (err) {
adapter.log.debug(`Can not read friendlyName of ${strLocation}`);
xmlFN = 'Unknown';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.manufacturerURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${strLocation}`);
xmlManufacturerURL = '';
}
// Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.modelNumber).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${strLocation}`);
xmlModelNumber = '';
}
// Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.modelDescription).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${strLocation}`);
xmlModelDescription = '';
}
// Looking for the modelName
try {
xmlModelName = getValueFromArray(path.modelName).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelName of ${strLocation}`);
xmlModelName = '';
}
// Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.modelURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${strLocation}`);
xmlModelURL = '';
}
// START - Creating the root object of a device
adapter.log.debug(`Creating root element for device: ${xmlFN}`);
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlFN,
extIcon: `http://${strLocation}:${strPort}${xmlIconURL}`
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType,
manufacturer: xmlManufacturer,
manufacturerURL: xmlManufacturerURL,
modelNumber: xmlModelNumber,
modelDescription: xmlModelDescription,
modelName: xmlModelName,
modelURL: xmlModelURL,
name: xmlFN,
}
}
});
let pathRoot = result.root.device[0];
let objectName = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectName, strLocation, strPort, pathRoot);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
// START - Creating SubDevices list for a device
let lenSubDevices = 0;
let xmlfriendlyName;
if (path.deviceList && path.deviceList[0].device) {
// Counting SubDevices
lenSubDevices = path.deviceList[0].device.length;
if (lenSubDevices) {
// adapter.log.debug('Found more than one SubDevice');
for (i = lenSubDevices - 1; i >= 0; i--) {
// Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].modelName);
} catch (err) {
adapter.log.debug(`Can not read modelName of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = path.deviceList[0].device[i].modelURL;
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
let pathSub = result.root.device[0].deviceList[0].device[i];
let objectNameSub = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
let TypeOfSubDevice = xmlTypeOfDevice;
//START - Creating SubDevices list for a sub-device
if (path.deviceList[0].device[i].deviceList && path.deviceList[0].device[i].deviceList[0].device) {
//Counting SubDevices
let i_SubSubDevices = path.deviceList[0].device[i].deviceList[0].device.length;
let i2;
if (i_SubSubDevices) {
for (i2 = i_SubSubDevices - 1; i2 >= 0; i--) {
adapter.log.debug(`Device ${i2} ` + path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType
.replace(/:\d/, '')
.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType);
} catch (err) {
adapter.log.debug('Can not read DeviceType of ' + xmlfriendlyName);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelName);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelURL);
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
pathSub = result.root.device[0].deviceList[0].device[i].deviceList[0].device[i2];
objectNameSub = `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, `${TypeOfSubDevice}.${xmlTypeOfDevice}`, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
}
}
}
}
}
}
}
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
});
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${strLocation}: ${error}`);
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
}
} else {
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
cb && cb();
}
});
}
function createServiceList(result, xmlFN, xmlTypeOfDevice, object, strLocation, strPort, path) {
if (!path.serviceList) {
adapter.log.debug('No service list found at ' + JSON.stringify(path));
return;
}
if (!path.serviceList[0] || !path.serviceList[0].service || !path.serviceList[0].service.length) {
adapter.log.debug('No services found in the service list');
return;
}
let i;
let xmlService;
let xmlServiceType;
let xmlServiceID;
let xmlControlURL;
let xmlEventSubURL;
let xmlSCPDURL;
let i_services = path.serviceList[0].service.length;
//Counting services
//adapter.log.debug('Number of services: ' + i_services);
for (i = i_services - 1; i >= 0; i--) {
try {
xmlService = getValueFromArray(path.serviceList[0].service[i].serviceType)
.replace(/urn:.*:service:/g, '')
.replace(/:\d/g, '')
.replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read service of ${xmlFN}`);
xmlService = 'Unknown';
}
try {
xmlServiceType = getValueFromArray(path.serviceList[0].service[i].serviceType);
} catch (err) {
adapter.log.debug(`Can not read serviceType of ${xmlService}`);
xmlServiceType = '';
}
try {
xmlServiceID = getValueFromArray(path.serviceList[0].service[i].serviceId);
} catch (err) {
adapter.log.debug(`Can not read serviceID of ${xmlService}`);
xmlServiceID = '';
}
try {
xmlControlURL = getValueFromArray(path.serviceList[0].service[i].controlURL);
} catch (err) {
adapter.log.debug(`Can not read controlURL of ${xmlService}`);
xmlControlURL = '';
}
try {
xmlEventSubURL = getValueFromArray(path.serviceList[0].service[i].eventSubURL);
} catch (err) {
adapter.log.debug(`Can not read eventSubURL of ${xmlService}`);
xmlEventSubURL = '';
}
try {
xmlSCPDURL = getValueFromArray(path.serviceList[0].service[i].SCPDURL);
if (!xmlSCPDURL.match(/^\//)) {
xmlSCPDURL = `/${xmlSCPDURL}`;
}
} catch (err) {
adapter.log.debug(`Can not read SCPDURL of ${xmlService}`);
xmlSCPDURL = '';
}
addTask({
name: 'setObjectNotExists',
id: `${object}.${xmlService}`,
obj: {
type: 'channel',
common: {
name: xmlService
},
native: {
serviceType: xmlServiceType,
serviceID: xmlServiceID,
controlURL: xmlControlURL,
eventSubURL: xmlEventSubURL,
SCPDURL: xmlSCPDURL,
name: xmlService
}
}
});
const sid = `${adapter.namespace}.${object}.${xmlService}.sid`;
addTask({
name: 'setObjectNotExists',
id: sid,
obj: {
type: 'state',
common: {
name: 'Subscription ID',
type: 'string',
role: 'state',
def: '',
read: true,
write: true
},
native: {}
}
});
// Add to SID list
getIDs()
.then(result => result.sids.indexOf(sid) === -1 && result.sids.push(sid));
let SCPDlocation = `http://${strLocation}:${strPort}${xmlSCPDURL}`;
let service = `${xmlFN}.${xmlTypeOfDevice}.${xmlService}`;
addTask({name: 'readSCPD', SCPDlocation, service});
}
}
// Read the SCPD File of a upnp device service
function readSCPD(SCPDlocation, service, cb) {
adapter.log.debug('readSCPD for ' + SCPDlocation);
request(SCPDlocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
try {
parseString(body, {explicitArray: true}, (err, result) => {
adapter.log.debug('Parsing the SCPD XML file for ' + SCPDlocation);
if (err) {
adapter.log.warn('Error: ' + err);
cb();
} else if (!result || !result.scpd) {
adapter.log.debug('Error by parsing of ' + SCPDlocation);
cb();
} else {
createServiceStateTable(result, service);
createActionList(result, service);
processTasks();
cb();
}
}); //END function
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${SCPDlocation}: ${error}`);
cb();
}
} else {
cb();
}
});
}
function createServiceStateTable(result, service) {
if (!result.scpd || !result.scpd.serviceStateTable) {
return;
}
let path = result.scpd.serviceStateTable[0] || result.scpd.serviceStateTable;
if (!path.stateVariable || !path.stateVariable.length) {
return;
}
let iStateVarLength = path.stateVariable.length;
let xmlName;
let xmlDataType;
// Counting stateVariable's
// adapter.log.debug('Number of stateVariables: ' + iStateVarLength);
try {
for (let i2 = iStateVarLength - 1; i2 >= 0; i2--) {
let stateVariableAttr;
let strAllowedValues = [];
let strMinimum;
let strMaximum;
let strDefaultValue;
let strStep;
stateVariableAttr = path.stateVariable[i2]['$'].sendEvents;
xmlName = getValueFromArray(path.stateVariable[i2].name);
xmlDataType = getValueFromArray(path.stateVariable[i2].dataType);
try {
let allowed = path.stateVariable[i2].allowedValueList[0].allowedValue;
strAllowedValues = Object.keys(allowed).map(xmlAllowedValue => allowed[xmlAllowedValue]).join(' ');
} catch (err) {
}
try {
strDefaultValue = getValueFromArray(path.stateVariable[i2].defaultValue);
} catch (err) {
}
if (path.stateVariable[i2].allowedValueRange) {
try {
strMinimum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].minimum);
} catch (err) {
}
try {
strMaximum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].maximum);
} catch (err) {
}
try {
strStep = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].step);
} catch (err) {
}
}
// Handles DataType ui2 as Number
let dataType;
if (xmlDataType.toString() === 'ui2') {
dataType = 'number';
} else {
dataType = xmlDataType.toString();
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
type: dataType,
role: 'state',
read: true,
write: true
},
native: {
name: xmlName,
sendEvents: stateVariableAttr,
allowedValues: strAllowedValues,
defaultValue: strDefaultValue,
minimum: strMinimum,
maximum: strMaximum,
step: strStep,
}
}
});
}//END for
} catch (err) {
}
//END Add serviceList for SubDevice
} //END function
function createActionList(result, service) {
if (!result || !result.scpd || !result.scpd.actionList || !result.scpd.actionList[0]) {
return;
}
let path = result.scpd.actionList[0];
if (!path.action || !path.action.length) {
return;
}
let actionLen = path.action.length;
//Counting action's
//adapter.log.debug('Number of actions: ' + actionLen);
for (let i2 = actionLen - 1; i2 >= 0; i2--) {
let xmlName = getValueFromArray(path.action[i2].name);
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'channel',
common: {
name: xmlName
},
native: {
name: xmlName
}
}
});
try {
createArgumentList(result, service, xmlName, i2, path);
} catch (err) {
adapter.log.debug(`There is no argument for ${xmlName}`);
}
}
}
function createArgumentList(result, service, actionName, action_number, path) {
let iLen = 0;
let action;
let _arguments;
// adapter.log.debug('Reading argumentList for ' + actionName);
action = path.action[action_number].argumentList;
if (action && action[0] && action[0].argument) {
_arguments = action[0].argument;
iLen = _arguments.length;
} else {
return;
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.request`,
obj: {
type: 'state',
common: {
name: 'Initiate poll',
role: 'button',
type: 'boolean',
def: false,
read: false,
write: true
},
native: {
actionName: actionName,
service: service,
request: true
}
}
}); //END adapter.setObject()
// Counting arguments's
for (let i2 = iLen - 1; i2 >= 0; i2--) {
let xmlName = 'Unknown';
let xmlDirection = '';
let xmlRelStateVar = '';
let argument = _arguments[i2];
try {
xmlName = getValueFromArray(argument.name);
} catch (err) {
adapter.log.debug(`Can not read argument "name" of ${actionName}`);
}
try {
xmlDirection = getValueFromArray(argument.direction);
} catch (err) {
adapter.log.debug(`Can not read direction of ${actionName}`);
}
try {
xmlRelStateVar = getValueFromArray(argument.relatedStateVariable);
} catch (err) {
adapter.log.debug(`Can not read relatedStateVariable of ${actionName}`);
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
role: 'state.argument.' + xmlDirection,
type: 'string',
def: '',
read: true,
write: true
},
native: {
direction: xmlDirection,
relatedStateVariable: xmlRelStateVar,
argumentNumber: i2 + 1,
name: xmlName,
}
}
}); //END adapter.setObject()
}
} //END function
//END Creating argumentList
let showTimer = null;
function processTasks(cb) {
if (!taskRunning && tasks.length) {
if (cb) {
globalCb = cb; // used by unload
}
taskRunning = true;
setImmediate(_processTasks);
adapter.log.debug('Started processTasks with ' + tasks.length + ' tasks');
showTimer = setInterval(() => adapter.log.debug(`Tasks ${tasks.length}...`), 5000);
} else if (cb) {
cb();
}
}
function addTask(task) {
tasks.push(task);
}
function _processTasks() {
if (!tasks.length) {
taskRunning = false;
adapter.log.debug('All tasks processed');
clearInterval(showTimer);
if (globalCb) {
globalCb();
globalCb = null;
}
} else {
const task = tasks.shift();
if (task.name === 'sendCommand') {
sendCommand(task.id, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'firstDevLookup') {
firstDevLookup(task.location, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'subscribeEvent') {
subscribeEvent(task.deviceID, () => setTimeout(_processTasks, 0));
} else if (task.name === 'setState') {
adapter.setState(task.id, task.state, err => {
if (typeof task.cb === 'function') {
task.cb(() => setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else
if (task.name === 'valChannel') {
valChannel(task.strState, task.serviceID, () => {
writeState(task.serviceID, task.stateName, task.val, () =>
setTimeout(_processTasks, 0));
});
} else
if (task.name === 'readSCPD') {
readSCPD(task.SCPDlocation, task.service, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'setObjectNotExists') {
if(task.obj.common.type){
switch (task.obj.common.type){
case 'bool':
task.obj.common.type = 'boolean';
break;
case 'i1':
case 'i2':
case 'i4':
case 'ui1':
case 'ui2':
case 'ui4':
case 'int':
case 'r4':
case 'r8':
case 'fixed.14.4':
case 'fixed':
case 'float':
task.obj.common.type = 'number';
break;
case 'char string':
case 'date':
case 'dateTime':
case 'dateTime.tz':
case 'time':
case 'time.tz':
case 'bin.base64':
case 'bin.hex':
case 'uri':
case 'uuid':
task.obj.common.type = 'string';
break;
}
if(task.obj.common.name === 'bool'){
task.obj.common.name = 'boolean';
}
}
adapter.setObjectNotExists(task.id, task.obj, () => {
if (task.obj.type === 'state' && task.id.match(/\.sid$/)) {
adapter.getState(task.id, (err, state) => {
if (!state) {
adapter.setState(task.id, false, true, (err, state) =>
setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else {
setTimeout(_processTasks, 0);
}
});
} else {
adapter.log.warn('Unknown task: ' + task.name);
setTimeout(_processTasks, 0);
}
}
}
function startServer() {
//START Server for Alive and ByeBye messages
// let own_uuid = 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5'; //this string is for filter message's from upnp Adapter
let server = new Server({ssdpIp: '239.255.255.250'});
// helper variables for start adding new devices
// let devices;
// Identification of upnp Adapter/ioBroker as upnp Service and it's capabilities
// at this time there is no implementation of upnp service capabilities, it is only necessary for the server to run
server.addUSN('upnp:rootdevice');
server.addUSN('urn:schemas-upnp-org:device:IoTManagementandControlDevice:1');
server.on('advertise-alive', headers => {
let usn = getValueFromArray(headers['USN'])
.replace(/uuid:/ig, '')
.replace(/::.*/ig, '');
let nt = getValueFromArray(headers['NT']);
let location = getValueFromArray(headers['LOCATION']);
if (!usn.match(/f40c2981-7329-40b7-8b04-27f187aecfb5/)) {
if (discoveredDevices.indexOf(location) === -1) {
discoveredDevices.push(location);
adapter.getDevices((err, devices) => {
let foundUUID = false;
for (let i = 0; i < devices.length; i++) {
if (!devices[i] || !devices[i].native || !devices[i].native.uuid) continue;
const deviceUUID = devices[i].native.uuid;
const deviceUSN = devices[i].native.deviceType;
// Set object Alive for the Service true
if (deviceUUID === usn && deviceUSN === nt) {
let maxAge = getValueFromArray(headers['CACHE-CONTROL'])
.replace(/max-age.=./ig, '')
.replace(/max-age=/ig, '')
.replace(/"/g, '');
addTask({
name: 'setState',
id: `${devices[i]._id}.Alive`,
state: {val: true, ack: true, expire: parseInt(maxAge)}
});
addTask({name: 'subscribeEvent', deviceID: devices[i]._id});
}
if (deviceUUID === usn) {
foundUUID = true;
break;
}
}
if (!foundUUID && adapter.config.enableAutoDiscover) {
adapter.log.debug(`Found new device: ${location}`);
addTask({name: 'firstDevLookup', location});
} else {
const pos = discoveredDevices.indexOf(location);
pos !== -1 && discoveredDevices.splice(pos, 1);
}
processTasks();
});
}
}
});
server.on('advertise-bye', headers => {
let usn = JSON.stringify(headers['USN']);
usn = usn.toString();
usn = usn.replace(/uuid:/g, '');
try {
usn.replace(/::.*/ig, '')
} catch (err) {
}
// let nt = JSON.stringify(headers['NT']);
// let location = JSON.stringify(headers['LOCATION']);
if (!usn.match(/.*f40c2981-7329-40b7-8b04-27f187aecfb5.*/)) {
adapter.getDevices((err, devices) => {
let device;
let deviceID;
let deviceUUID;
let deviceUSN;
for (device in devices) {
if (!devices.hasOwnProperty(device)) continue;
deviceUUID = JSON.stringify(devices[device]['native']['uuid']);
deviceUSN = JSON.stringify(devices[device]['native']['deviceType']);
//Set object Alive for the Service false
if (deviceUUID === usn) {
deviceID = JSON.stringify(devices[device]._id);
deviceID = deviceID.replace(/"/ig, '');
addTask({
name: 'setState',
id: `${deviceID}.Alive`,
state: {val: false, ack: true}
});
}
}
processTasks();
}); //END adapter.getDevices()
}
});
setTimeout(() => server.start(), 15000);
}
// Subscribe to every service that is alive. Triggered by change alive from false/null to true.
async function subscribeEvent(id, cb) {
const service = id.replace(/\.Alive/ig, '');
if (adapter.config.enableAutoSubscription === true) {
adapter.getObject(service, (err, obj) => {
let deviceIP = obj.native.ip;
let devicePort = obj.native.port;
const parts = obj._id.split('.');
parts.pop();
const channelID = parts.join('.');
adapter.getChannelsOf(channelID, async (err, channels) => {
for (let x = channels.length - 1; x >= 0; x--) {
const eventUrl = getValueFromArray(channels[x].native.eventSubURL).replace(/"/g, '');
if(channels[x].native.serviceType) {
try {
const infoSub = new Subscription(deviceIP, devicePort, eventUrl, 1000);
listener(eventUrl, channels[x]._id, infoSub);
} catch (err) {
}
}
}
cb();
}); //END adapter.getChannelsOf()
}); //END adapter.getObjects()
} else {
cb();
}
}
// message handler for subscriptions
function listener(eventUrl, channelID, infoSub) {
let variableTimeout;
let resetTimeoutTimer;
infoSub.on('subscribed', data => {
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('message', data => {
adapter.log.debug('Listener message: ' + JSON.stringify(data));
variableTimeout += 5;
setTimeout(() =>
getIDs()
.then(result => lookupService(data, JSON.parse(JSON.stringify(result.sids))))
,variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('error', err => {
adapter.log.debug(`Subscription error: ` + JSON.stringify(err));
// subscription.unsubscribe();
});
infoSub.on('resubscribed', data => {
// adapter.log.info('SID: ' + JSON.stringify(sid) + ' ' + eventUrl + ' ' + _channel._id);
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
}
function lookupService(data, SIDs, cb) {
if (!SIDs || !SIDs.length || !data || !data.sid) {
cb && cb();
} else {
const id = SIDs.shift();
adapter.getState(id, (err, state) => {
if (err || !state || typeof state !== 'object') {
adapter.log.error(`Error in lookupService: ${err || 'No object ' + id}`);
setImmediate(lookupService, data, cb);
} else {
setNewState(state, id.replace(/\.sid$/, ''), data, () =>
setImmediate(lookupService, data, cb));
}
});
}
}
function setNewState(state, serviceID, data, cb) {
adapter.log.debug('setNewState: ' + state + ' ' + JSON.stringify(data));
// Extract the value of the state
let valueSID = state.val;
if (valueSID !== null && valueSID !== undefined) {
valueSID = valueSID.toString().toLowerCase();
if (valueSID.indexOf(data.sid.toString().toLowerCase()) !== -1) {
serviceID = serviceID.replace(/\.sid$/, '');
// Select sub element with States
let newStates = data.body['e:propertyset']['e:property'];
if (newStates && newStates.LastChange && newStates.LastChange._) {
newStates = newStates.LastChange._;
adapter.log.info('Number 1: ' + newStates);
} else if (newStates) {
newStates = newStates.LastChange;
adapter.log.info('Number 2: ' + newStates);
} else {
adapter.log.info('Number 3: ' + newStates);
}
let newStates2 = JSON.stringify(newStates) || '';
// TODO: Must be refactored
if (newStates2 === undefined){
adapter.log.info('State: ' + state + ' Service ID: ' + serviceID + ' Data: ' + JSON.stringify(data));
}else if (newStates2.match(/<Event.*/ig)) {
parseString(newStates, (err, result) => {
let states = convertEventObject(result['Event']);
// split every array member into state name and value, then push it to ioBroker state
let stateName;
let val;
if (states) {
for (let x = states.length - 1; x >= 0; x--) {
let strState = states[x].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/"/i, '');
// looking for the value
val = strState.match(/val":"(\w*(:\w*|,\s\w*)*)/ig);
if (val) {
val = val[0];
val = val.replace(/val":"/ig, '');
}
addTask({name: 'valChannel', strState, serviceID, stateName, val});
}
processTasks();
}
cb();
}); //END parseString()
} else if (newStates2.match(/"\$":/ig)) {
let states = convertWM(newStates);
// split every array member into state name and value, then push it to ioBroker state
if (states) {
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
} else {
// Read all other messages and write the states to the related objects
let states = convertInitialObject(newStates);
if (states) {
// split every array member into state name and value, then push it to ioBroker state
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
}
} else {
cb();
}
} else {
cb();
}
}
// write state
function writeState(sID, sname, val, cb) {
adapter.getObject(`${sID}.A_ARG_TYPE_${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.A_ARG_TYPE_${sname}`, {val: val, ack: true}, err => {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
});
} else {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
}
});
}
// looking for the value of channel
function valChannel(strState, serviceID, cb) {
//looking for the value of channel
let channel = strState.match(/channel":"(\w*(:\w*|,\s\w*)*)/ig);
if (channel) {
channel = channel.toString();
channel = channel.replace(/channel":"/ig, '');
adapter.setState(`${serviceID}.A_ARG_TYPE_Channel`, {val: channel, ack: true}, cb);
} else {
cb()
}
}
// looking for the value
function valLookup(strState) {
let val = strState.match(/\w*":"(\w*\D\w|\w*|,\s\w*|(\w*:)*(\*)*(\/)*(,)*(-)*(\.)*)*/ig);
if (val) {
val = val.toString();
val = val.replace(/"\w*":"/i, '');
val = val.replace(/"/ig, '');
val = val.replace(/\w*:/, '')
}
return val;
}
// Not used now
// function convertEvent(data){
// let change = data.replace(/<\\.*>/ig, '{"');
// change = data.replace(/</ig, '{"');
// change = change.replace(/\s/ig, '""');
// change = change.replace(/=/ig, ':');
// change = change.replace(/\\/ig, '');
// change = change.replace(/>/ig, '}');
// }
//convert the event JSON into an array
function convertEventObject(result) {
const regex = new RegExp(/"\w*":\[{"\$":{("\w*":"(\w*:\w*:\w*|(\w*,\s\w*)*|\w*)"(,"\w*":"\w*")*)}/ig);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array
function convertInitialObject(result) {
const regex = new RegExp(/"\w*":"(\w*|\w*\D\w*|(\w*-)*\w*:\w*|(\w*,\w*)*|\w*:\S*\*)"/g);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array for windows media player/server
function convertWM(result) {
const regex = new RegExp(/"\w*":{".":"(\w*"|((http-get:\*:\w*\/((\w*\.)*|(\w*-)*|(\w*\.)*(\w*-)*)\w*:\w*\.\w*=\w*(,)*)*((http-get|rtsp-rtp-udp):\*:\w*\/(\w*(\.|-))*\w*:\*(,)*)*))/g);
return (JSON.stringify(result) || '').match(regex);
}
//END Event listener
// clear Alive and sid's states when Adapter stops
function clearAliveAndSIDStates(cb) {
// Clear sid
getIDs()
.then(result => {
result.sids.forEach(id => {
addTask({name: 'setState', id, state: {val: '', ack: true}});
});
result.alives.forEach(id => {
addTask({name: 'setState', id, state: {val: false, ack: true}});
});
processTasks(cb);
});
}
function getIDs() {
if (sidPromise) {
return sidPromise;
} else {
// Fill array arrSID if it is empty
sidPromise = new Promise(resolve => {
adapter.getStatesOf(`upnp.${adapter.instance}`, (err, _states) => {
const sids = [];
const alives = [];
err && adapter.log.error('Cannot get SIDs: ' + err);
if (_states) {
_states.forEach(obj => {
if (obj._id.match(/\.sid$/)) {
// if the match deliver an id of an object add them to the array
sids.push(obj._id);
} else
if (obj._id.match(/\.Alive/g)) {
alives.push(obj._id);
}
});
}
// adapter.log.debug('Array arrSID is now filled');
// When the array is filled start the search
resolve({sids, alives});
});
});
return sidPromise;
}
}
// control the devices
function sendCommand(id, cb) {
adapter.log.debug('Send Command for ' + id);
let parts = id.split('.');
parts.pop();
let actionName = parts.pop();
let service = parts.join('.');
id = id.replace('.request', '');
adapter.getObject(service, (err, obj) => {
let vServiceType = obj.native.serviceType;
let serviceName = obj.native.name;
let device = service.replace(`.${serviceName}`, '');
let vControlURL = obj.native.controlURL;
adapter.getObject(device, (err, obj) => {
let ip = obj.native.ip;
let port = obj.native.port;
let cName = JSON.stringify(obj._id);
cName = cName.replace(/\.\w*"$/g, '');
cName = cName.replace(/^"/g, '');
adapter.getStatesOf(cName, (err, _states) => {
let args = [];
for (let x = _states.length - 1; x >= 0; x--) {
let argumentsOfAction = _states[x]._id;
let obj = _states[x];
let test2 = id + '\\.';
try {
test2 = test2.replace(/\(/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\)/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\[/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/ ]/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
let re = new RegExp(test2, 'g');
let testResult = re.test(argumentsOfAction);
if (testResult && argumentsOfAction !== id) {
args.push(obj);
}
}
let body = '';
// get all states of the arguments as string
adapter.getStates(`${id}.*`, (err, idStates) => {
adapter.log.debug('get all states of the arguments as string ');
let helperBody = [];
let states = JSON.stringify(idStates);
states = states.replace(/,"ack":\w*,"ts":\d*,"q":\d*,"from":"(\w*\.)*(\d*)","lc":\d*/g, '');
for (let z = args.length - 1; z >= 0; z--) {
// check if the argument has to be send with the action
if (args[z].native.direction === 'in') {
let argNo = args[z].native.argumentNumber;
// check if the argument is already written to the helperBody array, if not found value and add to array
if (helperBody[argNo] == null) {
let test2 = getValueFromArray(args[z]._id);
// replace signs that could cause problems with regex
test2 = test2
.replace(/\(/gi, '.')
.replace(/\)/gi, '.')
.replace(/\[/gi, '.')
.replace(/]/gi, '.');
let test3 = test2 + '":{"val":("[^"]*|\\d*)}?';
let patt = new RegExp(test3, 'g');
let testResult2;
let testResult = states.match(patt);
testResult2 = JSON.stringify(testResult);
testResult2 = testResult2.match(/val\\":(\\"[^"]*|\d*)}?/g);
testResult2 = JSON.stringify(testResult2);
testResult2 = testResult2.replace(/\["val(\\)*":(\\)*/, '');
testResult2 = testResult2.replace(/]/, '');
testResult2 = testResult2.replace(/}"/, '');
testResult2 = testResult2.replace(/"/g, '');
//extract argument name from id string
let test1 = args[z]._id;
let argName = test1.replace(`${id}\.`, '');
helperBody[argNo] = '<' + argName + '>' + testResult2 + '</' + argName + '>';
}
}
}
//convert helperBody array to string and add it to main body string
helperBody = helperBody.toString().replace(/,/g, '');
body += helperBody;
body = `<u:${actionName} xmlns:u="${vServiceType}">${body}</u:${actionName}>`;
createMessage(vServiceType, actionName, ip, port, vControlURL, body, id, cb);
});
})
});
});
}
function readSchedules() {
return new Promise(resolve => {
adapter.getObjectView('system', 'custom', {startkey: adapter.namespace + '.', endkey: adapter.namespace + '.\uFFFF'}, (err, doc) => {
if (doc && doc.rows) {
for (let i = 0, l = doc.rows.length; i < l; i++) {
if (doc.rows[i].value) {
let id = doc.rows[i].id;
let obj = doc.rows[i].value;
if (id.startsWith(adapter.namespace) && obj[adapter.namespace] && obj[adapter.namespace].enabled && id.match(/\.request$/)) {
actions[id] = {cron: obj[adapter.namespace].schedule};
}
}
}
}
resolve();
});
});
}
// create Action message
function createMessage(sType, aName, _ip, _port, cURL, body, actionID, cb) {
const UA = 'UPnP/1.0, ioBroker.upnp';
let url = `http://${_ip}:${_port}${cURL}`;
const contentType = 'text/xml; charset="utf-8"';
let soapAction = `${sType}#${aName}`;
let postData = `
<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
<s:Body>${body}</s:Body>
</s:Envelope>`;
//Options for the SOAP message
let options = {
uri: url,
headers: {
'Content-Type': contentType,
'SOAPAction': `"${soapAction}"`,
'USER-AGENT': UA
},
method: 'POST',
body: postData
};
// Send Action message to Device/Service
request(options, (err, res, body) => {
adapter.log.debug('Options for request: ' + JSON.stringify(options));
if (err) {
adapter.log.warn(`Error sending SOAP request: ${err}`);
} else {
if (res.statusCode !== 200) {
adapter.log.warn(`Unexpected answer from upnp service: ` + JSON.stringify(res) + `\n Sent message: ` + JSON.stringify(options));
} else {
//look for data in the response
// die Zusätlichen infos beim Argument namen müssen entfernt werden damit er genutzt werden kann
let foundData = body.match(/<[^\/]\w*\s*[^<]*/g);
if (foundData) {
actionID = actionID.replace(/\.request$/, '');
for (let i = foundData.length - 1; i >= 0; i--) {
let foundArgName = foundData[i].match(/<\w*>/);
let strFoundArgName;
let argValue;
if (foundArgName) {
strFoundArgName = foundArgName[0];
// TODO: must be rewritten
strFoundArgName = strFoundArgName.replace(/["\][]}/g, '');
argValue = foundData[i].replace(strFoundArgName, '');
strFoundArgName = strFoundArgName.replace(/[<>]/g, '');
} else {
foundArgName = foundData[i].match(/<\w*\s/);
if (foundArgName) {
// TODO: must be rewritten
strFoundArgName = foundArgName[0];
strFoundArgName = strFoundArgName.replace(/["[\]<]/g, '').replace(/\s+$/, '');
argValue = foundData[i].replace(/<.*>/, '');
}
}
if (strFoundArgName !== null && strFoundArgName !== undefined) {
let argID = actionID + '.' + strFoundArgName;
addTask({
name: 'setState',
id: argID,
state: {val: argValue, ack: true},
cb: cb =>
//look for relatedStateVariable and setState
syncArgument(actionID, argID, argValue, cb)
});
}
}
processTasks();
} else {
adapter.log.debug('Nothing found: ' + JSON.stringify(body));
}
}
}
cb && cb();
});
}
// Sync Argument with relatedStateVariable
function syncArgument(actionID, argID, argValue, cb) {
adapter.getObject(argID, (err, obj) => {
if (obj) {
let relatedStateVariable = obj.native.relatedStateVariable;
let serviceID = actionID.replace(/\.\w*$/, '');
let relStateVarID = serviceID + '.' + relatedStateVariable;
let val = argValue;
if(obj.common.type === 'number'){
val = parseInt(argValue);
}
adapter.setState(relStateVarID, {val: argValue, ack: true}, cb);
} else {
cb && cb();
}
});
}
function nameFilter(name) {
if (typeof name === 'object' && name[0]) {
name = name[0];
}
let signs = [
String.fromCharCode(46),
String.fromCharCode(44),
String.fromCharCode(92),
String.fromCharCode(47),
String.fromCharCode(91),
String.fromCharCode(93),
String.fromCharCode(123),
String.fromCharCode(125),
String.fromCharCode(32),
String.fromCharCode(129),
String.fromCharCode(154),
String.fromCharCode(132),
String.fromCharCode(142),
String.fromCharCode(148),
String.fromCharCode(153),
String.fromCharCode(42),
String.fromCharCode(63),
String.fromCharCode(34),
String.fromCharCode(39),
String.fromCharCode(96)
];
//46=. 44=, 92=\ 47=/ 91=[ 93=] 123={ 125=} 32=Space 129=ü 154=Ü 132=ä 142=Ä 148=ö 153=Ö 42=* 63=? 34=" 39=' 96=`
signs.forEach((item, index) => {
let count = name.split(item).length - 1;
for (let i = 0; i < count; i++) {
name = name.replace(item, '_');
}
let result = name.search(/_$/);
if (result !== -1) {
name = name.replace(/_$/, '');
}
});
name = name.replace(/[*\[\]+?]+/g, '_');
return name;
}
function main() {
adapter.subscribeStates('*');
adapter.subscribeObjects('*');
adapter.log.info('Auto discover: ' + adapter.config.enableAutoDiscover);
readSchedules()
.then(() => {
if (adapter.config.enableAutoDiscover === true) {
sendBroadcast();
}
// read SIDs and Alive IDs
getIDs()
.then(result => {
adapter.log.debug(`Read ${result.sids.length} SIDs and ${result.alives.length} alives`);
// Filtering the Device description file addresses, timeout is necessary to wait for all answers
setTimeout(() => {
adapter.log.debug(`Found ${foundIPs.length} devices`);
if (adapter.config.rootXMLurl) {
firstDevLookup(adapter.config.rootXMLurl);
}
reschedule();
}, 5000);
//start the server
startServer();
});
});
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}
| Jey-Cee/ioBroker.upnp | main.js | JavaScript | mit | 83,360 |
if(Bar.app("Início")) throw "Barra já existe!";
/*/LOADING BAR
$.get("http://hosts.medorc.org/xn--stio-vpa/json/bar.Home.json"),
function(data){
//if(Bar.app(data.name)) throw "Barra já existe!";
$('#header').bar({
toolbox: data,
callback: function(bar){
//(auto) load requested addon
(function(startHash){
if(startHash && startHash != '#!Home' && startHash != '#!Início'){
// gets bar addon (or loads addon script) before callback
Bar.getBar(Bar.urls(startHash), function(error, addon){
// error getting addon
if(error) throw error + " error getting addon " + startHash + " @bar.Home";
// route to addon (select addon tab)
Frontgate.router.route(addon.href);
//console.log('Bar.route', bar, route);
});
}
})(Remote.attr("requestHash"));
// mostrar item IE apenas se o utilizador for "daniel"
if(Situs.attr().user == "daniel") $("#isec-ei").show();
Situs.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}
});
});
/*/
//AUTO LOADING BAR
Bar.load('#header', function(bar, data){
Frontgate.router.on("#Home", function(hash){
location.hash = "Início";
});
// mostrar item IE apenas se o utilizador for "daniel"
if(Frontgate.attr().user == "daniel") $("#isec-ei").show();
Frontgate.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}, FILE);//*/
//------------------------------------------------------------------
// BUG:
// when addon items are not hash banged (#!ToolboxItem)
// the tab is added to the navigator but the toolbox is not selected
//------------------------------------------------------------------
| vieiralisboa/ze | private/bars/bar.Home.js | JavaScript | mit | 2,099 |
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime"
],
"stage": 1
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"angular2": "npm:angular2@2.0.0-beta.1",
"babel": "npm:babel-core@5.8.35",
"babel-runtime": "npm:babel-runtime@5.8.35",
"clean-css": "npm:clean-css@3.4.9",
"core-js": "npm:core-js@1.2.6",
"css": "github:systemjs/plugin-css@0.1.20",
"reflect-metadata": "npm:reflect-metadata@0.1.2",
"rxjs": "npm:rxjs@5.0.0-beta.0",
"zone.js": "npm:zone.js@0.5.0",
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.6.0"
},
"github:jspm/nodelibs-constants@0.1.0": {
"constants-browserify": "npm:constants-browserify@0.0.1"
},
"github:jspm/nodelibs-crypto@0.1.0": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
},
"github:jspm/nodelibs-events@0.1.1": {
"events": "npm:events@1.0.2"
},
"github:jspm/nodelibs-http@1.7.1": {
"Base64": "npm:Base64@0.2.1",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-https@0.1.0": {
"https-browserify": "npm:https-browserify@0.0.0"
},
"github:jspm/nodelibs-os@0.1.0": {
"os-browserify": "npm:os-browserify@0.1.2"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-stream@0.1.0": {
"stream-browserify": "npm:stream-browserify@1.0.0"
},
"github:jspm/nodelibs-string_decoder@0.1.0": {
"string_decoder": "npm:string_decoder@0.10.31"
},
"github:jspm/nodelibs-url@0.1.0": {
"url": "npm:url@0.10.3"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"npm:amdefine@1.0.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"module": "github:jspm/nodelibs-module@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:angular2@2.0.0-beta.1": {
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"es6-promise": "npm:es6-promise@3.0.2",
"es6-shim": "npm:es6-shim@0.33.13",
"process": "github:jspm/nodelibs-process@0.1.2",
"reflect-metadata": "npm:reflect-metadata@0.1.2",
"rxjs": "npm:rxjs@5.0.0-beta.0",
"zone.js": "npm:zone.js@0.5.0"
},
"npm:asn1.js@4.3.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"bn.js": "npm:bn.js@4.6.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.35": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:browserify-aes@1.0.6": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"buffer-xor": "npm:buffer-xor@1.0.3",
"cipher-base": "npm:cipher-base@1.0.2",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:browserify-cipher@1.0.0": {
"browserify-aes": "npm:browserify-aes@1.0.6",
"browserify-des": "npm:browserify-des@1.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
},
"npm:browserify-des@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"des.js": "npm:des.js@1.0.0",
"inherits": "npm:inherits@2.0.1"
},
"npm:browserify-rsa@4.0.0": {
"bn.js": "npm:bn.js@4.6.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:browserify-sign@4.0.0": {
"bn.js": "npm:bn.js@4.6.6",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.2.0",
"inherits": "npm:inherits@2.0.1",
"parse-asn1": "npm:parse-asn1@5.0.0",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:buffer-xor@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:buffer@3.6.0": {
"base64-js": "npm:base64-js@0.0.8",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ieee754": "npm:ieee754@1.1.6",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:cipher-base@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0"
},
"npm:clean-css@3.4.9": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"commander": "npm:commander@2.8.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"http": "github:jspm/nodelibs-http@1.7.1",
"https": "github:jspm/nodelibs-https@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.4.4",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:commander@2.8.1": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"graceful-readlink": "npm:graceful-readlink@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:constants-browserify@0.0.1": {
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-js@1.2.6": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:core-util-is@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:create-ecdh@4.0.0": {
"bn.js": "npm:bn.js@4.6.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.2.0"
},
"npm:create-hash@1.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"ripemd160": "npm:ripemd160@1.0.1",
"sha.js": "npm:sha.js@2.4.4"
},
"npm:create-hmac@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:crypto-browserify@3.11.0": {
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"browserify-sign": "npm:browserify-sign@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"diffie-hellman": "npm:diffie-hellman@5.0.1",
"inherits": "npm:inherits@2.0.1",
"pbkdf2": "npm:pbkdf2@3.0.4",
"public-encrypt": "npm:public-encrypt@4.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:des.js@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
},
"npm:diffie-hellman@5.0.1": {
"bn.js": "npm:bn.js@4.6.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:elliptic@6.2.0": {
"bn.js": "npm:bn.js@4.6.6",
"brorand": "npm:brorand@1.0.5",
"hash.js": "npm:hash.js@1.0.3",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:es6-promise@3.0.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:es6-shim@0.33.13": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:evp_bytestokey@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0"
},
"npm:graceful-readlink@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:hash.js@1.0.3": {
"inherits": "npm:inherits@2.0.1"
},
"npm:https-browserify@0.0.0": {
"http": "github:jspm/nodelibs-http@1.7.1"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:miller-rabin@4.0.0": {
"bn.js": "npm:bn.js@4.6.6",
"brorand": "npm:brorand@1.0.5"
},
"npm:os-browserify@0.1.2": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:parse-asn1@5.0.0": {
"asn1.js": "npm:asn1.js@4.3.0",
"browserify-aes": "npm:browserify-aes@1.0.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"pbkdf2": "npm:pbkdf2@3.0.4",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pbkdf2@3.0.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:public-encrypt@4.0.0": {
"bn.js": "npm:bn.js@4.6.6",
"browserify-rsa": "npm:browserify-rsa@4.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.2"
},
"npm:punycode@1.3.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:randombytes@2.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:readable-stream@1.1.13": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:reflect-metadata@0.1.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:ripemd160@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:rxjs@5.0.0-beta.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sha.js@2.4.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.4.4": {
"amdefine": "npm:amdefine@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:stream-browserify@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.13"
},
"npm:string_decoder@0.10.31": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:url@0.10.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
},
"npm:zone.js@0.5.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
}
}
});
| gilAsier/angular2beta_errors | public/config.js | JavaScript | mit | 14,023 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\HP;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PreviewImage extends AbstractTag
{
protected $Id = 'PreviewImage';
protected $Name = 'PreviewImage';
protected $FullName = 'HP::Type2';
protected $GroupName = 'HP';
protected $g0 = 'MakerNotes';
protected $g1 = 'HP';
protected $g2 = 'Camera';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Preview Image';
protected $local_g2 = 'Preview';
protected $flag_Permanent = true;
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/HP/PreviewImage.php | PHP | mit | 860 |
$(document).ready(function() {
$.getJSON('/backend/go/' + go_term['id'] + '/locus_details', function(data) {
create_go_table(data);
});
$.getJSON('/backend/go/' + go_term['id'] + '/ontology_graph', function(data) {
var cy = create_cytoscape_vis("cy", layout, graph_style, data, null, false, "goOntology");
create_cy_download_button(cy, "cy_download", go_term['display_name'] + '_ontology')
if(data['all_children'] != null && data['all_children'].length > 0) {
var children_div = document.getElementById("children");
var more_children_div = document.getElementById("children_see_more");
for(var i=0; i < data['all_children'].length; i++) {
var a = document.createElement('a');
a.innerHTML = data['all_children'][i]['display_name'];
a.href = data['all_children'][i]['link']
if(i < 20) {
children_div.appendChild(a);
}
else {
more_children_div.appendChild(a);
}
if(i != data['all_children'].length-1) {
var comma = document.createElement('span');
comma.innerHTML = ' • ';
if(i < 20) {
children_div.appendChild(comma);
}
else {
more_children_div.appendChild(comma);
}
}
}
if(data['all_children'].length <= 20) {
$("#children_see_more_button").hide();
}
}
else {
$("#children_wrapper").hide()
}
});
});
function create_go_table(data) {
var manualDatatable = [];
var manualGenes = {};
var htpDatatable = [];
var htpGenes = {};
var computationalDatatable = [];
var computationalGenes = {};
for (var i=0; i < data.length; i++) {
var type = data[i].annotation_type;
if (type === 'manually curated') {
manualDatatable.push(go_data_to_table(data[i], i));
manualGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'high-throughput') {
htpDatatable.push(go_data_to_table(data[i], i));
htpGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'computational') {
computationalDatatable.push(go_data_to_table(data[i], i));
computationalGenes[data[i]["locus"]["id"]] = true;
}
}
set_up_header('manual_go_table', manualDatatable.length, 'entry', 'entries', Object.keys(manualGenes).length, 'gene', 'genes');
set_up_header('htp_go_table', htpDatatable.length, 'entry', 'entries', Object.keys(htpGenes).length, 'gene', 'genes');
set_up_header('computational_go_table', computationalDatatable.length, 'entry', 'entries', Object.keys(computationalGenes).length, 'gene', 'genes');
var options = {};
options["bPaginate"] = true;
options["aaSorting"] = [[3, "asc"]];
options["bDestroy"] = true;
// options["oLanguage"] = {"sEmptyTable": "No genes annotated directly to " + go_term['display_name']};
options["aoColumns"] = [
//Use of mData
{"bSearchable":false, "bVisible":false,"aTargets":[0],"mData":0}, //evidence_id
{"bSearchable":false, "bVisible":false,"aTargets":[1],"mData":1}, //analyze_id
{"aTargets":[2],"mData":2}, //gene
{"bSearchable":false, "bVisible":false,"aTargets":[3],"mData":3}, //gene systematic name
{"aTargets":[4],"mData":4}, //gene ontology term -----> qualifier
{"bSearchable":false, "bVisible":false,"aTargets":[5],"mData":5}, //gene ontology term id
{"aTargets":[6],"mData":6}, //qualifier -----> gene ontology term
{"bSearchable":false, "bVisible":false,"aTargets":[7],"mData":7}, //aspect
{"aTargets":[8],"mData":8}, //evidence -----> annotation_extension
{"aTargets":[9],"mData":9}, //method -----> evidence
{"bSearchable":false,"bVisible":false,"aTargets":[10],"mData":10}, //source -----> method
{"aTargets":[11],"mData":11}, //assigned on -----> source
{"aTargets":[12],"mData":12}, //annotation_extension -----> assigned on
{"aTargets":[13],"mData":13} // reference
];
create_or_hide_table(manualDatatable, options, "manual_go_table", go_term["display_name"], go_term["link"], go_term["id"], "manually curated", data);
create_or_hide_table(htpDatatable, options, "htp_go_table", go_term["display_name"], go_term["link"], go_term["id"], "high-throughput", data);
create_or_hide_table(computationalDatatable, options, "computational_go_table", go_term["display_name"], go_term["link"], go_term["id"], "computational", data);
}
function create_or_hide_table(tableData, options, tableIdentifier, goName, goLink, goId, annotationType, originalData) {
if (tableData.length) {
var localOptions = $.extend({ aaData: tableData, oLanguage: { sEmptyTable: 'No genes annotated directly to ' + goName } }, options);
var table = create_table(tableIdentifier, localOptions);
create_analyze_button(tableIdentifier + "_analyze", table, "<a href='" + goLink + "' class='gene_name'>" + goName + "</a> genes", true);
create_download_button(tableIdentifier + "_download", table, goName + "_annotations");
if(go_term['descendant_locus_count'] > go_term['locus_count']) {
create_show_child_button(tableIdentifier + "_show_children", table, originalData, "/backend/go/" + goId + "/locus_details_all", go_data_to_table, function(table_data) {
var genes = {};
for (var i=0; i < table_data.length; i++) {
genes[table_data[i][1]] = true;
}
set_up_header(tableIdentifier, table_data.length, 'entry', 'entries', Object.keys(genes).length, 'gene', 'genes');
}, annotationType);
}
return table;
} else {
$("#" + tableIdentifier + "_header").remove();
var $parent = $("#" + tableIdentifier).parent();
var emptyMessage = "There are no " + annotationType + " annotations for " + goName + ".";
$parent.html(emptyMessage);
}
};
var graph_style = cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 14,
'text-outline-width': 3,
'text-valign': 'center',
'width': 30,
'height': 30,
'border-color': '#fff',
'background-color': "#43a0df",
'text-outline-color': '#fff',
'color': '#888'
})
.selector('edge')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 12,
'color': 'grey',
'width': 2,
'source-arrow-shape': 'triangle'
})
.selector("node[sub_type='FOCUS']")
.css({
'width': 30,
'height': 30,
'background-color': "#fade71",
'text-outline-color': '#fff',
'color': '#888'
})
.selector("node[id='NodeMoreChildren']")
.css({
'width': 30,
'height': 30,
'shape': 'rectangle'
});
// .selector("node[sub_type='HAS_CHILDREN']")
// .css(
// {'background-color': "#165782"
// })
// .selector("node[sub_type='HAS_DESCENDANTS']")
// .css(
// {'background-color': "#43a0df"
// })
// .selector("node[sub_type='NO_DESCENDANTS']")
// .css(
// {'background-color': "#c9e4f6"
// });
var layout = {
"name": "breadthfirst",
"fit": true,
"directed": true
};
| yeastgenome/SGDFrontend | src/sgd/frontend/yeastgenome/static/js/go.js | JavaScript | mit | 7,443 |
package com.dreamteam.octodrive.model;
import com.parse.ParseObject;
public abstract class OctoObject {
protected String _objectId;
protected ParseObject _parseObject;
public ParseObject parseObject() {
return _parseObject;
}
public void setObjectId(String objectId) {
_objectId = objectId;
}
public String objectId() {
if (_objectId == null) {
_objectId = _parseObject.getObjectId();
}
return _objectId;
}
}
| lordzsolt/OctoDrive | app/src/main/java/com/dreamteam/octodrive/model/OctoObject.java | Java | mit | 500 |
!function($) {
$(document).on("keydown", 'input[data-type="numeric"]', function (e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
}(window.jQuery || window.ender); | carlalexander/jquery.numeric.input | jquery.numeric.input.js | JavaScript | mit | 420 |
package ca.ulaval.glo2004.Domain.Matrix;
import ca.ulaval.glo2004.Domain.StationExitPoint;
import java.io.Serializable;
public class ExitProductSortingHolder implements Serializable{
public StationExitPoint exitPoint;
public double value;
public ExitProductSortingHolder(StationExitPoint exitPoint, double value){
this.exitPoint = exitPoint;
this.value = value;
}
}
| klafooty/projetJava | src/main/java/ca/ulaval/glo2004/Domain/Matrix/ExitProductSortingHolder.java | Java | mit | 401 |
import Chip from '../../components/Chip'
import { vueTest } from '../utils'
describe('Chip', () => {
let vm
before((done) => {
vm = vueTest(Chip)
vm.$nextTick(done)
})
it('renders with text', () => {
const el = vm.$('#chip')
el.should.contain.text('Basic chip')
el.should.not.have.class('mdl-chip--contact')
el.should.not.have.class('mdl-chip--deletable')
})
it('renders with close button', () => {
const el = vm.$('#delete')
el.should.contain.text('Deletable chip')
el.should.not.have.class('mdl-chip--contact')
el.should.have.class('mdl-chip--deletable')
const action = vm.$('#delete .mdl-chip__action')
action.should.exist
action.should.have.text('cancel')
})
it('has custom icon', (done) => {
const action = vm.$('#delete .mdl-chip__action')
action.should.have.text('cancel')
vm.deleteIcon = 'star'
vm.nextTick()
.then(() => {
action.should.have.text('star')
})
.then(done, done)
})
it('emits close event', (done) => {
vm.deleted.should.be.false
const action = vm.$('#delete .mdl-chip__action')
action.click()
vm.nextTick()
.then(() => {
vm.deleted.should.be.true
vm.deleted = false
return vm.nextTick()
})
.then(done, done)
})
it('renders text inside circle', (done) => {
vm.$('#contact').should.have.class('mdl-chip--contact')
const el = vm.$('#contact .mdl-chip__contact')
el.should.contain.text(vm.contact)
el.should.not.have.class('mdl-chip--deletable')
vm.contact = 'A'
vm.nextTick()
.then(() => {
el.should.have.text('A')
})
.then(done, done)
})
it('renders image inside circle', () => {
vm.$('#image').should.have.class('mdl-chip--contact')
const el = vm.$('#image .mdl-chip__contact')
el.should.have.attr('src', 'https://getmdl.io/templates/dashboard/images/user.jpg')
el.should.not.have.class('mdl-chip--deletable')
})
})
| posva/vue-mdl | test/unit/specs/Chip.spec.js | JavaScript | mit | 1,991 |
#!/usr/bin/ruby
#
# Script to immediately start playing a track in the media player.
#
# Author:: Nicholas J Humfrey (mailto:njh@aelius.com)
# Copyright:: Copyright (c) 2008 Nicholas J Humfrey
# License:: Distributes under the same terms as Ruby
#
$:.unshift File.dirname(__FILE__)+'/../lib'
require 'mpris'
raise "Usage: play_track.rb <filename>" unless (ARGV.size == 1)
mpris = MPRIS.new
mpris.tracklist.add_track( ARGV[0], true )
| njh/ruby-mpris | examples/play_track.rb | Ruby | mit | 443 |
from . import packet
class Packet5(packet.Packet):
def __init__(self, player, slot):
super(Packet5, self).__init__(0x5)
self.add_data(player.playerID)
self.add_data(slot)
self.add_structured_data("<h", 0) # Stack
self.add_data(0) # Prefix
self.add_structured_data("<h", 0) # ItemID
| flammified/terrabot | terrabot/packets/packet5.py | Python | mit | 340 |
module Blackbeard
class FeatureMetric < SegmentedMetric
end
end
| goldstar/blackbeard | lib/blackbeard/feature_metric.rb | Ruby | mit | 68 |
import { hashHistory } from 'react-router'
import { auth } from 'lib/firebase'
export const redirect = path => hashHistory.push(path)
export const signInWithGoogle = () => {
const provider = new auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/userinfo.profile')
return auth().signInWithPopup(provider)
}
export const signInWithFacebook = () => {
const provider = new auth.FacebookAuthProvider()
return auth().signInWithPopup(provider)
}
export const signOut = () => {
return auth().signOut()
}
export const getCurrentUser = () => {
return Promise.resolve(auth().currentUser)
}
| panelando/panelando | app/lib/auth.js | JavaScript | mit | 629 |
#include "Chapter7.h"
#include "Interactable.h"
bool IInteractable::CanInteract_Implementation()
{
return true;
}
void IInteractable::PerformInteract_Implementation()
{
}
| sunithshetty/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook | Chapter07/Source/Chapter7/Interactable.cpp | C++ | mit | 175 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('managers', '0011_auto_20150422_2018'),
]
operations = [
migrations.AlterField(
model_name='managerprofile',
name='picture',
field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg', upload_to=b'profiles'),
preserve_default=True,
),
]
| ritashugisha/ASUEvents | ASUEvents/managers/migrations/0012_auto_20150422_2019.py | Python | mit | 511 |
/**
* @author: @AngularClass
*/
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
/**
* Webpack Constants
*/
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({
env: ENV
}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: false
});
module.exports = function (env) {
return webpackMerge(commonConfig({
env: ENV
}), {
/**
* Developer tool to enhance debugging
*
* See: http://webpack.github.io/docs/configuration.html#devtool
* See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
*/
devtool: 'source-map',
/**
* Options affecting the output of the compilation.
*
* See: http://webpack.github.io/docs/configuration.html#output
*/
output: {
/**
* The output directory as absolute path (required).
*
* See: http://webpack.github.io/docs/configuration.html#output-path
*/
path: helpers.root('dist'),
/**
* Specifies the name of each output file on disk.
* IMPORTANT: You must not specify an absolute path here!
*
* See: http://webpack.github.io/docs/configuration.html#output-filename
*/
filename: '[name].[chunkhash].bundle.js',
/**
* The filename of the SourceMaps for the JavaScript files.
* They are inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
*/
sourceMapFilename: '[name].[chunkhash].bundle.map',
/**
* The filename of non-entry chunks as relative path
* inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
*/
chunkFilename: '[id].[chunkhash].chunk.js'
},
module: {
rules: [
/*
* Extract CSS files from .src/styles directory to external CSS file
*/
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
}),
include: [helpers.root('src', 'styles')]
},
/*
* Extract and compile SCSS files from .src/styles directory to external CSS file
*/
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!sass-loader'
}),
include: [helpers.root('src', 'styles')]
},
]
},
/**
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
/**
* Webpack plugin to optimize a JavaScript file for faster initial load
* by wrapping eagerly-invoked functions.
*
* See: https://github.com/vigneshshanmugam/optimize-js-plugin
*/
new OptimizeJsPlugin({
sourceMap: false
}),
/**
* Plugin: ExtractTextPlugin
* Description: Extracts imported CSS files into external stylesheet
*
* See: https://github.com/webpack/extract-text-webpack-plugin
*/
new ExtractTextPlugin('[name].[contenthash].css'),
/**
* Plugin: DefinePlugin
* Description: Define free variables.
* Useful for having development builds with debug logging or adding global constants.
*
* Environment helpers
*
* See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
*/
// NOTE: when adding more properties make sure you include them in custom-typings.d.ts
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
}
}),
/**
* Plugin: UglifyJsPlugin
* Description: Minimize all JavaScript output of chunks.
* Loaders are switched into minimizing mode.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
*/
// NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
new UglifyJsPlugin({
// beautify: true, //debug
// mangle: false, //debug
// dead_code: false, //debug
// unused: false, //debug
// deadCode: false, //debug
// compress: {
// screw_ie8: true,
// keep_fnames: true,
// drop_debugger: false,
// dead_code: false,
// unused: false
// }, // debug
// comments: true, //debug
beautify: false, //prod
output: {
comments: false
}, //prod
mangle: {
screw_ie8: true
}, //prod
compress: {
screw_ie8: true,
warnings: false,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
negate_iife: false // we need this for lazy v8
},
}),
/**
* Plugin: NormalModuleReplacementPlugin
* Description: Replace resources that matches resourceRegExp with newResource
*
* See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
*/
new NormalModuleReplacementPlugin(
/angular2-hmr/,
helpers.root('config/empty.js')
),
new NormalModuleReplacementPlugin(
/zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
helpers.root('config/empty.js')
),
// AoT
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)upgrade/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)compiler/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)platform-browser-dynamic/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)ng_probe/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)by/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_node/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_renderer/,
// helpers.root('config/empty.js')
// ),
/**
* Plugin: CompressionPlugin
* Description: Prepares compressed versions of assets to serve
* them with Content-Encoding
*
* See: https://github.com/webpack/compression-webpack-plugin
*/
// install compression-webpack-plugin
// new CompressionPlugin({
// regExp: /\.css$|\.html$|\.js$|\.map$/,
// threshold: 2 * 1024
// })
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({
minimize: true,
debug: false,
options: {
/**
* Html loader advanced options
*
* See: https://github.com/webpack/html-loader#advanced-options
*/
// TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
htmlLoader: {
minimize: false,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
},
}
}),
/**
* Plugin: BundleAnalyzerPlugin
* Description: Webpack plugin and CLI utility that represents
* bundle content as convenient interactive zoomable treemap
*
* `npm run build:prod -- --env.analyze` to use
*
* See: https://github.com/th0r/webpack-bundle-analyzer
*/
],
/*
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: false,
module: false,
clearImmediate: false,
setImmediate: false
}
});
}
| AnastasiaPavlova/Angular2Traning | config/webpack.prod.js | JavaScript | mit | 9,907 |
package junit.util;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* JUnit4からのassertThatアサーションを使いやすくするためのラッパー処理群。<br>
* isのためのimportが面倒、Boxingは避けたいという御仁向け。<br>
* assertThatのシグネチャが改善される可能性を考慮してメソッド名は別名にしています。
*
* @author cobot00
*/
public final class AssertWrapper {
private AssertWrapper() {
// コンストラクタの隠蔽
}
public static void assertThatWrapper(int actual, int expected) {
assertThat(Integer.valueOf(actual), is(Integer.valueOf(expected)));
}
public static void assertThatWrapper(long actual, long expected) {
assertThat(Long.valueOf(actual), is(Long.valueOf(expected)));
}
public static void assertThatWrapper(double actual, double expected) {
assertThat(Double.valueOf(actual), is(Double.valueOf(expected)));
}
public static void assertThatWrapper(String actual, String expected) {
assertThat(actual, is(expected));
}
public static void assertEqualsWrapper(boolean actual, boolean expected) {
if (expected) {
assertTrue("\n Expected [" + expected + "] But actual [" + actual + "]", actual);
} else {
assertFalse("\n Expected [" + expected + "] But actual [" + actual + "]", actual);
}
}
public static void assertThatWrapper(int actual, int expected, String message) {
assertThat(message, Integer.valueOf(actual), is(Integer.valueOf(expected)));
}
public static void assertThatWrapper(double actual, double expected, String message) {
assertThat(message, Double.valueOf(actual), is(Double.valueOf(expected)));
}
public static void assertThatWrapper(long actual, long expected, String message) {
assertThat(message, Long.valueOf(actual), is(Long.valueOf(expected)));
}
public static void assertThatWrapper(String actual, String expected, String message) {
assertThat(message, actual, is(expected));
}
}
| cobot00/JUnitForEnterprise | test/junit/util/AssertWrapper.java | Java | mit | 2,145 |
from distutils.core import setup
version = '1.1.1'
setup(name='CacheGenerator',
version=version,
description="CacheGenerator for Django",
author="Ricardo Santos",
author_email="ricardo@getgears.com",
url="http://github.com/ricardovice/CacheGenerator/",
packages = ['cachegenerator']
)
| ricardovice/CacheGenerator | setup.py | Python | mit | 329 |
package log
import (
"io"
"github.com/sirupsen/logrus"
)
type Fields logrus.Fields
type Level uint8
var DebugLevel = Level(logrus.DebugLevel)
var InfoLevel = Level(logrus.InfoLevel)
var WarnLevel = Level(logrus.WarnLevel)
var ErrorLevel = Level(logrus.ErrorLevel)
var logger = logrus.New()
func SetOutput(w io.Writer) {
logger.Out = w
}
func WithField(key string, value interface{}) *logrus.Entry {
return logger.WithField(key, value)
}
func Debug(args ...interface{}) {
logger.Debug(args...)
}
func Debugf(format string, args ...interface{}) {
logger.Debugf(format, args...)
}
func Debugln(format string) {
logger.Debugln(format)
}
func Info(args ...interface{}) {
logger.Info(args...)
}
func Infof(format string, args ...interface{}) {
logger.Infof(format, args...)
}
func Infoln(format string) {
logger.Infoln(format)
}
func Warn(args ...interface{}) {
logger.Warn(args...)
}
func Warnf(format string, args ...interface{}) {
logger.Warnf(format, args...)
}
func Warnln(format string) {
logger.Warnln(format)
}
func Error(args ...interface{}) {
logger.Error(args...)
}
func Errorf(format string, args ...interface{}) {
logger.Errorf(format, args...)
}
func Errorln(format string) {
logger.Errorln(format)
}
func Print(args ...interface{}) {
logger.Print(args...)
}
func Printf(format string, args ...interface{}) {
logger.Printf(format, args...)
}
func Println(args ...interface{}) {
logger.Println(args...)
}
func WithFields(fields Fields) *logrus.Entry {
return logger.WithFields(logrus.Fields(fields))
}
func WithError(err error) *logrus.Entry {
return logger.WithField("error", err)
}
func SetLevel(level Level) {
logger.Level = (logrus.Level(level))
}
func Fatal(args ...interface{}) {
logger.Fatal(args...)
}
func Fatalf(format string, args ...interface{}) {
logger.Fatalf(format, args...)
}
func Fatalln(format string) {
logger.Fatalln(format)
}
| cadenzr/cadenzr | log/log.go | GO | mit | 1,909 |
<?php
/*
|--------------------------------------------------------------------------
| Defining Global Patterns
|--------------------------------------------------------------------------
| If you would like a route parameter to always be constrained by a given
| regular expression, you may use the pattern method:
|
*/
Route::pattern('id', '[0-9]+');
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', [
'as' => 'escritorio',
'uses' => 'EscritorioController@inicio',
'before' => 'esUsuario',
]);
/**
* Grupo de rutas para el control de acceso a la aplicación.
*
* @role any
*/
Route::group(['prefix' => '/', 'namespace' => 'Autenticacion'], function() {
Route::any('/acceder', [
'as' => 'autenticar',
'uses' => 'UsuarioController@acceder',
'before' => 'esExterno',
]);
Route::any('/restore', [
'as' => 'contraseña',
'uses' => 'UsuarioController@restore',
'before' => 'esExterno',
]);
Route::any('/cambiar/{token?}', [
'as' => 'contraseña-cambiar',
'uses' => 'UsuarioController@cambiar',
'before' => 'esExterno',
]);
Route::any('/salir', [
'as' => 'salir',
'uses' => 'UsuarioController@salir',
'before' => 'esUsuario',
]);
});
/**
* Rutas para el módulo de sistema.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/configuracion/sistema', 'before' => 'esUsuario', 'namespace' => 'Configuracion'], function() {
Route::get('/', [
'as' => 'configuracion::sistema-inicio',
'uses' => 'SistemaController@inicio',
// 'before' => 'rol:1',
]);
Route::post('/guarda', [
'as' => 'configuracion::sistema-guarda',
'uses' => 'SistemaController@guarda',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de usuarios.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/catalogo/usuario', 'before' => 'esUsuario', 'namespace' => 'Catalogo'], function() {
Route::get('/', [
'as' => 'catalogo::usuario',
'uses' => 'UsuarioController@inicio',
// 'before' => 'rol:1',
]);
Route::get('/nuevo', [
'as' => 'catalogo::usuario-nuevo',
'uses' => 'UsuarioController@nuevo',
// 'before' => 'rol:1',
]);
Route::get('/{id}/edita', [
'as' => 'catalogo::usuario-edita',
'uses' => 'UsuarioController@edita',
// 'before' => 'rol:1',
]);
Route::get('/{id}/borra', [
'as' => 'catalogo::usuario-borra',
'uses' => 'UsuarioController@borra',
// 'before' => 'rol:1',
]);
Route::post('/guardar/{id?}', [
'as' => 'catalogo::usuario-guardar',
'uses' => 'UsuarioController@guardar',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de proveedor.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/catalogo/proveedor', 'before' => 'esUsuario', 'namespace' => 'Catalogo'], function() {
Route::get('/', [
'as' => 'catalogo::proveedor',
'uses' => 'ProveedorController@inicio',
// 'before' => 'rol:1',
]);
Route::get('/nuevo', [
'as' => 'catalogo::proveedor-nuevo',
'uses' => 'ProveedorController@nuevo',
// 'before' => 'rol:1',
]);
Route::get('/{id}/edita', [
'as' => 'catalogo::proveedor-edita',
'uses' => 'ProveedorController@edita',
// 'before' => 'rol:1',
]);
Route::get('/{id}/estatus', [
'as' => 'catalogo::proveedor-estatus',
'uses' => 'ProveedorController@estatus',
// 'before' => 'rol:1',
]);
Route::post('/guardar/{id?}', [
'as' => 'catalogo::proveedor-guardar',
'uses' => 'ProveedorController@guardar',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de recepción (entradas) de facturas.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/factura/entrada', 'before' => 'esUsuario', 'namespace' => 'Factura'], function() {
Route::get('/', [
'as' => 'factura::entrada',
'uses' => 'EntradaController@inicio',
// 'before' => 'rol:1',
]);
Route::post('/guarda', [
'as' => 'factura::entrada-guarda',
'uses' => 'EntradaController@guarda',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de revisión (revisión) de facturas.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/factura/revision', 'before' => 'esUsuario', 'namespace' => 'Factura'], function() {
Route::get('/', [
'as' => 'factura::revision',
'uses' => 'RevisionController@inicio',
// 'before' => 'rol:1',
]);
Route::get('/{id}/proveedor', [
'as' => 'factura::revision-proveedor',
'uses' => 'RevisionController@proveedor',
// 'before' => 'rol:1',
]);
Route::get('/{id}/factura', [
'as' => 'factura::revision-factura',
'uses' => 'RevisionController@factura',
// 'before' => 'rol:1',
]);
Route::get('/{id}/detalle', [
'as' => 'factura::revision-detalle',
'uses' => 'RevisionController@detalle',
// 'before' => 'rol:1',
]);
Route::post('/{id}/guardar', [
'as' => 'factura::revision-guarda',
'uses' => 'RevisionController@guarda',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de consulta (consulta) de facturas.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/factura/consulta', 'before' => 'esUsuario', 'namespace' => 'Factura'], function() {
Route::get('/', [
'as' => 'factura::consulta',
'uses' => 'ConsultaController@inicio',
// 'before' => 'rol:1',
]);
});
/**
* Rutas para el módulo de envío de contrarecibos.
*
* @role 1 - Administrador
*/
Route::group(['prefix' => '/contrarecibo/envio', 'before' => 'esUsuario', 'namespace' => 'Contrarecibo'], function() {
Route::get('/', [
'as' => 'contrarecibo::envio',
'uses' => 'EnvioController@inicio',
// 'before' => 'rol:1',
]);
Route::get('/{id}/proveedor', [
'as' => 'contrarecibo::envio-proveedor',
'uses' => 'EnvioController@proveedor',
// 'before' => 'rol:1',
]);
Route::post('{id}/guardar', [
'as' => 'contrarecibo::envio-guarda',
'uses' => 'EnvioController@guarda',
// 'before' => 'rol:1',
]);
});
| egalink/proveedores | app/routes.php | PHP | mit | 7,126 |
/* eslint no-console: warn */
const _ = require('lodash');
const { processScore } = require('../helpers/game.js');
const getRandomQuiz = require('../../app/helpers/quizRandomizer.js');
module.exports = function socketHandler(io) {
const players = [];
const game = io.of('/game');
game.on('connect', function (socket) {
socket.join('gameRoom');
console.log('connected !!');
console.log('socket ID', socket.id);
console.log('players', players);
socket.on('score update', broadcastScore.bind(null, socket));
socket.on('spectator join', sendPlayers.bind(null, socket, players));
socket.on('player join', handleGame.bind(null, socket));
socket.on('player input', broadcastPlayerCode.bind(null, socket));
});
game.on('disconnect', (socket) => {
console.log('disconnected', socket.id);
});
const handleGame = (socket, player ) => {
console.log('handling game', player);
addPlayer(players, player);
sendPlayers(socket, players);
// if all players ready
if (players.length >= 2) {
// send randomCodeQuizURL
game.emit('quiz url', getRandomQuiz());
}
};
const broadcastScore = (socket, { id, score, passCount, failCount }) => {
console.log('broadcasting score');
socket.to('gameRoom').emit('score update', { id, score: processScore(score), passCount, failCount });
};
const broadcastPlayerCode = (socket, { id, randomCode, code }) => {
socket.to('gameRoom').emit('player input', { id, randomCode, code });
};
const sendPlayers = (socket, players) => {
console.log('sending players');
socket.to('gameRoom').emit('player join', { players });
};
};
function addPlayer(players, newPlayer) {
// !_.some(players, player => _.includes(player, newPlayer.id)) && players.push(newPlayer);
players[newPlayer.id - 1] = newPlayer;
}
| OperationSpark/code-clash | src/socket/index.js | JavaScript | mit | 1,848 |
'use strict';
import Component from './component';
import VolumeAttachment from './volume-attachment';
import Port from './port';
import {isString} from './util';
const Server = function (properties) {
if (!(this instanceof Server)) {
return new Server(properties);
}
Component.call(this, {
ports: [],
...properties
});
};
Server.prototype = Object.create(Component.prototype);
Server.prototype.constructor = Server;
Server.prototype.getDependencies = function () {
return [
...this.dependencies,
...this.properties.ports
]
};
Server.prototype.attachVolume = function (volume, mountPoint) {
const attachment = new VolumeAttachment({
id: `${isString(volume) ? volume : volume.properties.id}-attachment`,
server: this,
volume,
mountPoint
});
this.dependencies.push(attachment);
return this;
};
Server.prototype.attachPort = function (port) {
this.properties.ports.push(port);
return this;
};
Server.prototype.getSchema = function () {
return {
zone: {
type: String
},
name: {
type: String
},
image: {
type: String,
required: true
},
flavor: {
type: String,
required: true
},
keyPair: {
type: String
},
ports: {
type: Array,
items: [String, Port]
}
};
};
Server.prototype.getResources = function () {
const {
id, zone, name, flavor,
keyPair, image, ports
} = this.properties;
const networks = ports.map(port => ({
port: Component.resolve(port)
}));
const properties = {
flavor,
image
};
Object.assign(
properties,
name ? {name} : {},
zone ? {zone} : {},
keyPair ? {key_name: keyPair} : {},
networks.length ? {networks} : {}
);
return {
[id]: {
type: 'OS::Nova::Server',
properties
}
};
};
export default Server;
| kazet15/heat-templates | src/server.js | JavaScript | mit | 1,872 |
/**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kakao;
import com.kakao.helper.Logger;
/**
* unlink 요청 ({@link UserManagement#requestUnlink(com.kakao.UnlinkResponseCallback)}) 호출할 때 넘겨주고 콜백을 받는다.
* @author MJ
*/
public abstract class UnlinkResponseCallback extends UserResponseCallback {
/**
* unlink를 성공적으로 마친 경우로
* 일반적으로 로그인창으로 이동하도록 구현한다.
* @param userId unlink된 사용자 id
*/
protected abstract void onSuccess(final long userId);
/**
* unlink 요청전이나 요청 결과가 세션이 close된 경우로
* 일반적으로 로그인창으로 이동하도록 구현한다.
* @param errorResult 세션이 닫힌 이유
*/
protected abstract void onSessionClosedFailure(final APIErrorResult errorResult);
/**
* 세션이 닫힌 경우({@link #onSessionClosedFailure})를 제외한 이유로 가입 요청이 실패한 경우
* 아래 에러 종류에 따라 적절한 처리를 한다. <br/>
* {@link ErrorCode#INVALID_PARAM_CODE}, <br/>
* {@link ErrorCode#INVALID_SCOPE_CODE}, <br/>
* {@link ErrorCode#NOT_SUPPORTED_API_CODE}, <br/>
* {@link ErrorCode#INTERNAL_ERROR_CODE}, <br/>
* {@link ErrorCode#NOT_REGISTERED_USER_CODE}, <br/>
* {@link ErrorCode#CLIENT_ERROR_CODE}, <br/>
* {@link ErrorCode#EXCEED_LIMIT_CODE}, <br/>
* {@link ErrorCode#KAKAO_MAINTENANCE_CODE} <br/>
* @param errorResult unlink를 실패한 이유
*/
protected abstract void onFailure(final APIErrorResult errorResult);
/**
* {@link UserResponseCallback}를 구현한 것으로 unlink 요청이 성공했을 때 호출된다.
* 세션을 닫고 케시를 지우고, 사용자 콜백 {@link #onSuccess(long)}을 호출한다.
* 결과 User 객체가 비정상이면 에러처리한다.
* @param user unlink된 사용자 id를 포함한 사용자 객체
*/
@Override
protected void onSuccessUser(final User user) {
if (user == null || user.getId() <= 0)
onError("UnlinkResponseCallback : onSuccessUser is called but the result user is null.", new APIErrorResult(null, "the result of Signup request is null."));
else {
Logger.getInstance().d("UnlinkResponseCallback : unlinked successfully. user = " + user);
Session.getCurrentSession().close(null);
onSuccess(user.getId());
}
}
/**
* {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 전 또는 요청 중에 세션이 닫혀 로그인이 필요할 때 호출된다.
* 사용자 콜백 {@link #onSessionClosedFailure(APIErrorResult)}을 호출한다.
* @param errorResult 세션이 닫히 계기
*/
@Override
protected void onHttpSessionClosedFailure(final APIErrorResult errorResult) {
Logger.getInstance().d("UnlinkResponseCallback : session is closed before requesting unlink. errorResult = " + errorResult);
onSessionClosedFailure(errorResult);
}
/**
* {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 중에 서버에서 요청을 수행하지 못했다는 결과를 받았을 때 호출된다.
* 세션의 상태에 따라 {@link #onSessionClosedFailure(APIErrorResult)} 콜백 또는 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다.
* @param errorResult 실패한 결과
*/
@Override
protected void onHttpFailure(final APIErrorResult errorResult) {
onError("UnlinkResponseCallback : server error occurred during requesting unlink.", errorResult);
}
/**
* 에러가 발생했을 때의 처리로
* 세션이 닫혔으면 {@link #onSessionClosedFailure(APIErrorResult)} 콜백을 아니면 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다.
* @param msg 로깅 메시지
* @param errorResult 에러 발생원인
*/
private void onError(final String msg, final APIErrorResult errorResult) {
Logger.getInstance().d(msg + errorResult);
if (!Session.getCurrentSession().isOpened())
onSessionClosedFailure(errorResult);
else
onFailure(errorResult);
}
}
| haruio/haru-example-memo | kakao/src/com/kakao/UnlinkResponseCallback.java | Java | mit | 4,973 |
<?php
/**
* (c) shopware AG <info@shopware.com>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ShopwarePlugins\Connect\Components\ShippingCosts;
use Shopware\Connect\ShippingCosts\Rule;
use Shopware\Connect\ShippingCosts\Rules;
use Shopware\Connect\ShippingCosts\RulesVisitor;
use ShopwarePlugins\Connect\Components\Translations\TranslationServiceInterface;
class ShippingCostRuleVisitor extends RulesVisitor
{
/**
* @var array
*/
public $rules = [];
public $vatMode;
public $vat;
protected $currentRule = null;
/** @var \ShopwarePlugins\Connect\Components\Translations\TranslationServiceInterface */
protected $translationService;
public function __construct(TranslationServiceInterface $translationService)
{
$this->translationService = $translationService;
}
/**
* Store var(mode) for later price calculation
*
* @param Rules $rules
*/
public function startVisitRules(Rules $rules)
{
$this->vatMode = $rules->vatMode;
$this->vat = $rules->vat;
}
public function stopVisitRules(Rules $rules)
{
}
/**
* When a rule is visited: set type
*
* @param Rule $rule
*/
public function startVisitRule(Rule $rule)
{
switch (get_class($rule)) {
case 'Shopware\Connect\ShippingCosts\Rule\CountryDecorator':
$type = 'country';
break;
case 'Shopware\Connect\ShippingCosts\Rule\FreeCarriageLimit':
$type = 'freeCarriage';
break;
case 'Shopware\Connect\ShippingCosts\Rule\WeightDecorator':
$type = 'weight';
break;
case 'Shopware\Connect\ShippingCosts\Rule\MinimumBasketValue':
$type = 'minimum';
break;
case 'Shopware\Connect\ShippingCosts\Rule\UnitPrice':
$type = 'price';
break;
default:
$type = null;
}
if (null === $type) {
return;
}
$this->currentRule = ['type' => $type];
}
/**
* After a rule was visited, merge it into the $rules property
*
* @param Rule $rule
*/
public function stopVisitRule(Rule $rule)
{
$this->mergeCurrentRule();
}
/**
* @param Rule\FixedPrice $rule
*/
public function visitFixedPrice(Rule\FixedPrice $rule)
{
foreach ($this->currentRule['values'] as &$data) {
$data['netPrice'] = $rule->price;
$data['grossPrice'] = $this->calculateGrossPrice($rule->price);
}
$this->currentRule['name'] = $rule->label;
}
public function visitUnitPrice(Rule\UnitPrice $rule)
{
foreach ($this->currentRule['values'] as &$data) {
$data['netPrice'] = $rule->price;
$data['grossPrice'] = $this->calculateGrossPrice($rule->price);
}
$this->currentRule['name'] = $rule->label;
}
public function visitDownstreamCharges(Rule\DownstreamCharges $rule)
{
// TODO: Implement visitDownstreamCharges() method.
}
public function visitCountryDecorator(Rule\CountryDecorator $rule)
{
$this->currentRule['values'] = array_map(
function ($value) {
return ['value' => $value];
},
$this->translationService->get('countries', $rule->countries)
);
}
public function visitWeightDecorator(Rule\WeightDecorator $rule)
{
$this->currentRule['maxWeight'] = $rule->maxWeight;
}
public function visitMinimumBasketValue(Rule\MinimumBasketValue $rule)
{
$this->currentRule['minimumBasketValue'] = $rule->minimum;
}
/**
* Calculate the gross price for a given net price. Will use the fixed vat rate or 19% as highest tax rate.
* This might result in a amount which is higher than the actual amount of a basket - but as we don't know
* what a customer actually purchases, we calculate with the higher tax so that the customer will have to pay
* *less* at worst.
*
* @param $netPrice
* @return float
*/
private function calculateGrossPrice($netPrice)
{
switch ($this->vatMode) {
case 'fix':
$vat = $this->vat + 1;
break;
default:
$vat = 1.19;
}
return round($netPrice * $vat, 2);
}
/**
* Merge a rule into the $rules property
*
* If multiple rules of the same type are existing, merge them in order to have a unified table
*/
private function mergeCurrentRule()
{
$type = $this->currentRule['type'];
if (null === $type) {
return;
}
$this->rules[$type][] = $this->currentRule;
}
}
| shopware/SwagConnect | Components/ShippingCosts/ShippingCostRuleVisitor.php | PHP | mit | 4,969 |
package com.target.control;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JpaUtil {
private static EntityManager em;
private static EntityManagerFactory factory;
static {
try {
factory = Persistence.createEntityManagerFactory("jpa");
em = factory.createEntityManager();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public static EntityManager getFactory() {
return em;
}
}
| Malehaly/studies-java-jpa-junit | jpa/ExercicioHandsOn09/src/com/target/control/JpaUtil.java | Java | mit | 530 |
package com.crescentflare.appconfig.helper;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.util.TypedValue;
/**
* Library helper: resource access
* A helper library to access app resources for skinning the user interface
*/
public class AppConfigResourceHelper
{
static public int getAccentColor(Context context)
{
int identifier = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName());
if (identifier == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
identifier = android.R.attr.colorAccent;
}
if (identifier > 0)
{
TypedValue typedValue = new TypedValue();
TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{identifier});
if (a != null)
{
int color = a.getColor(0, 0);
a.recycle();
return color;
}
}
return Color.BLACK;
}
static public int getColor(Context context, String name)
{
int identifier = context.getResources().getIdentifier(name, "color", context.getPackageName());
if (identifier > 0)
{
return context.getResources().getColor(identifier);
}
return Color.TRANSPARENT;
}
static public String getString(Context context, String name)
{
int identifier = context.getResources().getIdentifier(name, "string", context.getPackageName());
if (identifier > 0)
{
return context.getResources().getString(identifier);
}
return "";
}
static public int getIdentifier(Context context, String name)
{
return context.getResources().getIdentifier(name, "id", context.getPackageName());
}
}
| crescentflare/DynamicAppConfigAndroid | AppConfigLib/src/main/java/com/crescentflare/appconfig/helper/AppConfigResourceHelper.java | Java | mit | 1,901 |
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace UrbanSketchers.Pages
{
/// <summary>
/// the root page
/// </summary>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RootPage
{
private bool _isFirst = true;
/// <summary>
/// Initializes a new instance of the RootPage class.
/// </summary>
public RootPage()
{
InitializeComponent();
//MasterPage.ListView.ItemSelected += ListView_ItemSelected;
}
//private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
//{
// var item = e.SelectedItem as RootPageMenuItem;
// if (item == null)
// return;
// var page = (Page)Activator.CreateInstance(item.TargetType);
// page.Title = item.Title;
// Detail = new NavigationPage(page);
// IsPresented = false;
// //MasterPage.ListView.SelectedItem = null;
//}
/// <summary>
/// Navigate to the map page
/// </summary>
protected override async void OnAppearing()
{
base.OnAppearing();
if (_isFirst)
{
var mapPage = new MapPage();
if (Detail is NavigationPage navigation)
{
var homePage = navigation.Navigation.NavigationStack.First();
navigation.Navigation.InsertPageBefore(mapPage, homePage);
await navigation.PopToRootAsync(false);
}
_isFirst = false;
}
}
}
} | mscherotter/UrbanSketchers | UrbanSketchers/UrbanSketchers/Pages/RootPage.xaml.cs | C# | mit | 1,707 |
require "rack/tls_tools/hpkp"
require "rack/tls_tools/hsts"
require "rack/tls_tools/secure_cookies"
module Rack
module TlsTools
end
end
| jkraemer/rack-tls_tools | lib/rack/tls_tools.rb | Ruby | mit | 141 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Core.Curves;
using Qwack.Core.Models;
namespace Qwack.Models.Risk.Mutators
{
public class CurveShiftMutator
{
public static IAssetFxModel AssetCurveShiftRelative(string assetId, double[] shiftSizes, IAssetFxModel model)
{
var o = model.Clone();
var curve = model.GetPriceCurve(assetId);
switch(curve)
{
case BasicPriceCurve pc:
var npc = new BasicPriceCurve(pc.BuildDate, pc.PillarDates, pc.Prices.Select((p,ix) => ix<shiftSizes.Length ? p * (1.0 + shiftSizes[ix]): p * (1.0+ shiftSizes.Last())).ToArray(), pc.CurveType, pc.CurrencyProvider, pc.PillarLabels)
{
AssetId = pc.AssetId,
Name = pc.Name,
CollateralSpec = pc.CollateralSpec,
Currency = pc.Currency,
};
o.AddPriceCurve(assetId, npc);
break;
default:
throw new Exception("Unable to mutate curve type");
}
return o;
}
public static IPvModel AssetCurveShiftRelative(string assetId, double[] shiftSizes, IPvModel model)
{
var newVanillaModel = AssetCurveShiftRelative(assetId, shiftSizes, model.VanillaModel);
return model.Rebuild(newVanillaModel, model.Portfolio);
}
public static IAssetFxModel AssetCurveShiftAbsolute(string assetId, double[] shiftSizes, IAssetFxModel model)
{
var o = model.Clone();
var curve = model.GetPriceCurve(assetId);
switch (curve)
{
case BasicPriceCurve pc:
var npc = new BasicPriceCurve(pc.BuildDate, pc.PillarDates, pc.Prices.Select((p, ix) => ix < shiftSizes.Length ? p + shiftSizes[ix] : p + shiftSizes.Last()).ToArray(), pc.CurveType, pc.CurrencyProvider, pc.PillarLabels)
{
AssetId = pc.AssetId,
Name = pc.Name,
CollateralSpec = pc.CollateralSpec,
Currency = pc.Currency,
};
o.AddPriceCurve(assetId, npc);
break;
default:
throw new Exception("Unable to mutate curve type");
}
return o;
}
public static IPvModel AssetCurveShiftAbsolute(string assetId, double[] shiftSizes, IPvModel model)
{
var newVanillaModel = AssetCurveShiftAbsolute(assetId, shiftSizes, model.VanillaModel);
return model.Rebuild(newVanillaModel, model.Portfolio);
}
}
}
| cetusfinance/qwack | src/Qwack.Models/Risk/Mutators/CurveShiftMutator.cs | C# | mit | 2,852 |
define([
'./src/vertebrae'
], function(Vertebrae) {
return Vertebrae;
}); | Evisions/vertebrae | index.js | JavaScript | mit | 78 |
class Image < ActiveRecord::Base
dragonfly_accessor :image
attr_accessible :image, :title
end
| ggouzi/Rails_Exif_Information | app/models/image.rb | Ruby | mit | 99 |
//==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file gdDeprecationStatisticsView.cpp
///
//==================================================================================
//------------------------------ gdDeprecationStatisticsView.cpp ------------------------------
// Qt
#include <AMDTApplicationComponents/Include/acQtIncludes.h>
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTBaseTools/Include/gtPtrVector.h>
#include <AMDTAPIClasses/Include/apMonitoredFunctionBreakPoint.h>
#include <AMDTAPIClasses/Include/apFunctionCallStatistics.h>
#include <AMDTAPIClasses/Include/apGLShaderObject.h>
#include <AMDTAPIClasses/Include/apStatistics.h>
#include <AMDTAPIClasses/Include/Events/apEventsHandler.h>
#include <AMDTApplicationComponents/Include/acColours.h>
#include <AMDTApplicationComponents/Include/acIcons.h>
#include <AMDTApiFunctions/Include/gaGRApiFunctions.h>
#include <AMDTApplicationComponents/Include/acFunctions.h>
// AMDTApplicationFramework:
#include <AMDTApplicationFramework/Include/afAppStringConstants.h>
// Local:
#include <AMDTGpuDebuggingComponents/Include/gdCommandIDs.h>
#include <AMDTGpuDebuggingComponents/Include/gdStringConstants.h>
#include <AMDTGpuDebuggingComponents/Include/gdAidFunctions.h>
#include <AMDTGpuDebuggingComponents/Include/gdDeprecationStringConstants.h>
#include <AMDTApplicationFramework/Include/afGlobalVariableChangedEvent.h>
#include <AMDTGpuDebuggingComponents/Include/gdGDebuggerGlobalVariablesManager.h>
#include <AMDTGpuDebuggingComponents/Include/views/gdDeprecationStatisticsView.h>
// Minimal percentages to show each type of warning (note that the number is floating point
// so this is actually the maximum percentage of the tier below:
#define GD_YELLOW_WARNING_MIN_PCT 0
#define GD_ORANGE_WARNING_MIN_PCT 33.33
#define GD_RED_WARNING_MIN_PCT 66.67
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::gdDeprecationStatisticsView
// Description: Constructor
// Arguments: wxWindow* pParent - my parent window
// wxWindowID id
// const wxPoint& pos
// const wxSize& size
// long style
// Return Val:
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
gdDeprecationStatisticsView::gdDeprecationStatisticsView(QWidget* pParent)
: gdStatisticsViewBase(pParent, GD_STATISTICS_VIEW_DEPRECATION_INDEX, GD_STR_StatisticsViewerDeprectionStatisticsShortName),
_totalAmountOfDeprecatedFunctionCalls(0), _totalAmountOfFunctionCallsInFrame(0)
{
// Add breakpoint actions to context menu:
_addBreakpointActions = true;
// Call the base class initialization function:
init();
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::~gdDeprecationStatisticsView
// Description: Destructor
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
gdDeprecationStatisticsView::~gdDeprecationStatisticsView()
{
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::initListCtrlColumns
// Description: Sets the columns widths and titles
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
void gdDeprecationStatisticsView::initListCtrlColumns()
{
// Create the "Deprecation Statistics View" columns:
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn1Title);
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn2Title);
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn3Title);
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn4Title);
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn5Title);
_listControlColumnTitles.push_back(GD_STR_DeprecationStatisticsViewerColumn6Title);
// Create the columns titles:
_listControlColumnWidths.push_back(0.20f);
_listControlColumnWidths.push_back(0.25f);
_listControlColumnWidths.push_back(0.10f);
_listControlColumnWidths.push_back(0.10f);
_listControlColumnWidths.push_back(0.14f);
_listControlColumnWidths.push_back(0.14f);
// Make sure that thousand separators are removed:
m_removeThousandSeparatorOnCopy = true;
// Add postfixes to the columns:
m_columnsPostfixes.push_back("");
m_columnsPostfixes.push_back("");
m_columnsPostfixes.push_back("");
m_columnsPostfixes.push_back("");
m_columnsPostfixes.push_back("");
m_columnsPostfixes.push_back("%");
_widestColumnIndex = 5;
_initialSortColumnIndex = 2;
_sortInfo._sortOrder = Qt::DescendingOrder;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::updateFunctionCallsStatisticsList
// Description: Update the current statistics into the listCTRL
// Arguments: const apStatistics& currentStatistics
// Return Val: void
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
bool gdDeprecationStatisticsView::updateFunctionCallsStatisticsList(const apStatistics& currentStatistics)
{
bool retVal = true;
// Delete the items and their user data:
clearAllStatisticsItems();
// Enable the list
setEnabled(true);
// Reset total number of function calls:
_totalAmountOfDeprecatedFunctionCalls = 0;
_totalAmountOfFunctionCallsInFrame = 0;
// Get the number of function calls statistics:
int functionStatisticsAmount = currentStatistics.amountOfFunctionCallsStatistics();
if (functionStatisticsAmount > 0)
{
// Reset column width - since we change it in non analyze mode:
resetColumnsWidth();
// Calculate the total amount of function calls:
for (int i = 0; i < functionStatisticsAmount; i++)
{
const apFunctionCallStatistics* pFunctionCallStatisticsData = NULL;
bool rc = currentStatistics.getFunctionCallStatistics(i, pFunctionCallStatisticsData);
GT_IF_WITH_ASSERT(rc && pFunctionCallStatisticsData != NULL)
{
// Add the function to the total counter:
gtUInt64 amountOfTimesCalled = pFunctionCallStatisticsData->_amountOfTimesCalled;
_totalAmountOfFunctionCallsInFrame += amountOfTimesCalled;
}
}
// Get current execution mode:
bool rc = gaGetDebuggedProcessExecutionMode(_executionMode);
GT_ASSERT(rc);
// Fill the list:
for (int i = 0; i < functionStatisticsAmount; i++)
{
const apFunctionCallStatistics* pFunctionCallStatisticsData = NULL;
bool ret = currentStatistics.getFunctionCallStatistics(i, pFunctionCallStatisticsData);
GT_IF_WITH_ASSERT(ret && pFunctionCallStatisticsData != NULL)
{
// For analyze mode, count all the deprecation status:
if (_executionMode == AP_ANALYZE_MODE)
{
// Iterate the function deprecation statuses, and add if not 0:
for (int j = AP_DEPRECATION_NONE + 1; j < AP_DEPRECATION_STATUS_AMOUNT; j++)
{
int currentDeprecationStatusNumOfCalls = (*pFunctionCallStatisticsData)._amountOfDeprecatedTimesCalled[j];
if (currentDeprecationStatusNumOfCalls > 0)
{
// Add the function to the list:
retVal = retVal && addFunctionToList(*pFunctionCallStatisticsData, (apFunctionDeprecationStatus)j);
}
}
}
else
{
// Get the function id:
const apMonitoredFunctionId functionId = pFunctionCallStatisticsData->_functionId;
// Get the function type:
unsigned int functionType;
bool rc2 = gaGetMonitoredFunctionType(functionId, functionType);
GT_ASSERT(rc2);
// For debug mode, add only the fully deprecated function:
if (functionType & AP_DEPRECATED_FUNC)
{
retVal = retVal && addFunctionToList(*pFunctionCallStatisticsData, AP_DEPRECATION_FULL);
}
}
}
}
if (_activeContextId.isOpenGLContext())
{
// Add GLSL version deprecation:
addGLSLDeprecationItems();
}
// Add the "More..." item to the list:
// NOTICE: Sigal 26/6/2011 When analyze mode is supported, we should remove this comment!
// addMoreItemToList();
// Add the "Total" item to the list:
addTotalItemToList();
// Sort the item in the list control:
sortItems(0, _sortInfo._sortOrder);
}
else
{
addRow(AF_STR_NotAvailableA);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::addFunctionToList
// Description: Adds function counter statistics item to the list (for function with enumerations)
// Arguments: const apFunctionCallStatistics& functionStatistics - the function statistics object
// apFunctionDeprecationStatus deprecationStatus - the function deprecation status
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
bool gdDeprecationStatisticsView::addFunctionToList(const apFunctionCallStatistics& functionStatistics, apFunctionDeprecationStatus deprecationStatus)
{
bool retVal = true;
// Get the function ID:
apMonitoredFunctionId functionId = functionStatistics._functionId;
// Get the function name:
gtString functionName;
retVal = retVal && gaGetMonitoredFunctionName(functionId, functionName);
GT_IF_WITH_ASSERT(retVal)
{
// Get total number of calls:
gtUInt64 totalNumberOfCalls = 0;
if (_executionMode == AP_DEBUGGING_MODE)
{
totalNumberOfCalls = functionStatistics._amountOfTimesCalled;
}
else
{
// Check the number of function call (for this deprecation status):
totalNumberOfCalls = functionStatistics._amountOfDeprecatedTimesCalled[deprecationStatus];
}
// Add this item number of calls to total calls counter:
_totalAmountOfDeprecatedFunctionCalls += totalNumberOfCalls;
gtString totalCallsAmountString;
gtString totalCallsPercentageString;
totalCallsAmountString.appendFormattedString(L"%ld", totalNumberOfCalls);
totalCallsAmountString.addThousandSeperators();
float percentageCalled = 0;
if (_totalAmountOfFunctionCallsInFrame > 0)
{
// Calculate the appearers percentage:
percentageCalled = totalNumberOfCalls;
percentageCalled *= 100;
percentageCalled /= _totalAmountOfFunctionCallsInFrame;
totalCallsPercentageString.appendFormattedString(L"%.2f", percentageCalled);
}
else
{
totalCallsPercentageString.append(AF_STR_NotAvailable);
}
apAPIVersion deprecatedAtVersion = AP_GL_VERSION_NONE;
apAPIVersion removedAtVersion = AP_GL_VERSION_NONE;
if ((_executionMode == AP_DEBUGGING_MODE) || (deprecationStatus == AP_DEPRECATION_FULL))
{
// Get the deprecated at and removed at versions:
gaGetMonitoredFunctionDeprecationVersion(functionId, deprecatedAtVersion, removedAtVersion);
}
else
{
// Get the deprecation version from the deprecation status class:
bool rc = apFunctionDeprecation::getDeprecationAndRemoveVersionsByStatus(deprecationStatus, deprecatedAtVersion, removedAtVersion);
GT_ASSERT(rc);
}
// Build the deprecation versions strings:
gtString deprecatedAtStr;
gtString removedAtStr;
bool rc1 = apAPIVersionToString(deprecatedAtVersion, deprecatedAtStr);
GT_ASSERT(rc1);
bool rc2 = apAPIVersionToString(removedAtVersion, removedAtStr);
GT_ASSERT(rc2);
// Add the deprecation status to the function name:
// (we have items in format of: glTexImage - Deprecated Argument Value
gtString deprecationStatusStr;
bool rc = apFunctionDeprecationStatusToString(deprecationStatus, deprecationStatusStr);
GT_ASSERT(rc);
// Define the item strings:
QStringList rowStrings;
rowStrings << acGTStringToQString(functionName);
rowStrings << acGTStringToQString(deprecationStatusStr);
rowStrings << acGTStringToQString(totalCallsAmountString);
rowStrings << acGTStringToQString(totalCallsPercentageString);
rowStrings << acGTStringToQString(deprecatedAtStr);
rowStrings << acGTStringToQString(removedAtStr);
// Add the item data:
gdStatisticsViewItemData* pItemData = new gdStatisticsViewItemData;
// Fill the item data;
pItemData->_functionName = functionName;
pItemData->_functionId = functionId;
pItemData->_totalAmountOfTimesCalled = totalNumberOfCalls;
pItemData->_percentageOfTimesCalled = percentageCalled;
pItemData->_deprecatedAtVersion = deprecatedAtVersion;
pItemData->_removedAtVersion = removedAtVersion;
pItemData->_deprecationStatus = deprecationStatus;
// Add row to table:
addRow(rowStrings, pItemData, false, Qt::Unchecked, icon(1));
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::addTotalItemToList
// Description: Adds the "Total" item to the list control.
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
void gdDeprecationStatisticsView::addTotalItemToList()
{
// Get the amount of list items:
int listSize = rowCount();
if (listSize == 0)
{
// Add an item stating that there are not items:
addEmptyListItem();
}
else
{
// Calculate the % of deprecated function calls:
float deprecatedCallsPercentage = ((float)_totalAmountOfDeprecatedFunctionCalls / (float)_totalAmountOfFunctionCallsInFrame) * 100.0f;
// Build displayed strings:
gtASCIIString totalString;
gtASCIIString totalAmountOfFunctionCallsString;
gtASCIIString totalPrecentageString;
totalString.appendFormattedString("Total (%d items)", listSize);
totalAmountOfFunctionCallsString.appendFormattedString("%ld", _totalAmountOfDeprecatedFunctionCalls);
totalAmountOfFunctionCallsString.addThousandSeperators();
totalPrecentageString.appendFormattedString("%.2f", deprecatedCallsPercentage);
QStringList list;
list << totalString.asCharArray();
list << AF_STR_EmptyA;
list << totalAmountOfFunctionCallsString.asCharArray();
list << totalPrecentageString.asCharArray();
list << AF_STR_EmptyA;
list << AF_STR_EmptyA;
addRow(list, NULL, false, Qt::Unchecked, icon(0));
setItemBold(rowCount() - 1);
}
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::addTotalItemToList
// Description: Adds the "More..." item to the list control in debugging mode.
// Author: Sigal Algranaty
// Date: 17/3/2009
// ---------------------------------------------------------------------------
void gdDeprecationStatisticsView::addMoreItemToList()
{
if (_executionMode != AP_ANALYZE_MODE)
{
// Get the amount of list items:
QStringList list;
// Insert the item (enumerator) into the list:
list << AF_STR_MoreA;
list << GD_STR_StateChangeStatisticsViewerNonAnalyzeModeA;
list << AF_STR_NotAvailableA;
list << AF_STR_NotAvailableA;
list << AF_STR_NotAvailableA;
list << AF_STR_NotAvailableA;
// Get the icon:
QPixmap* pIcon = icon(2);
addRow(list, NULL, false, Qt::Unchecked, pIcon);
}
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::initializeImageList
// Description: Create and populate the image list for this item
// Author: Sigal Algranaty
// Date: 25/2/2009
// ---------------------------------------------------------------------------
void gdDeprecationStatisticsView::initializeImageList()
{
// Create the icons from the xpm files:
QPixmap* pEmptyIcon = new QPixmap;
acSetIconInPixmap(*pEmptyIcon, AC_ICON_EMPTY);
QPixmap* pYellowWarningIcon = new QPixmap;
acSetIconInPixmap(*pYellowWarningIcon, AC_ICON_WARNING_YELLOW);
QPixmap* pInfoIcon = new QPixmap;
acSetIconInPixmap(*pInfoIcon, AC_ICON_WARNING_INFO);
// Add the icons to the list
_listIconsVec.push_back(pEmptyIcon); // 0
_listIconsVec.push_back(pYellowWarningIcon); // 1
_listIconsVec.push_back(pInfoIcon); // 2
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::getItemDeprecationVersions
// Description: Given an item index, the function returns the monitored function
// OpenGL deprecation version, and OpenGL remove version
// Arguments: int itemIndex
// apAPIVersion& deprecatedAtVersion
// apAPIVersion& removedAtVersion
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 2/3/2009
// ---------------------------------------------------------------------------
bool gdDeprecationStatisticsView::getItemDeprecationVersions(int itemIndex, apAPIVersion& deprecatedAtVersion, apAPIVersion& removedAtVersion)
{
bool retVal = false;
gdStatisticsViewItemData* pItemData = gdStatisticsViewBase::getItemData(itemIndex);
GT_IF_WITH_ASSERT(pItemData != NULL)
{
deprecatedAtVersion = pItemData->_deprecatedAtVersion;
removedAtVersion = pItemData->_removedAtVersion;
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::getItemDeprecationStatus
// Description: Return a selected item deprecation status
// Arguments: int itemIndex
// apFunctionDeprecationStatus& functionDeprecationStatus
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 10/3/2009
// ---------------------------------------------------------------------------
bool gdDeprecationStatisticsView::getItemDeprecationStatus(int itemIndex, apFunctionDeprecationStatus& functionDeprecationStatus)
{
bool retVal = false;
gdStatisticsViewItemData* pItemData = gdStatisticsViewBase::getItemData(itemIndex);
GT_IF_WITH_ASSERT(pItemData != NULL)
{
functionDeprecationStatus = pItemData->_deprecationStatus;
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::getItemFunctionId
// Description: Return a selected item deprecation status
// Arguments: int itemIndex
// int& functionID
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 10/3/2009
// ---------------------------------------------------------------------------
bool gdDeprecationStatisticsView::getItemFunctionId(int itemIndex, int& functionID)
{
bool retVal = false;
// Get the list size:
gdStatisticsViewItemData* pItemData = gdStatisticsViewBase::getItemData(itemIndex);
GT_IF_WITH_ASSERT(pItemData != NULL)
{
functionID = pItemData->_functionId;
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gdDeprecationStatisticsView::addGLSLDeprecationItems
// Description: Go through the shader objects and check their version
// Add deprecation item for a shader object with a deprecated version
// Author: Sigal Algranaty
// Date: 24/3/2009
// ---------------------------------------------------------------------------
void gdDeprecationStatisticsView::addGLSLDeprecationItems()
{
int amountOfShaders = 0;
bool rc = gaGetAmountOfShaderObjects(_activeContextId._contextId, amountOfShaders);
if (rc)
{
// Iterate the shaders
// (check if there is a shader which is not belong to any program):
for (int curShaderId = 0; curShaderId < amountOfShaders; curShaderId++)
{
// Get the current shader name:
GLuint curShaderName = 0;
rc = gaGetShaderObjectName(_activeContextId._contextId, curShaderId, curShaderName);
if (rc)
{
// Get the current shader details:
gtAutoPtr<apGLShaderObject> aptrShaderDetails = NULL;
rc = gaGetShaderObjectDetails(_activeContextId._contextId, curShaderName, aptrShaderDetails);
// Check the shader version deprecation status:
apGLShaderObject* pShaderObject = aptrShaderDetails.pointedObject();
if (rc && (pShaderObject != NULL))
{
// Get the shader version;
apGLSLVersion shaderVersion = pShaderObject->shaderVersion();
if ((shaderVersion == AP_GLSL_VERSION_1_0) || (shaderVersion == AP_GLSL_VERSION_1_1) || (shaderVersion == AP_GLSL_VERSION_1_2))
{
// Add deprecation:
gtString functionName;
functionName.appendFormattedString(GD_STR_DeprecationShaderName, pShaderObject->shaderName());
gtString deprecationStatusStr;
rc = apFunctionDeprecationStatusToString(AP_DEPRECATION_GLSL_VERSION, deprecationStatusStr);
// Get the deprecation version from the deprecation status class:
apAPIVersion deprecatedAtVersion, removedAtVersion;
rc = apFunctionDeprecation::getDeprecationAndRemoveVersionsByStatus(AP_DEPRECATION_GLSL_VERSION, deprecatedAtVersion, removedAtVersion);
GT_ASSERT(rc);
// Build the deprecation versions strings:
gtString deprecatedAtStr;
gtString removedAtStr;
bool rc1 = apAPIVersionToString(deprecatedAtVersion, deprecatedAtStr);
GT_ASSERT(rc1);
bool rc2 = apAPIVersionToString(removedAtVersion, removedAtStr);
GT_ASSERT(rc2);
// Add the item:
QStringList rowStrings;
// Insert the item into the list:
rowStrings << acGTStringToQString(functionName);
rowStrings << acGTStringToQString(deprecationStatusStr);
rowStrings << AF_STR_NotAvailableA;
rowStrings << AF_STR_NotAvailableA;
rowStrings << acGTStringToQString(deprecatedAtStr);
rowStrings << acGTStringToQString(removedAtStr);
// Add the item data:
gdStatisticsViewItemData* pItemData = new gdStatisticsViewItemData;
// Fill the item data;
pItemData->_functionName = functionName;
pItemData->_functionId = ap_glShaderSource;
pItemData->_totalAmountOfTimesCalled = 0;
pItemData->_percentageOfTimesCalled = 0;
pItemData->_deprecatedAtVersion = deprecatedAtVersion;
pItemData->_removedAtVersion = removedAtVersion;
pItemData->_deprecationStatus = AP_DEPRECATION_GLSL_VERSION;
// Add the row:
addRow(rowStrings, pItemData, false, Qt::Unchecked, icon(1));
}
}
}
}
}
}
// -------------------------------------------------------------------------- -
// Name: gdDeprecationStatisticsView::getItemTooltip
// Description: Get an item tooltip
// Arguments: int itemIndex
// Return Val: gtString
// Author: Yuri Rshtunique
// Date: November 10, 2014
// ---------------------------------------------------------------------------
gtString gdDeprecationStatisticsView::getItemTooltip(int itemIndex)
{
gtString retVal;
// Get the item data:
gdStatisticsViewItemData* pItemData = (gdStatisticsViewItemData*)getItemData(itemIndex);
if (pItemData != NULL)
{
// Build the tooltip string:
gtString functionName = pItemData->_functionName;
gtString deprecationStatusStr;
bool rc = apFunctionDeprecationStatusToString(pItemData->_deprecationStatus, deprecationStatusStr);
GT_ASSERT(rc);
retVal.appendFormattedString(L"%ls: %ls", functionName.asCharArray(), deprecationStatusStr.asCharArray());
}
return retVal;
}
| ilangal-amd/CodeXL | CodeXL/Components/GpuDebugging/AMDTGpuDebuggingComponents/views/src/gdDeprecationStatisticsView.cpp | C++ | mit | 26,164 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
namespace ComponentTest
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| Ugonna/AutocompleteTextBox | ComponentTest/App.xaml.cs | C# | mit | 4,221 |
using Microsoft.Xna.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Spectrum.Framework.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spectrum.Framework.Content
{
public class InitDataParser : CachedContentParser<InitData, InitData>
{
public InitDataParser() : base("json")
{
Prefix = "InitData";
}
protected override InitData LoadData(string path, string name)
{
using (var reader = new StreamReader(File.OpenRead(path)))
{
var output = JConvert.Deserialize<InitData>(reader.ReadToEnd()).ToImmutable();
if (output.Name == null) output.Name = name;
output.Path = name;
output.FullPath = path;
return output;
}
}
protected override InitData SafeCopy(InitData data)
{
return data;
}
}
}
| alex-sherman/Spectrum | Framework/Content/InitDataParser.cs | C# | mit | 1,040 |
<?php
namespace pizza\SiteBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('pizza_site');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| KatrienDeSmet/PizzaWebsite | src/pizza/SiteBundle/DependencyInjection/Configuration.php | PHP | mit | 875 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Lytro;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class AccelerometerY extends AbstractTag
{
protected $Id = 'DevicesAccelerometerSampleArrayY';
protected $Name = 'AccelerometerY';
protected $FullName = 'Lytro::Main';
protected $GroupName = 'Lytro';
protected $g0 = 'Lytro';
protected $g1 = 'Lytro';
protected $g2 = 'Camera';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Accelerometer Y';
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/Lytro/AccelerometerY.php | PHP | mit | 815 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("HttpWebRequestInUWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HttpWebRequestInUWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | TelerikAcademy/Windows-Applications | 16. Working-with-Remote-Data/Demo/HttpWebRequestInUWP/Properties/AssemblyInfo.cs | C# | mit | 1,058 |
#!/usr/bin/env python3
# JN 2015-07-29
"""
Log file parser for Cheetah by Johannes Niediek
This script reads out the reference settings
by sequentially following all crs, rbs, and gbd commands.
Please keep in mind that the following scenario is possible with Cheetah:
Start the recording
Stop the recording
Change the reference settings
Start the recording
If you do this there will be .ncs with their reference changing
at some point during the recording.
In most cases, this is probably not what you want,
so this script displays a warning message if you did it.
Cheetah ATLAS:
There is an undocumented channel nummber 32000038.
I reverse-engineered its use, but that might depend on the exact version
of ATLAS etc.
This script partially mirrors the system of variable definitions
in Cheeatah. For complex arithmethic with variables, the script might fail.
Please check the GitHub repository (github.com/jniediek/combinato.git)
for updates and manual.
Contact me (jonied@posteo.de) for access to the repository.
"""
from __future__ import print_function, division
import os
import re
from collections import defaultdict
import datetime
from csv import writer as csv_writer
DATE_FNAME = 'start_stop_datetime.txt'
def parse_times(setting):
"""
read out the date and times of a recording
"""
def timestr2timeobj(time_str):
"""
convert a time string with milliseconds to a datetime object
"""
time, milli = time_str.split('.')
time = datetime.datetime.strptime(time, '%H:%M:%S')
time += datetime.timedelta(seconds=int(milli)/1000)
return time
tstart, tstop = [timestr2timeobj(rec[1])
for rec in setting.start_rec, setting.stop_rec]
if setting.folder is None:
folder_date_obj = None
else:
date_str = date_pattern.match(setting.folder).groups()[0]
folder_date_obj = datetime.datetime.strptime(date_str,
r'%Y-%m-%d_%H-%M-%S')
tstart = datetime.datetime.combine(folder_date_obj, tstart.time())
tstop = datetime.datetime.combine(folder_date_obj, tstop.time())
# by default assume that recording is stopped once every day
if tstop < tstart:
tstop += datetime.timedelta(days=1)
return folder_date_obj, tstart, tstop
class Setting(object):
"""
simple class that stores reference settings
"""
def __init__(self):
self.num2name = None
self.name2num = None
self.lrefs = None
self.grefs = None
self.crefs = None
self.start_rec = None
self.stop_rec = None
self.start_timestamp = None
self.stop_timestamp = None
self.folder = None
DEBUG = False
# The following are the interesting commands
# You can still trick the parser, e.g. by sending -SetChannelNumber commands
# via NetCom.
# But it's very easy to adapt the parser to such situations
set_drs_strings = ('Processing line: -SetDRS', # old systems
'Processing line: -SetAcqEntReference') # new systems
set_channel_pattern = re.compile(r'Processing line:\s*-SetChannelNumber')
channel_number_pattern = re.compile(r'.*\"(.*)\" (\d.*)')
channel_number_pattern_var = re.compile(r'.* (.*) (.*)')
drs_command_pattern = re.compile(r'DRS Command\(b(\w) (\w*)\s{1,2}'
r'(\d*)\s{0,2}(\d*)')
variable_pattern = re.compile(r'.*(%\w*) = \"?(\w*)\"?')
date_pattern = re.compile(r'.*(\d{4}-\d{1,2}-\d{1,2}_'
'\d{1,2}-\d{1,2}-\d{1,2}).*')
def board_num_to_chan(board, num):
return (board - 1) * 16 + num
def chan_to_board_num(chan):
return 2 * int(chan/32) + 1, chan % 32
def parser(fname):
"""
transform logfile into header, log, and ignored lines
"""
with open(fname, 'r') as fid:
lines = fid.readlines()
fid.close()
in_header = True
is_notice = False
ignored_lines = []
protocol = []
header = {}
for line in lines:
if line[:13] == '-* NOTICE *-':
is_notice = True
else:
is_notice = False
if in_header:
# this means header is over
if is_notice:
in_header = False
else:
if len(line) > 3:
key, value = line.split(':', 1)
header[key] = value.strip()
else:
if is_notice:
fields = line[15:].split(' - ', 4)
time = fields[0]
stamp = int(fields[1])
msg = fields[2].strip().replace('\r', '')
if len(fields) == 4:
msg2 = fields[3].strip().replace('\r', '')
else:
msg2 = ''
protocol.append((time, stamp, msg, msg2))
elif line.startswith('Log file successfully moved to'):
target = line.split()[-1]
# this indicates a log file move
# mov is our key
protocol.append((0, 0, 'mov', target))
else:
ignored_lines.append(line.strip())
try:
bn = 'Cheetah ' + header['Cheetah Build Number']
except KeyError:
bn = 'ATLAS ' + header['Cheetah ATLAS Build Number']
print(bn)
return header, protocol, ignored_lines
def all_defined_check(chnum2name, crefs):
"""
check if a reference has been defined for all existing channels
"""
# print(chnum2name)
for chnum in chnum2name:
board, lnum = chan_to_board_num(chnum)
try:
ref = crefs[chnum]
if DEBUG:
print('Channel {} (board {} channel {}) - {}'.
format(chnum, board, lnum, ref))
except KeyError:
print('No reference defined for channel {} ({})'.
format(chnum, chnum2name[chnum][0]))
def print_refs(lrefs, grefs):
"""
overview of local and global refrences
"""
sorted_keys = sorted(lrefs.keys())
for board, ref in sorted_keys:
lref = lrefs[(board, ref)]
if lref in grefs:
gboard = grefs[lref]
stri = 'global, board {}'.format(gboard)
else:
stri = 'local'
print('board {} ref {} - {} ({})'.
format(board, ref, lrefs[(board, ref)], stri))
def analyze_drs(protocol):
"""
go through a protocol and analyze all drs settings
"""
# for each board, store the 8 local refs
# 32..35 are the 4 local reference wires
# 36, 37 are subject ground, patient ground
# 38 seems to be specific to ATLAS
# this is a (board, ref) -> local_num dict
local_refs = dict()
# 8 ref numbers can be driven globally
# this is a ref_num -> board dict
global_refs = dict()
# each channel has a reference which
# refers to its board's local referenes
# this is a ch_num -> ref_num dict
channel_refs = dict()
# name2num is unique
ch_name2num = dict()
# num2name is *not* unique, values are lists
ch_num2name = defaultdict(list)
# save the settings
all_settings = []
variables = dict()
temp_setting = None
for line in protocol:
time, timestamp, msg1, msg2 = line
if temp_setting is None:
temp_setting = Setting()
if msg1 == 'mov':
temp_setting.folder = msg2
elif '::SendDRSCommand()' in msg1:
# log all reference settings (command file and GUI interaction)
board, cmd, arg1, arg2 = drs_command_pattern.match(msg2).groups()
arg1 = int(arg1)
board = int(board, 16)
if cmd != 'hsp':
arg2 = int(arg2)
else:
arg2 = ''
if cmd == 'gbd':
# this is the global drive
# if a reference is driven globally, it overrides
# the local settings of that reference
if arg2 == 1:
global_refs[arg1] = board
print('{} is now driven by board {}'.format(arg1, board))
elif arg2 == 0:
if arg1 in global_refs:
del global_refs[arg1]
if cmd == 'rbs':
# each board stores 8 references
# arg1 is the stored number
# arg2 is the channel it points to
if (board, arg1) in local_refs:
if DEBUG:
print('board {} ref {} was {}, is now {}'.
format(board, arg1,
local_refs[(board, arg1)], arg2))
local_refs[(board, arg1)] = arg2
elif cmd == 'crs':
# each channel is indexed by board and local number
# arg1 is the local channel number
# arg2 is the local reference it points to
# try:
# local_ref = local_refs[(board, arg2)]
# except KeyError:
# print(msg2)
# raise Warning('Using undefined reference!')
chnum = board_num_to_chan(board, arg1)
channel_refs[chnum] = arg2
# print(cmd, board, arg1, chnum, local_ref)
elif 'StartRecording' in msg1:
temp_setting.num2name = ch_num2name.copy()
temp_setting.name2num = ch_name2num.copy()
temp_setting.lrefs = local_refs.copy()
temp_setting.grefs = global_refs.copy()
temp_setting.crefs = channel_refs.copy()
temp_setting.start_rec = (msg1, time)
temp_setting.start_timestamp = timestamp
elif 'StopRecording' in msg1:
# here, the setting is definite and has to be saved
temp_setting.stop_rec = (msg1, time)
temp_setting.stop_timestamp = timestamp
all_settings.append(temp_setting)
temp_setting = None
elif ' = ' in msg2:
# assigning a variable
var, val = variable_pattern.match(msg2).groups()
variables[var] = val
elif '%currentADChannel += 1' in msg2:
# this is a hack, but it seems to work well
print('Applying hack for += 1 syntax, check results!')
var, val = msg2.split('+=')
variables['%currentADChannel'] = str(int(variables['%currentADChannel']) + 1)
if set_channel_pattern.match(msg2):
# log channel numbers
if '%' in msg2:
var, ch_num = channel_number_pattern_var.match(msg2).groups()
var = var.strip()
ch_num = ch_num.strip()
try:
ch_name = variables[var]
except KeyError:
print('{}, but something is wrong with setting channel'
'numbers. Check for errors'
' in the Cheetah logfile itself.'.format(msg2))
continue
if '%' in ch_num:
ch_num = variables[ch_num]
else:
result = channel_number_pattern.match(msg2)
if result is not None:
ch_name, ch_num = result.groups()
else:
print('Parser skipped the following line: ' + msg2)
continue
ch_num = int(ch_num)
if ch_name in ch_name2num:
raise Warning('channel number reset')
ch_name2num[ch_name] = ch_num
ch_num2name[ch_num].append(ch_name)
elif msg2.startswith(set_drs_strings):
# if needed, insert code to
# log reference settings from command file
pass
return all_settings
def create_rep(num2name, name2num, crefs, lrefs, grefs):
"""
create a human readable representation of the referencing
"""
all_defined_check(num2name, crefs)
if DEBUG:
print_refs(lrefs, grefs)
chnames = []
for num in sorted(num2name.keys()):
chnames += num2name[num]
out_str = []
for name in chnames:
try:
chan = name2num[name]
except KeyError:
print('Processing {}, but no channel number was '
'assigned. Check results carefully!'.format(name))
continue
ch_board, ch_board_num = chan_to_board_num(chan)
local_ref_num = crefs[chan] # gives the local ref number
# this is now a local number, so it's in 0..7
maybe_global = False
if local_ref_num in grefs:
ref_board = grefs[local_ref_num]
if ref_board != ch_board:
maybe_global = True
# here, I have to check whether the
# driving channel is the same number on my local board
# i.e., if b1_15 is b1_ref_2 and b1_ref_2 is gd
# and b3_7 has ref_2, then it's global only if b3_15 is b3_ref_2
else:
ref_board = ch_board
ref_num = lrefs[(ref_board, local_ref_num)]
ref_num2 = lrefs[(ch_board, local_ref_num)]
add_str = ''
if maybe_global:
# print('Special case, global ref {}, local ref {}'
# .format(ref_num, lrefs[(ch_board, local_ref_num)]))
if ref_num2 != 38:
add_str = ' ?'
if ref_num != ref_num2:
# print(ref_num, lrefs[(ch_board, local_ref_num)])
ref_board = ch_board
ref_num = ref_num2
else:
add_str = ' ???'
ref_board = ch_board
ref_num = ref_num2
pass
# print('Using channel 38')
if ref_board == ch_board:
board_str = 'local{}'.format(add_str)
else:
board_str = 'global{}'.format(add_str)
if ref_num > 31:
# these are the reference wires
if ref_num == 38:
ref_name = 'board {} Unknown Ground'.format(ref_board)
elif ref_num == 36:
ref_name = 'board {} Patient Ground'.format(ref_board)
else:
tnum = (ref_num - 32) * 8
refchan = board_num_to_chan(ref_board, tnum)
if refchan in num2name:
pref_name = num2name[refchan]
idx = 0
if len(pref_name) == 2:
if pref_name[0][0] == 'u':
idx = 1
ref_name = pref_name[idx][:-1] + ' reference wire'
else:
ref_name = 'board {} head stage {} reference wire'.\
format(ref_board, ref_num - 32)
else:
global_num = board_num_to_chan(ref_board, ref_num)
chlist = num2name[global_num]
if len(chlist):
ref_name = chlist[0]
else:
ref_name = 'UNDEF'
if name == ref_name:
board_str += ' ZERO'
out_str.append(('{:03d}'.format(chan), name, ref_name, board_str))
return out_str
def check_logfile(fname, write_csv=False, nback=0, write_datetime=False):
"""
run over a Cheetah logfile and analyzed reference settings etc
"""
_, protocol, _ = parser(fname)
base_name = os.path.splitext(os.path.basename(fname))[0]
all_settings = analyze_drs(protocol)
for i_setting, setting in enumerate(all_settings):
print()
if setting.folder is None:
msg = 'Warning: Recording Stop -> Start without folder change!'
else:
msg = setting.folder
print('Start: {} ({})'.format(setting.start_rec[1],
setting.start_timestamp))
print('Stop: {} ({})'.format(setting.stop_rec[1],
setting.stop_timestamp))
# print('Duration: {} min'.
# format((setting.stop_rec[1] - setting.start_rec[1])))
out_str = create_rep(setting.num2name, setting.name2num,
setting.crefs, setting.lrefs, setting.grefs)
if write_csv:
setting = all_settings[-nback-1]
if setting.folder is None:
msg = 'Warning: Recording Stop -> Start without folder change!'
else:
msg = setting.folder
out_str = create_rep(setting.num2name, setting.name2num,
setting.crefs, setting.lrefs, setting.grefs)
outfname = base_name + '_{:02d}.csv'.\
format(len(all_settings) - nback - 1)
with open(outfname, 'w') as outf:
outf.write('# {} {} {}\n'.format(msg,
setting.start_rec[1],
setting.stop_rec[1]))
csvwriter = csv_writer(outf)
for line in out_str:
csvwriter.writerow(line)
if write_datetime:
setting = all_settings[-nback-1]
date, start, stop = parse_times(setting)
print(date, start, stop)
if date is None:
out = '# Date not guessed because Recording was stopped'\
' and re-started without folder change!\n'
else:
out = '# {}\ncreate_folder {}\n'.\
format(setting.folder, date.strftime('%Y-%m-%d %H:%M:%S'))
start_ts = setting.start_timestamp
stop_ts = setting.stop_timestamp
for name, d, t in (('start', start, start_ts),
('stop', stop, stop_ts)):
out += name + '_recording {} {} {}\n'.\
format(d.date().isoformat(), d.time().isoformat(), t)
diff_time = (stop_ts - start_ts)/1e6 - (stop - start).seconds
out += 'cheetah_ahead: {}\n'.format(diff_time)
if os.path.exists(DATE_FNAME):
print('{} exists, not overwriting!'.format(DATE_FNAME))
else:
with open(DATE_FNAME, 'w') as fid:
fid.write(out)
if __name__ == '__main__':
from argparse import ArgumentParser
aparser = ArgumentParser(epilog='Johannes Niediek (jonied@posteo.de)')
aparser.add_argument('--write-csv', action='store_true', default=False,
help='Write out to logfile_number.csv')
aparser.add_argument('--write-datetime', action='store_true',
default=False, help='Write start/stop timestamps to'
' file {}'.format(DATE_FNAME))
aparser.add_argument('--logfile', nargs=1,
help='Logfile, default: CheetahLogFile.txt')
aparser.add_argument('--nback', nargs=1, type=int,
help='Save last-n\'th setting', default=[0])
args = aparser.parse_args()
if not args.logfile:
logfile = 'CheetahLogFile.txt'
else:
logfile = args.logfile[0]
check_logfile(logfile, args.write_csv, args.nback[0], args.write_datetime)
| jniediek/combinato | tools/parse_cheetah_logfile.py | Python | mit | 19,113 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEscuelasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('escuelas', function (Blueprint $table) {
$table->increments('id');
$table->string('codigo', 10)->unique();
$table->string('nombre', 100);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('escuelas');
}
}
| nelsonalejandrosaz/SIUPS | database/migrations/2017_06_06_212901_create_escuelas_table.php | PHP | mit | 690 |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*namespace com.google.zxing.qrcode.detector {*/
import BitMatrix from '../../common/BitMatrix';
import MathUtils from '../../common/detector/MathUtils';
import DetectorResult from '../../common/DetectorResult';
// import GridSampler from '../../common/GridSampler';
import GridSamplerInstance from '../../common/GridSamplerInstance';
import PerspectiveTransform from '../../common/PerspectiveTransform';
import DecodeHintType from '../../DecodeHintType';
import NotFoundException from '../../NotFoundException';
import ResultPoint from '../../ResultPoint';
import ResultPointCallback from '../../ResultPointCallback';
import Version from '../decoder/Version';
import AlignmentPattern from './AlignmentPattern';
import AlignmentPatternFinder from './AlignmentPatternFinder';
import FinderPattern from './FinderPattern';
import FinderPatternFinder from './FinderPatternFinder';
import FinderPatternInfo from './FinderPatternInfo';
/*import java.util.Map;*/
/**
* <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
* is rotated or skewed, or partially obscured.</p>
*
* @author Sean Owen
*/
export default class Detector {
private resultPointCallback: ResultPointCallback;
public constructor(private image: BitMatrix) { }
protected getImage(): BitMatrix {
return this.image;
}
protected getResultPointCallback(): ResultPointCallback {
return this.resultPointCallback;
}
/**
* <p>Detects a QR Code in an image.</p>
*
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/
// public detect(): DetectorResult /*throws NotFoundException, FormatException*/ {
// return detect(null)
// }
/**
* <p>Detects a QR Code in an image.</p>
*
* @param hints optional hints to detector
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/
public detect(hints: Map<DecodeHintType, any>): DetectorResult /*throws NotFoundException, FormatException*/ {
this.resultPointCallback = (hints === null || hints === undefined) ? null :
/*(ResultPointCallback) */hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
const finder = new FinderPatternFinder(this.image, this.resultPointCallback);
const info = finder.find(hints);
return this.processFinderPatternInfo(info);
}
protected processFinderPatternInfo(info: FinderPatternInfo): DetectorResult {
const topLeft: FinderPattern = info.getTopLeft();
const topRight: FinderPattern = info.getTopRight();
const bottomLeft: FinderPattern = info.getBottomLeft();
const moduleSize: number /*float*/ = this.calculateModuleSize(topLeft, topRight, bottomLeft);
if (moduleSize < 1.0) {
throw new NotFoundException('No pattern found in proccess finder.');
}
const dimension = Detector.computeDimension(topLeft, topRight, bottomLeft, moduleSize);
const provisionalVersion: Version = Version.getProvisionalVersionForDimension(dimension);
const modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
let alignmentPattern: AlignmentPattern = null;
// Anything above version 1 has an alignment pattern
if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
// Guess where a "bottom right" finder pattern would have been
const bottomRightX: number /*float*/ = topRight.getX() - topLeft.getX() + bottomLeft.getX();
const bottomRightY: number /*float*/ = topRight.getY() - topLeft.getY() + bottomLeft.getY();
// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
const correctionToTopLeft: number /*float*/ = 1.0 - 3.0 / modulesBetweenFPCenters;
const estAlignmentX = /*(int) */Math.floor(topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
const estAlignmentY = /*(int) */Math.floor(topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
// Kind of arbitrary -- expand search radius before giving up
for (let i = 4; i <= 16; i <<= 1) {
try {
alignmentPattern = this.findAlignmentInRegion(moduleSize,
estAlignmentX,
estAlignmentY,
i);
break;
} catch (re/*NotFoundException*/) {
if (!(re instanceof NotFoundException)) {
throw re;
}
// try next round
}
}
// If we didn't find alignment pattern... well try anyway without it
}
const transform: PerspectiveTransform =
Detector.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
const bits: BitMatrix = Detector.sampleGrid(this.image, transform, dimension);
let points: ResultPoint[];
if (alignmentPattern === null) {
points = [bottomLeft, topLeft, topRight];
} else {
points = [bottomLeft, topLeft, topRight, alignmentPattern];
}
return new DetectorResult(bits, points);
}
private static createTransform(topLeft: ResultPoint,
topRight: ResultPoint,
bottomLeft: ResultPoint,
alignmentPattern: ResultPoint,
dimension: number /*int*/): PerspectiveTransform {
const dimMinusThree: number /*float*/ = dimension - 3.5;
let bottomRightX: number; /*float*/
let bottomRightY: number; /*float*/
let sourceBottomRightX: number; /*float*/
let sourceBottomRightY: number; /*float*/
if (alignmentPattern !== null) {
bottomRightX = alignmentPattern.getX();
bottomRightY = alignmentPattern.getY();
sourceBottomRightX = dimMinusThree - 3.0;
sourceBottomRightY = sourceBottomRightX;
} else {
// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();
bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();
sourceBottomRightX = dimMinusThree;
sourceBottomRightY = dimMinusThree;
}
return PerspectiveTransform.quadrilateralToQuadrilateral(
3.5,
3.5,
dimMinusThree,
3.5,
sourceBottomRightX,
sourceBottomRightY,
3.5,
dimMinusThree,
topLeft.getX(),
topLeft.getY(),
topRight.getX(),
topRight.getY(),
bottomRightX,
bottomRightY,
bottomLeft.getX(),
bottomLeft.getY());
}
private static sampleGrid(image: BitMatrix,
transform: PerspectiveTransform,
dimension: number /*int*/): BitMatrix /*throws NotFoundException*/ {
const sampler = GridSamplerInstance.getInstance();
return sampler.sampleGridWithTransform(image, dimension, dimension, transform);
}
/**
* <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
* of the finder patterns and estimated module size.</p>
*/
private static computeDimension(topLeft: ResultPoint,
topRight: ResultPoint,
bottomLeft: ResultPoint,
moduleSize: number/*float*/): number /*int*/ /*throws NotFoundException*/ {
const tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
const tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
let dimension = Math.floor((tltrCentersDimension + tlblCentersDimension) / 2) + 7;
switch (dimension & 0x03) { // mod 4
case 0:
dimension++;
break;
// 1? do nothing
case 2:
dimension--;
break;
case 3:
throw new NotFoundException('Dimensions could be not found.');
}
return dimension;
}
/**
* <p>Computes an average estimated module size based on estimated derived from the positions
* of the three finder patterns.</p>
*
* @param topLeft detected top-left finder pattern center
* @param topRight detected top-right finder pattern center
* @param bottomLeft detected bottom-left finder pattern center
* @return estimated module size
*/
protected calculateModuleSize(topLeft: ResultPoint,
topRight: ResultPoint,
bottomLeft: ResultPoint): number/*float*/ {
// Take the average
return (this.calculateModuleSizeOneWay(topLeft, topRight) +
this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0;
}
/**
* <p>Estimates module size based on two finder patterns -- it uses
* {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
* width of each, measuring along the axis between their centers.</p>
*/
private calculateModuleSizeOneWay(pattern: ResultPoint, otherPattern: ResultPoint): number/*float*/ {
const moduleSizeEst1: number /*float*/ = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */Math.floor(pattern.getX()),
/*(int) */Math.floor(pattern.getY()),
/*(int) */Math.floor(otherPattern.getX()),
/*(int) */Math.floor(otherPattern.getY()));
const moduleSizeEst2: number /*float*/ = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */Math.floor(otherPattern.getX()),
/*(int) */Math.floor(otherPattern.getY()),
/*(int) */Math.floor(pattern.getX()),
/*(int) */Math.floor(pattern.getY()));
if (isNaN(moduleSizeEst1)) {
return moduleSizeEst2 / 7.0;
}
if (isNaN(moduleSizeEst2)) {
return moduleSizeEst1 / 7.0;
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0;
}
/**
* See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
* a finder pattern by looking for a black-white-black run from the center in the direction
* of another point (another finder pattern center), and in the opposite direction too.
*/
private sizeOfBlackWhiteBlackRunBothWays(fromX: number /*int*/, fromY: number /*int*/, toX: number /*int*/, toY: number /*int*/): number/*float*/ {
let result: number /*float*/ = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
// Now count other way -- don't run off image though of course
let scale: number /*float*/ = 1.0;
let otherToX = fromX - (toX - fromX);
if (otherToX < 0) {
scale = fromX / /*(float) */(fromX - otherToX);
otherToX = 0;
} else if (otherToX >= this.image.getWidth()) {
scale = (this.image.getWidth() - 1 - fromX) / /*(float) */(otherToX - fromX);
otherToX = this.image.getWidth() - 1;
}
let otherToY = /*(int) */Math.floor(fromY - (toY - fromY) * scale);
scale = 1.0;
if (otherToY < 0) {
scale = fromY / /*(float) */(fromY - otherToY);
otherToY = 0;
} else if (otherToY >= this.image.getHeight()) {
scale = (this.image.getHeight() - 1 - fromY) / /*(float) */(otherToY - fromY);
otherToY = this.image.getHeight() - 1;
}
otherToX = /*(int) */Math.floor(fromX + (otherToX - fromX) * scale);
result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
// Middle pixel is double-counted this way; subtract 1
return result - 1.0;
}
/**
* <p>This method traces a line from a point in the image, in the direction towards another point.
* It begins in a black region, and keeps going until it finds white, then black, then white again.
* It reports the distance from the start to this point.</p>
*
* <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
* may be skewed or rotated.</p>
*/
private sizeOfBlackWhiteBlackRun(fromX: number /*int*/, fromY: number /*int*/, toX: number /*int*/, toY: number /*int*/): number/*float*/ {
// Mild variant of Bresenham's algorithm
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
const steep: boolean = Math.abs(toY - fromY) > Math.abs(toX - fromX);
if (steep) {
let temp = fromX;
fromX = fromY;
fromY = temp;
temp = toX;
toX = toY;
toY = temp;
}
const dx = Math.abs(toX - fromX);
const dy = Math.abs(toY - fromY);
let error = -dx / 2;
const xstep = fromX < toX ? 1 : -1;
const ystep = fromY < toY ? 1 : -1;
// In black pixels, looking for white, first or second time.
let state = 0;
// Loop up until x == toX, but not beyond
const xLimit = toX + xstep;
for (let x = fromX, y = fromY; x !== xLimit; x += xstep) {
const realX = steep ? y : x;
const realY = steep ? x : y;
// Does current pixel mean we have moved white to black or vice versa?
// Scanning black in state 0,2 and white in state 1, so if we find the wrong
// color, advance to next state or end if we are in state 2 already
if ((state === 1) === this.image.get(realX, realY)) {
if (state === 2) {
return MathUtils.distance(x, y, fromX, fromY);
}
state++;
}
error += dy;
if (error > 0) {
if (y === toY) {
break;
}
y += ystep;
error -= dx;
}
}
// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
// is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if (state === 2) {
return MathUtils.distance(toX + xstep, toY, fromX, fromY);
}
// else we didn't find even black-white-black; no estimate is really possible
return NaN;
}
/**
* <p>Attempts to locate an alignment pattern in a limited region of the image, which is
* guessed to contain it. This method uses {@link AlignmentPattern}.</p>
*
* @param overallEstModuleSize estimated module size so far
* @param estAlignmentX x coordinate of center of area probably containing alignment pattern
* @param estAlignmentY y coordinate of above
* @param allowanceFactor number of pixels in all directions to search from the center
* @return {@link AlignmentPattern} if found, or null otherwise
* @throws NotFoundException if an unexpected error occurs during detection
*/
protected findAlignmentInRegion(overallEstModuleSize: number/*float*/,
estAlignmentX: number /*int*/,
estAlignmentY: number /*int*/,
allowanceFactor: number/*float*/): AlignmentPattern {
// Look for an alignment pattern (3 modules in size) around where it
// should be
const allowance = /*(int) */Math.floor(allowanceFactor * overallEstModuleSize);
const alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
const alignmentAreaRightX = Math.min(this.image.getWidth() - 1, estAlignmentX + allowance);
if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
throw new NotFoundException('Alignment top exceeds estimated module size.');
}
const alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
const alignmentAreaBottomY = Math.min(this.image.getHeight() - 1, estAlignmentY + allowance);
if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
throw new NotFoundException('Alignment bottom exceeds estimated module size.');
}
const alignmentFinder = new AlignmentPatternFinder(
this.image,
alignmentAreaLeftX,
alignmentAreaTopY,
alignmentAreaRightX - alignmentAreaLeftX,
alignmentAreaBottomY - alignmentAreaTopY,
overallEstModuleSize,
this.resultPointCallback
);
return alignmentFinder.find();
}
}
| zxing-js/library | src/core/qrcode/detector/Detector.ts | TypeScript | mit | 16,330 |
# Simple plotter for Gut books.
# All this does is draw a sqare for every stat in the input
# and color it based on the score.
#
# Another fine example of how Viz lies to you. You will
# need to fudge the range by adjusting the clipping.
import numpy as np
import matplotlib.pyplot as plt
import sys as sys
if len(sys.argv) <2:
print "Need an input file with many rows of 'id score'\n"
sys.exit(1)
fname = sys.argv[1]
vals = np.loadtxt(fname)
ids = vals[:,0]
score = vals[:,1]
score_max = 400; #max(score)
#score_max = max(score)
score = np.clip(score, 10, score_max)
score = score/score_max
# want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300
NUM_COLS=300
fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(111)
ax.set_axis_bgcolor('0.50')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
for i in range(len(vals)):
#print i, ids[i]
row = int(ids[i]) / NUM_COLS
col = int(ids[i]) % NUM_COLS
cval = score[i] #score[i]*score[i] # Square the values to drop the lower end
cmap = plt.get_cmap('hot')
val = cmap(cval)
ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn))
ax.set_aspect('equal')
print cmap(0.1)
print cmap(0.9)
plt.xlim([0,NUM_COLS])
plt.ylim([0,1+int(max(ids))/NUM_COLS])
plt.show()
| craigulmer/gut-buster | squareplot.py | Python | mit | 1,320 |
using NBitcoin;
using ReactiveUI;
using Splat;
using System;
using System.Globalization;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.CoinJoin.Client.Rounds;
using WalletWasabi.CoinJoin.Common.Models;
using WalletWasabi.Gui.Models;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Models;
using WalletWasabi.Logging;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using Avalonia;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinViewModel : ViewModelBase, IDisposable
{
private bool _isSelected;
private SmartCoinStatus _status;
private ObservableAsPropertyHelper<bool> _coinJoinInProgress;
private ObservableAsPropertyHelper<bool> _confirmed;
private ObservableAsPropertyHelper<string> _cluster;
private ObservableAsPropertyHelper<int> _anonymitySet;
private volatile bool _disposedValue = false;
public CoinViewModel(Wallet wallet, CoinListViewModel owner, SmartCoin model)
{
Global = Locator.Current.GetService<Global>();
Model = model;
Wallet = wallet;
Owner = owner;
RefreshSmartCoinStatus();
Disposables = new CompositeDisposable();
_coinJoinInProgress = Model
.WhenAnyValue(x => x.CoinJoinInProgress)
.ToProperty(this, x => x.CoinJoinInProgress, scheduler: RxApp.MainThreadScheduler)
.DisposeWith(Disposables);
_confirmed = Model
.WhenAnyValue(x => x.Confirmed)
.ToProperty(this, x => x.Confirmed, scheduler: RxApp.MainThreadScheduler)
.DisposeWith(Disposables);
_anonymitySet = Model
.WhenAnyValue(x => x.HdPubKey.AnonymitySet)
.ToProperty(this, x => x.AnonymitySet, scheduler: RxApp.MainThreadScheduler)
.DisposeWith(Disposables);
_cluster = Model
.WhenAnyValue(x => x.HdPubKey.Cluster, x => x.HdPubKey.Cluster.Labels)
.Select(x => x.Item2.ToString())
.ToProperty(this, x => x.Cluster, scheduler: RxApp.MainThreadScheduler)
.DisposeWith(Disposables);
this.WhenAnyValue(x => x.Status)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ => this.RaisePropertyChanged(nameof(ToolTip)));
Observable
.Merge(Model.WhenAnyValue(x => x.IsBanned, x => x.SpentAccordingToBackend, x => x.Confirmed, x => x.CoinJoinInProgress).Select(_ => Unit.Default))
.Merge(Observable.FromEventPattern(Wallet.ChaumianClient, nameof(Wallet.ChaumianClient.StateUpdated)).Select(_ => Unit.Default))
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ => RefreshSmartCoinStatus())
.DisposeWith(Disposables);
Global.BitcoinStore.SmartHeaderChain
.WhenAnyValue(x => x.TipHeight).Select(_ => Unit.Default)
.Merge(Model.WhenAnyValue(x => x.Height).Select(_ => Unit.Default))
.Throttle(TimeSpan.FromSeconds(0.1)) // DO NOT TAKE THIS THROTTLE OUT, OTHERWISE SYNCING WITH COINS IN THE WALLET WILL STACKOVERFLOW!
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ => this.RaisePropertyChanged(nameof(Confirmations)))
.DisposeWith(Disposables);
Global.UiConfig
.WhenAnyValue(x => x.PrivacyMode)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(AmountBtc));
this.RaisePropertyChanged(nameof(Cluster));
}).DisposeWith(Disposables);
DequeueCoin = ReactiveCommand.Create(() => Owner.PressDequeue(Model), this.WhenAnyValue(x => x.CoinJoinInProgress));
OpenCoinInfo = ReactiveCommand.Create(() =>
{
var shell = IoC.Get<IShell>();
var coinInfo = shell.Documents?.OfType<CoinInfoTabViewModel>()?.FirstOrDefault(x => x.Coin?.Model == Model);
if (coinInfo is null)
{
coinInfo = new CoinInfoTabViewModel(this);
shell.AddDocument(coinInfo);
}
shell.Select(coinInfo);
});
CopyCluster = ReactiveCommand.CreateFromTask(async () => await Application.Current.Clipboard.SetTextAsync(Cluster));
Observable
.Merge(DequeueCoin.ThrownExceptions) // Don't notify about it. Dequeue failure (and success) is notified by other mechanism.
.Merge(OpenCoinInfo.ThrownExceptions)
.Merge(CopyCluster.ThrownExceptions)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
private CompositeDisposable Disposables { get; set; }
private Wallet Wallet { get; }
public CoinListViewModel Owner { get; }
private Global Global { get; }
public bool CanBeDequeued => Owner.CanDequeueCoins;
public ReactiveCommand<Unit, Unit> DequeueCoin { get; }
public ReactiveCommand<Unit, Unit> OpenCoinInfo { get; }
public ReactiveCommand<Unit, Unit> CopyCluster { get; }
public SmartCoin Model { get; }
public bool Confirmed => _confirmed?.Value ?? false;
public bool CoinJoinInProgress => _coinJoinInProgress?.Value ?? false;
public string Address => Model.ScriptPubKey.GetDestinationAddress(Global.Network).ToString();
public int Confirmations => Model.Height.Type == HeightType.Chain
? (int)Global.BitcoinStore.SmartHeaderChain.TipHeight - Model.Height.Value + 1
: 0;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public string ToolTip => Status switch
{
SmartCoinStatus.Confirmed => "This coin is confirmed.",
SmartCoinStatus.Unconfirmed => "This coin is unconfirmed.",
SmartCoinStatus.MixingOnWaitingList => "This coin is waiting for its turn to be coinjoined.",
SmartCoinStatus.MixingBanned => $"The coordinator banned this coin from participation until {Model?.BannedUntilUtc?.ToString("yyyy - MM - dd HH: mm", CultureInfo.InvariantCulture)}.",
SmartCoinStatus.MixingInputRegistration => "This coin is registered for coinjoin.",
SmartCoinStatus.MixingConnectionConfirmation => "This coin is currently in Connection Confirmation phase.",
SmartCoinStatus.MixingOutputRegistration => "This coin is currently in Output Registration phase.",
SmartCoinStatus.MixingSigning => "This coin is currently in Signing phase.",
SmartCoinStatus.SpentAccordingToBackend => "According to the Backend, this coin is spent. Wallet state will be corrected after confirmation.",
SmartCoinStatus.MixingWaitingForConfirmation => "Coinjoining unconfirmed coins is not allowed, unless the coin is a coinjoin output itself.",
_ => "This is impossible."
};
public Money Amount => Model.Amount;
public string AmountBtc => Model.Amount.ToString(false, true);
public int Height => Model.Height;
public string TransactionId => Model.TransactionId.ToString();
public uint OutputIndex => Model.Index;
public int AnonymitySet => _anonymitySet?.Value ?? 1;
public string InCoinJoin => Model.CoinJoinInProgress ? "Yes" : "No";
public string Cluster => _cluster?.Value ?? "";
public string PubKey => Model.HdPubKey.PubKey.ToString();
public string KeyPath => Model.HdPubKey.FullKeyPath.ToString();
public SmartCoinStatus Status
{
get => _status;
set => this.RaiseAndSetIfChanged(ref _status, value);
}
private void RefreshSmartCoinStatus()
{
Status = GetSmartCoinStatus();
}
private SmartCoinStatus GetSmartCoinStatus()
{
Model.SetIsBanned(); // Recheck if the coin's ban has expired.
if (Model.IsBanned)
{
return SmartCoinStatus.MixingBanned;
}
if (Model.CoinJoinInProgress && Wallet.ChaumianClient is { })
{
ClientState clientState = Wallet.ChaumianClient.State;
foreach (var round in clientState.GetAllMixingRounds())
{
if (round.CoinsRegistered.Contains(Model))
{
if (round.State.Phase == RoundPhase.InputRegistration)
{
return SmartCoinStatus.MixingInputRegistration;
}
else if (round.State.Phase == RoundPhase.ConnectionConfirmation)
{
return SmartCoinStatus.MixingConnectionConfirmation;
}
else if (round.State.Phase == RoundPhase.OutputRegistration)
{
return SmartCoinStatus.MixingOutputRegistration;
}
else if (round.State.Phase == RoundPhase.Signing)
{
return SmartCoinStatus.MixingSigning;
}
}
}
}
if (Model.SpentAccordingToBackend)
{
return SmartCoinStatus.SpentAccordingToBackend;
}
if (Model.Confirmed)
{
if (Model.CoinJoinInProgress)
{
return SmartCoinStatus.MixingOnWaitingList;
}
else
{
return SmartCoinStatus.Confirmed;
}
}
else // Unconfirmed
{
if (Model.CoinJoinInProgress)
{
return SmartCoinStatus.MixingWaitingForConfirmation;
}
else
{
return SmartCoinStatus.Unconfirmed;
}
}
}
public CompositeDisposable GetDisposables() => Disposables;
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
Disposables?.Dispose();
}
Disposables = null;
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable Support
}
}
| nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/CoinViewModel.cs | C# | mit | 8,992 |
/*Problem 13. Solve tasks
Write a program that can solve these tasks:
Reverses the digits of a number
Calculates the average of a sequence of integers
Solves a linear equation a * x + b = 0
Create appropriate methods.
Provide a simple text-based menu for the user to choose which task to solve.
Validate the input data:
The decimal number should be non-negative
The sequence should not be empty
a should not be equal to 0*/
using System;
using System.Linq;
using System.Globalization;
class Program
{
static void Main()
{
string user = "0";
while (user == "0")
{
Console.WriteLine("Program options: ");
Console.WriteLine("1) Reverses the digits of a number");
Console.WriteLine("2) Calculates the average of a sequence of integers");
Console.WriteLine("3) Solves a linear equation 'a * x + b = 0'");
Console.Write("Enter your choice: ");
user = Console.ReadLine();
switch (user)
{
case "1": ReverseDigits();
return;
case "2": FindAverageSumOfSequence();
return;
case "3": SolveLinearEquation();
return;
default:
Console.Clear();
user = "0";
break;
}
}
}
static void ReverseDigits()
{
decimal number = 0;
do
{
Console.Write("Enter a non-negative number (real or integer): ");
number = decimal.Parse(Console.ReadLine());
}
while (number < 0);
string temp = number.ToString(CultureInfo.InvariantCulture);
string result = string.Empty;
for (int i = temp.Length - 1; i >= 0; i--)
{
result += temp[i];
}
Console.WriteLine("Result: {0} -> {1}", number, decimal.Parse(result));
}
static void FindAverageSumOfSequence()
{
int n = 0;
do
{
Console.Write("Enter a non-negative number N (size of array): ");
n = int.Parse(Console.ReadLine());
}
while (n <= 0);
int[] numbers = new int[n];
Console.WriteLine("\nEnter a {0} number(s) to array: ", n);
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(" {0}: ", i + 1);
numbers[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nAverage sum = {0}", numbers.Average());
return;
}
static void SolveLinearEquation()
{
decimal a = 0;
do
{
Console.Write("Enter a non-zero number A: ");
a = decimal.Parse(Console.ReadLine());
}
while (a == 0);
Console.Write("Enter a number B: ");
decimal b = decimal.Parse(Console.ReadLine());
Console.WriteLine("\nResult -> x = -b / a = {0}", -b / a);
}
}
| MarinMarinov/C-Sharp-Part-2 | Homework 03-Methods/Problem 13. Solve tasks/Program.cs | C# | mit | 3,087 |
import Ember from 'ember';
import StatefulMixin from './mixins/stateful';
export default Ember.Object.extend(StatefulMixin);
| IvyApp/ivy-stateful | addon/state-machine.js | JavaScript | mit | 126 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("QtmCaptureBroadcasts")]
[assembly: AssemblyDescription("Show QTM udp broadcasts ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Qualisys")]
[assembly: AssemblyProduct("QtmCaptureBroadcasts")]
[assembly: AssemblyCopyright("Copyright © Qualisys 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b8d704-8ffb-47a4-a45f-f800c4507b10")]
// 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")]
| qualisys/RTClientSDK.Net | QtmCaptureBroadcasts/Properties/AssemblyInfo.cs | C# | mit | 1,451 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
Easing,
View,
} from 'react-native';
const INDETERMINATE_WIDTH_FACTOR = 0.3;
const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR);
export default class ProgressBar extends Component {
static propTypes = {
animated: PropTypes.bool,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
borderWidth: PropTypes.number,
children: PropTypes.node,
color: PropTypes.string,
height: PropTypes.number,
indeterminate: PropTypes.bool,
progress: PropTypes.number,
style: View.propTypes.style,
unfilledColor: PropTypes.string,
width: PropTypes.number,
};
static defaultProps = {
animated: true,
borderRadius: 4,
borderWidth: 1,
color: 'rgba(0, 122, 255, 1)',
height: 6,
indeterminate: false,
progress: 0,
width: 150,
};
constructor(props) {
super(props);
const progress = Math.min(Math.max(props.progress, 0), 1);
this.state = {
progress: new Animated.Value(props.indeterminate ? INDETERMINATE_WIDTH_FACTOR : progress),
animationValue: new Animated.Value(BAR_WIDTH_ZERO_POSITION),
};
}
componentDidMount() {
if (this.props.indeterminate) {
this.animate();
}
}
componentWillReceiveProps(props) {
if (props.indeterminate !== this.props.indeterminate) {
if (props.indeterminate) {
this.animate();
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
}).start();
}
}
if (
props.indeterminate !== this.props.indeterminate ||
props.progress !== this.props.progress
) {
const progress = (props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(props.progress, 0), 1)
);
if (props.animated) {
Animated.spring(this.state.progress, {
toValue: progress,
bounciness: 0,
}).start();
} else {
this.state.progress.setValue(progress);
}
}
}
animate() {
this.state.animationValue.setValue(0);
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: 1000,
easing: Easing.linear,
isInteraction: false,
}).start((endState) => {
if (endState.finished) {
this.animate();
}
});
}
render() {
const {
borderColor,
borderRadius,
borderWidth,
children,
color,
height,
style,
unfilledColor,
width,
...restProps
} = this.props;
const innerWidth = width - (borderWidth * 2);
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor,
};
const progressStyle = {
backgroundColor: color,
height,
width: innerWidth,
transform: [{
translateX: this.state.animationValue.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
}),
}, {
translateX: this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth / -2, 0],
}),
}, {
scaleX: this.state.progress,
}],
};
return (
<View style={[containerStyle, style]} {...restProps}>
<Animated.View style={progressStyle} />
{children}
</View>
);
}
}
| fengshanjian/react-native-komect-uikit | src/Progress/Bar.js | JavaScript | mit | 3,584 |
package gr.iti.openzoo.pojos;
/**
*
* @author Michalis Lazaridis <michalis.lazaridis@iti.gr>
*/
public class Triple<L,M,R> {
private final L left;
private final M middle;
private final R right;
public Triple(L left, M middle, R right) {
this.left = left;
this.middle = middle;
this.right = right;
}
public L getLeft() { return left; }
public M getMiddle() { return middle; }
public R getRight() { return right; }
@Override
public int hashCode() { return (left.hashCode() ^ middle.hashCode() ^ right.hashCode()) % Integer.MAX_VALUE; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Triple)) return false;
Triple triplo = (Triple) o;
return this.left.equals(triplo.getLeft()) &&
this.middle.equals(triplo.getMiddle()) &&
this.right.equals(triplo.getRight());
}
@Override
public String toString()
{
return "Triple ( " + getLeft().toString() + ", " + getMiddle().toString() + ", " + getRight().toString() + " )";
}
}
| VisualComputingLab/OpenZoo | OpenZUI/src/java/gr/iti/openzoo/pojos/Triple.java | Java | mit | 1,025 |
package us.myles.ViaVersion.protocols.protocol1_9to1_8;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.remapper.PacketHandler;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.MovementTracker;
public class PlayerMovementMapper extends PacketHandler {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
MovementTracker tracker = wrapper.user().get(MovementTracker.class);
tracker.incrementIdlePacket();
// If packet has the ground data
if (wrapper.is(Type.BOOLEAN, 0)) {
tracker.setGround(wrapper.get(Type.BOOLEAN, 0));
}
}
}
| Matsv/ViaVersion | common/src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/PlayerMovementMapper.java | Java | mit | 696 |
<?php
namespace PMocks\Loader;
class Exception extends \PMocks\Exception
{
} | psmokotnin/PMocks | PMocks/Loader/Exception.php | PHP | mit | 78 |
const basicJson = require('./basic.json')
export const jsonExport = {
basicJson
}
| ericwooley/jsonable | tests/files/json-include.json.js | JavaScript | mit | 85 |
package dp;
/**
* Question: http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
*/
public class CountBinaryWithoutConsecutiveOnes {
public int count(int N) {
int[][] memo = new int[N + 1][2];
for (int i = 0; i < memo.length; i++) {
for (int j = 0; j < memo[i].length; j++) {
memo[i][j] = -1;
}
}
return countBinary(N, false, memo);
}
private int countBinary(int N, boolean prevSet, int[][] memo) {
if (N == 0) return 1;
int i = (prevSet) ? 1 : 0;
if (memo[N][i] == -1) {
memo[N][i] = countBinary(N - 1, false, memo);
if (!prevSet) {
memo[N][i] += countBinary(N - 1, true, memo);
}
}
return memo[N][i];
}
public int countBottomUp(int N) {
int a = 1, b = 1, c = 0;
for (int i = 1; i <= N; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
| scaffeinate/crack-the-code | geeks-for-geeks/src/dp/CountBinaryWithoutConsecutiveOnes.java | Java | mit | 1,025 |
from verbs.baseforms import forms
class SuspendForm(forms.VerbForm):
name = "Suspend"
slug = "suspend"
duration_min_time = forms.IntegerField() | Bionetbook/bionetbook | bnbapp/bionetbook/_old/verbs/forms/suspend.py | Python | mit | 159 |
Csabuilder::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Use http://github.com/ryanb/letter_opener for
# development email delivery
config.action_mailer.delivery_method = :letter_opener
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
# config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
| giratikanon/csa-builder | config/environments/development.rb | Ruby | mit | 1,595 |
/*
* wjquery.calendar 0.1.1
* by composite (wonchu.net@gmail.com)
* http://www.wonchu.net
* This project licensed under a MIT License.
0.1.0 : 최초작성
0.1.1 : 소스정리
*/
(function ($) {
const WCALENDAR_SV = {
ns: "wcalendar",
dateFormat: "YYYYMMDD",
lang: {
ko: {
week: ["일", "월", "화", "수", "목", "금", "토"]
}
}
};
$.fn.wcalendar = function (method) {
let result, _arguments = arguments;
this.each(function (i, element) {
const $element = $(element);
let $container,
_option = {};
if ($element.prop("tagName").toLowerCase() == "input") {
if ($element.attr("data-wrap-id")) {
$container = $("#" + $element.attr("data-wrap-id"));
} else {
const _id = "wcalendar_" + new Date().getTime();
$element.after("<div id=\"" + _id + "\" />");
_option.element = $element;
$element.attr("data-wrap-id", _id);
$container = $("#" + _id);
}
} else {
$container = $element;
}
const plugin = $container.data(WCALENDAR_SV.ns);
if (plugin && typeof method === 'string') {
if (plugin[method]) {
result = plugin[method].apply(this, Array.prototype.slice.call(_arguments, 1));
} else {
alert('Method ' + method + ' does not exist on jQuery.wcalendar');
}
} else if (!plugin && (typeof method === 'object' || !method)) {
let wcalendar = new WCALENDAR();
$container.data(WCALENDAR_SV.ns, wcalendar);
wcalendar.init($container, $.extend(_option, $.fn.wcalendar.defaultSettings, method || {}));
}
});
return result ? result : $(this);
};
$.fn.wcalendar.defaultSettings = {
width: "200px",
locale: "ko",
dateFormat: "YYYY.MM.DD",
showPrevNextDays: true,
dateIconClass: "wcalendar-dateicon",
mdHoliday: {
"0101": {
ko: "신정"
},
"0505": {
ko: "어린이날"
}
},
holiday: {
"20210519": {
ko: "부처님오신날"
}
}
};
function WCALENDAR() {
let $container, options;
function init(_container, _options) {
$container = _container;
options = _options;
if (options.selectDate) {
options.selectDate = moment(options.selectDate, options.dateFormat);
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
} else {
options.selectDate = moment();
}
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.init($container, options);
}
function draw() {
_WCALENDAR.draw($container, options);
}
function prev() {
options.targetDate = options.targetDate.add(-1, "months");
_WCALENDAR.draw($container, options);
}
function next() {
options.targetDate = options.targetDate.add(1, "months");
_WCALENDAR.draw($container, options);
}
function set(dt) {
options.targetDate = moment(dt, options.dateFormat);
_WCALENDAR.draw($container, options);
}
function select() {
options.targetDate = moment($(".wcalendar-month .title-year", $container).val() + $.pad($(".wcalendar-month .title-month", $container).val(), 2) + "01", "YYYYMMDD");
_WCALENDAR.draw($container, options);
}
function click() {
const _index = $(".wcalendar-undock").index($container);
$(".wcalendar-undock").each(function () {
if ($(".wcalendar-undock").index(this) != _index && $(this).is(":visible")) {
$(this).hide();
}
});
if ($container.is(":visible")) {
$container.hide();
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
options.hasVal = "Y";
} else {
options.selectDate = moment();
options.hasVal = "N";
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.draw($container, options);
$container.show();
}
}
function destory() {
if (options.element) {
options.element.removeClass("wcalendar-input");
if (options.element.next("." + options.dateIconClass)) {
options.element.next("." + options.dateIconClass).remove();
}
}
$container.remove();
}
return {
init: init,
draw: draw,
prev: prev,
next: next,
set: set,
select: select,
click: click,
destory: destory
};
}
var _WCALENDAR = {
init: function ($container, options) {
if (options.element) {
options.element.addClass("wcalendar-input");
$container.addClass("wcalendar-undock").css({
"top": options.element.position().top + options.element.outerHeight(),
"left": options.element.position().left,
"width": options.width
});
const $icon = $("<span class=\"" + options.dateIconClass + "\" />");
options.element.after($icon);
$icon.click(function () {
$container.wcalendar("click");
});
options.element.click(function () {
$container.wcalendar("click");
});
$(document).on("click.wcalendar-undock", function (event) {
if ($(event.target).closest(".wcalendar-wrap, .wcalendar-input, ." + options.dateIconClass).length === 0) {
$container.hide();
}
});
}
$container.html(
"<div class=\"wcalendar-wrap\">" +
" <div class=\"wcalendar-month\">" +
" <ul>" +
" <li class=\"prev\"><a href=\"javascript:;\"><span>❮</span></a></li>" +
" <li class=\"next\"><a href=\"javascript:;\"><span>❯</span></a></li>" +
" <li><select class=\"title-year\"></select> <select class=\"title-month\"></select></li>" +
" </ul>" +
" </div>" +
" <ul class=\"wcalendar-weekdays\"></ul>" +
" <ul class=\"wcalendar-days\"></ul>" +
"</div>"
);
this.draw($container, options);
$(".wcalendar-month li>a", $container).click(function () {
$container.wcalendar($(this).parent().attr("class"));
});
$container.find(".wcalendar-days").on("click", "a", function () {
var $t = $(this);
$t.parent().siblings().find("a.active").removeClass("active");
$t.addClass("active");
if (options.callback) {
options.callback($(this).attr("data-val"));
} else if (options.element) {
options.element.val($(this).attr("data-val"));
$container.hide();
}
});
},
draw: function ($container, options) {
const curentDate = moment(),
selectDate = options.selectDate,
targetDate = options.targetDate,
firstDate = targetDate.clone().startOf("month"),
lastDate = targetDate.clone().endOf("month");
let _prevDate, _targetDate, _nextDate;
this.makeSelectOption($(".wcalendar-month .title-year", $container), targetDate.year() - 10, targetDate.year() + 10, targetDate.year());
this.makeSelectOption($(".wcalendar-month .title-month", $container), 1, 12, options.targetDate.month() + 1);
$(".wcalendar-month .title-month, .wcalendar-month .title-year", $container).off("change").on("change", function () {
$container.wcalendar("select");
});
let _weekdays = [];
for (let n = 0; n < 7; n++) {
_weekdays.push("<li>" + WCALENDAR_SV.lang[options.locale].week[n] + "</li>");
}
$container.find(".wcalendar-weekdays").empty().append(_weekdays.join(""));
let _days = [];
for (let i = firstDate.day(); i > 0; i--) {
if (options.showPrevNextDays) {
_prevDate = firstDate.clone().add(-i, "days");
_days.push(this.makeItem(options, "prev", _prevDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
for (let j = 0; j < lastDate.date(); j++) {
_targetDate = firstDate.clone().add(j, "days");
_days.push(this.makeItem(options, "target", _targetDate, curentDate, selectDate));
}
for (let k = 1; k <= (6 - lastDate.day()); k++) {
if (options.showPrevNextDays) {
_nextDate = lastDate.clone().add(k, "days");
_days.push(this.makeItem(options, "next", _nextDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
$container.find(".wcalendar-days").empty().append(_days.join(""));
},
makeItem: function (options, mode, dt, dt2, dt3) {
let classNames = [],
titles = [],
_classNames = "",
_titles = "";
const dtf = dt.format(WCALENDAR_SV.dateFormat),
dtfmd = dt.format("MMDD"),
dtf2 = dt2.format(WCALENDAR_SV.dateFormat),
dtf3 = dt3.format(WCALENDAR_SV.dateFormat);
classNames.push(mode);
if (dtf2 == dtf) {
classNames.push("today");
}
if (dtf3 == dtf ) {
if(options.hasVal && options.hasVal=="N"){
//nothing
}else{
classNames.push("active");
}
}
if (options.mdHoliday && options.mdHoliday[dtfmd]) {
classNames.push("md-holiday");
titles.push(options.mdHoliday[dtfmd][options.locale]);
}
if (options.holiday && options.holiday[dtf]) {
classNames.push("holiday");
titles.push(options.holiday[dtf][options.locale]);
}
if (classNames.length > 0) {
_classNames = " class=\"" + (classNames.join(" ")) + "\"";
}
if (titles.length > 0) {
_titles = " title=\"" + (titles.join(" ")) + "\"";
}
return "<li>" +
" <a href=\"javascript:;\" data-val=\"" + dt.format(options.dateFormat) + "\"" + _titles + _classNames + ">" + dt.date() + "</a>" +
"</li>";
},
makeSelectOption: function ($t, start, end, v) {
let _options = [];
for (let i = start; i <= end; i++) {
_options.push("<option value=\"" + i + "\"" + (i == v ? " selected=\"selected\"" : "") + ">" + i + "</option>");
}
$t.empty().append(_options.join(""));
}
}
})(jQuery); | bibaboo/bibaboo.github.com | js/lib/wjquery/wjquery.calendar.js | JavaScript | mit | 12,657 |
<?php
/* SensioDistributionBundle::Configurator/final.html.twig */
class __TwigTemplate_97f044a3817b39b7b53a0966d7ee406e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("SensioDistributionBundle::Configurator/layout.html.twig");
$this->blocks = array(
'content_class' => array($this, 'block_content_class'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "SensioDistributionBundle::Configurator/layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content_class($context, array $blocks = array())
{
echo "config_done";
}
// line 4
public function block_content($context, array $blocks = array())
{
// line 5
echo " <h1>Well done!</h1>
";
// line 6
if ($this->getContext($context, "is_writable")) {
// line 7
echo " <h2>Your distribution is configured!</h2>
";
} else {
// line 9
echo " <h2 class=\"configure-error\">Your distribution is almost configured but...</h2>
";
}
// line 11
echo " <h3>
<span>
";
// line 13
if ($this->getContext($context, "is_writable")) {
// line 14
echo " Your parameters.yml file has been overwritten with these parameters (in <em>";
echo twig_escape_filter($this->env, $this->getContext($context, "yml_path"), "html", null, true);
echo "</em>):
";
} else {
// line 16
echo " Your parameters.yml file is not writeable! Here are the parameters you can copy and paste in <em>";
echo twig_escape_filter($this->env, $this->getContext($context, "yml_path"), "html", null, true);
echo "</em>:
";
}
// line 18
echo " </span>
</h3>
<textarea class=\"symfony-configuration\">";
// line 21
echo twig_escape_filter($this->env, $this->getContext($context, "parameters"), "html", null, true);
echo "</textarea>
";
// line 23
if ($this->getContext($context, "welcome_url")) {
// line 24
echo " <ul>
<li><a href=\"";
// line 25
echo twig_escape_filter($this->env, $this->getContext($context, "welcome_url"), "html", null, true);
echo "\">Go to the Welcome page</a></li>
</ul>
";
}
}
public function getTemplateName()
{
return "SensioDistributionBundle::Configurator/final.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 82 => 25, 79 => 24, 77 => 23, 72 => 21, 67 => 18, 61 => 16, 55 => 14, 53 => 13, 49 => 11, 45 => 9, 41 => 7, 39 => 6, 36 => 5, 33 => 4, 27 => 3,);
}
}
| edconolly/symfony-test | app/cache/dev/twig/97/f0/44a3817b39b7b53a0966d7ee406e.php | PHP | mit | 3,293 |
export * as dijkstra from './dijkstra';
export * as unweighted from './unweighted';
export {
singleSource,
singleSourceLength,
bidirectional,
brandes
} from './unweighted';
export {edgePathFromNodePath} from './utils';
| graphology/graphology | src/shortest-path/index.d.ts | TypeScript | mit | 229 |
# Copyright 2008-2009 Amazon.com, Inc. or its affiliates. All Rights
# Reserved. Licensed under the Amazon Software License (the
# "License"). You may not use this file except in compliance with the
# License. A copy of the License is located at
# http://aws.amazon.com/asl or in the "license" file accompanying this
# file. This file is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
# the License for the specific language governing permissions and
# limitations under the License.
require 'ec2/common/s3support'
require 'ec2/amitools/uploadbundleparameters'
require 'uri'
require 'ec2/amitools/instance-data'
require 'ec2/amitools/manifestv20071010'
require 'rexml/document'
require 'digest/md5'
require 'base64'
require 'ec2/amitools/tool_base'
#------------------------------------------------------------------------------#
UPLOAD_BUNDLE_NAME = 'ec2-upload-bundle'
UPLOAD_BUNDLE_MANUAL =<<TEXT
#{UPLOAD_BUNDLE_NAME} is a command line tool to upload a bundled Amazon Image to S3 storage
for use by EC2. An Amazon Image may be one of the following:
- Amazon Machine Image (AMI)
- Amazon Kernel Image (AKI)
- Amazon Ramdisk Image (ARI)
#{UPLOAD_BUNDLE_NAME} will:
- create an S3 bucket to store the bundled AMI in if it does not already exist
- upload the AMI manifest and parts files to S3, granting specified privileges
- on them (defaults to EC2 read privileges)
To manually retry an upload that failed, #{UPLOAD_BUNDLE_NAME} can optionally:
- skip uploading the manifest
- only upload bundled AMI parts from a specified part onwards
TEXT
#------------------------------------------------------------------------------#
class BucketLocationError < AMIToolExceptions::EC2FatalError
def initialize(bucket, location, bucket_location)
location = "US" if location == :unconstrained
bucket_location = "US" if bucket_location == :unconstrained
super(10, "Bucket \"#{bucket}\" already exists in \"#{bucket_location}\" and \"#{location}\" was specified.")
end
end
#----------------------------------------------------------------------------#
# Upload the specified file.
class BundleUploader < AMITool
def upload(s3_conn, bucket, key, file, acl, retry_upload)
retry_s3(retry_upload) do
begin
md5 = get_md5(file)
s3_conn.put(bucket, key, file, {"x-amz-acl"=>acl, "content-md5"=>md5})
return
rescue EC2::Common::HTTP::Error::PathInvalid => e
raise FileNotFound(file)
rescue => e
raise TryFailed.new("Failed to upload \"#{file}\": #{e.message}")
end
end
end
#----------------------------------------------------------------------------#
def get_md5(file)
Base64::encode64(Digest::MD5::digest(File.open(file) { |f| f.read })).strip
end
#----------------------------------------------------------------------------#
#
# Availability zone names are generally in the format => ${REGION}${ZONENUMBER}.
# Examples being us-east-1b, us-east-1c, etc.
#
def get_availability_zone()
instance_data = EC2::InstanceData.new
instance_data.availability_zone
end
#----------------------------------------------------------------------------#
# Return a list of bundle part filename and part number tuples from the manifest.
def get_part_info(manifest)
parts = manifest.ami_part_info_list.map do |part|
[part['filename'], part['index']]
end
parts.sort
end
#------------------------------------------------------------------------------#
def uri2string(uri)
s = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}"
# Remove the trailing '/'.
return (s[-1..-1] == "/" ? s[0..-2] : s)
end
#------------------------------------------------------------------------------#
# Get the bucket's location.
def get_bucket_location(s3_conn, bucket)
begin
response = s3_conn.get_bucket_location(bucket)
rescue EC2::Common::HTTP::Error::Retrieve => e
if e.code == 404
# We have a "Not found" S3 response, which probably means the bucket doesn't exist.
return nil
end
raise e
end
$stdout.puts "check_bucket_location response: #{response.body}" if @debug and response.text?
docroot = REXML::Document.new(response.body).root
bucket_location = REXML::XPath.first(docroot, '/LocationConstraint').text
bucket_location ||= :unconstrained
end
#------------------------------------------------------------------------------#
# Check if the bucket exists and is in an appropriate location.
def check_bucket_location(bucket, bucket_location, location)
if bucket_location.nil?
# The bucket does not exist. Safe, but we need to create it.
return false
end
if location.nil?
# The bucket exists and we don't care where it is.
return true
end
if location != bucket_location
# The bucket isn't where we want it. This is a problem.
raise BucketLocationError.new(bucket, location, bucket_location)
end
# The bucket exists and is in the right place.
return true
end
#------------------------------------------------------------------------------#
# Create the specified bucket if it does not exist.
def create_bucket(s3_conn, bucket, bucket_location, location, retry_create)
begin
if check_bucket_location(bucket, bucket_location, location)
return true
end
$stdout.puts "Creating bucket..."
options = {'Content-Length' => '0'}
retry_s3(retry_create) do
error = "Could not create or access bucket #{bucket}"
begin
rsp = s3_conn.create_bucket(bucket, location == :unconstrained ? nil : location, options)
rescue EC2::Common::HTTP::Error::Retrieve => e
error += ": server response #{e.message} #{e.code}"
raise TryFailed.new(e.message)
rescue RuntimeError => e
error += ": error message #{e.message}"
raise e
end
end
end
end
#------------------------------------------------------------------------------#
# If we return true, we have a v2-compliant name.
# If we return false, we wish to use a bad name.
# Otherwise we quietly wander off to die in peace.
def check_bucket_name(bucket)
if EC2::Common::S3Support::bucket_name_s3_v2_safe?(bucket)
return true
end
message = "The specified bucket is not S3 v2 safe (see S3 documentation for details):\n#{bucket}"
if warn_confirm(message)
# Assume the customer knows what he's doing.
return false
else
# We've been asked to stop, so quietly wander off to die in peace.
raise EC2StopExecution.new()
end
end
#------------------------------------------------------------------------------#
# mapping from region names to S3 location constraints
S3_LOCATION_CONSTRAINTS = {
'us-east-1' => :unconstrained,
'eu-west-1' => 'EU',
'us-west-1' => 'us-west-1',
'ap-southeast-1' => 'ap-southeast-1',
'ap-northeast-1' => 'ap-northeast-1',
}
# list of regions
REGIONS = ['us-east-1', 'eu-west-1', 'us-west-1', 'ap-southeast-1', 'ap-northeast-1']
def get_region()
zone = get_availability_zone()
if zone.nil?
return nil
end
# assume region names do not have a common naming scheme. Therefore we manually go through all known region names
REGIONS.each do |region|
match = zone.match(region)
if not match.nil?
return region
end
end
nil
end
# This is very much a best effort attempt. If in doubt, we don't warn.
def cross_region?(location, bucket_location)
# If the bucket exists, its S3 location is canonical.
s3_region = bucket_location
s3_region ||= location
s3_region ||= :unconstrained
region = get_region()
if region.nil?
# If we can't get the region, assume we're fine since there's
# nothing more we can do.
return false
end
return s3_region != S3_LOCATION_CONSTRAINTS[region]
end
#------------------------------------------------------------------------------#
def warn_about_migrating()
message = ["You are bundling in one region, but uploading to another. If the kernel",
"or ramdisk associated with this AMI are not in the target region, AMI",
"registration will fail.",
"You can use the ec2-migrate-manifest tool to update your manifest file",
"with a kernel and ramdisk that exist in the target region.",
].join("\n")
unless warn_confirm(message)
raise EC2StopExecution.new()
end
end
#------------------------------------------------------------------------------#
def get_s3_conn(s3_url, user, pass, method)
EC2::Common::S3Support.new(s3_url, user, pass, method, @debug)
end
#------------------------------------------------------------------------------#
#
# Get parameters and display help or manual if necessary.
#
def upload_bundle(url,
bucket,
keyprefix,
user,
pass,
location,
manifest_file,
retry_stuff,
part,
directory,
acl,
skipmanifest)
begin
# Get the S3 URL.
s3_uri = URI.parse(url)
s3_url = uri2string(s3_uri)
v2_bucket = check_bucket_name(bucket)
s3_conn = get_s3_conn(s3_url, user, pass, (v2_bucket ? nil : :path))
# Get current location and bucket location.
bucket_location = get_bucket_location(s3_conn, bucket)
# Load manifest.
xml = File.open(manifest_file) { |f| f.read }
manifest = ManifestV20071010.new(xml)
# If in interactive mode, warn when bundling a kernel into our AMI and we are uploading cross-region
if interactive? and manifest.kernel_id and cross_region?(location, bucket_location)
warn_about_migrating()
end
# Create storage bucket if required.
create_bucket(s3_conn, bucket, bucket_location, location, retry_stuff)
# Upload AMI bundle parts.
$stdout.puts "Uploading bundled image parts to the S3 bucket #{bucket} ..."
get_part_info(manifest).each do |part_info|
if part.nil? or (part_info[1] >= part)
path = File.join(directory, part_info[0])
upload(s3_conn, bucket, keyprefix + part_info[0], path, acl, retry_stuff)
$stdout.puts "Uploaded #{part_info[0]}"
else
$stdout.puts "Skipping #{part_info[0]}"
end
end
# Encrypt and upload manifest.
unless skipmanifest
$stdout.puts "Uploading manifest ..."
upload(s3_conn, bucket, keyprefix + File::basename(manifest_file), manifest_file, acl, retry_stuff)
$stdout.puts "Uploaded manifest."
else
$stdout.puts "Skipping manifest."
end
$stdout.puts 'Bundle upload completed.'
rescue EC2::Common::HTTP::Error => e
$stderr.puts e.backtrace if @debug
raise S3Error.new(e.message)
end
end
#------------------------------------------------------------------------------#
# Overrides
#------------------------------------------------------------------------------#
def get_manual()
UPLOAD_BUNDLE_MANUAL
end
def get_name()
UPLOAD_BUNDLE_NAME
end
def main(p)
upload_bundle(p.url,
p.bucket,
p.keyprefix,
p.user,
p.pass,
p.location,
p.manifest,
p.retry,
p.part,
p.directory,
p.acl,
p.skipmanifest)
end
end
#------------------------------------------------------------------------------#
# Script entry point. Execute only if this file is being executed.
if __FILE__ == $0
BundleUploader.new().run(UploadBundleParameters)
end
| sujoyg/tool | vendor/ec2-ami-tools-1.3-66634/lib/ec2/amitools/uploadbundle.rb | Ruby | mit | 12,081 |
<?php
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
define('ROOT', realpath(__DIR__) . DS);
if (!file_exists($autoload = ROOT . 'vendor/autoload.php')) {
throw new RuntimeException('Dependencies not installed.');
}
require $autoload;
unset($autoload); | basekit/imanee | bootstrap.php | PHP | mit | 273 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("Lithogen.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lithogen.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f9b28de6-52cc-4634-8320-9bee3b84c97b")]
// 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")]
| PhilipDaniels/Lithogen | Lithogen/Lithogen.Core/Properties/AssemblyInfo.cs | C# | mit | 1,438 |
from __future__ import absolute_import
import json
from twisted.internet import defer, error
from twisted.python import failure
from twisted.test import proto_helpers
from twisted.trial import unittest
from txjsonrpc import jsonrpc, jsonrpclib
class TestJSONRPC(unittest.TestCase):
def setUp(self):
self.deferred = defer.Deferred()
exposed = {
"foo" : lambda : setattr(self, "fooFired", True),
"bar" : lambda p : setattr(self, "barResult", p ** 2),
"baz" : lambda p, q : (q, p),
"late" : lambda p : self.deferred,
}
self.factory = jsonrpc.JSONRPCFactory(exposed.get)
self.proto = self.factory.buildProtocol(("127.0.0.1", 0))
self.tr = proto_helpers.StringTransportWithDisconnection()
self.proto.makeConnection(self.tr)
def assertSent(self, expected):
expected["jsonrpc"] = "2.0"
self.assertEqual(json.loads(self.tr.value()[2:]), expected)
def test_notify(self):
"""
notify() sends a valid JSON RPC notification.
"""
self.proto.notify("foo")
self.assertSent({"method" : "foo", "params" : []})
self.tr.clear()
self.proto.notify("bar", [3])
self.assertSent({"method" : "bar", u"params" : [3]})
def test_request(self):
"""
request() sends a valid JSON RPC request and returns a deferred.
"""
d = self.proto.request("foo")
self.assertSent({"id" : "1", "method" : "foo", "params" : []})
d.addCallback(lambda r : self.assertEqual(r, [2, 3, "bar"]))
receive = {"jsonrpc" : "2.0", "id" : "1", "result" : [2, 3, "bar"]}
self.proto.stringReceived(json.dumps(receive))
return d
def test_unhandledError(self):
"""
An unhandled error gets logged and disconnects the transport.
"""
v = failure.Failure(ValueError("Hey a value error"))
self.proto.unhandledError(v)
errors = self.flushLoggedErrors(ValueError)
self.assertEqual(errors, [v])
def test_invalid_json(self):
"""
Invalid JSON causes a JSON RPC ParseError and disconnects.
"""
self.proto.stringReceived("[1,2,")
err = {"id" : None, "error" : jsonrpclib.ParseError().toResponse()}
self.assertSent(err)
errors = self.flushLoggedErrors(jsonrpclib.ParseError)
self.assertEqual(len(errors), 1)
def test_invalid_request(self):
"""
An invalid request causes a JSON RPC InvalidRequest and disconnects.
"""
self.proto.stringReceived(json.dumps({"id" : 12}))
err = jsonrpclib.InvalidRequest({"reason" : "jsonrpc"})
self.assertSent({"id" : None, "error" : err.toResponse()})
errors = self.flushLoggedErrors(jsonrpclib.InvalidRequest)
self.assertEqual(len(errors), 1)
def test_unsolicited_result(self):
"""
An incoming result for an id that does not exist raises an error.
"""
receive = {"jsonrpc" : "2.0", "id" : "1", "result" : [2, 3, "bar"]}
self.proto.stringReceived(json.dumps(receive))
err = jsonrpclib.InternalError({
"exception" : "KeyError", "message" : "u'1'",
})
expect = {"jsonrpc" : "2.0", "id" : None, "error" : err.toResponse()}
sent = json.loads(self.tr.value()[2:])
tb = sent["error"]["data"].pop("traceback")
self.assertEqual(sent, expect)
self.assertTrue(tb)
# TODO: Raises original exception. Do we want InternalError instead?
errors = self.flushLoggedErrors(KeyError)
self.assertEqual(len(errors), 1)
def _errorTest(self, err):
d = self.proto.request("foo").addErrback(lambda f : self.assertEqual(
f.value.toResponse(), err.toResponse()
))
receive = {"jsonrpc" : "2.0", "id" : "1", "error" : {}}
receive["error"] = {"code" : err.code, "message" : err.message}
self.proto.stringReceived(json.dumps(receive))
return d
def test_parse_error(self):
self._errorTest(jsonrpclib.ParseError())
def test_invalid_request(self):
self._errorTest(jsonrpclib.InvalidRequest())
def test_method_not_found(self):
self._errorTest(jsonrpclib.MethodNotFound())
def test_invalid_params(self):
self._errorTest(jsonrpclib.InvalidParams())
def test_internal_error(self):
self._errorTest(jsonrpclib.InternalError())
def test_application_error(self):
self._errorTest(jsonrpclib.ApplicationError(code=2400, message="Go."))
def test_server_error(self):
self._errorTest(jsonrpclib.ServerError(code=-32020))
def test_received_notify(self):
receive = {"jsonrpc" : "2.0", "method" : "foo"}
self.proto.stringReceived(json.dumps(receive))
self.assertTrue(self.fooFired)
receive = {"jsonrpc" : "2.0", "method" : "bar", "params" : [2]}
self.proto.stringReceived(json.dumps(receive))
self.assertEqual(self.barResult, 4)
def test_received_notify_no_method(self):
receive = {"jsonrpc" : "2.0", "method" : "quux"}
self.proto.stringReceived(json.dumps(receive))
errors = self.flushLoggedErrors(jsonrpclib.MethodNotFound)
self.assertEqual(len(errors), 1)
def test_received_notify_wrong_param_type(self):
receive = {"jsonrpc" : "2.0", "method" : "foo", "params" : [1, 2]}
self.proto.stringReceived(json.dumps(receive))
receive = {"jsonrpc" : "2.0", "method" : "bar", "params" : "foo"}
self.proto.stringReceived(json.dumps(receive))
errors = self.flushLoggedErrors(TypeError)
self.assertEqual(len(errors), 2)
def test_received_request(self):
receive = {
"jsonrpc" : "2.0", "id" : "1", "method" : "baz", "params" : [1, 2]
}
self.proto.stringReceived(json.dumps(receive))
self.assertSent({"jsonrpc" : "2.0", "id" : "1", "result" : [2, 1]})
def test_received_request_deferred(self):
receive = {
"jsonrpc" : "2.0", "id" : "3",
"method" : "late", "params" : {"p" : 3}
}
self.proto.stringReceived(json.dumps(receive))
self.deferred.callback(27)
self.assertSent({"jsonrpc" : "2.0", "id" : "3", "result" : 27})
def test_received_request_no_method(self):
receive = {"jsonrpc" : "2.0", "id" : "3", "method" : "quux"}
self.proto.stringReceived(json.dumps(receive))
errors = self.flushLoggedErrors(jsonrpclib.MethodNotFound)
self.assertEqual(len(errors), 1)
sent = json.loads(self.tr.value()[2:])
self.assertIn("error", sent)
self.assertEqual(sent["error"]["code"], jsonrpclib.MethodNotFound.code)
def test_received_request_error(self):
receive = {
"jsonrpc" : "2.0", "id" : "1", "method" : "foo", "params" : [1, 2]
}
self.proto.stringReceived(json.dumps(receive))
response = json.loads(self.tr.value()[2:])
self.assertNotIn("result", response)
self.assertEqual(response["id"], "1")
self.assertEqual(response["error"]["data"]["exception"], "TypeError")
self.assertTrue(response["error"]["data"]["traceback"])
errors = self.flushLoggedErrors(TypeError)
self.assertEqual(len(errors), 1)
errors = self.flushLoggedErrors(error.ConnectionLost)
self.assertEqual(len(errors), 1)
def test_fail_all(self):
d1, d2 = self.proto.request("foo"), self.proto.request("bar", [1, 2])
exc = failure.Failure(ValueError("A ValueError"))
self.proto.failAll(exc)
d3 = self.proto.request("baz", "foo")
for d in d1, d2, d3:
d.addErrback(lambda reason: self.assertIs(reason, exc))
def test_connection_lost(self):
self.proto.connectionLost(failure.Failure(error.ConnectionLost("Bye")))
return self.proto.request("foo").addErrback(
lambda f : self.assertIs(f.type, error.ConnectionLost)
)
| Julian/txjsonrpc-tcp | txjsonrpc/tests/test_jsonrpc.py | Python | mit | 8,101 |
import { exec } from "child_process"
import test from "tape"
import cliBin from "./utils/cliBin"
test("--watch error if no input files", (t) => {
exec(
`${ cliBin }/testBin --watch`,
(err, stdout, stderr) => {
t.ok(
err,
"should return an error when <input> or <output> are missing when " +
"`--watch` option passed"
)
t.ok(
stderr.includes("--watch requires"),
"should show an explanation when <input> or <output> are missing when" +
" `--watch` option passed"
)
t.end()
}
)
})
| MoOx/cli-for-files | src/__tests__/watcher.error-no-input.js | JavaScript | mit | 579 |
module Iibee
VERSION = "0.1.21"
end
| quantiguous/iibee | lib/iibee/version.rb | Ruby | mit | 38 |