repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Akagi201/learning-golang | src/misc/mysql/conn-pool.go | 1250 | //数据库连接池测试
// ab -c 100 -n 1000 'http://localhost:9090/pool'
// show processlist
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func init() {
db, _ = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8")
db.SetMaxOpenConns(2000)
db.SetMaxIdleConns(1000)
db.Ping()
}
func main() {
startHttpServer()
}
func startHttpServer() {
http.HandleFunc("/pool", pool)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func pool(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query("SELECT * FROM user limit 1")
defer rows.Close()
checkErr(err)
columns, _ := rows.Columns()
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for j := range values {
scanArgs[j] = &values[j]
}
record := make(map[string]string)
for rows.Next() {
//将行数据保存到record字典
err = rows.Scan(scanArgs...)
for i, col := range values {
if col != nil {
record[columns[i]] = string(col.([]byte))
}
}
}
fmt.Println(record)
fmt.Fprintln(w, "finish")
}
func checkErr(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}
| mit |
ikedam/gaetest | testutil/appengine_sdk.go | 3122 | // +build appengine
package testutil
import (
sdk_appengine "appengine"
"appengine_internal"
"fmt"
"io"
"net/http"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/aetest"
)
func (m *AppengineMock) mockInstance(inst aetest.Instance) aetest.Instance {
return &mockInstance{
base: inst,
mocker: m,
}
}
// implements sdk_appengine.Context
type internal_context_mock struct {
baseAppengineContext sdk_appengine.Context
baseContext context.Context
req *http.Request
mocker *AppengineMock
}
func (i *mockInstance) newRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
req, err := i.base.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
baseAppengineContext := appengine_internal.NewContext(req)
baseContext := appengine.NewContext(req)
ctx := &internal_context_mock{
baseAppengineContext: baseAppengineContext,
baseContext: i.mocker.MockContext(baseContext),
req: req,
mocker: i.mocker,
}
return req.WithContext(context.WithValue(
req.Context(),
appengine_internal.ContextKey,
ctx,
)), nil
}
func (c *internal_context_mock) Debugf(format string, args ...interface{}) {
c.mocker.logList = append(c.mocker.logList, logRecord{
level: LogLevelDebug,
message: fmt.Sprintf(format, args...),
})
c.baseAppengineContext.Debugf(format, args...)
}
func (c *internal_context_mock) Infof(format string, args ...interface{}) {
c.mocker.logList = append(c.mocker.logList, logRecord{
level: LogLevelInfo,
message: fmt.Sprintf(format, args...),
})
c.baseAppengineContext.Infof(format, args...)
}
func (c *internal_context_mock) Warningf(format string, args ...interface{}) {
c.mocker.logList = append(c.mocker.logList, logRecord{
level: LogLevelWarning,
message: fmt.Sprintf(format, args...),
})
c.baseAppengineContext.Warningf(format, args...)
}
func (c *internal_context_mock) Errorf(format string, args ...interface{}) {
c.mocker.logList = append(c.mocker.logList, logRecord{
level: LogLevelError,
message: fmt.Sprintf(format, args...),
})
c.baseAppengineContext.Errorf(format, args...)
}
func (c *internal_context_mock) Criticalf(format string, args ...interface{}) {
c.mocker.logList = append(c.mocker.logList, logRecord{
level: LogLevelCritical,
message: fmt.Sprintf(format, args...),
})
c.baseAppengineContext.Criticalf(format, args...)
}
func (c *internal_context_mock) Call(service, method string, in, out appengine_internal.ProtoMessage, opts *appengine_internal.CallOptions) error {
// return c.baseAppengineContext.Call(service, method, in, out, opts)
mocked := c.baseContext
cancel := func() {}
if opts != nil && opts.Timeout > 0 {
mocked, cancel = context.WithTimeout(mocked, opts.Timeout)
}
defer cancel()
return appengine.APICall(mocked, service, method, in, out)
}
func (c *internal_context_mock) FullyQualifiedAppID() string {
return c.baseAppengineContext.FullyQualifiedAppID()
}
func (c *internal_context_mock) Request() interface{} {
return c.req
}
| mit |
jhbruhn/communicat0r | public/javascripts/script.js | 357 | var socket = io.connect();
//
Sound.initialize();
var factor = (2 * Math.PI) / 44100.0;
var s = new Sound();
Microphone.initialize();
Microphone.onready(function() {
Microphone.enable();
Microphone.ondata(function(data) {
socket.emit('input', data);
});
});
socket.on('output', function (data) {
s.buffer(data.data);
s.play();
}); | mit |
Vanare/behat-cucumber-formatter | src/Node/ExampleRow.php | 924 | <?php
namespace Vanare\BehatCucumberJsonFormatter\Node;
class ExampleRow
{
/**
* @var array
*/
private $cells = [];
/**
* @var int
*/
private $line = 0;
/**
* @var string
*/
private $id = '';
/**
* @return array
*/
public function getCells()
{
return $this->cells;
}
/**
* @param array $cells
*/
public function setCells($cells)
{
$this->cells = $cells;
}
/**
* @return int
*/
public function getLine()
{
return $this->line;
}
/**
* @param int $line
*/
public function setLine($line)
{
$this->line = $line;
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param string $id
*/
public function setId($id)
{
$this->id = $id;
}
}
| mit |
vimeo/psalm | src/Psalm/Issue/UndefinedPropertyFetch.php | 153 | <?php
namespace Psalm\Issue;
class UndefinedPropertyFetch extends PropertyIssue
{
public const ERROR_LEVEL = 6;
public const SHORTCODE = 39;
}
| mit |
CodeKittey/lycheeJS | projects/cultivator/api/source/Main.js | 9795 |
lychee.define('tool.Main').requires([
'lychee.data.HTML',
'lychee.data.JSON',
'lychee.data.MD',
'tool.API'
]).includes([
'lychee.app.Main'
]).tags({
platform: 'html'
}).supports(function(lychee, global) {
if (global.location instanceof Object && typeof global.location.hash === 'string') {
if (typeof global.onhashchange !== 'undefined') {
return true;
}
}
return false;
}).exports(function(lychee, tool, global, attachments) {
var _API = tool.API;
var _API_CACHE = {};
var _SRC_CACHE = {};
var _DATA = {};
var _HTML = lychee.data.HTML;
var _JSON = lychee.data.JSON;
var _MD = lychee.data.MD;
/*
* HACKS BECAUSE FUCKING JAVASCRIPT IDIOTS
*/
(function(global) {
global.onhashchange = function() {
var elements = [].slice.call(document.querySelectorAll('article:nth-of-type(1) table a'));
var reference = global.location.hash.split('!')[1].split('#');
elements.forEach(function(element) {
element.classList.remove('active');
});
// Example: #!lychee.Debugger#methods-expose
// reference[0] = 'lychee.Debugger';
// reference[1] = 'methods-expose';
_DATA.reference[0] = reference[0];
_DATA.reference[1] = reference[1];
_render_view('api', reference[0], reference[1]);
};
})(global);
/*
* HELPERS
*/
var _load_documents = function() {
_DATA.api.forEach(function(path) {
var identifier = 'lychee.' + path.split('/').join('.');
if (path.substr(0, 4) === 'core') {
identifier = path === 'core/lychee' ? 'lychee' : 'lychee.' + path.split('/').pop();
}
var stuff = new Stuff('/libraries/lychee/api/' + path + '.md');
stuff.onload = function(result) {
_API_CACHE[identifier] = this.buffer;
};
stuff.load();
});
_DATA.src.filter(function(path) {
if (path.substr(0, 8) === 'platform') {
return path.substr(0, 13) === 'platform/html';
}
return true;
}).forEach(function(path) {
var identifier = 'lychee.' + path.split('/').join('.');
if (path.substr(0, 8) === 'platform') {
identifier = 'lychee.' + path.split('/').slice(2).join('.');
} else if (path.substr(0, 4) === 'core') {
identifier = path === 'core/lychee' ? 'lychee' : 'lychee.' + path.split('/').pop();
}
var stuff = new Stuff('/libraries/lychee/source/' + path + '.js?' + Date.now(), true);
stuff.onload = function(result) {
_SRC_CACHE[identifier] = this.buffer;
};
stuff.load();
});
};
var _walk_directory = function(files, node, path) {
if (node instanceof Array) {
if (node.indexOf('js') !== -1 || node.indexOf('md') !== -1) {
files.push(path);
}
} else if (node instanceof Object) {
Object.keys(node).forEach(function(child) {
_walk_directory(files, node[child], path + '/' + child);
});
}
};
var _package_definitions = function(json) {
var files = [];
if (json !== null) {
_walk_directory(files, json, '');
}
return files.map(function(value) {
return value.substr(1);
}).sort(function(a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
};
var _render_navi = function(data) {
var code = '';
var documented = data.api.map(function(path) {
if (path.substr(0, 4) === 'core') {
return path === 'core/lychee' ? 'lychee' : 'lychee.' + path.split('/').pop();
} else {
return 'lychee.' + path.split('/').join('.');
}
});
var definitions = data.src.map(function(path) {
if (path.substr(0, 8) === 'platform') {
return 'lychee.' + path.split('/').slice(2).join('.');
} else if (path.substr(0, 4) === 'core') {
return path === 'core/lychee' ? 'lychee' : 'lychee.' + path.split('/').pop();
} else {
return 'lychee.' + path.split('/').join('.');
}
}).unique().sort(function(a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
code += '<tr><td>';
code += '<ul class="select">';
code += definitions.filter(function(id) {
return documented.indexOf(id) !== -1;
}).map(function(id) {
return '<li><input type="radio" name="reference" value="' + id + '"><span>' + id + '</span></li>';
}).join('');
code += '</ul>';
code += '</td></tr>';
ui.render(code, 'article:nth-of-type(1) table');
ui.render('Definitions (' + documented.length + '/' + definitions.length + ')', 'article:nth-of-type(1) h3');
setTimeout(function() {
var elements = [].slice.call(document.querySelectorAll('article:nth-of-type(1) table a'));
var hash = (location.hash.split('!')[1] || 'lychee').split('#')[0];
var index = elements.map(function(element) {
return element.innerHTML;
}).indexOf(hash);
if (index !== -1) {
elements[index].classList.add('active');
}
}, 200);
};
var _render_view = function(view, identifier, reference) {
var code = '';
var markdown = _API_CACHE[identifier] || '';
var generated = new _API(identifier, _SRC_CACHE[identifier] || '').toMD();
if (view === 'code') {
markdown = _SRC_CACHE[identifier] || '';
}
if (markdown === '') {
if (view === 'api') {
code += '<article id="constructor">';
code += '<pre><code class="javascript">' + identifier + ';</code></pre>';
code += '<textarea>' + generated + '</textarea>';
code += '</article>';
ui.render(code, 'article:nth-of-type(2) div');
} else if (view === 'code') {
code += '<pre><code class="javascript">\n\nconsole.log(\'No source code available.\');\n\n</code></pre>';
ui.render(code, 'article:nth-of-type(2) div');
} else if (view === 'edit') {
code += '<article id="constructor">';
code += '<pre><code class="javascript">' + identifier + ';</code></pre>';
code += '<textarea>' + (markdown || generated) + '</textarea>';
code += '</article>';
ui.render(code, 'article:nth-of-type(2) div');
}
} else {
if (view === 'api') {
var seen = {
constructor: false,
events: false,
methods: false,
properties: false
};
code += _HTML.encode(_MD.decode(markdown));
ui.render(code, 'article:nth-of-type(2) div');
setTimeout(function() {
var element = global.document.querySelector('#' + reference);
if (element !== null) {
element.scrollIntoView({
block: 'start',
behaviour: 'smooth'
});
}
}, 200);
} else if (view === 'code') {
code += '<pre><code class="javascript">';
code += markdown;
code += '</pre></code>';
ui.render(code, 'article:nth-of-type(2) div');
} else if (view === 'edit') {
code += '<article id="constructor">';
code += '<pre><code class="javascript">' + identifier + ';</code></pre>';
code += '<textarea>' + (markdown || generated) + '</textarea>';
code += '</article>';
ui.render(code, 'article:nth-of-type(2) div');
}
setTimeout(function() {
var links = [].slice.call(global.document.querySelectorAll('a'));
if (links.length > 0) {
links.forEach(function(link) {
var hash = (global.location.hash.split('!')[1] || 'lychee').split('#')[0];
var href = link.getAttribute('href');
if (href.substr(0, 1) !== '#') {
href = '#!' + href;
} else {
href = '#!' + hash + href;
}
link.setAttribute('href', href);
});
}
var codes = [].slice.call(global.document.querySelectorAll('code'));
if (codes.length > 0) {
codes.forEach(function(code) {
hljs.highlightBlock(code);
});
}
}, 0);
}
};
/*
* IMPLEMENTATION
*/
var Class = function(data) {
var settings = lychee.extend({
client: null,
input: null,
jukebox: null,
renderer: null,
server: null,
viewport: {
fullscreen: false
}
}, data);
lychee.app.Main.call(this, settings);
/*
* INITIALIZATION
*/
this.bind('load', function(oncomplete) {
var config = new Config('/libraries/lychee/lychee.pkg');
var that = this;
config.onload = function(result) {
if (result === true) {
_DATA = {
api: _package_definitions(this.buffer.api.files || null),
src: _package_definitions(this.buffer.source.files || null),
reference: (location.hash.split('!')[1] || 'lychee').split('#'),
view: 'api'
};
oncomplete(true);
} else {
oncomplete(false);
}
};
config.load();
}, this);
this.bind('init', function() {
_render_navi(_DATA);
_load_documents();
setTimeout(function() {
_render_view('api', _DATA.reference[0], _DATA.reference[1] || null);
}, 1000);
}, this, true);
this.bind('api', function() {
_render_view('api', _DATA.reference[0], _DATA.reference[1] || null);
}, this);
this.bind('code', function() {
_render_view('code', _DATA.reference[0], _DATA.reference[1] || null);
}, this);
this.bind('edit', function() {
_render_view('edit', _DATA.reference[0], _DATA.reference[1] || null);
}, this);
this.bind('download', function() {
var id = _DATA.reference[0] || '';
var blob = _API_CACHE[id] || null;
if (blob === null) {
var textarea = document.querySelector('textarea');
if (textarea !== null) {
blob = _API_CACHE[id] = '\n' + textarea.value.trim() + '\n\n';
}
}
var filename = id.split('.').pop() + '.md';
var buffer = new Buffer(blob, 'utf8');
_API_CACHE[id] = blob;
ui.download(filename, buffer);
}, this);
this.bind('submit', function(id, settings) {
if (id === 'settings') {
var reference = settings.reference || null;
if (reference !== null) {
global.location.hash = '!' + reference;
}
}
}, this);
};
Class.prototype = {
};
return Class;
});
| mit |
fit2cloud/aliyun-api-java-wrapper | src/main/java/com/fit2cloud/aliyun/ecs/model/response/ListSecurityPermissionsResponse.java | 1561 | package com.fit2cloud.aliyun.ecs.model.response;
import com.fit2cloud.aliyun.Response;
import com.fit2cloud.aliyun.ecs.model.Permissions;
public class ListSecurityPermissionsResponse extends Response {
private String Description;
private Permissions Permissions;
private String SecurityGroupId;
private String SecurityGroupName;
private String RegionId;
private String VpcId;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Permissions getPermissions() {
return Permissions;
}
public void setPermissions(Permissions permissions) {
Permissions = permissions;
}
public String getSecurityGroupId() {
return SecurityGroupId;
}
public void setSecurityGroupId(String securityGroupId) {
SecurityGroupId = securityGroupId;
}
public String getSecurityGroupName() {
return SecurityGroupName;
}
public void setSecurityGroupName(String securityGroupName) {
SecurityGroupName = securityGroupName;
}
public String getRegionId() {
return RegionId;
}
public void setRegionId(String regionId) {
RegionId = regionId;
}
public String getVpcId() {
return VpcId;
}
public void setVpcId(String vpcId) {
VpcId = vpcId;
}
@Override
public String toString() {
return "ListSecurityPermissionsResponse [Description=" + Description
+ ", Permissions=" + Permissions + ", SecurityGroupId="
+ SecurityGroupId + ", SecurityGroupName=" + SecurityGroupName
+ ", RegionId=" + RegionId + ", VpcId=" + VpcId + "]";
}
}
| mit |
alphagov/govuk_admin_template | spec/layout/layout_spec.rb | 3728 | require "spec_helper"
describe "Layout" do
subject(:body) { page.body }
it "yields the specified content" do
visit "/"
expect(body).to include("app_title")
expect(body).to include("navbar_right")
expect(body).to include("navbar_item")
expect(body).to include("main_content")
expect(body).to include("footer_version")
expect(body).to include("footer_top")
expect(body).to include("body_start")
expect(body).to include("body_end")
expect(page).to have_title "page_title"
end
context "when no environment set" do
it "defaults to not showing any environment details" do
GovukAdminTemplate.environment_style = nil
visit "/"
expect(page).not_to have_selector(".environment-label")
expect(page).not_to have_selector(".environment-message")
expect(page.body).to match(/favicon-.*.png/)
end
end
context "when in a development environment" do
it "includes details about the current environment" do
GovukAdminTemplate.environment_style = "development"
visit "/"
expect(page).to have_selector(".environment-label", text: "Development")
expect(page).to have_selector(".environment-development")
expect(page.body).to match(/favicon-development-.*.png/)
end
end
context "when in a test environment" do
it "includes details about the current environment" do
GovukAdminTemplate.environment_style = "test"
visit "/"
expect(page.body).to match(/favicon-test-.*.png/)
end
end
it "renders a link to a custom home path" do
visit "/"
expect(page).to have_selector('a[href="/style-guide"]', text: "app_title")
end
it "renders a bootstrap header" do
visit "/"
within ".navbar" do
expect(page).to have_selector("a.navbar-brand", text: "app_title")
end
within "nav" do
expect(page).to have_selector("ul.navbar-nav li a", text: "navbar_item")
end
end
it "renders a content region from the application" do
visit "/"
within "main" do
expect(page).to have_selector("h1", text: "main_content")
end
end
it "renders a fixed width container by default" do
visit "/"
expect(page).to have_selector("body > section.container")
end
it "can render a full width page" do
visit "/full-width"
expect(page).to have_selector("body > section.container-fluid")
end
it "can render a custom navbar" do
visit "/navbar"
expect(body).not_to include("app_title")
expect(body).not_to include("navbar_right")
expect(body).not_to include("navbar_item")
expect(page).to have_selector("h1", text: "custom navbar")
end
it "renders a footer" do
visit "/"
within "footer" do
expect(page).to have_selector("a", text: "Crown Copyright")
end
end
it "does not include analytics in development" do
visit "/"
expect(page).to have_no_selector("script.analytics", visible: :hidden)
end
it "renders a flash" do
visit "/with-flashes"
expect(page).to have_content("I am an alert with type success")
expect(page).not_to have_content("I am some other flash")
end
describe "in production" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
allow(ENV).to receive(:fetch).with("GOVUK_APP_DOMAIN").and_return("root.gov.uk")
end
it "includes analytics" do
visit "/"
expect(page).to have_selector("script.analytics", visible: :hidden)
expect(page.body).to include("'root.gov.uk'")
end
it "can specify a custom pageview URL" do
visit "/custom-pageview-url"
expect(page.html).to include("GOVUKAdmin.trackPageview('/not-the-actual-url-the-user-navigated-to');")
end
end
end
| mit |
aizhar777/buch | resources/lang/ru/modules.php | 2309 | <?php
return [
'access_denied' => 'В доступе отказано. У вас нет разрешения на эту операцию!',
'breadcrumbs' => [
'dashboard' => 'Панель управления',
'users' => 'Пользователи',
'roles' => 'Группы пользователей',
'role' => 'Группа :Role',
'permissions' => 'Разрешения',
'permission' => 'Разрешение на :permission',
'profile' => 'Профиль',
'empty' => 'Пусто',
'trades' => 'Сделки',
],
'menu' => [
'context' => [
'add' => 'Добавить',
'create' => 'Создать',
'edit' => 'Редактировать',
'update' => 'Обновить',
'delete' => 'Удалить',
'close' => 'Закрыть',
'action' => 'Действия',
'back' => 'Назад',
],
'view' => [
"view" => 'Посмотреть',
'roles' => 'Посмотреть группы пользователей',
'permissions' => 'Посмотреть список разрешений',
],
'dropdown' => 'Выпадающее меню'
//'' => ''
],
'list' => 'Список',
'empty' => 'Пусто',
'printer' => [
'check' => 'Товарный чек',
'order' => 'Прих. Кассовый ордер',
'invoice' => 'Счет-фактура',
'certificate' => 'Акт вып. работ',
'portrait' => 'Книжная',
'landscape' => 'Альбомная',
//'' => '',
],
'no' => 'Нет',
'yes' => 'Да',
//'' => '',
'messages' => [
'access_denied' => 'В доступе отказано. У вас нет разрешения на эту операцию!',
'not_enough_rights_to_view' => 'У вас нет разрешения на эту операцию!',
],
'subdivision' => 'Подразделение',
'stock' => 'Склад',
'trade' => 'Сделка',
'trades' => 'Сделки',
'requisites' => 'Реквизиты',
'permissions' => 'Разрешения',
//'' => '',
]; | mit |
cthoret/personal-website | src/Clemac/PortfolioBundle/Entity/Achievement.php | 2552 | <?php
namespace Clemac\PortfolioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* achievement
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Clemac\PortfolioBundle\Entity\AchievementRepository")
*/
class Achievement
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="description", type="text")
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="imgae", type="string", length=255, nullable=true)
*/
private $imgae;
/**
* @var string
*
* @ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return achievement
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param string $description
* @return achievement
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set string
*
* @param string $imgae
* @return achievement
*/
public function setImage($imgae)
{
$this->imgae = $imgae;
return $this;
}
/**
* Get file
*
* @return string
*/
public function getImage()
{
return $this->imgae;
}
/**
* Get file
*
* @return string
*/
public function getWebPathImage()
{
return 'upload/' . $this->imgae;
}
/**
* Set url
*
* @param string $url
* @return achievement
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
}
| mit |
niieani/nandu | app/tests/Blipoteka/UserTest.php | 2657 | <?php
/**
* Blipoteka.pl
*
* LICENSE
*
* This source file is subject to the Simplified BSD License that is
* bundled with this package in the file docs/LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://blipoteka.pl/license
*
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Blipoteka
* @package Blipoteka_Tests
* @copyright Copyright (c) 2010-2011 Jakub Argasiński ([email protected])
* @license http://blipoteka.pl/license Simplified BSD License
*/
/**
* User entity test case
*
* @author Jakub Argasiński <[email protected]>
*
*/
class Blipoteka_UserTest extends PHPUnit_Framework_TestCase {
/**
* @var Blipoteka_User
*/
private $user;
/**
* Set up an example user with minimum information required
* @see PHPUnit_Framework_TestCase::setUp()
*/
protected function setUp() {
$this->user = new Blipoteka_User();
$this->user->city_id = 756135;
$this->user->password = 'password';
$this->user->name = 'user_' . Void_Util_Base62::encode(time());
$this->user->blip = 'blip_' . Void_Util_Base62::encode(time());
$this->user->email = $this->user->name . '@blipoteka.pl';
}
/**
* Test if e-mail validation works as expected
*/
public function testValidateEmail() {
try {
$this->user->email = 'invalid_email_address';
$this->user->save();
} catch (Doctrine_Validator_Exception $e) {
$this->assertEquals($this->user->getErrorStack()->count(), 1);
$this->assertEquals(count($this->user->getErrorStack()->get('email')), 1);
$this->assertStringEndsWith('nie jest poprawnym adresem e-mail', current($this->user->getErrorStack()->get('email')));
return;
}
$this->fail('Doctrine_Validator_Exception has not been raised.');
}
/**
* We expect account activation date to be greater than or equal to the account's creation date
* @expectedException Doctrine_Record_Exception
*/
public function testConstraintActivatedAtTimestamp() {
$activated_at = new Zend_Date($this->user->created_at);
$activated_at->subDay(1);
$this->user->activated_at = $activated_at->get(Zend_Date::W3C);
$this->user->save();
}
/**
* We expect user's logon date to be greater than or equal to the account's creation date
* @expectedException Doctrine_Record_Exception
*/
public function testConstraintLoggedAtTimestamp() {
$log_date = new Zend_Date($this->user->created_at);
$log_date->subDay(1);
$this->user->log_date = $log_date->get(Zend_Date::W3C);
$this->user->save();
}
} | mit |
lioneil/pluma | config/mimetypes.php | 2014 | <?php
return [
/**
*--------------------------------------------------------------------------
* Mime Types
*--------------------------------------------------------------------------
*
* An attempt to document most of the file formats used frequently on the
* web. This is by no means definitive nor accurate, so use at your own risk.
*
* This file, we don't know why it's here. We just left it here in fear of
* breaking something somewhere in the app.
*
*/
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
];
| mit |
northwesternapis/ruby-client | lib/northwestern-api.rb | 1136 | require 'net/http'
require 'uri'
require 'json'
module Northwestern
BASE_URL = 'https://api.asg.northwestern.edu/'
class << self
def terms(params={})
self.get('/terms', {})
end
def schools(params={})
self.get('/schools', {})
end
def terms(params={})
self.get('/terms', {})
end
def subjects(params={})
self.get('/subjects', params)
end
def courses(params={})
self.get('/courses', params)
end
def course_details(params={})
self.get('/courses/details', params)
end
def instructors(params={})
self.get('/instructors', params)
end
def rooms(params={})
self.get('/rooms', params)
end
def room_details(params={})
self.get('/rooms/details', params)
end
def get(path, params)
if defined? Northwestern::API_KEY
uri = URI(BASE_URL)
uri.path = path
uri.query = URI.encode_www_form(params.merge(
{ key: Northwestern::API_KEY }
))
JSON.parse(Net::HTTP.get(uri))
else
"Please set your API key (see readme)"
end
end
end
end
| mit |
QuantumFractal/Morinda | Morinda/Component/Component.cs | 223 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Morinda
{
/// <summary>
/// Base interface for Components
/// </summary>
interface Component
{
}
}
| mit |
innogames/gitlabhq | spec/controllers/registrations_controller_spec.rb | 19821 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe RegistrationsController do
include TermsHelper
before do
stub_application_setting(require_admin_approval_after_user_signup: false)
end
describe '#new' do
subject { get :new }
it 'renders new template and sets the resource variable' do
expect(subject).to render_template(:new)
expect(response).to have_gitlab_http_status(:ok)
expect(assigns(:resource)).to be_a(User)
end
end
describe '#create' do
let_it_be(:base_user_params) do
{ first_name: 'first', last_name: 'last', username: 'new_username', email: '[email protected]', password: 'Any_password' }
end
let_it_be(:user_params) { { user: base_user_params } }
let(:session_params) { {} }
subject { post(:create, params: user_params, session: session_params) }
context '`blocked_pending_approval` state' do
context 'when the `require_admin_approval_after_user_signup` setting is turned on' do
before do
stub_application_setting(require_admin_approval_after_user_signup: true)
end
it 'signs up the user in `blocked_pending_approval` state' do
subject
created_user = User.find_by(email: '[email protected]')
expect(created_user).to be_present
expect(created_user.blocked_pending_approval?).to eq(true)
end
it 'does not log in the user after sign up' do
subject
expect(controller.current_user).to be_nil
end
it 'shows flash message after signing up' do
subject
expect(response).to redirect_to(new_user_session_path(anchor: 'login-pane'))
expect(flash[:notice])
.to eq('You have signed up successfully. However, we could not sign you in because your account is awaiting approval from your GitLab administrator.')
end
it 'emails the access request to approvers' do
expect_next_instance_of(NotificationService) do |notification|
allow(notification).to receive(:new_instance_access_request).with(User.find_by(email: '[email protected]'))
end
subject
end
context 'email confirmation' do
context 'when `send_user_confirmation_email` is true' do
before do
stub_application_setting(send_user_confirmation_email: true)
end
it 'does not send a confirmation email' do
expect { subject }
.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
end
end
end
context 'audit events' do
context 'when not licensed' do
before do
stub_licensed_features(admin_audit_log: false)
end
it 'does not log any audit event' do
expect { subject }.not_to change(AuditEvent, :count)
end
end
end
end
context 'when the `require_admin_approval_after_user_signup` setting is turned off' do
it 'signs up the user in `active` state' do
subject
created_user = User.find_by(email: '[email protected]')
expect(created_user).to be_present
expect(created_user.active?).to eq(true)
end
it 'does not show any flash message after signing up' do
subject
expect(flash[:notice]).to be_nil
end
it 'does not email the approvers' do
expect(NotificationService).not_to receive(:new)
subject
end
context 'email confirmation' do
context 'when `send_user_confirmation_email` is true' do
before do
stub_application_setting(send_user_confirmation_email: true)
end
it 'sends a confirmation email' do
expect { subject }
.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
end
end
end
end
end
context 'email confirmation' do
context 'when send_user_confirmation_email is false' do
it 'signs the user in' do
stub_application_setting(send_user_confirmation_email: false)
expect { subject }.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).not_to be_nil
end
end
context 'when send_user_confirmation_email is true' do
before do
stub_application_setting(send_user_confirmation_email: true)
end
context 'when soft email confirmation is not enabled' do
before do
stub_feature_flags(soft_email_confirmation: false)
allow(User).to receive(:allow_unconfirmed_access_for).and_return 0
end
it 'does not authenticate the user and sends a confirmation email' do
expect { subject }.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).to be_nil
end
context 'when registration is triggered from an accepted invite' do
context 'when it is part of our invite email experiment', :experiment do
let_it_be(:member) { create(:project_member, :invited, invite_email: user_params.dig(:user, :email)) }
let(:originating_member_id) { member.id }
let(:session_params) do
{
invite_email: user_params.dig(:user, :email),
originating_member_id: originating_member_id
}
end
context 'when member exists from the session key value' do
it 'tracks the experiment' do
expect(experiment('members/invite_email')).to track(:accepted)
.with_context(actor: member)
.on_next_instance
subject
end
end
context 'when member does not exist from the session key value' do
let(:originating_member_id) { -1 }
it 'tracks the experiment' do
expect(experiment('members/invite_email')).not_to track(:accepted)
subject
end
end
end
context 'when it is part of our invite_signup_page_interaction experiment', :experiment do
let_it_be(:member) { create(:project_member, :invited, invite_email: user_params.dig(:user, :email)) }
let(:originating_member_id) { member.id }
let(:session_params) do
{
invite_email: user_params.dig(:user, :email),
originating_member_id: originating_member_id
}
end
context 'when member exists from the session key value' do
it 'tracks the experiment' do
expect(experiment(:invite_signup_page_interaction)).to track(:form_submission)
.with_context(actor: member)
.on_next_instance
subject
end
end
context 'when member does not exist from the session key value' do
let(:originating_member_id) { -1 }
it 'tracks the experiment' do
expect(experiment(:invite_signup_page_interaction)).not_to track(:form_submission)
subject
end
end
end
context 'when invite email matches email used on registration' do
let(:session_params) { { invite_email: user_params.dig(:user, :email) } }
it 'signs the user in without sending a confirmation email', :aggregate_failures do
expect { subject }.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).to be_confirmed
end
end
context 'when invite email does not match the email used on registration' do
let(:session_params) { { invite_email: '[email protected]' } }
it 'does not authenticate the user and sends a confirmation email', :aggregate_failures do
expect { subject }.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).to be_nil
end
end
end
end
context 'when soft email confirmation is enabled' do
before do
stub_feature_flags(soft_email_confirmation: true)
allow(User).to receive(:allow_unconfirmed_access_for).and_return 2.days
end
it 'authenticates the user and sends a confirmation email' do
expect { subject }.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).to be_present
expect(response).to redirect_to(users_sign_up_welcome_path)
end
context 'when invite email matches email used on registration' do
let(:session_params) { { invite_email: user_params.dig(:user, :email) } }
it 'signs the user in without sending a confirmation email', :aggregate_failures do
expect { subject }.not_to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).to be_confirmed
end
end
context 'when invite email does not match the email used on registration' do
let(:session_params) { { invite_email: '[email protected]' } }
it 'authenticates the user and sends a confirmation email without confirming', :aggregate_failures do
expect { subject }.to have_enqueued_mail(DeviseMailer, :confirmation_instructions)
expect(controller.current_user).not_to be_confirmed
end
end
end
end
context 'when signup_enabled? is false' do
it 'redirects to sign_in' do
stub_application_setting(signup_enabled: false)
expect { subject }.not_to change(User, :count)
expect(response).to redirect_to(new_user_session_path)
end
end
end
context 'when reCAPTCHA is enabled' do
before do
stub_application_setting(recaptcha_enabled: true)
end
after do
# Avoid test ordering issue and ensure `verify_recaptcha` returns true
unless Recaptcha.configuration.skip_verify_env.include?('test')
Recaptcha.configuration.skip_verify_env << 'test'
end
end
it 'displays an error when the reCAPTCHA is not solved' do
allow_any_instance_of(described_class).to receive(:verify_recaptcha).and_return(false)
subject
expect(response).to render_template(:new)
expect(flash[:alert]).to eq(_('There was an error with the reCAPTCHA. Please solve the reCAPTCHA again.'))
end
it 'redirects to the welcome page when the reCAPTCHA is solved' do
subject
expect(response).to redirect_to(users_sign_up_welcome_path)
end
end
context 'when invisible captcha is enabled' do
before do
stub_application_setting(invisible_captcha_enabled: true)
InvisibleCaptcha.timestamp_threshold = treshold
end
let(:treshold) { 4 }
let(:session_params) { { invisible_captcha_timestamp: form_rendered_time.iso8601 } }
let(:form_rendered_time) { Time.current }
let(:submit_time) { form_rendered_time + treshold }
let(:auth_log_attributes) do
{
message: auth_log_message,
env: :invisible_captcha_signup_bot_detected,
remote_ip: '0.0.0.0',
request_method: 'POST',
path: '/users'
}
end
describe 'the honeypot has not been filled and the signup form has not been submitted too quickly' do
it 'creates an account' do
travel_to(submit_time) do
expect { post(:create, params: user_params, session: session_params) }.to change(User, :count).by(1)
end
end
end
describe 'honeypot spam detection' do
let(:user_params) { super().merge(firstname: 'Roy', lastname: 'Batty') }
let(:auth_log_message) { 'Invisible_Captcha_Honeypot_Request' }
it 'logs the request, refuses to create an account and renders an empty body' do
travel_to(submit_time) do
expect(Gitlab::Metrics).to receive(:counter)
.with(:bot_blocked_by_invisible_captcha_honeypot, 'Counter of blocked sign up attempts with filled honeypot')
.and_call_original
expect(Gitlab::AuthLogger).to receive(:error).with(auth_log_attributes).once
expect { post(:create, params: user_params, session: session_params) }.not_to change(User, :count)
expect(response).to have_gitlab_http_status(:ok)
expect(response.body).to be_empty
end
end
end
describe 'timestamp spam detection' do
let(:auth_log_message) { 'Invisible_Captcha_Timestamp_Request' }
context 'the sign up form has been submitted without the invisible_captcha_timestamp parameter' do
let(:session_params) { nil }
it 'logs the request, refuses to create an account and displays a flash alert' do
travel_to(submit_time) do
expect(Gitlab::Metrics).to receive(:counter)
.with(:bot_blocked_by_invisible_captcha_timestamp, 'Counter of blocked sign up attempts with invalid timestamp')
.and_call_original
expect(Gitlab::AuthLogger).to receive(:error).with(auth_log_attributes).once
expect { post(:create, params: user_params, session: session_params) }.not_to change(User, :count)
expect(response).to redirect_to(new_user_session_path)
expect(flash[:alert]).to eq(I18n.t('invisible_captcha.timestamp_error_message'))
end
end
end
context 'the sign up form has been submitted too quickly' do
let(:submit_time) { form_rendered_time }
it 'logs the request, refuses to create an account and displays a flash alert' do
travel_to(submit_time) do
expect(Gitlab::Metrics).to receive(:counter)
.with(:bot_blocked_by_invisible_captcha_timestamp, 'Counter of blocked sign up attempts with invalid timestamp')
.and_call_original
expect(Gitlab::AuthLogger).to receive(:error).with(auth_log_attributes).once
expect { post(:create, params: user_params, session: session_params) }.not_to change(User, :count)
expect(response).to redirect_to(new_user_session_path)
expect(flash[:alert]).to eq(I18n.t('invisible_captcha.timestamp_error_message'))
end
end
end
end
end
context 'terms of service' do
context 'when terms are enforced' do
before do
enforce_terms
end
it 'creates the user with accepted terms' do
subject
expect(controller.current_user).to be_present
expect(controller.current_user.terms_accepted?).to be(true)
end
end
context 'when terms are not enforced' do
it 'creates the user without accepted terms' do
subject
expect(controller.current_user).to be_present
expect(controller.current_user.terms_accepted?).to be(false)
end
end
end
it "logs a 'User Created' message" do
expect(Gitlab::AppLogger).to receive(:info).with(/\AUser Created: username=new_username [email protected].+\z/).and_call_original
subject
end
it 'handles when params are new_user' do
post(:create, params: { new_user: base_user_params })
expect(controller.current_user).not_to be_nil
end
it 'sets name from first and last name' do
post :create, params: { new_user: base_user_params }
expect(User.last.first_name).to eq(base_user_params[:first_name])
expect(User.last.last_name).to eq(base_user_params[:last_name])
expect(User.last.name).to eq("#{base_user_params[:first_name]} #{base_user_params[:last_name]}")
end
it 'sets the username and caller_id in the context' do
expect(controller).to receive(:create).and_wrap_original do |m, *args|
m.call(*args)
expect(Gitlab::ApplicationContext.current)
.to include('meta.user' => base_user_params[:username],
'meta.caller_id' => 'RegistrationsController#create')
end
subject
end
end
describe '#destroy' do
let(:user) { create(:user) }
before do
sign_in(user)
end
def expect_failure(message)
expect(flash[:alert]).to eq(message)
expect(response).to have_gitlab_http_status(:see_other)
expect(response).to redirect_to profile_account_path
end
def expect_password_failure
expect_failure(s_('Profiles|Invalid password'))
end
def expect_username_failure
expect_failure(s_('Profiles|Invalid username'))
end
def expect_success
expect(flash[:notice]).to eq s_('Profiles|Account scheduled for removal.')
expect(response).to have_gitlab_http_status(:see_other)
expect(response).to redirect_to new_user_session_path
end
context 'user requires password confirmation' do
it 'fails if password confirmation is not provided' do
post :destroy
expect_password_failure
end
it 'fails if password confirmation is wrong' do
post :destroy, params: { password: 'wrong password' }
expect_password_failure
end
it 'succeeds if password is confirmed' do
post :destroy, params: { password: '12345678' }
expect_success
end
end
context 'user does not require password confirmation' do
before do
stub_application_setting(password_authentication_enabled_for_web: false)
stub_application_setting(password_authentication_enabled_for_git: false)
end
it 'fails if username confirmation is not provided' do
post :destroy
expect_username_failure
end
it 'fails if username confirmation is wrong' do
post :destroy, params: { username: 'wrong username' }
expect_username_failure
end
it 'succeeds if username is confirmed' do
post :destroy, params: { username: user.username }
expect_success
end
end
context 'prerequisites for account deletion' do
context 'solo-owned groups' do
let(:group) { create(:group) }
context 'if the user is the sole owner of at least one group' do
before do
create(:group_member, :owner, group: group, user: user)
end
it 'fails' do
delete :destroy, params: { password: '12345678' }
expect_failure(s_('Profiles|You must transfer ownership or delete groups you are an owner of before you can delete your account'))
end
end
end
end
it 'sets the username and caller_id in the context' do
expect(controller).to receive(:destroy).and_wrap_original do |m, *args|
m.call(*args)
expect(Gitlab::ApplicationContext.current)
.to include('meta.user' => user.username,
'meta.caller_id' => 'RegistrationsController#destroy')
end
post :destroy
end
end
end
| mit |
CountrySideEngineer/Ev3Controller | dev/src/Ev3Controller/Ev3Command/Command_30.cs | 917 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ev3Controller.Ev3Command
{
public abstract class Command_30 : ACommand_ResLenFlex
{
#region Constructors and the Finalizer
/// <summary>
/// Constructor
/// </summary>
/// <param name="CommandParam"></param>
public Command_30(ICommandParam CommandParam) : base(CommandParam) { }
#endregion
#region Other methods and private properties in calling order
/// <summary>
/// Initialize command and response code, and its command name.
/// </summary>
protected override void Init()
{
this.Name = "GetColorSensor";
this.Cmd = 0x30;
this.Res = 0x31;
base.Init();
}
#endregion
}
}
| mit |
havoc-io/mutagen | cmd/mutagen/compose/port.go | 1380 | package compose
import (
"github.com/spf13/cobra"
)
// portCommand is the port command.
var portCommand = &cobra.Command{
Use: "port",
Run: passthrough,
SilenceUsage: true,
DisableFlagParsing: true,
}
// portConfiguration stores configuration for the port command.
var portConfiguration struct {
// help indicates the presence of the -h/--help flag.
help bool
// protocol stores the value of the --protocol flag.
protocol string
// index stores the value of the --index flag.
index string
}
func init() {
// We don't set an explicit help function since we disable flag parsing for
// this command and simply pass arguments directly through to the underlying
// command. We still explicitly register a -h/--help flag below for shell
// completion support.
// Grab a handle for the command line flags.
flags := portCommand.Flags()
// Wire up flags. We don't bother specifying usage information since we'll
// shell out to Docker Compose if we need to display help information. In
// the case of this command, we also disable flag parsing and shell out
// directly, so we only register these flags to support shell completion.
flags.BoolVarP(&portConfiguration.help, "help", "h", false, "")
flags.StringVar(&portConfiguration.protocol, "protocol", "", "")
flags.StringVar(&portConfiguration.index, "index", "", "")
}
| mit |
kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/SoapPayClass.java | 4910 |
package ru.lanbilling.webservice.wsdl;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for soapPayClass complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="soapPayClass">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="classid" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="descr" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="externcode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "soapPayClass", propOrder = {
"classid",
"name",
"descr",
"externcode"
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class SoapPayClass {
@XmlElement(defaultValue = "-1")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected Long classid;
@XmlElement(defaultValue = "")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected String name;
@XmlElement(defaultValue = "")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected String descr;
@XmlElement(defaultValue = "")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected String externcode;
/**
* Gets the value of the classid property.
*
* @return
* possible object is
* {@link Long }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public Long getClassid() {
return classid;
}
/**
* Sets the value of the classid property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setClassid(Long value) {
this.classid = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the descr property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public String getDescr() {
return descr;
}
/**
* Sets the value of the descr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setDescr(String value) {
this.descr = value;
}
/**
* Gets the value of the externcode property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public String getExterncode() {
return externcode;
}
/**
* Sets the value of the externcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setExterncode(String value) {
this.externcode = value;
}
}
| mit |
screeny05/corrode | test/corrode-helper.test.js | 1434 | const { expect } = require('chai');
const Corrode = require('../src');
/** @test {Corrode} */
describe('Corrode - Helpers', () => {
beforeEach(function(){
this.base = new Corrode();
this.eqArray = require('./helpers/asserts').eqArray.bind(this);
});
/**
* coverage fix
* @test {Corrode#debug}
*/
it('debugs', function(done){
let output = [];
const orgConsoleLog = console.log;
console.log = (...strings) => output = strings;
this.base
.loop('array', function(end, discard, i){
this
.uint8('values')
.map.push();
})
.debug();
this.eqArray([3, 5, 7], function(){
expect(output).to.deep.equal([
'{ array: [ 3, 5, 7 ] }'
]);
console.log = orgConsoleLog;
done();
}, {
array: [3, 5, 7],
});
});
/** @test {Corrode#fromBuffer} */
it('converts from buffer', function(){
this.base
.loop('array', function(end, discard, i){
this
.uint8('values')
.map.push();
})
.fromBuffer(Buffer.from([0, 1, 2, 3, 4, 5]), vars => {
expect(vars).to.deep.equal({
array: [0, 1, 2, 3, 4, 5]
});
});
});
});
| mit |
Mj258/weiboapi | anjularjsdemo/demo/show-properties.ts | 277 | // TypeScript
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
selector: 'display'
})
@View({
template: `
<p>My name: {{ myName }}</p>
`
})
class DisplayComponent {
myName: string;
constructor() {
this.myName = "Alice";
}
} | mit |
wp-plugins/nokautwl | src/NokautWL/Routing/ProductsUrl.php | 3031 | <?php
namespace NokautWL\Routing;
use Nokaut\ApiKit\Ext\Data;
use NokautWL\Admin\Options;
class ProductsUrl
{
/**
* @var string
*/
private static $baseUrl;
/**
* @var string
*/
private static $defaultProductsQuery;
/**
* @return string
*/
private static function getBaseUrl()
{
if (!self::$baseUrl) {
self::$baseUrl = Routing::getBaseUrl();
}
return self::$baseUrl;
}
/**
* @return string
*/
private static function getDefaultProductQuery()
{
if (!self::$defaultProductsQuery) {
self::$defaultProductsQuery = Routing::getDefaultProductQuery();
}
return self::$defaultProductsQuery;
}
/**
* @param string $nokautProductsUrl
* @return string
*/
public static function productsUrl($nokautProductsUrl)
{
// usuwanie domyslnych dla kategorii wordpress kategorii nokaut w url
$nokautProductsUrl = preg_replace('/' . preg_quote(self::getDefaultProductQuery(), '/') . '/', '', $nokautProductsUrl);
$productsUrl = self::getBaseUrl() . ltrim($nokautProductsUrl, '/');
if (isset($_GET[ProductsView::VIEW_KEYWORD])) {
$productsUrl .= '?' . ProductsView::VIEW_KEYWORD . '=' . $_GET[ProductsView::VIEW_KEYWORD];
}
return $productsUrl;
}
/**
* @param $nokautProductUrl
* @return string
*/
public static function productUrl($nokautProductUrl)
{
return '/' . Options::getOption(Options::OPTION_URL_PART_PRODUCT_PAGE) . '/' . $nokautProductUrl.'.html';
}
/**
* @param Data\Collection\Filters\Categories $filtersCategories
* @return bool
*/
public static function showProductsCategoryFacet(Data\Collection\Filters\Categories $filtersCategories)
{
if (count(Routing::getNokautCategoryIds()) == 1
&& count($filtersCategories) == 1
&& current(Routing::getNokautCategoryIds()) == $filtersCategories->getLast()->getId()
) {
return false;
}
return true;
}
/**
* @param \Nokaut\ApiKit\Ext\Data\Collection\Filters\Categories $filtersSelectedCategories
* @return bool
*/
public static function showProductsCategoryFilter(Data\Collection\Filters\Categories $filtersSelectedCategories)
{
if (count(Routing::getNokautCategoryIds()) == 1
&& count($filtersSelectedCategories) == 1
&& current(Routing::getNokautCategoryIds()) == $filtersSelectedCategories->getLast()->getId()
) {
return false;
}
if (count(Routing::getNokautCategoryIds()) > 1
and count(Routing::getNokautCategoryIds()) == count($filtersSelectedCategories)
) {
return false;
}
foreach ($filtersSelectedCategories as $filter) {
if (!$filter->getTotal()) {
return false;
}
}
return true;
}
} | mit |
noelrappin/summer_breeze | lib/summer_breeze/fixture.rb | 3416 | module SummerBreeze
class Fixture
extend SummerBreeze::BeforeAndAfter
attr_accessor :name, :controller, :initializers, :controller_class, :action,
:method, :limit_to_selector, :params, :session, :flash, :filename
def initialize(name, controller, &initialize_block)
@name = name
@filename = name
@controller = controller
@params = {}
@session = {}
@flash = {}
@method = "GET"
@initializers = []
instance_eval(&initialize_block) if block_given?
parse_name
self
end
def parse_name
return if action.present?
result = name.match(/(.*)((\.|#).*)/)
if result
self.action = result[1]
self.limit_to_selector = result[2]
else
self.action = name
end
end
def initialize_with(symbol_or_proc)
self.initializers << symbol_or_proc
end
[:controller_class, :action, :method, :limit_to_selector, :params, :session, :flash, :filename].each do |sym|
define_method(sym) do |new_value = :no_op, &block|
unless new_value == :no_op
send(:"#{sym}=", new_value)
return
end
if new_value == :no_op && block.present?
send(:"#{sym}=", block)
return
end
result = instance_variable_get("@#{sym}")
if result.is_a?(Proc)
return result.call
else
return result
end
end
end
def run_initializers
initializers.each do |initializer|
proc = initializer
if initializer.is_a?(Symbol)
proc = controller.container.initializers[initializer]
end
#note, should the actual run have it's own context?
controller.instance_eval(&proc) if proc
end
end
def call_controller
controller.process(action, params, session, flash, method)
end
def run
controller.reset
Controller.run_befores(self.controller)
Fixture.run_befores(self)
run_initializers
call_controller
save_response
Fixture.run_afters(self)
Controller.run_afters(self.controller)
end
def fixture_path
path = File.join(::Rails.root, 'tmp', 'summer_breeze')
Dir.mkdir(path) unless File.exists?(path)
path
end
def fixture_file
File.join(fixture_path, "#{filename}.html")
end
def html_document
@html_document ||= Nokogiri::HTML(response_body)
end
def scrub_html_document
remove_third_party_scripts(html_documen)
convert_body_tag_to_div
end
def remove_third_party_scripts(doc)
scripts = doc.at('#third-party-scripts')
scripts.remove if scripts
doc
end
def save_response
File.open(fixture_file, 'w') do |f|
f << scrubbed_response
end
end
def response_body
@response_body ||= controller.controller.response.body
end
def scrubbed_response
result = html_document
result = remove_third_party_scripts(result)
if limit_to_selector.present?
result = result.css(limit_to_selector).first.to_s
else
result = result.to_s
end
convert_body_tag_to_div(result)
end
def convert_body_tag_to_div(markup)
markup.gsub("<body", '<div').gsub("</body>", "</div>")
end
end
end | mit |
knub/skypyblue | tests/testrunner.py | 749 | #!/usr/bin/env python3
"""
Usage:
./testrunner.py -> executes all tests
./testrunner.py <TestCaseClass> -> executes only tests from this testcase
"""
if __name__ != "__main__": exit()
import unittest, sys
sys.path.append("../src")
sys.path.append("./performance")
from constraint_system_tests import *
from variable_tests import *
from helper_method_tests import *
from mvine_tests import *
from exec_tests import *
from midpoint_tests import *
from extended_midpoint_tests import *
from update_method_graph_tests import *
from constraint_tests import *
from constraint_factory_tests import *
from cycle_tests import *
from chain_tests import *
# from benchmark import *
# run_benchmark([2, 0, 50])
unittest.main()
| mit |
bricooke/my-biz-expenses | vendor/gems/currency-0.4.0/lib/currency/exchange/rate/source/historical.rb | 1823 | # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com>
# See LICENSE.txt for details.
require 'currency/exchange/rate/source/base'
# Gets historical rates from database using Active::Record.
# Rates are retrieved using Currency::Exchange::Rate::Source::Historical::Rate as
# a database proxy.
#
# See Currency::Exchange::Rate::Source::Historical::Writer for a rate archiver.
#
class Currency::Exchange::Rate::Source::Historical < Currency::Exchange::Rate::Source::Base
# Select specific rate source.
# Defaults to nil
attr_accessor :source
def initialize
@source = nil # any
super
end
def source_key
@source ? @source.join(',') : ''
end
# This Exchange's name is the same as its #uri.
def name
"historical #{source_key}"
end
def initialize(*opt)
super
@rates_cache = { }
@raw_rates_cache = { }
end
def clear_rates
@rates_cache.clear
@raw_rates_cache.clear
super
end
# Returns a Rate.
def get_rate(c1, c2, time)
# rate =
get_rates(time).select{ | r | r.c1 == c1 && r.c2 == c2 }[0]
# $stderr.puts "#{self}.get_rate(#{c1}, #{c2}, #{time.inspect}) => #{rate.inspect}"
# rate
end
# Return a list of base Rates.
def get_rates(time = nil)
@rates_cache["#{source_key}:#{time}"] ||=
get_raw_rates(time).collect do | rr |
rr.to_rate
end
end
# Return a list of raw rates.
def get_raw_rates(time = nil)
@raw_rates_cache["#{source_key}:#{time}"] ||=
::Currency::Exchange::Rate::Source::Historical::Rate.new(:c1 => nil, :c2 => nil, :date => time, :source => source).
find_matching_this(:all)
end
end # class
require 'currency/exchange/rate/source/historical/rate'
| mit |
dtiarks/ThesisPlot | Chap5/pi_phase_shift_estimate.py | 5855 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 13 11:25:42 2017
@author: daniel
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import json
import io
from scipy.optimize import newton
from scipy import integrate
from scipy.optimize import curve_fit
import re
c = 299792458 # m/s, speed of light CODATA 2014
a0 = 0.52917721067e-10 # m, Bohr radius
C6 = 2.3e23 * 4.36e-18 * a0**6 # Jm^6, Van-der-Waals coefficient for the 67s - 69s
hbar = 6.626070040e-34/(2 * np.pi) # Js, Planck constant, CODATA 2014
rho_peak = 1.8e12/1e-6 # peak density in cm^-3/centi^-3
d = 2.534e-29 # Cm, dipole matrix element (D. A. Steck)
Gamma_e = 2*np.pi * 6.065e6 # decay rate (D. A. Steck)
epsilon_0 = 8.854187817e-12 # dielectric constant, CODATA 2014
L = 61e-6 # medium length in m
omega_s = 2*np.pi * 384.23e12 # rad/s, transition frequency
gamma_21 = 2.2/(2*np.pi)
chi_0 = 2*rho_peak*d**2 / (epsilon_0*hbar*Gamma_e) # prefactor of the susceptibility for the cycling transition (|R> polarization)
#R_b=18e-6
def fitFunc(t, A, phi,C):
return A*np.sin(2*np.pi*20*t+phi)+C
def susceptibility(Delta_s, Delta_c, gamma_21, Omega_c, ladder=True):
delta = (Delta_s + (-1 + 2*int(ladder)) * Delta_c)
return 1j*(gamma_21 - 2j * delta)/(np.abs(Omega_c)**2 + (1 - 2j * Delta_s)*(gamma_21 - 2j * delta))
def susceptibility_off(Delta_s, Delta_c, gamma_21, Omega_c, ladder=True):
return -1/(2*Delta_s+1j)
def vdW_pot(r, r0):
return -C6 * (r-r0)**-6
def cond_phase(d_c,om_c,d_o):
im_chi_vdw = lambda x,y: omega_s/(c)*np.imag(susceptibility(y, d_c - vdW_pot(x, 1e-10)/(hbar*Gamma_e), gamma_21, om_c))
od_vdw = lambda x: integrate.quad(im_chi_vdw, -L/2, L/2,args=(x,))[0]
intersection = newton(lambda x: L*omega_s/(c)*np.imag(susceptibility(x, d_c, gamma_21, om_c) - susceptibility(x, d_c, gamma_21, 0))-d_o, -d_c)
# intersection = newton(lambda x: L*omega_s/(c)*np.imag(susceptibility(x, d_c, gamma_21, om_c)) - od_vdw(x)-d_o, -d_c)
chi_nb = susceptibility(intersection, d_c, gamma_21, om_c)
phi_0=omega_s/(2*c) * L * chi_0 * np.real(chi_nb)
r_chi_vdw = lambda x: np.real(susceptibility(intersection, d_c - vdW_pot(x, 1e-10)/(hbar*Gamma_e), gamma_21, om_c))
phi_1=omega_s/(2*c) * chi_0 *integrate.quad(r_chi_vdw, -L/2, L/2)[0]
d_phi=phi_1-phi_0
return intersection,d_phi
def cond_trans(d_c,om_c,d_o):
intersection = newton(lambda x: L*omega_s/(c)*np.imag(susceptibility(x, d_c, gamma_21, om_c) - susceptibility(x, d_c, gamma_21, 0))-d_o, -d_c)
im_chi_vdw = lambda x: np.imag(susceptibility(intersection, d_c - vdW_pot(x, 1e-10)/(hbar*Gamma_e), gamma_21, om_c))
t_1=omega_s/c * chi_0 *integrate.quad(im_chi_vdw, -L/2, L/2)[0]
return intersection,np.exp(-t_1)
# the parameters, all in units of Gamma_3
Delta_c = 2*np.pi*9.2*10**6/Gamma_e
Delta_s = -2*np.pi*10.*10**6/Gamma_e
ds_off = 2*np.pi*0.0*10**6/Gamma_e
Omega_c = 2*np.pi*10.4*10**6/Gamma_e
#Ga=Omega_c**2/(4*np.abs(Delta_s))
Ga=np.true_divide(Omega_c**2*np.abs(Delta_s),1+np.sqrt((4*np.abs(Delta_s)**2+1)**2-4*np.abs(Delta_s)**2*1))
R_b=1.0*(C6/(hbar*Gamma_e)/Ga)**(1./6.)
print("Blockade Radius: %.2f um"%(R_b*1e6))
od_new = lambda x: omega_s/c*chi_0*L*np.imag(susceptibility(x-ds_off, Delta_c , gamma_21, Omega_c))
ph_new = lambda x: 0.5*omega_s/c*chi_0*L*np.real(susceptibility(x-ds_off, Delta_c , gamma_21, Omega_c))-0.5*omega_s/c*chi_0*L/15.*np.real(susceptibility(x, Delta_c , gamma_21, Omega_c))
#od0_new = lambda x: 0.7*omega_s/(c)* L*chi_0*np.imag(susceptibility(x-ds_off, Delta_c , gamma_21, 0*Omega_c))
od0_new = lambda x: omega_s/c*chi_0*L*np.imag(susceptibility_off(x-0*ds_off, Delta_c , gamma_21, 0*Omega_c))
ph0_new = lambda x: 0.5*omega_s/c*chi_0*L*np.real(susceptibility_off(x-0*ds_off, Delta_c , gamma_21, 0*Omega_c))-0.5*omega_s/c*chi_0*L/15.*np.real(susceptibility_off(x, Delta_c , gamma_21, 0*Omega_c))
od_max=omega_s/c*chi_0*L
print("gamma_21: %.2f"%gamma_21)
print("est. od_max: %.2f"%od_max)
od_max=26.3
chi_nb = susceptibility(Delta_s, Delta_c, gamma_21, Omega_c)
phi_0=0.5*od_max*np.real(chi_nb)
r_chi_vdw = lambda x: np.real(susceptibility(Delta_s, Delta_c - vdW_pot(x, 1e-10)/(hbar*Gamma_e), gamma_21, Omega_c))
phi_1=0.5*od_max*integrate.quad(r_chi_vdw, -L/2, L/2)[0]/L
D_phi_blockaded=phi_1-phi_0
#D_phi=ph_new(Delta_s)-ph0_new(Delta_s)
#D_phi_blockaded = D_phi*2*R_b/L
print("Expected cond. phase shift: %.3f rad"%D_phi_blockaded)
#R_b=15e-6
print("Simple cond. phase shift: %.3f rad"%(6.6*2*R_b/L))
#fig=plt.figure(1, figsize=(8, 9), dpi=80,)
#fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.2)
#
#ax0 = fig.add_subplot(211)
#ax0.clear()
#ds=np.linspace(4,16,num=n)
#dsf=np.linspace(4,16,num=len(freqFitO))
##dsf2=np.linspace(4,16,num=len(freqFitO))
#ax0.plot(ds,2*np.log(aRef[:,0]/a[:,0]),'ro',label="$\Omega_c=$???")
#ax0.plot(ds,2*np.log(aRef[:,1]/a[:,1]),'bo',label="$\Omega_c=$0")
##ax0.plot(dsf,OfitOff,"b")
##ax0.plot(dsf,OfitOn,"r")
#
#ax0.plot(freqFitP,OfitOff,"b")
#ax0.plot(freqFitP,OfitOn,"r")
#ax0.plot(dsf,od_new(dsf*1e6*2*np.pi/Gamma_e),"g")
#ax0.plot(dsf,od0_new(dsf*1e6*2*np.pi/Gamma_e),"k")
#
#ax0.tick_params(axis="x",which="both",labelbottom="off")
#ax0.set_ylabel("OD")
#trans = ax0.get_xaxis_transform() # x in data untis, y in axes fraction
#ax0.annotate('(a)', xy=(4.3,0.9 ), xycoords=trans)
#
#
#ax1 = fig.add_subplot(212)
#ax1.clear()
#
#
#dsf=np.linspace(4,16,num=len(freqFitP))
#ax1.plot(ds,(p[:,0]-pRef[:,0]),'ro',label="control on")
#ax1.plot(ds,(p[:,1]-pRef[:,1]),'bo',label="control off")
##ax1.plot(dsf,pfitOff,"b")
##ax1.plot(dsf,pfitOn,"r")
#
#ax1.plot(freqFitP,pfitOff,"b")
#ax1.plot(freqFitP,pfitOn,"r")
#ax1.plot(dsf,ph_new(dsf*1e6*2*np.pi/Gamma_e)+0*phase_offset,"g")
#ax1.plot(dsf,ph0_new(dsf*1e6*2*np.pi/Gamma_e)+0*phase_offset,"k")
#
#plt.show()
| mit |
kkolodziejczak/Archivist | Documentation/html/search/functions_d.js | 2550 | var searchData=
[
['save',['Save',['../class_archivist_1_1_storage.html#ab2b3fd85dcd58550b561abf0067a7640',1,'Archivist::Storage']]],
['savesettings',['SaveSettings',['../class_archivist_1_1_settings_view_model.html#a5cb9a0b51d9af637d1a22c9abb426496',1,'Archivist::SettingsViewModel']]],
['selectprojectclick',['SelectProjectClick',['../class_archivist_1_1_projects_view_model.html#a0ec1919f3c348116253935edc5a031aa',1,'Archivist::ProjectsViewModel']]],
['setdefault',['SetDefault',['../class_archivist_1_1_settings_view_model.html#a6a57846d68ba0f21be3f0e18412621df',1,'Archivist::SettingsViewModel']]],
['setdefaultsettings',['SetDefaultSettings',['../class_archivist_1_1_storage.html#a2d59f337f0b8d67688dbec4b58d0e193',1,'Archivist::Storage']]],
['setpropertyvalue',['SetPropertyValue',['../class_xaml_generated_namespace_1_1_generated_internal_type_helper.html#ade0f04c0f7b18dd5b170e071d5534d38',1,'XamlGeneratedNamespace.GeneratedInternalTypeHelper.SetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, object value, System.Globalization.CultureInfo culture)'],['../class_xaml_generated_namespace_1_1_generated_internal_type_helper.html#ade0f04c0f7b18dd5b170e071d5534d38',1,'XamlGeneratedNamespace.GeneratedInternalTypeHelper.SetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, object value, System.Globalization.CultureInfo culture)']]],
['settingsviewmodel',['SettingsViewModel',['../class_archivist_1_1_settings_view_model.html#a07d0833bd854041d02604db550f44b39',1,'Archivist::SettingsViewModel']]],
['setvalue',['SetValue',['../class_archivist_1_1_base_attached_property.html#aa32cfdc7f7fdaae6afe5a061c057a95d',1,'Archivist::BaseAttachedProperty']]],
['show',['Show',['../class_archivist_1_1_message_box.html#a2407b1bf50a877c08f8777cb1cefd790',1,'Archivist.MessageBox.Show(string message, string title)'],['../class_archivist_1_1_message_box.html#a9ca0ffd80c42b234699eb5a043fec951',1,'Archivist.MessageBox.Show(string message, string title, MessageBoxType type)']]],
['swapeditedprojectinformation',['SwapEditedProjectInformation',['../class_archivist_1_1_projects_view_model.html#a2a6d85a6dafe85f674b4f58118656093',1,'Archivist::ProjectsViewModel']]],
['switchkey',['SwitchKey',['../class_archivist_1_1_keyboard_shortcut_manager.html#a691433b6bf65894d943995d259a2e3a3',1,'Archivist::KeyboardShortcutManager']]],
['switchpage',['SwitchPage',['../class_archivist_1_1_main_window_view_model.html#a10c5e83d7aa5db0e1cb36065a72dd676',1,'Archivist::MainWindowViewModel']]]
];
| mit |
nationalfield/symfony | lib/plugins/sfPropelPlugin/lib/vendor/phing/types/selectors/OrSelector.php | 2553 | <?php
/*
* $Id: OrSelector.php 123 2006-09-14 20:19:08Z mrook $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/types/selectors/BaseSelectorContainer.php';
/**
* This selector has a collection of other selectors, any of which have to
* select a file in order for this selector to select it.
*
* @author Hans Lellelid <[email protected]> (Phing)
* @author Bruce Atherton <[email protected]> (Ant)
* @package phing.types.selectors
*/
class OrSelector extends BaseSelectorContainer {
public function toString() {
$buf = "";
if ($this->hasSelectors()) {
$buf .= "{orselect: ";
$buf .= parent::toString();
$buf .= "}";
}
return $buf;
}
/**
* Returns true (the file is selected) if any of the other selectors
* agree that the file should be selected.
*
* @param basedir the base directory the scan is being done from
* @param filename the name of the file to check
* @param file a PhingFile object for the filename that the selector
* can use
* @return boolean Whether the file should be selected or not
*/
public function isSelected(PhingFile $basedir, $filename, PhingFile $file) {
$this->validate();
$selectors = $this->selectorElements();
// First, check that all elements are correctly configured
for($i=0,$size=count($selectors); $i < $size; $i++) {
$result = $selectors[$i]->isSelected($basedir, $filename, $file);
if ($result) {
return true;
}
}
return false;
}
}
| mit |
jguadagno/StartR | src/StartR.Lib/Messaging/IHandleCallBackEntity.cs | 280 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StartR.Domain;
namespace StartR.Lib.Messaging
{
public interface IHandleCallBackEntity<ICommand, IEntity>
{
void Handle(ICommand msg, Action<IEntity> completion);
}
}
| mit |
hulop/BLELocalization | location-service-library/src/hulo/localization/project/TrainDataReader.java | 1589 | /*******************************************************************************
* Copyright (c) 2014, 2015 IBM Corporation
*
* 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 hulo.localization.project;
import org.apache.wink.json4j.JSONObject;
public interface TrainDataReader {
public boolean hasReadMethod(JSONObject formatJSON);
public TrainData read(String projectPath, JSONObject formatJSON, MapData mapData, String group);
}
| mit |
FLamparski/meteor-moment-locales | bower_components/moment/locale/en-au.js | 2518 | // moment.js locale configuration
// locale : australian english (en-au)
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else if (typeof Meteor === 'object' && typeof global === 'object') {
factory(global.moment); // Meteor server
} else if (typeof window === 'object') {
factory(window.moment); // Any browser global
} else {
console.warn('Moment is being loaded through a language global!');
factory(moment); // Language global -- last resort
}
}(function (moment) {
return moment.defineLocale('en-au', {
months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
longDateFormat : {
LT : 'h:mm A',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY LT',
LLLL : 'dddd, D MMMM YYYY LT'
},
calendar : {
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
nextWeek : 'dddd [at] LT',
lastDay : '[Yesterday at] LT',
lastWeek : '[Last] dddd [at] LT',
sameElse : 'L'
},
relativeTime : {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
},
ordinal : function (number) {
var b = number % 10,
output = (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
| mit |
opengl-8080/slidedown | src/main/java/gl8080/slidedown/util/observer/IOObserver.java | 457 | package gl8080.slidedown.util.observer;
import gl8080.slidedown.util.observer.Observer;
import java.io.IOException;
import java.io.UncheckedIOException;
@FunctionalInterface
public interface IOObserver extends Observer {
@Override
default void update() {
try {
this.ioUpdate();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
void ioUpdate() throws IOException;
}
| mit |
wardmundy/php-api-tesla | set_hvac_on.php | 250 | #!/usr/bin/php -q
<?php
// Copyright (C) 2017, Ward Mundy & Associates LLC with MIT license
include("init.php");
init();
$response =queryTeslaAPI($TOKEN, "api/1/vehicles/".$ID."/command/auto_conditioning_start",true);
var_export($response);
?>
| mit |
johanlantz/headsetpresenter | HeadsetPresenter_Bluetools/HeadsetPresenter/Speech/Source Files/MixerControl.cpp | 12725 | #include "StdAfx.h"
#include "..\Header Files\mixercontrol.h"
#include "mmsystem.h"
#include "SS_Log.h"
bool MixerControl::RUN_THREAD = true;
int MixerControl::pollInterval = 1000;
CString MixerControl::nameOfAudioInDevice = "";
MixerControl::MixerControl(void)
{
}
MixerControl::~MixerControl(void)
{
}
DWORD WINAPI ThreadFunc2(LPVOID lpParam)
{
MixerControl* mc = (MixerControl*)lpParam;
mc->RunForceThread();
return 0;
}
void MixerControl::StartForceThread()
{
DWORD dwThrdParam = 1;
hThread = CreateThread(NULL,0,ThreadFunc2,this,0,&dwThreadId);
if(hThread == NULL)
{
MessageBox(NULL,"Create thread failed in Cfg","",MB_OK);
}
}
void MixerControl::RunForceThread()
{
LogEnterFunction("MC:RunForceThread");
RUN_THREAD = true;
int mixerId = GetIdOfDeviceContaining(nameOfAudioInDevice);
if(mixerId < 0)
{
RUN_THREAD = false;
MessageBox(NULL,"No mixer found, thread not started","",MB_OK);
}
else
{
SetVolume(mixerId);
SelectMic(mixerId);
}
while(RUN_THREAD)
{
UnMuteLineIn(mixerId);
UnMuteMic(mixerId);
Sleep(pollInterval);
}
}
void MixerControl::StopForceThread()
{
LogEnterFunction("MC:StopThread");
RUN_THREAD=false;
}
void MixerControl::SetPollInterval(int newPollInterval)
{
LogEnterFunction("MC:SetPollInterval");
pollInterval = newPollInterval;
}
void MixerControl::SetNameOfAudioInDevice(CString iNameOfAudioInDevice)
{
nameOfAudioInDevice = iNameOfAudioInDevice;
}
int MixerControl::GetIdOfDeviceContaining(CString deviceName)
{
LogEnterFunction("MC:GetIdOfDeviceContaining");
Log("MC:Will try to find mixer called %s",deviceName);
int noOfDevices = mixerGetNumDevs();
int retVal = NO_DEV_FOUND;
if(noOfDevices == 0)
{
retVal = NO_DEVICES_FOUND;
}
else //We have atleat one mixer
{
int deviceCounter = 0;
HMIXER hmx;
MIXERCAPS mxCaps;
do
{
//1 Open the mixer to be able to get capabilities
if(mixerOpen(&hmx, deviceCounter, 0, 0, 0) != MMSYSERR_NOERROR)
{
MessageBox(NULL,"Failed to open mixer","",MB_OK);
return MIXER_OPEN_ERROR;
}
//2. Mixer open ok, now query for caps
ZeroMemory(&mxCaps, sizeof(MIXERCAPS));
if(mixerGetDevCaps(reinterpret_cast<UINT>(hmx), &mxCaps, sizeof(MIXERCAPS)) != MMSYSERR_NOERROR)
{
return MIXER_GET_CAPS_ERROR;
}
Log("MC:Found mixer:%s",mxCaps.szPname);
//MessageBox(NULL,mxCaps.szPname,"",MB_OK);
//if(CString(mxCaps.szPname).Find(partOfDeviceName) != -1)
if(CString(mxCaps.szPname)== deviceName)
{
Log("MC:Mixer is a match");
retVal = deviceCounter;
}
deviceCounter++;
mixerClose(hmx);
}while(deviceCounter < noOfDevices);
}
if(retVal == NO_DEV_FOUND)
{
Log("MC:No mixer found for %s",deviceName);
MessageBox(NULL,"HeadsetPresenter failed to find a mixer matching your audioIn device.\nThis is simply a case not implemented because it did not seemed likely to ever happen.\n\nContact us at [email protected] so that we can investigate why this happened and implement a solution asap.","no mixer",MB_OK|MB_TOPMOST|MB_ICONINFORMATION);
}
Log("MC:Returning id=%d",retVal);
return retVal;
}
void MixerControl::SetVolume(int mixerId)
{
LogEnterFunction("MC:SetVolume");
// Open the mixer device
HMIXER hmx;
mixerOpen(&hmx, mixerId, 0, 0, 0);
// Get the line info for the wave in destination line
MIXERLINE mxl;
mxl.cbStruct = sizeof(mxl);
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl,
MIXER_GETLINEINFOF_COMPONENTTYPE);
// Now find the microphone source line connected to this wave in
// destination
DWORD cConnections = mxl.cConnections;
for(DWORD j=0; j<cConnections; j++){
mxl.dwSource = j;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl, MIXER_GETLINEINFOF_SOURCE);
if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == mxl.dwComponentType)
break;
}
// Find a volume control, if any, of the microphone line
LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof MIXERCONTROL);
MIXERLINECONTROLS mxlctrl = {sizeof mxlctrl, mxl.dwLineID,
MIXERCONTROL_CONTROLTYPE_VOLUME, 1, sizeof MIXERCONTROL, pmxctrl};
if(!mixerGetLineControls((HMIXEROBJ) hmx, &mxlctrl,
MIXER_GETLINECONTROLSF_ONEBYTYPE)){
// Found!
DWORD cChannels = mxl.cChannels;
if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl)
cChannels = 1;
LPMIXERCONTROLDETAILS_UNSIGNED pUnsigned =
(LPMIXERCONTROLDETAILS_UNSIGNED)
malloc(cChannels * sizeof MIXERCONTROLDETAILS_UNSIGNED);
MIXERCONTROLDETAILS mxcd = {sizeof(mxcd), pmxctrl->dwControlID,
cChannels, (HWND)0,
sizeof MIXERCONTROLDETAILS_UNSIGNED, (LPVOID) pUnsigned};
mixerGetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
// Set the volume to the middle (for both channels as needed)
pUnsigned[0].dwValue = pUnsigned[cChannels - 1].dwValue =
(pmxctrl->Bounds.dwMinimum+pmxctrl->Bounds.dwMaximum)/2;
mixerSetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
free(pmxctrl);
free(pUnsigned);
}
else
free(pmxctrl);
mixerClose(hmx);
}
void MixerControl::UnMuteMic(int mixerId)
{
//LogEnterFunction("MC:UnMuteMic");
//MessageBox("UnMuteMic");
// Open the mixer device
HMIXER hmx;
mixerOpen(&hmx, mixerId, 0, 0, 0);
// Get the line info for the wave in destination line
MIXERLINE mxl;
mxl.cbStruct = sizeof(mxl);
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl, MIXER_GETLINEINFOF_COMPONENTTYPE);
// Now find the microphone source line connected to this wave in
// destination
DWORD cConnections = mxl.cConnections;
for(DWORD j=0; j<cConnections; j++){
mxl.dwSource = j;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl, MIXER_GETLINEINFOF_SOURCE);
if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == mxl.dwComponentType)
break;
}
// Find a mute control, if any, of the microphone line
LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof MIXERCONTROL);
MIXERLINECONTROLS mxlctrl = {sizeof mxlctrl, mxl.dwLineID,
MIXERCONTROL_CONTROLTYPE_MUTE, 1, sizeof MIXERCONTROL, pmxctrl};
if(!mixerGetLineControls((HMIXEROBJ) hmx, &mxlctrl,
MIXER_GETLINECONTROLSF_ONEBYTYPE)){
// Found, so proceed
DWORD cChannels = mxl.cChannels;
if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl)
cChannels = 1;
LPMIXERCONTROLDETAILS_BOOLEAN pbool =
(LPMIXERCONTROLDETAILS_BOOLEAN) malloc(cChannels * sizeof
MIXERCONTROLDETAILS_BOOLEAN);
MIXERCONTROLDETAILS mxcd = {sizeof(mxcd), pmxctrl->dwControlID,
cChannels, (HWND)0,
sizeof MIXERCONTROLDETAILS_BOOLEAN, (LPVOID) pbool};
mixerGetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
// Unmute the microphone line (for both channels)
pbool[0].fValue = pbool[cChannels - 1].fValue = 0;
mixerSetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
free(pmxctrl);
free(pbool);
}
else
free(pmxctrl);
mixerClose(hmx);
}
void MixerControl::UnMuteLineIn(int mixerId)
{
//LogEnterFunction("MC:UnMuteLineIn");
//MessageBox("UnMuteLineIn");
// Open the mixer device
HMIXER hmx;
mixerOpen(&hmx, mixerId, 0, 0, 0);
// Get the line info for the wave in destination line
MIXERLINE mxl;
mxl.cbStruct = sizeof(mxl);
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl, MIXER_GETLINEINFOF_COMPONENTTYPE);
// Now find the microphone source line connected to this wave in
// destination
DWORD cConnections = mxl.cConnections;
for(DWORD j=0; j<cConnections; j++){
mxl.dwSource = j;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl, MIXER_GETLINEINFOF_SOURCE);
if (MIXERLINE_COMPONENTTYPE_SRC_LINE == mxl.dwComponentType)
break;
}
// Find a mute control, if any, of the microphone line
LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof MIXERCONTROL);
MIXERLINECONTROLS mxlctrl = {sizeof mxlctrl, mxl.dwLineID,
MIXERCONTROL_CONTROLTYPE_MUTE, 1, sizeof MIXERCONTROL, pmxctrl};
if(!mixerGetLineControls((HMIXEROBJ) hmx, &mxlctrl,
MIXER_GETLINECONTROLSF_ONEBYTYPE)){
// Found, so proceed
DWORD cChannels = mxl.cChannels;
if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl)
cChannels = 1;
LPMIXERCONTROLDETAILS_BOOLEAN pbool =
(LPMIXERCONTROLDETAILS_BOOLEAN) malloc(cChannels * sizeof
MIXERCONTROLDETAILS_BOOLEAN);
MIXERCONTROLDETAILS mxcd = {sizeof(mxcd), pmxctrl->dwControlID,
cChannels, (HWND)0,
sizeof MIXERCONTROLDETAILS_BOOLEAN, (LPVOID) pbool};
mixerGetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
// Unmute the microphone line (for both channels)
pbool[0].fValue = pbool[cChannels - 1].fValue = 0;
mixerSetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_SETCONTROLDETAILSF_VALUE);
free(pmxctrl);
free(pbool);
}
else
free(pmxctrl);
mixerClose(hmx);
}
void MixerControl::SelectMic(int mixerId)
{
LogEnterFunction("MC:SelectMic");
// Open the mixer device
HMIXER hmx;
mixerOpen(&hmx, mixerId, 0, 0, 0);
// Get the line info for the wave in destination line
MIXERLINE mxl;
mxl.cbStruct = sizeof(mxl);
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mixerGetLineInfo((HMIXEROBJ)hmx, &mxl,
MIXER_GETLINEINFOF_COMPONENTTYPE);
// Find a LIST control, if any, for the wave in line
LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(mxl.cControls * sizeof
MIXERCONTROL);
MIXERLINECONTROLS mxlctrl = {sizeof mxlctrl, mxl.dwLineID, 0,
mxl.cControls, sizeof MIXERCONTROL, pmxctrl};
mixerGetLineControls((HMIXEROBJ) hmx, &mxlctrl,
MIXER_GETLINECONTROLSF_ALL);
// Now walk through each control to find a type of LIST control. This
// can be either Mux, Single-select, Mixer or Multiple-select.
DWORD i;
for(i=0; i < mxl.cControls; i++)
if (MIXERCONTROL_CT_CLASS_LIST == (pmxctrl[i].dwControlType
&MIXERCONTROL_CT_CLASS_MASK))
break;
if (i < mxl.cControls) { // Found a LIST control
// Check if the LIST control is a Mux or Single-select type
BOOL bOneItemOnly = FALSE;
switch (pmxctrl[i].dwControlType) {
case MIXERCONTROL_CONTROLTYPE_MUX:
case MIXERCONTROL_CONTROLTYPE_SINGLESELECT:
bOneItemOnly = TRUE;
}
DWORD cChannels = mxl.cChannels, cMultipleItems = 0;
if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl[i].fdwControl)
cChannels = 1;
if (MIXERCONTROL_CONTROLF_MULTIPLE & pmxctrl[i].fdwControl)
cMultipleItems = pmxctrl[i].cMultipleItems;
// Get the text description of each item
LPMIXERCONTROLDETAILS_LISTTEXT plisttext =
(LPMIXERCONTROLDETAILS_LISTTEXT)
malloc(cChannels * cMultipleItems * sizeof
MIXERCONTROLDETAILS_LISTTEXT);
MIXERCONTROLDETAILS mxcd = {sizeof(mxcd), pmxctrl[i].dwControlID,
cChannels,
(HWND)cMultipleItems, sizeof MIXERCONTROLDETAILS_LISTTEXT,
(LPVOID) plisttext};
mixerGetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_GETCONTROLDETAILSF_LISTTEXT);
// Now get the value for each item
LPMIXERCONTROLDETAILS_BOOLEAN plistbool =
(LPMIXERCONTROLDETAILS_BOOLEAN)
malloc(cChannels * cMultipleItems * sizeof
MIXERCONTROLDETAILS_BOOLEAN);
mxcd.cbDetails = sizeof MIXERCONTROLDETAILS_BOOLEAN;
mxcd.paDetails = plistbool;
mixerGetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_GETCONTROLDETAILSF_VALUE);
// Select the "Microphone" item
for (DWORD j=0; j<cMultipleItems; j = j + cChannels)
if (0 == strcmp(plisttext[j].szName, "Microphone"))
// Select it for both left and right channels
plistbool[j].fValue = plistbool[j+ cChannels - 1].fValue = 1;
else if (bOneItemOnly)
// Mux or Single-select allows only one item to be selected
// so clear other items as necessary
plistbool[j].fValue = plistbool[j+ cChannels - 1].fValue = 0;
// Now actually set the new values in
mixerSetControlDetails((HMIXEROBJ)hmx, &mxcd,
MIXER_GETCONTROLDETAILSF_VALUE);
free(pmxctrl);
free(plisttext);
free(plistbool);
}
else
free(pmxctrl);
mixerClose(hmx);
} | mit |
JoseRego/summer-rush | Assets/Scripts/Gameplay/PacmanColliding.cs | 1632 | using UnityEngine;
using System.Collections;
public class PacmanColliding : MonoBehaviour {
public GameObject gameController;
private InterfaceScript inter;
private SoundController soundCtrl;
private LevelController lvlCtrl;
// Use this for initialization
void Start () {
inter = gameController.GetComponent<InterfaceScript>();
soundCtrl = GameObject.FindGameObjectWithTag("SoundController").GetComponent<SoundController>();
lvlCtrl = gameController.GetComponent<LevelController>();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "bolas")
{
inter.score += 100;
soundCtrl.ball_eating_sound.Play();
if(other.gameObject.GetComponent<animation>().isSpecial){
lvlCtrl.VulnarableEnemies();
}
GameObject.Destroy(other.gameObject);
}
if(other.gameObject.tag == "Collecionavel")
{
inter.score+= 1000;
soundCtrl.collectableEating.Play();
GameObject.Destroy(other.gameObject);
}
if(other.gameObject.tag == "Inimigo")
{
if(lvlCtrl.inimigos_vulneraveis){
inter.score += 1000;
soundCtrl.ghost_eating.Play();
// GameObject.Destroy(other.gameObject);
enemyAI ai = other.gameObject.GetComponent<enemyAI>();
other.gameObject.transform.position = ai.origin_point;
ai.currentState = enemyAI.State.COCANDOTOMATADA;
Invoke("sirenPlaying",0.5f);
}else
{
gameObject.GetComponent<PacmanController>().isAlive = false;
}
}
}
void sirenPlaying()
{
soundCtrl.siren.Play();
Invoke("sirenStop",2.0f);
}
void sirenStop()
{
soundCtrl.siren.Stop();
}
}
| mit |
Ivorius/pohoda-export | src/InvoiceItem.php | 7303 | <?php
/**
* Author: Ivo Toman
*/
namespace Pohoda;
class InvoiceItem
{
const VAT_NONE = "none";
const VAT_HIGH = "high";
const VAT_LOW = "low";
const VAT_THIRD = "third";
private $text;
private $quantity = '1.0';
private $unit;
private $coefficient = '1.0';
private $payVAT = false; //unitPrice is with (true) or without (false) VAT
private $rateVAT;
private $percentVAT;
private $discountPercentage;
private $homeCurrency = [
"unitPrice" => null, //mandatory
"price" => null, //optional
"priceVAT" => null, //optional
"priceSum" => null, //only for export from pohoda
];
private $foreignCurrency = [
"unitPrice" => null, //mandatory
"price" => null, //optional
"priceVAT" => null, //optional
"priceSum" => null, //only for export from pohoda
];
private $note;
private $code;
private $guarantee = 48;
private $guaranteeType = "month";
private $stockItem; //odkaz na skladovou zasobu
/**
* @return string $text
*/
public function getText()
{
return $this->text;
}
public function setText($text)
{
if (Validators::isMaxLength($text, 90) === false)
$text = mb_substr($text, 0, 90);
$this->text = $text;
}
/**
* @return float
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* @param float $quantity
*/
public function setQuantity($quantity)
{
Validators::assertNumeric($quantity);
$this->quantity = $quantity;
}
/**
* @return string $unit
*/
public function getUnit()
{
return $this->unit;
}
public function setUnit($unit)
{
Validators::assertMaxLength($unit, 10);
$this->unit = $unit;
}
/**
* @return float
*/
public function getCoefficient()
{
return $this->coefficient;
}
/**
* @param float $coefficient
*/
public function setCoefficient($coefficient)
{
Validators::assertNumeric($coefficient);
$this->coefficient = $coefficient;
}
/**
* @return boolean
*/
public function isPayVAT()
{
return $this->payVAT;
}
/**
* @param boolean $payVAT
*/
public function setPayVAT($payVAT)
{
Validators::assertBoolean($payVAT);
$this->payVAT = $payVAT;
}
/**
* @param bool $bool
*/
public function setWithVAT($bool = true)
{
$this->setPayVAT($bool);
}
/**
* @return bool
*/
public function isWithVAT()
{
return $this->isPayVAT();
}
/**
* @return
*/
public function getRateVAT()
{
return $this->rateVAT;
}
/**
* @param mixed $rateVAT
*/
public function setRateVAT($rateVAT)
{
$rates = [
self::VAT_NONE => "bez DPH",
self::VAT_HIGH => "Základní sazba",
self::VAT_LOW => "Snížena sazba",
self::VAT_THIRD => "2. snížená sazba"
];
Validators::assertKeyInList($rateVAT, $rates);
$this->rateVAT = $rateVAT;
}
/**
* @return float
*/
public function getPercentVAT()
{
return $this->percentVAT;
}
/**
* @param float $percentVAT
*/
public function setPercentVAT($percentVAT)
{
Validators::assertNumeric($percentVAT);
$this->percentVAT = $percentVAT;
}
/**
* @return float
*/
public function getDiscountPercentage()
{
return $this->discountPercentage;
}
/**
* @param float $discountPercentage
*/
public function setDiscountPercentage($discountPercentage)
{
Validators::assertNumeric($discountPercentage);
if ($discountPercentage < -999 || $discountPercentage > 999)
throw new \InvalidArgumentException($discountPercentage . " must be betweeen -999 and 999");
$this->discountPercentage = $discountPercentage;
}
/**
* @return array
*/
public function getHomeCurrency()
{
return $this->homeCurrency;
}
public function getUnitPrice()
{
return $this->homeCurrency["unitPrice"];
}
/**
* @param float $price
*/
public function setUnitPrice($price)
{
Validators::assertNumeric($price);
$this->homeCurrency["unitPrice"] = $price;
}
public function getPrice()
{
return $this->homeCurrency["price"];
}
/**
* @param float $price
*/
public function setPrice($price)
{
//without tax (vat)
Validators::assertNumeric($price);
$this->homeCurrency["price"] = $price;
}
public function getPriceVAT()
{
return $this->homeCurrency["priceVAT"];
}
/**
* @param float $price
*/
public function setPriceVAT($price)
{
//only vat itself
Validators::assertNumeric($price);
$this->homeCurrency["priceVAT"] = $price;
}
public function getPriceSum()
{
return $this->homeCurrency["priceSum"];
}
public function setPriceSum($price)
{
//price with vat
trigger_error("PriceSUM is only for export from POHODA");
Validators::assertNumeric($price);
$this->homeCurrency["priceSum"] = $price;
}
/**
* @return array
*/
public function getForeignCurrency()
{
return $this->foreignCurrency;
}
public function getForeignUnitPrice()
{
return $this->foreignCurrency["unitPrice"];
}
/**
* @param float $price
*/
public function setForeignUnitPrice($price)
{
Validators::assertNumeric($price);
$this->foreignCurrency["unitPrice"] = $price;
}
public function getForeignPrice()
{
return $this->foreignCurrency["price"];
}
/**
* @param float $price
*/
public function setForeignPrice($price)
{
//without tax (vat)
Validators::assertNumeric($price);
$this->foreignCurrency["price"] = $price;
}
public function getForeignPriceVAT()
{
return $this->foreignCurrency["priceVAT"];
}
/**
* @param float $price
*/
public function setForeignPriceVAT($price)
{
//only vat itself
Validators::assertNumeric($price);
$this->foreignCurrency["priceVAT"] = $price;
}
public function getForeignPriceSum()
{
return $this->foreignCurrency["priceSum"];
}
public function setForeignPriceSum($price)
{
//price with vat
trigger_error("PriceSUM is only for export from POHODA");
Validators::assertNumeric($price);
$this->foreignCurrency["priceSum"] = $price;
}
/**
* @return string
*/
public function getNote()
{
return $this->note;
}
/**
* @param string $note
*/
public function setNote($note)
{
if (Validators::isMaxLength($note, 90) === false)
$note = mb_substr($note, 0, 90);
$this->note = $note;
}
/**
* @return null|string
*/
public function getCode()
{
return $this->code;
}
/**
* @param string $code
*/
public function setCode($code)
{
Validators::assertMaxLength($code, 64);
$this->code = $code;
}
/**
* @return int
*/
public function getGuarantee()
{
return $this->guarantee;
}
/**
* @param int $guarantee
*/
public function setGuarantee($guarantee)
{
Validators::assertNumeric($guarantee);
$this->guarantee = $guarantee;
}
/**
* @return string
*/
public function getGuaranteeType()
{
return $this->guaranteeType;
}
/**
* @param string $guaranteeType
*/
public function setGuaranteeType($guaranteeType)
{
$types = [
"none" => "bez záruky",
"hour" => "v hodinách",
"day" => "ve dnech",
"month" => "v měsících",
"year" => "v letech",
"life" => "doživotní záruka",
];
Validators::assertKeyInList($guaranteeType, $types);
$this->guaranteeType = $guaranteeType;
}
/**
* @return mixed
*/
public function getStockItem()
{
return $this->stockItem;
}
/**
* @param mixed $stockItem
*/
public function setStockItem($stockItem)
{
$this->stockItem = $stockItem;
}
}
| mit |
alphonsekurian/corefx | src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs | 81234 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public class HttpClientHandlerTest
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test contest";
private const string Username = "testuser";
private const string Password = "password";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public readonly static object[][] EchoServers = Configuration.Http.EchoServers;
public readonly static object[][] VerifyUploadServers = Configuration.Http.VerifyUploadServers;
public readonly static object[][] CompressedServers = Configuration.Http.CompressedServers;
public readonly static object[][] HeaderValueAndUris = {
new object[] { "X-CustomHeader", "x-value", Configuration.Http.RemoteEchoServer },
new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RemoteEchoServer },
new object[] { "X-CustomHeader", "x-value", Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1) },
new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1) },
};
public readonly static object[][] Http2Servers = Configuration.Http.Http2Servers;
public readonly static object[][] Http2NoPushServers = Configuration.Http.Http2NoPushServers;
public readonly static object[][] RedirectStatusCodes = {
new object[] { 300 },
new object[] { 301 },
new object[] { 302 },
new object[] { 303 },
new object[] { 307 }
};
// Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"
public readonly static IEnumerable<object[]> HttpMethods =
GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1");
public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent =
GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1");
public readonly static IEnumerable<object[]> HttpMethodsThatDontAllowContent =
GetMethods("HEAD", "TRACE");
private static bool IsWindows10Version1607OrGreater => PlatformDetection.IsWindows10Version1607OrGreater;
private static IEnumerable<object[]> GetMethods(params string[] methods)
{
foreach (string method in methods)
{
foreach (bool secure in new[] { true, false })
{
yield return new object[] { method, secure };
}
}
}
public HttpClientHandlerTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
using (var handler = new HttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.True(handler.AllowAutoRedirect);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
CookieContainer cookies = handler.CookieContainer;
Assert.NotNull(cookies);
Assert.Equal(0, cookies.Count);
Assert.Null(handler.Credentials);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.False(handler.PreAuthenticate);
Assert.Equal(null, handler.Proxy);
Assert.True(handler.SupportsAutomaticDecompression);
Assert.True(handler.SupportsProxy);
Assert.True(handler.SupportsRedirectConfiguration);
Assert.True(handler.UseCookies);
Assert.False(handler.UseDefaultCredentials);
Assert.True(handler.UseProxy);
// Changes from .NET Framework (Desktop).
Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
Assert.NotNull(handler.Properties);
}
}
[Fact]
public void MaxRequestContentBufferSize_Get_ReturnsZero()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(0, handler.MaxRequestContentBufferSize);
}
}
[Fact]
public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException()
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
var handler = new HttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.NegotiateAuthUriForDefaultCreds(secure:false);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Fact]
public void Properties_Get_CountIsZero()
{
var handler = new HttpClientHandler();
IDictionary<String, object> dict = handler.Properties;
Assert.Same(dict, handler.Properties);
Assert.Equal(0, dict.Count);
}
[Fact]
public void Properties_AddItemToDictionary_ItemPresent()
{
var handler = new HttpClientHandler();
IDictionary<String, object> dict = handler.Properties;
var item = new Object();
dict.Add("item", item);
object value;
Assert.True(dict.TryGetValue("item", out value));
Assert.Equal(item, value);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(remoteServer))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Theory]
[MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))]
public async Task GetAsync_IPBasedUri_Success(IPAddress address)
{
using (var client = new HttpClient())
{
var options = new LoopbackServer.Options { Address = address };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData()
{
foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() })
{
if (addr != null)
{
yield return new object[] { addr };
}
}
}
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
{
using (var client = new HttpClient())
{
HttpResponseMessage response;
for (int i = 0; i < 3; i++)
{
response = await client.GetAsync(Configuration.Http.RemoteEchoServer);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response.Dispose();
}
}
}
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
{
HttpResponseMessage response = null;
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer);
}
Assert.NotNull(response);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer);
TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, cts.Token));
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(server))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server)
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found");
Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found");
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
{
using (var client = new HttpClient())
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:statusCode,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:statusCode,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.SecureRemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
Uri targetUri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:targetUri,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(targetUri, response.RequestMessage.RequestUri);
}
}
}
[ActiveIssue(8945, PlatformID.Windows)]
[Theory]
[InlineData(3, 2)]
[InlineData(3, 3)]
[InlineData(3, 4)]
public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops)
{
using (var client = new HttpClient(new HttpClientHandler() { MaxAutomaticRedirections = maxHops }))
{
Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: hops));
if (hops <= maxHops)
{
using (HttpResponseMessage response = await t)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
else
{
await Assert.ThrowsAsync<HttpRequestException>(() => t);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation()
{
using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true }))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1,
relative: true);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Theory]
[InlineData(200)]
[InlineData(201)]
[InlineData(400)]
public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode)
{
using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) =>
{
Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl);
Task redirectTask = LoopbackServer.ReadRequestAndSendResponseAsync(redirectServer);
await LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 {statusCode} OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Location: {redirectUrl}\r\n" +
"\r\n");
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(origUrl, response.RequestMessage.RequestUri);
Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location");
}
});
});
}
}
[Theory]
[PlatformSpecific(PlatformID.AnyUnix)]
[InlineData("#origFragment", "", "#origFragment", false)]
[InlineData("#origFragment", "", "#origFragment", true)]
[InlineData("", "#redirFragment", "#redirFragment", false)]
[InlineData("", "#redirFragment", "#redirFragment", true)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", false)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", true)]
public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate(
string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect)
{
using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
origUrl = new Uri(origUrl.ToString() + origFragment);
Uri redirectUrl = useRelativeRedirect ?
new Uri(origUrl.PathAndQuery + redirFragment, UriKind.Relative) :
new Uri(origUrl.ToString() + redirFragment);
Uri expectedUrl = new Uri(origUrl.ToString() + expectedFragment);
Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl);
Task firstRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 302 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Location: {redirectUrl}\r\n" +
"\r\n");
Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse));
Task secondRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"\r\n");
await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse);
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(expectedUrl, response.RequestMessage.RequestUri);
}
});
}
}
[Fact]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri redirectUri = Configuration.Http.RedirectUriForCreds(
secure:false,
statusCode:302,
userName:Username,
password:Password);
using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
Uri redirectUri = Configuration.Http.RedirectUriForCreds(
secure:false,
statusCode:statusCode,
userName:Username,
password:Password);
_output.WriteLine(uri.AbsoluteUri);
_output.WriteLine(redirectUri.AbsoluteUri);
var credentialCache = new CredentialCache();
credentialCache.Add(uri, "Basic", _credential);
var handler = new HttpClientHandler();
handler.Credentials = credentialCache;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie"));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue)
{
var handler = new HttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(Configuration.Http.RemoteEchoServer, new Cookie(cookieName, cookieValue));
handler.CookieContainer = cookieContainer;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue)
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
string.Format("{0}={1};Path=/", cookieName, cookieValue));
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory, MemberData(nameof(HeaderValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
}
private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength)
{
string emptyHeaderValue = $"{name}=; Path=/";
Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length);
int valueCount = overallHeaderValueLength - emptyHeaderValue.Length;
string value = new string(repeat, valueCount);
return new KeyValuePair<string, string>(name, value);
}
public static object[][] CookieNameValues =
{
// WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values,
// using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders
// returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer.
// Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the
// iteration index, which would cause header values to be missed if not handled correctly.
//
// In particular, WinHttpQueryHeader behaves as follows for the following header value lengths:
// * 0-127 chars: succeeds, index advances from 0 to 1.
// * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1.
// * 256+ chars: fails due to insufficient buffer, index stays at 0.
//
// The below overall header value lengths were chosen to exercise reading header values at these
// edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers.
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) },
new object[]
{
new KeyValuePair<string, string>(
".AspNetCore.Antiforgery.Xam7_OeLcN4",
"CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM")
}
};
[Theory]
[MemberData(nameof(CookieNameValues))]
public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1)
{
var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM");
var cookie3 = new KeyValuePair<string, string>("name", "value");
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponse = client.GetAsync(url);
await LoopbackServer.ReadRequestAndSendResponseAsync(server,
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" +
$"Set-Cookie : {cookie2.Key}={cookie2.Value}; Path=/\r\n" + // space before colon to verify header is trimmed and recognized
$"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" +
"\r\n");
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
CookieCollection cookies = handler.CookieContainer.GetCookies(url);
Assert.Equal(3, cookies.Count);
Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value);
Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value);
Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value);
}
}
});
}
[Fact]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock()
{
using (var client = new HttpClient())
{
const int NumGets = 5;
Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets)
select client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray();
for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available
{
using (HttpResponseMessage response = await responseTasks[i])
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[Fact]
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer);
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Fact]
public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
await writer.WriteAsync(
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 16000\r\n" +
"\r\n" +
"less than 16000 bytes");
using (HttpResponseMessage response = await getResponse)
{
var buffer = new byte[8000];
using (Stream clientStream = await response.Content.ReadAsStreamAsync())
{
int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine($"Bytes read from stream: {bytesRead}");
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
}
return null;
});
}
});
}
[Fact]
public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses()
{
await LoopbackServer.CreateServerAsync(async (socket1, url1) =>
{
await LoopbackServer.CreateServerAsync(async (socket2, url2) =>
{
await LoopbackServer.CreateServerAsync(async (socket3, url3) =>
{
var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
// First server connects but doesn't send any response yet
Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) =>
{
await unblockServers.Task;
return null;
});
// Second server connects and sends some but not all headers
Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync($"HTTP/1.1 200 OK\r\n");
await unblockServers.Task;
return null;
});
// Third server connects and sends all headers and some but not all of the body
Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n");
await writer.WriteAsync("1234567890");
await unblockServers.Task;
await writer.WriteAsync("1234567890");
s.Shutdown(SocketShutdown.Send);
return null;
});
// Make three requests
Task<HttpResponseMessage> get1, get2;
HttpResponseMessage response3;
using (var client = new HttpClient())
{
get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead);
get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead);
response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead);
}
// Requests 1 and 2 should be canceled as we haven't finished receiving their headers
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get2);
// Request 3 should still be active, and we should be able to receive all of the data.
unblockServers.SetResult(true);
using (response3)
{
Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync());
}
});
});
});
}
#region Post Methods Tests
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "Test String";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
HttpResponseMessage response;
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Repeat call.
content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData)
{
using (var client = new HttpClient())
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
private sealed class StreamContentWithSyncAsyncCopy : StreamContent
{
private readonly Stream _stream;
private readonly bool _syncCopy;
public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream)
{
_stream = stream;
_syncCopy = syncCopy;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
if (_syncCopy)
{
try
{
_stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException(exc);
}
}
return base.SerializeToStreamAsync(stream, context);
}
}
public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData
{
get
{
foreach (object[] serverArr in VerifyUploadServers) // target server
foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync
{
Uri server = (Uri)serverArr[0];
byte[] data = new byte[1234];
new Random(42).NextBytes(data);
// A MemoryStream
{
var memStream = new MemoryStream(data, writable: false);
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data };
}
// A multipart content that provides its own stream from CreateContentReadStreamAsync
{
var mc = new MultipartContent();
mc.Add(new ByteArrayContent(data));
var memStream = new MemoryStream();
mc.CopyToAsync(memStream).GetAwaiter().GetResult();
yield return new object[] { server, mc, memStream.ToArray() };
}
// A stream that provides the data synchronously and has a known length
{
var wrappedMemStream = new MemoryStream(data, writable: false);
var syncKnownLengthStream = new DelegateStream(
canReadFunc: () => wrappedMemStream.CanRead,
canSeekFunc: () => wrappedMemStream.CanSeek,
lengthFunc: () => wrappedMemStream.Length,
positionGetFunc: () => wrappedMemStream.Position,
positionSetFunc: p => wrappedMemStream.Position = p,
readFunc: (buffer, offset, count) => wrappedMemStream.Read(buffer, offset, count),
readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token));
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data synchronously and has an unknown length
{
int syncUnknownLengthStreamOffset = 0;
Func<byte[], int, int, int> readFunc = (buffer, offset, count) =>
{
int bytesRemaining = data.Length - syncUnknownLengthStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, count);
Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy);
syncUnknownLengthStreamOffset += bytesToCopy;
return bytesToCopy;
};
var syncUnknownLengthStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readFunc: readFunc,
readAsyncFunc: (buffer, offset, count, token) => Task.FromResult(readFunc(buffer, offset, count)));
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data asynchronously
{
int asyncStreamOffset = 0, maxDataPerRead = 100;
Func<byte[], int, int, int> readFunc = (buffer, offset, count) =>
{
int bytesRemaining = data.Length - asyncStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count));
Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy);
asyncStreamOffset += bytesToCopy;
return bytesToCopy;
};
var asyncStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readFunc: readFunc,
readAsyncFunc: async (buffer, offset, count, token) =>
{
await Task.Delay(1).ConfigureAwait(false);
return readFunc(buffer, offset, count);
});
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data };
}
// Providing data from a FormUrlEncodedContent's stream
{
var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key", "val") });
yield return new object[] { server, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") };
}
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_NullContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer, null))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
var content = new StringContent(string.Empty);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure)
{
const string ContentString = "This is the content string.";
var content = new StringContent(ContentString);
Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(
secure,
302,
secure ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer,
1);
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain(ContentString, responseContent);
Assert.DoesNotContain("Content-Length", responseContent);
}
}
[OuterLoop] // takes several seconds
[Theory]
[InlineData(302, false)]
[InlineData(307, true)]
public async Task PostAsync_Redirect_LargePayload(int statusCode, bool expectRedirectToPost)
{
using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose))
{
string contentString = string.Join("", Enumerable.Repeat("Content", 100000));
byte[] contentBytes = Encoding.UTF32.GetBytes(contentString);
fs.Write(contentBytes, 0, contentBytes.Length);
fs.Flush(flushToDisk: true);
fs.Position = 0;
Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(false, statusCode, Configuration.Http.SecureRemoteEchoServer, 1);
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs)))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
if (expectRedirectToPost)
{
Assert.InRange(response.Content.Headers.ContentLength.GetValueOrDefault(), contentBytes.Length, int.MaxValue);
}
}
}
}
[Fact]
public async Task PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered()
{
using (var client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
bool contentDisposed = false;
Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new DelegateContent
{
SerializeToStreamAsyncDelegate = (contentStream, contentTransport) => contentStream.WriteAsync(new byte[100], 0, 100),
TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100),
DisposeDelegate = _ => contentDisposed = true
}
}, HttpCompletionOption.ResponseContentRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
// Read headers from client
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
// Send back all headers and some but not all of the response
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n");
await writer.WriteAsync("abcd"); // less than contentLength
// The request content should not be disposed of until all of the response has been sent
await Task.Delay(1); // a little time to let data propagate
Assert.False(contentDisposed, "Expected request content not to be disposed");
// Send remaining response content
await writer.WriteAsync("efghij");
s.Shutdown(SocketShutdown.Send);
// The task should complete and the request content should be disposed
using (HttpResponseMessage response = await post)
{
Assert.True(contentDisposed, "Expected request content to be disposed");
Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync());
}
return null;
});
});
}
}
[Fact]
public async Task PostAsync_ResponseHeadersRead_RequestContentDisposedAfterRequestFullySentAndResponseHeadersReceived()
{
using (var client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var trigger = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
bool contentDisposed = false;
Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new DelegateContent
{
SerializeToStreamAsyncDelegate = async (contentStream, contentTransport) =>
{
await contentStream.WriteAsync(new byte[50], 0, 50);
await trigger.Task;
await contentStream.WriteAsync(new byte[50], 0, 50);
},
TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100),
DisposeDelegate = _ => contentDisposed = true
}
}, HttpCompletionOption.ResponseHeadersRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
// Read headers from client
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
// Send back all headers and some but not all of the response
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n");
await writer.WriteAsync("abcd"); // less than contentLength
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.False(contentDisposed, "Expected request content to not be disposed while request data still being sent");
}
else // [ActiveIssue(9006, PlatformID.AnyUnix)]
{
await post;
Assert.True(contentDisposed, "Current implementation will dispose of the request content once response headers arrive");
}
// Allow request content to complete
trigger.SetResult(true);
// Send remaining response content
await writer.WriteAsync("efghij");
s.Shutdown(SocketShutdown.Send);
// The task should complete and the request content should be disposed
using (HttpResponseMessage response = await post)
{
Assert.True(contentDisposed, "Expected request content to be disposed");
Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync());
}
return null;
});
});
}
}
private sealed class DelegateContent : HttpContent
{
internal Func<Stream, TransportContext, Task> SerializeToStreamAsyncDelegate;
internal Func<Tuple<bool, long>> TryComputeLengthDelegate;
internal Action<bool> DisposeDelegate;
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return SerializeToStreamAsyncDelegate != null ?
SerializeToStreamAsyncDelegate(stream, context) :
Task.CompletedTask;
}
protected override bool TryComputeLength(out long length)
{
if (TryComputeLengthDelegate != null)
{
var result = TryComputeLengthDelegate();
length = result.Item2;
return result.Item1;
}
length = 0;
return false;
}
protected override void Dispose(bool disposing) =>
DisposeDelegate?.Invoke(disposing);
}
[Theory]
[InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")]
[InlineData(HttpStatusCode.MethodNotAllowed, "")]
public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.StatusCodeUri(
false,
(int)statusCode,
reasonPhrase)))
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal(reasonPhrase, response.ReasonPhrase);
}
}
}
[PlatformSpecific(PlatformID.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBindingHasExpectedValue()
{
using (var client = new HttpClient())
{
string expectedContent = "Test contest";
var content = new ChannelBindingAwareContent(expectedContent);
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
_output.WriteLine("Channel Binding: {0}", channelBinding);
}
}
}
#endregion
#region Various HTTP Method Tests
[Theory, MemberData(nameof(HttpMethods))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
}
}
}
[Theory, MemberData(nameof(HttpMethodsThatAllowContent))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer);
request.Content = new StringContent(ExpectedContent);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
ExpectedContent);
}
}
}
[Theory]
[InlineData("12345678910", 0)]
[InlineData("12345678910", 5)]
public async Task SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success(string stringContent, int startingPosition)
{
using (var handler = new HttpMessageInvoker(new HttpClientHandler()))
{
byte[] byteContent = Encoding.ASCII.GetBytes(stringContent);
var content = new MemoryStream();
content.Write(byteContent, 0, byteContent.Length);
content.Position = startingPosition;
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer) { Content = new StreamContent(content) };
for (int iter = 0; iter < 2; iter++)
{
using (HttpResponseMessage response = await handler.SendAsync(request, CancellationToken.None))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
Assert.Contains(stringContent.Substring(startingPosition), responseContent);
if (startingPosition != 0)
{
Assert.DoesNotContain(stringContent.Substring(0, startingPosition), responseContent);
}
}
}
}
}
[Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))]
public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer)
{
Content = new StringContent(ExpectedContent)
};
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE")
{
// [ActiveIssue(9023, PlatformID.Windows)]
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
else
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.False(responseContent.Contains(ExpectedContent));
}
}
}
}
#endregion
#region Version tests
[Fact]
public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request()
{
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0));
Assert.Equal(new Version(1, 0), receivedRequestVersion);
}
[Fact]
public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request()
{
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1));
Assert.Equal(new Version(1, 1), receivedRequestVersion);
}
[Fact]
public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request()
{
// The default value for HttpRequestMessage.Version is Version(1,1).
// So, we need to set something different (0,0), to test the "unknown" version.
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0,0));
Assert.Equal(new Version(1, 1), receivedRequestVersion);
}
[Theory, MemberData(nameof(Http2Servers))]
[ActiveIssue(10958, PlatformID.Windows)]
public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server)
{
// We don't currently have a good way to test whether HTTP/2 is supported without
// using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses.
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler, false))
{
// It is generally expected that the test hosts will be trusted, so we don't register a validation
// callback in the usual case.
//
// However, on our Debian 8 test machines, a combination of a server side TLS chain,
// the client chain processor, and the distribution's CA bundle results in an incomplete/untrusted
// certificate chain. See https://github.com/dotnet/corefx/issues/9244 for more details.
if (PlatformDetection.IsDebian8)
{
// Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
{
Assert.InRange(chain.ChainStatus.Length, 0, 1);
if (chain.ChainStatus.Length > 0)
{
Assert.Equal(X509ChainStatusFlags.PartialChain, chain.ChainStatus[0].Status);
}
return true;
};
}
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(
response.Version == new Version(2, 0) ||
response.Version == new Version(1, 1),
"Response version " + response.Version);
}
}
}
[ConditionalTheory(nameof(IsWindows10Version1607OrGreater)), MemberData(nameof(Http2NoPushServers))]
public async Task SendAsync_RequestVersion20_ResponseVersion20(Uri server)
{
_output.WriteLine(server.AbsoluteUri.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(new Version(2, 0), response.Version);
}
}
}
private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion)
{
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = requestVersion;
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
List<string> receivedRequest = await LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
string statusLine = receivedRequest[0];
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = new Version(1, 0);
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = new Version(1, 1);
}
else
{
Assert.True(false, "Invalid HTTP request version");
}
}
});
return receivedRequestVersion;
}
#endregion
#region Proxy tests
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
expectCreds: true);
Uri proxyUrl = new Uri($"http://localhost:{port}");
const string BasicAuth = "Basic";
if (wrapCredsInCache)
{
Assert.IsAssignableFrom<NetworkCredential>(creds);
var cache = new CredentialCache();
cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
creds = cache;
}
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
Task.WaitAll(proxyTask, responseTask, responseStringTask);
TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);
NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth);
string expectedAuth =
nc == null || nc == CredentialCache.DefaultCredentials ? null :
string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
$"{nc.Domain}\\{nc.UserName}:{nc.Password}";
Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
}
}
[Theory]
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy }))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
[Fact]
public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
Task.WaitAll(proxyTask, responseTask);
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
private static IEnumerable<object[]> BypassedProxies()
{
yield return new object[] { null };
yield return new object[] { new PlatformNotSupportedWebProxy() };
yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) };
}
private static IEnumerable<object[]> CredentialsForProxy()
{
yield return new object[] { null, false };
foreach (bool wrapCredsInCache in new[] { true, false })
{
yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache };
yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache };
}
}
#endregion
#region Uri wire transmission encoding tests
[Fact]
public async Task SendRequest_UriPathHasReservedChars_ServerReceivedExpectedPath()
{
await LoopbackServer.CreateServerAsync(async (server, rootUrl) =>
{
var uri = new Uri($"http://{rootUrl.Host}:{rootUrl.Port}/test[]");
_output.WriteLine(uri.AbsoluteUri.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, uri);
string statusLine = string.Empty;
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
List<string> receivedRequest = await LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(receivedRequest[0].Contains(uri.PathAndQuery), $"statusLine should contain {uri.PathAndQuery}");
}
}
});
}
#endregion
}
}
| mit |
ardune/layouttest | LayoutTest/Features/Shared/Window1.xaml.cs | 608 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace LayoutTest.Features.Shared
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
}
| mit |
camsys/transam_sign | app/models/support_size_type.rb | 154 | class SupportSizeType < ActiveRecord::Base
default_scope { order(:name) }
scope :active, -> { where(active: true) }
def to_s
name
end
end
| mit |
howma03/sporticus | workspace/web-client-angular/src/app/organisation/manage/manage-group/add-group-member-dialog/add-group-member-dialog.component.ts | 826 | import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {User} from '../../../../services/users.service';
@Component({
selector: 'app-add-group-member-dialog',
templateUrl: './add-group-member-dialog.component.html',
styleUrls: ['./add-group-member-dialog.component.css']
})
export class AddGroupMemberDialogComponent implements OnInit {
constructor(public dialogRef: MatDialogRef<AddGroupMemberDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
this.groupId = data.groupId;
this.organisationId = data.organisationId;
this.members = data.members;
}
public groupId: number;
public organisationId: number;
public members: User[];
ngOnInit() {
}
close() {
this.dialogRef.close();
}
}
| mit |
atumachimela/oec | config/env/development.js | 1368 | 'use strict';
module.exports = {
db: 'mongodb://localhost/e-amity-dev',
app: {
title: 'PRO SERVICE - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
}; | mit |
DavidLGoldberg/voting-server-tutorial | src/index.js | 259 | import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';
import { createHistory } from 'history';
const history = createHistory();
ReactDOM.render(
<Root history={history} />,
document.getElementById('root')
);
| mit |
4Catalyzer/found | examples/global-pending/src/index.js | 2052 | import ElementsRenderer from 'found/ElementsRenderer';
import Link from 'found/Link';
import StaticContainer from 'found/StaticContainer';
import createBrowserRouter from 'found/createBrowserRouter';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
function LinkItem(props) {
return (
<li>
<Link {...props} activeStyle={{ fontWeight: 'bold' }} />
</li>
);
}
const propTypes = {
children: PropTypes.node,
};
function App({ children }) {
return (
<div>
<ul>
<LinkItem to="/">Main</LinkItem>
<ul>
<LinkItem to="/foo">Foo</LinkItem>
<LinkItem to="/bar">Bar</LinkItem>
</ul>
</ul>
{children}
</div>
);
}
App.propTypes = propTypes;
const BrowserRouter = createBrowserRouter({
routeConfig: [
{
path: '/',
Component: App,
children: [
{
Component: () => <div>Main</div>,
},
{
path: 'foo',
getComponent: () =>
new Promise((resolve) => {
setTimeout(resolve, 1000, () => <div>Foo</div>);
}),
},
{
path: 'bar',
Component: ({ data }) => <div>{data}</div>, // eslint-disable-line react/prop-types
getData: () =>
new Promise((resolve) => {
setTimeout(resolve, 1000, 'Bar');
}),
},
],
},
],
renderPending: () => (
<div>
<StaticContainer>{null}</StaticContainer>
<div
style={{
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
background: 'white',
opacity: 0.5,
}}
/>
</div>
),
renderReady: (
{ elements }, // eslint-disable-line react/prop-types
) => (
<div>
<StaticContainer shouldUpdate>
<ElementsRenderer elements={elements} />
</StaticContainer>
</div>
),
});
ReactDOM.render(<BrowserRouter />, document.getElementById('root'));
| mit |
mpociot/laravel-apidoc-generator | src/Extracting/Strategies/RequestHeaders/GetFromRouteRules.php | 436 | <?php
namespace Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders;
use Illuminate\Routing\Route;
use Mpociot\ApiDoc\Extracting\Strategies\Strategy;
use ReflectionClass;
use ReflectionMethod;
class GetFromRouteRules extends Strategy
{
public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
{
return $routeRules['headers'] ?? [];
}
}
| mit |
Hedde/fabric-bolt | fabric_bolt/hosts/migrations/0001_initial.py | 940 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Host'
db.create_table(u'hosts_host', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal(u'hosts', ['Host'])
def backwards(self, orm):
# Deleting model 'Host'
db.delete_table(u'hosts_host')
models = {
u'hosts.host': {
'Meta': {'object_name': 'Host'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['hosts'] | mit |
VR-Robotica/AvatarComponents | Assets/VR_Robotica/SimpleEyeGaze/Scripts/VRR_ObjectOfInterest.cs | 2088 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace com.VR_Robotica.AvatarComponents
{
/// <summary>
/// Attach this script to any object to Identify it as something the Avatar is
/// interested in looking at. A designer can specify which points on the object
/// are of interest by adding them to the PointsOfInterest Array in the editor.
/// </summary>
public class VRR_ObjectOfInterest : MonoBehaviour
{
[Tooltip("Toggle to AUTOMATICALLY populate PointsOfInterest with all the children of this object")]
public bool UseAllChildren;
[Tooltip("Define Specific Areas of an object that an avatar can cycle through and look at.")]
public Transform[] PointsOfInterest;
// TODO: Add weighted priorities for Object and Points
// public int ObjectPriority;
// public int[] PointsPriority;
private void Awake()
{
createCollider();
createPointsOfInterest();
}
private void createCollider()
{
Collider collider = this.gameObject.GetComponent<Collider>();
if(collider == null)
{
Debug.LogWarning("This Object Needs a Custom Collider, creating default.");
SphereCollider sc = this.gameObject.AddComponent<SphereCollider>();
sc.isTrigger = true;
sc.radius = 0.1f;
}
}
private void createPointsOfInterest()
{
// If there are no points of interests manually added in the inspector...
if (PointsOfInterest == null || PointsOfInterest.Length == 0)
{
// check the boolean toggle to automatically populate with the children
if (UseAllChildren)
{
PointsOfInterest = new Transform[this.transform.childCount];
for (int i = 0; i < PointsOfInterest.Length; i++)
{
PointsOfInterest[i] = this.transform.GetChild(i);
}
if(PointsOfInterest.Length == 0)
{
Debug.LogWarning(this.gameObject.name + ": ERROR : No Children were found.");
return;
}
}
else
{
// or default to using the object's pivot point
PointsOfInterest = new Transform[1];
PointsOfInterest[0] = this.transform;
}
}
}
}
} | mit |
Steven-N-Hart/vcf-miner | mongo_view/src/main/webapp/js/collections/DatabaseIndexList.js | 206 | // COLLECTION of DatabaseIndex models
var DatabaseIndexList = Backbone.Collection.extend({
model: DatabaseIndex,
localStorage: new Backbone.LocalStorage("mongo-backbone"),
comparator: 'todo'
}); | mit |
carborgar/gestionalumnostfg | gestionalumnos/urls.py | 6315 | from django.conf.urls import patterns, include, url
from principal.forms import ValidatingPasswordChangeForm
from django.contrib.auth import views as auth_views
# Custom error views
handler404 = 'principal.views.StaticViews.error_404'
handler500 = 'principal.views.StaticViews.error_500'
urlpatterns = patterns(
'',
# Translation URLS
url(r'^i18n/', include('django.conf.urls.i18n')),
# Application views
url(r'^$', 'principal.views.StaticViews.home'),
url(r'^cookies_policy$', 'principal.views.StaticViews.cookies_policy'),
url(r'^login/$', auth_views.login, {'template_name': 'login.html'}),
url(r'^password_change/$', auth_views.password_change, {'password_change_form': ValidatingPasswordChangeForm,'template_name': 'user/password_change.html', 'post_change_redirect': '/'}),
url(r'^logout/$', auth_views.logout_then_login),
url(r'^admin/certification/create', 'principal.views.CertificationViews.create_certification'),
url(r'^admin/certification/list', 'principal.views.CertificationViews.list_certifications'),
url(r'^admin/certification/search/$', 'principal.views.CertificationViews.search'),
url(r'^admin/certification/delete/(?P<certification_id>[0-9]+)$', 'principal.views.CertificationViews.delete_certification'),
url(r'^admin/certification/details/(?P<certification_id>[0-9]+)$', 'principal.views.CertificationViews.details_certification'),
url(r'^lecturer/details/(?P<lecturer_id>[0-9]+)?$', 'principal.views.TutorialViews.view_tutorials'),
url(r'^subject/list/', 'principal.views.SubjectViews.list_subjects'),
url(r'^student/lecturer/list/(?P<subject_id>[0-9]+)$', 'principal.views.LecturerViews.list_lecturers'),
url(r'^student/tutorial/create/$', 'principal.views.TutorialViews.create_tutorial'),
url(r'^rest/lecturer/(?P<subject_id>[0-9]+)$', 'principal.views.LecturerViews.get_lecturers_json'),
url(r'^rest/subject/all$', 'principal.views.SubjectViews.get_all_json'),
url(r'^admin/department/list', 'principal.views.DepartmentViews.list_departments'),
url(r'^admin/department/edit/(?P<department_id>[0-9]+)?$', 'principal.views.DepartmentViews.edit_department'),
url(r'^admin/department/search/$', 'principal.views.DepartmentViews.search'),
url(r'^admin/department/details/(?P<department_id>[0-9]+)$', 'principal.views.DepartmentViews.details_department'),
url(r'^admin/user/create', 'principal.views.UserViews.create_user'),
url(r'^admin/user/list', 'principal.views.UserViews.list_users'),
url(r'^admin/user/delete/(?P<user_id>[0-9]+)$', 'principal.views.UserViews.delete_user'),
url(r'^admin/user/search/$', 'principal.views.UserViews.search'),
url(r'^admin/user/details/(?P<user_id>[0-9]+)$', 'principal.views.UserViews.details_user'),
url(r'^profile/view/(?P<student_id>[0-9]+)?$', 'principal.views.ProfileViews.view_profile'),
url(r'^admin/subject/create', 'principal.views.SubjectViews.create_subject'),
url(r'^admin/subject/link/(?P<subject_id>[0-9]+)$', 'principal.views.SubjectLinkViews.create'),
url(r'^subject/details/(?P<subject_id>[0-9]+)$', 'principal.views.SubjectViews.subject_details'),
url(r'^admin/subject/delete/(?P<subject_id>[0-9]+)$', 'principal.views.SubjectViews.delete_subject'),
url(r'^admin/subject/delete/users/(?P<subject_id>[0-9]+)$', 'principal.views.SubjectViews.delete_users_subject'),
url(r'^student/profile/edit$', 'principal.views.ProfileViews.edit_profile'),
url(r'^lecturer/tutorial/edit/(?P<tutorial_id>[0-9]+)$', 'principal.views.TutorialViews.view_tutorials'),
url(r'^lecturer/tutorial/delete/(?P<tutorial_id>[0-9]+)$', 'principal.views.TutorialViews.delete_tutorial'),
url(r'^lecturer/tutorial/enable', 'principal.views.TutorialViews.enable_tutorials'),
url(r'^lecturer/tutorial/disable', 'principal.views.TutorialViews.disable_tutorials'),
url(r'^lecturer/tutorialRequest/list', 'principal.views.TutorialRequestViews.view_requests'),
url(r'^lecturer/request/accept/(?P<tutorial_request_id>[0-9]+)$', 'principal.views.TutorialRequestViews.accept_request'),
url(r'^lecturer/request/reject$', 'principal.views.TutorialRequestViews.view_requests'),
url(r'^tutorialRequest/accepted', 'principal.views.TutorialRequestViews.accepted_requests'),
url(r'^student/tutorialRequest/all', 'principal.views.TutorialRequestViews.student_all_requests'),
url(r'^rest/lecturer/tutorial/(?P<timestamp_from>[0-9]+)/(?P<timestamp_to>[0-9]+)/(?P<utc_offset>-?[0-9]+)$', 'principal.views.TutorialViews.tutorials_json'),
url(r'^admin/subject/link/user/(?P<subject_id>[0-9]+)/(?P<user_id>[0-9]+)?$', 'principal.views.SubjectLinkViews.link_user_subject'),
url(r'^admin/subject/unlink/user/(?P<subject_id>[0-9]+)/(?P<user_id>[0-9]+)$', 'principal.views.SubjectLinkViews.unlink_user_subject'),
url(r'^admin/user/import/$', 'principal.views.UserViews.import_users'),
url(r'^admin/department/import/$', 'principal.views.DepartmentViews.import_department'),
url(r'^lecturer/tutorial/calendar/$', 'principal.views.TutorialRequestViews.tutorial_calendar'),
url(r'^lecturer/student/list/$', 'principal.views.ProfileViews.lecturer_students'),
url(r'^lecturer/profile/edit/$', 'principal.views.ProfileViews.edit_lecturer'),
url(r'^news/((?P<new_id>[0-9]+)/(?P<method>\w{2}))?$', 'principal.views.NewViews.news'),
url(r'^news/add$', 'principal.views.NewViews.news'),
url(r'^new/save', 'principal.views.NewViews.news'),
url(r'^admin/subject/import/$', 'principal.views.SubjectViews.import_subject'),
url(r'^admin/subject/import/link/(?P<subject_id>[0-9]+)$', 'principal.views.SubjectLinkViews.import_link_subject'),
url(r'^admin/subject/unlink/certification/(?P<subject_id>[0-9]+)/(?P<certification_id>[0-9]+)$', 'principal.views.SubjectLinkViews.unlink_certification_subject'),
url(r'^student/tutorial/seek/(?P<lecturer_id>[0-9]+)?', 'principal.views.TutorialRequestViews.seek_tutorial'),
url(r'^rest/tutorials', 'principal.views.TutorialRequestViews.tutorials_json'),
url(r'^subject/search/$', 'principal.views.SubjectViews.search'),
url(r'^lecturer/tutorial/assign', 'principal.views.TutorialRequestViews.auto_assign_tutorial'),
url(r'^rest/lecturer/request/accept', 'principal.views.TutorialRequestViews.accept_from_mail'),
)
| mit |
rootsdev/gedcomx-fs-js | test/NameForm.js | 912 | var assert = require('chai').assert,
GedcomX = require('gedcomx-js');
describe('NameForm property extensions', function(){
describe('nameFormInfo', function(){
var json = {
"nameFormInfo" : [ {
"order" : "http://familysearch.org/v1/Eurotypic"
} ]
};
it('Create with JSON', function(){
test(GedcomX.NameForm(json));
});
it('Build', function(){
test(GedcomX.NameForm()
.addNameFormInfo(
GedcomX.NameFormInfo()
.setOrder(json.nameFormInfo[0].order)
));
});
it('toJSON', function(){
assert.deepEqual(GedcomX.NameForm(json).toJSON(), json);
});
function test(nameForm){
assert.equal(nameForm.getNameFormInfo().length, 1);
var nameFormInfo = nameForm.getNameFormInfo()[0];
assert.equal(nameFormInfo.getOrder(), json.nameFormInfo[0].order);
}
});
}); | mit |
WeCamp/flyingliquourice | src/Domain/Game/FieldAlreadyBeenShotException.php | 117 | <?php
namespace Wecamp\FlyingLiquorice\Domain\Game;
class FieldAlreadyBeenShotException extends GameException
{
}
| mit |
kolrinah/pmc_sf2 | src/Pmc/IntranetBundle/Form/FiltrosPublicacoesType.php | 3060 | <?php
/**
* Description of FiltrosPublicacoesType
*
* @author Héctor Martínez / +58-416-9052533
*/
namespace Pmc\IntranetBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
class FiltrosPublicacoesType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('patron', 'text', array('label'=>'Padrão',
'required'=>false,
'attr'=>array(
'maxlength'=>'20',
'class'=>'form-control',
'placeholder'=>'Escreva seu padrão de pesquisa',
'title'=>'Padrão de pesquisa')))
->add('secretarias', 'entity', array('label'=>'Filtrar por Secretaria:',
'class' => 'PmcIntranetBundle:Secretaria',
'property' => 'nome',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('s')
->orderBy('s.nome', 'ASC');},
'required'=>false,
'multiple'=>true,
'expanded'=>true,))
->add('status', 'choice', array('label' => 'Filtrar por Status:',
'required' => false,
'multiple'=> false,
'expanded'=> true,
'empty_value' => false,
'choices' => array('0' => 'Mostrar solo Ativos',
'1' => 'Mostrar solo Inativos',
'3' => 'Mostrar Todos',)))
->add('puntero', 'hidden', array('attr'=>array('value'=>'0')) )
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
/*'data_class' => 'Pmc\IntranetBundle\Entity\Secretaria',*/
'csrf_protection' => true,
'csrf_field_name' => '_token',
// una clave única para ayudar generar la ficha secreta
'intention' => 'task_item',
));
}
public function getName()
{
return 'form';
}
}
?>
| mit |
ricmrodrigues/webapplicationframeworks | myproject/config/initializers/secret_token.rb | 500 | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Myproject::Application.config.secret_token = '0ccbd3db4d2f027117e56533a63a8241e387db893dfca45a1ea5a13374cafbc13fc3745b768d9f120288fbe794f4f1d4dbdbb448c2a28a3a7bf64dcebf0ced93'
| mit |
Deathnerd/CSC310 | src/main/com/gilleland/george/exceptions/ElementNotFoundException.java | 153 | package com.gilleland.george.exceptions;
/**
* Created by Wes Gilleland on 11/23/2015.
*/
public class ElementNotFoundException extends Exception {
}
| mit |
asabirov/yspell | lib/yspell/cli/presenter.rb | 1742 | # coding: utf-8
require 'rainbow'
module YSpell
module CLI
class Presenter
require 'rainbow/ext/string'
def initialize(out, err)
@out = out
@err = err
@verbose = false
end
def draw(text, spell_errors, options)
@verbose = options.verbose
if spell_errors.empty?
@out.puts text
@out.puts
@out.puts "It seems ok!".color(:green)
return
end
highlight_errors(text, spell_errors, options)
if options.suggestions == :after
print_suggestions(spell_errors)
end
end
def puts(text)
@out.puts text
end
def error(text)
@err.puts text.color(:red)
end
def info(msg)
@out.puts(msg) if @verbose
end
private
def highlight_errors(text, errors, options)
row = 0
text.each_line do |line|
row_errors = errors.select{|err| err.row == row}.sort_by{|err| err.position}.reverse
@out.puts print_text_with_highlights(line, row_errors, options)
row = row + 1
end
end
def print_text_with_highlights(string, errors, options)
errors.each do |error|
replace_with = error.colored_word
if options.suggestions == :inline
replace_with << " (#{error.suggestions.join(', ')}?)".color(:yellow)
end
string[error.column...(error.column + error.length)] = replace_with
end
string
end
def print_suggestions(errors)
@out.puts
errors.each do |error|
@out.puts "#{error.word} — #{error.suggestions.join(', ')}".color(:yellow)
end
end
end
end
end | mit |
chstein/sportdiary | sources/Sporty.Jobs/IScheduledJob.cs | 213 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sporty.Jobs
{
public interface IScheduledJob
{
void Run();
}
}
| mit |
lenonwang/AndroidLibrary | AndroidProjectLibrary/src/com/goldpalm/shanggang/utils/package-info.java | 188 | /**
* Copyright@2014
*
* Author is wanglei.
*
* All right reserved
*
* Created on 2014 2014-9-1 下午12:16:20
*/
/**
* @author wanglei
*/
package com.goldpalm.shanggang.utils; | mit |
Tnifey/webpack-kit | webpack.config.js | 3303 | const webpack = require('webpack');
const path = require('path');
const HWP = require('html-webpack-plugin');
const BSWP = require('browser-sync-webpack-plugin');
const NIWP = require('npm-install-webpack-plugin');
module.exports = {
/* entry point */
entry: "./src/app.js", // default: ./src/app.js
/* output options */
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
/* target */
target: "web",
/* modules */
module: {
/* loaders */
rules: [
/* babel-loader */
{
test: /\.jsx?$/,
loader: "babel-loader",
options: {
presets: ["env"],
}
},
/* html loader */
{
test: /\.html?$/,
loader: "html-loader",
options: {
minimize: true,
removeComments: true,
removeCommentsFromCDATA: true,
collapseWhitespace: true,
conservativeCollapse: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
removeScriptTypeAttributes: true,
removeStyleTypeAttributes: true,
}
},
/* css loader / style loader */
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true,
}
},
]
},
/* sass loader | scss loader */
{
test: /\.(sass|scss)$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true,
}
},
"sass-loader"
]
},
/* svg inline loader - svg */
{
test: /\.svg$/,
loader: "svg-inline-loader"
},
/* json loader - .json */
{
test: /\.json$/,
loader: "json-loader"
},
/* json5 loader - .json5 */
{
test: /\.json5$/,
loader: "json5-loader"
},
/* raw text */
{
test: /\.(txt|raw)$/,
loader: "raw-loader",
},
/* fonts loader */
{
test: /\.(ttf|woff2?|otf|fnt|eot)$/,
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "assets/fonts",
}
},
/* images loader */
{
test: /\.(bmp|gif|ico|jpe?g|png|tiff?|webp)$/,
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "assets/images/",
}
},
/* audio loader */
{
test: /\.(wav|mp3|ogg|flac|acc)$/,
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "assets/audios/",
}
},
/* video loader */
{
test: /\.(mp4|webm|ogv|wmv)$/,
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "assets/videos/",
}
},
/* file loader */
{
test: /\.(7z|arj|deb|pkg|rar|rpm|gz|z|zip|bin|dmg|iso|toast|vcd|apk|bat|bin|cgi|pl|com|exe|gadget|jar|py|wsf|docx?|odt|pdf|rtf|tex|odp|pp[st]|pptx)$/,
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "assets/files/",
}
},
]
},
/* Plugins */
plugins: [
/* create index.html */
new HWP(),
/* browser sync */
new BSWP({
host: 'localhost',
port: 3000,
cache: false,
server: {
baseDir: "dist"
},
notify: false, // without notification bubble
}),
/* automatically installing & saving dependencies - npm install plugin */
new NIWP({
dev: false,
quiet: true,
peerDependencies: true,
}),
]
} | mit |
emartech/split-sms | lib/gsmvalidator.js | 1637 | 'use strict';
// '@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ\x20!"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà\f^{}\\[~]|€'
var GSM_charCodes = [
10,12,13,32,33,34,35,36,
37,38,39,40,41,42,43,44,
45,46,47,48,49,50,51,52,
53,54,55,56,57,58,59,60,
61,62,63,64,65,66,67,68,
69,70,71,72,73,74,75,76,
77,78,79,80,81,82,83,84,
85,86,87,88,89,90,91,92,
93,94,95,97,98,99,100,101,
102,103,104,105,106,107,108,
109,110,111,112,113,114,115,
116,117,118,119,120,121,122,
123,124,125,126,161,163,164,
165,167,191,196,197,198,199,
201,209,214,216,220,223,224,
228,229,230,232,233,236,241,
242,246,248,249,252,915,916,
920,923,926,928,931,934,936,
937,8364
];
// '\f|^€{}[~]\\'
var GSMe_charCodes = [12,91,92,93,94,123,124,125,126,8364];
function existsInArray(code, array) {
var len = array.length;
var i = 0;
while (i < len) {
var e = array[i];
if (code === e) return true;
i++;
}
return false;
}
function validateCharacter(character) {
var code = character.charCodeAt(0);
return existsInArray(code, GSM_charCodes);
}
function validateMessage(message) {
for (var i = 0; i < message.length; i++) {
if (!validateCharacter(message.charAt(i)))
return false;
}
return true;
}
function validateExtendedCharacter(character) {
var code = character.charCodeAt(0);
return existsInArray(code, GSMe_charCodes);
}
module.exports.validateCharacter = validateCharacter;
module.exports.validateMessage = validateMessage;
module.exports.validateExtendedCharacter = validateExtendedCharacter;
| mit |
Shigeppon/derrata | app/models/resource_data.rb | 44 | class ResourceData < ActiveRecord::Base
end
| mit |
andersonjonathan/Navitas | navitas/recipes/migrations/0002_recipe_modified.py | 558 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('recipes', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='modified',
field=models.DateTimeField(default=datetime.datetime(2017, 3, 30, 22, 30, 19, 895832, tzinfo=utc), editable=False),
preserve_default=False,
),
]
| mit |
jakegornall/MeatFestWebsite | node_modules/flow-runtime/lib/errorReporting/makeTypeError.js | 2524 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.default = makeTypeError;
var _Validation = require('../Validation');
var _RuntimeTypeError = require('./RuntimeTypeError');
var _RuntimeTypeError2 = _interopRequireDefault(_RuntimeTypeError);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var delimiter = '\n-------------------------------------------------\n\n';
function makeTypeError(validation) {
if (!validation.hasErrors()) {
return;
}
var input = validation.input,
context = validation.context;
var collected = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = validation.errors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ref = _step.value;
var _ref2 = _slicedToArray(_ref, 3);
var path = _ref2[0];
var message = _ref2[1];
var expectedType = _ref2[2];
var expected = expectedType ? expectedType.toString() : "*";
var actual = context.typeOf((0, _Validation.resolvePath)(input, path)).toString();
var field = (0, _Validation.stringifyPath)(validation.inputName ? [validation.inputName].concat(path) : path);
collected.push(field + ' ' + message + '\n\nExpected: ' + expected + '\n\nActual: ' + actual + '\n');
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var error = new _RuntimeTypeError2.default(collected.join(delimiter));
return error;
} | mit |
spleenboy/pallium | app/ui/SortableList.js | 2614 | import React, { Component, PropTypes } from 'react';
import styles from './SortableList.css';
export default class SortableList extends Component {
static propTypes = {
items: PropTypes.array.isRequired,
onChange: PropTypes.func,
onSortStart: PropTypes.func,
onSortStop: PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
sortIndex: -1,
}
}
handleDragOver(i, e) {
e.dataTransfer.dropEffect = 'move';
e.target.classList.add(styles.active);
e.preventDefault();
}
handleDragLeave(i, e) {
e.dataTransfer.dropEffect = 'none';
e.target.classList.remove(styles.active);
}
handleDragDrop(newIndex, e) {
e.target.classList.remove(styles.active);
const oldIndex = this.state.sortIndex;
// If you're moving from the top, the slots shift up by one number
if (oldIndex === 0 && newIndex > 0) {
newIndex--;
}
this.props.onChange && this.props.onChange(oldIndex, newIndex);
this.setState({sortIndex: -1});
}
handleDragStart(sortItem, sortIndex, e) {
this.setState({sortIndex});
this.props.onSortStart && this.props.onSortStart(sortItem, sortIndex, e);
}
handleDragEnd(sortItem, sortIndex, e) {
this.setState({sortIndex: -1});
}
render() {
if (!this.props.items) {
return null;
}
if (this.props.items.length < 2) {
return (
<div>{this.props.items}</div>
);
}
const dropzone = (ctx, index, key) => {
return (
<div
key={key}
onDragOver={ctx.handleDragOver.bind(ctx, index)}
onDragLeave={ctx.handleDragLeave.bind(ctx, index)}
onDrop={ctx.handleDragDrop.bind(ctx, index)}
className={styles.droppable}></div>
);
};
let items = [];
this.props.items.forEach((item, i) => {
const style = this.state.sortIndex === i ? styles.dragging : styles.item;
items.push(dropzone(this, i, items.length))
items.push(
<div key={items.length} className={styles.item}>
<div
className={styles.draggable}
onDragStart={this.handleDragStart.bind(this, item, i)}
onDragEnd={this.handleDragEnd.bind(this, item, i)}
draggable={true}
>
{item}
</div>
</div>
);
});
items.push(dropzone(this, this.props.items.length, items.length));
let sortState = this.state.sortIndex >= 0 ? styles.sorting : styles.waiting;
return (
<div className={`${styles.sortable} ${sortState}`}>
{items}
</div>
);
}
}
| mit |
beowulfe/HAP-Java | src/main/java/io/github/hapjava/characteristics/impl/slat/SlatTypeEnum.java | 768 | package io.github.hapjava.characteristics.impl.slat;
import io.github.hapjava.characteristics.CharacteristicEnum;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
/** 0 ”Horizontal” 1 ”Vertical” */
public enum SlatTypeEnum implements CharacteristicEnum {
HORIZONTAL(0),
VERTICAL(1);
private static final Map<Integer, SlatTypeEnum> reverse;
static {
reverse =
Arrays.stream(SlatTypeEnum.values())
.collect(Collectors.toMap(SlatTypeEnum::getCode, t -> t));
}
public static SlatTypeEnum fromCode(Integer code) {
return reverse.get(code);
}
private final int code;
SlatTypeEnum(int code) {
this.code = code;
}
@Override
public int getCode() {
return code;
}
}
| mit |
mathiasbynens/iso-8859-15 | scripts/transform-data.js | 2188 | const fs = require('fs');
const jsesc = require('jsesc');
const template = require('lodash.template');
function format(object) {
return jsesc(object, {
json: true,
compact: false,
}) + '\n';
}
function parse(source) {
const indexByCodePoint = {};
const indexByPointer = {};
let decoded = '';
const encoded = [];
var lines = source.split('\n');
for (const line of lines) {
const data = line.trim().split('\t');
if (data.length != 3) {
continue;
}
const pointer = Number(data[0]);
const codePoint = Number(data[1]);
const symbol = String.fromCodePoint(codePoint);
decoded += symbol;
encoded.push(pointer + 0x80);
indexByCodePoint[codePoint] = pointer;
indexByPointer[pointer] = symbol;
}
return {
decoded: decoded,
encoded: encoded,
indexByCodePoint: indexByCodePoint,
indexByPointer: indexByPointer
};
}
const source = fs.readFileSync('./data/index.txt', 'utf-8');
const result = parse(source);
fs.writeFileSync(
'./data/index-by-code-point.json',
format(result.indexByCodePoint)
);
fs.writeFileSync(
'./data/index-by-pointer.json',
format(result.indexByPointer)
);
fs.writeFileSync(
'./data/decoded.json',
format(result.decoded)
);
fs.writeFileSync(
'./data/encoded.json',
format(result.encoded)
);
const TEMPLATE_OPTIONS = {
interpolate: /<\%=([\s\S]+?)%\>/g,
};
// tests/tests.src.js → tests/tests.js
const TEST_TEMPLATE = fs.readFileSync('./tests/tests.src.mjs', 'utf8');
const createTest = template(TEST_TEMPLATE, TEMPLATE_OPTIONS);
const testCode = createTest(require('./export-data.js'));
fs.writeFileSync('./tests/tests.mjs', testCode);
// src/iso-8859-15.src.mjs → iso-8859-15.mjs
const LIB_TEMPLATE = fs.readFileSync('./src/iso-8859-15.src.mjs', 'utf8');
const createLib = template(LIB_TEMPLATE, TEMPLATE_OPTIONS);
const libCode = createLib(require('./export-data.js'));
fs.writeFileSync('./iso-8859-15.mjs', libCode);
// src/iso-8859-15.d.ts → iso-8859-15.d.ts
const TYPES_TEMPLATE = fs.readFileSync('./src/iso-8859-15.d.ts', 'utf8');
const createTypes = template(TYPES_TEMPLATE, TEMPLATE_OPTIONS);
const typesCode = createTypes(require('./export-data.js'));
fs.writeFileSync('./iso-8859-15.d.ts', typesCode);
| mit |
GluuFederation/oxCore | oxJsfUtil/src/main/java/org/gluu/jsf2/customization/Utils.java | 1806 | package org.gluu.jsf2.customization;
import java.io.File;
import org.gluu.util.StringHelper;
/**
* Created by eugeniuparvan on 5/1/17.
*/
public final class Utils {
private static final String SERVER_BASE_PATH = "server.base";
private static final String CUSTOM_PAGES_PATH = "/custom/pages";
private static final String CUSTOM_LOCALIZATION_PATH = "/custom/i18n";
private Utils() { }
public static boolean isCustomPagesDirExists() {
String externalResourceBase = getCustomPagesPath();
if (StringHelper.isNotEmpty(externalResourceBase)) {
File folder = new File(externalResourceBase);
boolean result = folder.exists() && folder.isDirectory();
return result;
} else {
return false;
}
}
public static boolean isCustomLocalizationDirExists() {
String externalResourceBase = getCustomLocalizationPath();
if (StringHelper.isNotEmpty(externalResourceBase)) {
File folder = new File(externalResourceBase);
boolean result = folder.exists() && folder.isDirectory();
return result;
} else {
return false;
}
}
public static String getCustomPagesPath() {
String externalResourceBase = System.getProperty(SERVER_BASE_PATH);
if (StringHelper.isNotEmpty(externalResourceBase)) {
externalResourceBase += CUSTOM_PAGES_PATH;
}
return externalResourceBase;
}
public static String getCustomLocalizationPath() {
String externalResourceBase = System.getProperty(SERVER_BASE_PATH);
if (StringHelper.isNotEmpty(externalResourceBase)) {
externalResourceBase += CUSTOM_LOCALIZATION_PATH;
}
return externalResourceBase;
}
}
| mit |
ParrotFx/Parrot.Ruby | Lexer/unexpected_token_exception.rb | 51 | class UnexpectedTokenException < StandardError
end | mit |
cofoundry-cms/cofoundry | src/Cofoundry.Web.Admin/Admin/Modules/Shared/Js/UIComponents/DocumentAssets/FormFieldDocumentAsset.js | 4816 | /**
* A form field control for an image asset that uses a search and pick dialog
* to allow the user to change the selected file.
*/
angular.module('cms.shared').directive('cmsFormFieldDocumentAsset', [
'_',
'shared.internalModulePath',
'shared.internalContentPath',
'shared.modalDialogService',
'shared.stringUtilities',
'shared.documentService',
'shared.urlLibrary',
'baseFormFieldFactory',
function (
_,
modulePath,
contentPath,
modalDialogService,
stringUtilities,
documentService,
urlLibrary,
baseFormFieldFactory) {
/* CONFIG */
var config = {
templateUrl: modulePath + 'UIComponents/DocumentAssets/FormFieldDocumentAsset.html',
scope: _.extend(baseFormFieldFactory.defaultConfig.scope, {
asset: '=cmsAsset',
loadState: '=cmsLoadState',
updateAsset: '@cmsUpdateAsset' // update the asset property if it changes
}),
passThroughAttributes: ['required'],
link: link
};
return baseFormFieldFactory.create(config);
/* LINK */
function link(scope, el, attributes, controllers) {
var vm = scope.vm,
isRequired = _.has(attributes, 'required'),
isAssetInitialized;
init();
return baseFormFieldFactory.defaultConfig.link(scope, el, attributes, controllers);
/* INIT */
function init() {
vm.urlLibrary = urlLibrary;
vm.showPicker = showPicker;
vm.remove = remove;
vm.isRemovable = _.isObject(vm.model) && !isRequired;
vm.filter = parseFilters(attributes);
scope.$watch("vm.asset", setAsset);
scope.$watch("vm.model", setAssetById);
}
/* EVENTS */
function remove() {
setAsset(null);
}
function showPicker() {
modalDialogService.show({
templateUrl: modulePath + 'UIComponents/DocumentAssets/DocumentAssetPickerDialog.html',
controller: 'DocumentAssetPickerDialogController',
options: {
currentAsset: vm.previewAsset,
filter: vm.filter,
onSelected: onSelected
}
});
function onSelected(newAsset) {
if (!newAsset && vm.asset) {
setAsset(null);
} else if (!vm.asset || (newAsset && vm.asset.documentAssetId !== newAsset.documentAssetId)) {
setAsset(newAsset);
}
}
}
/**
* When the model is set without a preview asset, we need to go get the full
* asset details. This query can be bypassed by setting the cms-asset attribute
*/
function setAssetById(assetId) {
// Remove the id if it is 0 or invalid to make sure required validation works
if (!assetId) {
vm.model = assetId = undefined;
}
if (assetId && (!vm.previewAsset || vm.previewAsset.documentAssetId != assetId)) {
documentService.getById(assetId).then(function (asset) {
setAsset(asset);
});
}
}
/**
* Initialise the state when the asset is changed
*/
function setAsset(asset) {
if (asset) {
vm.previewAsset = asset;
vm.isRemovable = !isRequired;
vm.model = asset.documentAssetId;
if (vm.updateAsset) {
vm.asset = asset;
}
} else if (isAssetInitialized) {
// Ignore if we are running this first time to avoid overwriting the model with a null vlaue
vm.previewAsset = null;
vm.isRemovable = false;
if (vm.model) {
vm.model = null;
}
if (vm.updateAsset) {
vm.asset = null;
}
}
setButtonText();
isAssetInitialized = true;
}
/* Helpers */
function parseFilters(attributes) {
var filter = {},
attributePrefix = 'cms';
setAttribute('Tags');
setAttribute('FileExtension');
setAttribute('FileExtensions');
return filter;
function setAttribute(attributeName) {
var filterName = stringUtilities.lowerCaseFirstWord(attributeName);
filter[filterName] = attributes[attributePrefix + attributeName];
}
}
function setButtonText() {
vm.buttonText = vm.model ? 'Change' : 'Select';
}
}
}]); | mit |
jreinert/social-share-privacy | lib/generators/social_share_privacy/install_generator.rb | 534 | module SocialSharePrivacy
module Generators
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
def copy_locales
copy_file "en_social_share_privacy.yml", "config/locales/en_social_share_privacy.yml"
copy_file "de_social_share_privacy.yml", "config/locales/de_social_share_privacy.yml"
end
def copy_initializer
copy_file "social_share_privacy.rb", "config/initializers/social_share_privacy.rb"
end
end
end
end
| mit |
minodisk/DefinitelyTyped | types/gulp-pug/gulp-pug-tests.ts | 198 | import { src, dest } from 'gulp';
import * as gulpPug from 'gulp-pug';
let s1 = gulpPug();
let s2 = gulpPug({});
let s3 = gulpPug({ basedir: '.' });
src('fixtures.js').pipe(s1).pipe(s2).pipe(s3);
| mit |
okhosting/OKHOSTING.Hosting | src/PCL/OKHOSTING.Hosting.Shared.Plesk/Sql/Server.cs | 9461 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OKHOSTING.Hosting.SQL;
using System.Xml.Linq;
namespace OKHOSTING.Hosting.Shared.Plesk.SQL
{
public class Server: Hosting.SQL.Server
{
public Plesk.Server Container
{
get; set;
}
public int PleskId
{
get;
set;
}
public DataBaseType DataBaseType
{
get;
set;
}
public override bool IsReadOnly
{
get
{
return false;
}
}
protected override int CountDataBases
{
get
{
return ((ICollection<DataBase>) this).Count();
}
}
protected override int CountUsers
{
get
{
return ((ICollection<OKHOSTING.SQL.Schema.User>) this).Count();
}
}
public override void Add(Hosting.SQL.DataBase item)
{
var database = (DataBase) item;
var container = (Account) database.Container;
XDocument request = XDocument.Parse(Resources.Commands.AddSQLDatabase);
//Adding Database ID
request.Element("packet").Element("database").Element("add-db").Element("domain-id").Value = container.PleskId.ToString();
//Adding Database name
request.Element("packet").Element("database").Element("add-db").Element("name").Value = database.Name;
//Adding Database type
request.Element("packet").Element("database").Element("add-db").Element("type").Value = database.DataBaseType.ToString();
//add sql server id
request.Element("packet").Element("database").Element("add-db").Element("db-server-id").Value = PleskId.ToString();
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("add-db").Element("result").Element("status").Value == "ok")
{
database.PleskId = int.Parse(result.Element("packet").Element("database").Element("add-db").Element("result").Element("id").Value);
}
else
{
throw new Exception(request, result, "Error creating database");
}
}
public override void Add(OKHOSTING.SQL.Schema.User item)
{
var user = (User) item;
var database = (DataBase) item.DataBase;
var container = (Account) database.Container;
XDocument request = XDocument.Parse(Resources.Commands.AddSQLUser);
request.Element("packet").Element("database").Element("add-db-user").Element("db-id").Value = database.PleskId.ToString();
request.Element("packet").Element("database").Element("add-db-user").Element("login").Value = user.Username;
request.Element("packet").Element("database").Element("add-db-user").Element("password").Value = user.Password;
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("add-db-user").Element("result").Element("status").Value == "ok")
{
user.PleskId = int.Parse(result.Element("packet").Element("database").Element("add-db-user").Element("result").Element("id").Value);
}
else
{
throw new Exception(request, result, "Error creating database user");
}
}
public override bool Contains(Hosting.SQL.DataBase item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
XDocument request = XDocument.Parse(Resources.Commands.GetSQLDataBases);
var database = (DataBase) item;
XElement dbid = new XElement("id");
dbid.Value = database.PleskId.ToString();
request.Element("packet").Element("database").Element("get-db").Element("filter").Add(dbid);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("get-db").Element("result").Element("status").Value == "ok")
{
return true;
}
else
{
return false;
}
}
public override bool Contains(OKHOSTING.SQL.Schema.User item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
XDocument request = XDocument.Parse(Resources.Commands.GetSQLUsers);
var user = (User) item;
XElement dbid = new XElement("id");
dbid.Value = user.PleskId.ToString();
request.Element("packet").Element("database").Element("get-db-users").Element("filter").Add(dbid);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("get-db-users").Element("result").Element("status").Value == "ok")
{
return true;
}
else
{
return false;
}
}
public override bool Remove(Hosting.SQL.DataBase item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
DataBase database = (DataBase) item;
XDocument request = XDocument.Parse(Resources.Commands.RemoveSQLDatabase);
XElement dbid = new XElement("id");
dbid.Value = database.PleskId.ToString();
request.Element("packet").Element("database").Element("del-db").Element("filter").Add(dbid);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("del-db").Element("result").Element("status").Value == "ok")
{
return true;
}
else
{
throw new Exception(request, result, "Error deleting database");
}
}
public override bool Remove(OKHOSTING.SQL.Schema.User item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
var user = (User) item;
XDocument request = XDocument.Parse(Resources.Commands.RemoveSQLUser);
XElement id = new XElement("id");
id.Value = user.PleskId.ToString();
request.Element("packet").Element("database").Element("del-db-user").Element("filter").Add(id);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
if (result.Element("packet").Element("database").Element("del-db-user").Element("result").Element("status").Value == "ok")
{
user.PleskId = int.Parse(result.Element("packet").Element("database").Element("del-db-user").Element("result").Element("id").Value);
return true;
}
else
{
throw new Exception(request, result, "Error deleting database user");
}
}
protected override void ClearDataBases()
{
XDocument request = XDocument.Parse(Resources.Commands.RemoveSQLDatabase);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
}
protected override void ClearUsers()
{
XDocument request = XDocument.Parse(Resources.Commands.RemoveSQLUser);
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
}
protected override IEnumerator<Hosting.SQL.DataBase> GetEnumerator()
{
return GetDatabases(null).GetEnumerator();
}
public IEnumerable<Hosting.SQL.DataBase> GetDatabases(Domain domain)
{
XDocument request = XDocument.Parse(Resources.Commands.GetSQLDataBases);
if (domain != null)
{
XElement domainid = new XElement("domain-id");
domainid.Value = domain.PleskId.ToString();
request.Element("packet").Element("database").Element("get-db").Element("filter").Add(domainid);
}
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
//Validating if exists data on result
if (result.Element("packet").Element("database").Element("get-db").Element("result").Element("status").Value != "ok")
{
throw new Exception(request, result, "Error downloading databases");
}
//Crossing the result nodes
foreach (XElement node in result.Descendants("result"))
{
if (node.Element("id") == null)
{
continue;
}
//only return databases in this particular server
if (PleskId != int.Parse(node.Element("db-server-id").Value))
{
continue;
}
DataBase database = new DataBase();
database.DataBaseType = (DataBaseType) Enum.Parse(typeof(DataBaseType), node.Element("type").Value);
database.Name = node.Element("name").Value;
database.PleskId = int.Parse(node.Element("id").Value);
database.Container = domain;
database.Server = this;
yield return database;
}
}
protected override IEnumerator<OKHOSTING.SQL.Schema.User> GetUserEnumerator()
{
return GetDatabaseUsers(null).GetEnumerator();
}
public IEnumerable<OKHOSTING.SQL.Schema.User> GetDatabaseUsers(DataBase database)
{
XDocument request = XDocument.Parse(Resources.Commands.GetSQLUsers);
if (database != null)
{
XElement dbid = new XElement("db-id");
dbid.Value = database.PleskId.ToString();
request.Element("packet").Element("database").Element("get-db-users").Element("filter").Add(dbid);
}
XDocument result = Container.RunCommand(request);
Container.ValidateErrors(request, result);
//Validating if exists data on result
if (result.Element("packet").Element("database").Element("get-db-users").Element("result").Element("status").Value != "ok")
{
throw new Exception(request, result, "Error downloading database users");
}
//Crossing the result nodes
foreach (XElement node in result.Descendants("result"))
{
User user = new User();
if (node.Element("id") == null)
{
continue;
}
user.PleskId = int.Parse(node.Element("id").Value);
user.Username = node.Element("login").Value;
user.DataBase = database;
yield return user;
}
}
}
} | mit |
petar-p/Java | Homeworks/01-IntroductionToJava/exercises/SummationOfSeries.java | 767 | package exercises;
import java.util.Scanner;
public class SummationOfSeries {
// Write a program that displays the result of
// 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + ... n
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program prints the summation of numbers from 1 to n.");
System.out.print("Please, enter the number n: ");
int biggestNumber = input.nextInt();
input.close();
System.out.println();
int summation = 0;
System.out.print("The sum of ");
for (int i = 1; i <= biggestNumber ; i++) {
System.out.print(i);
if (i != biggestNumber) {
System.out.print(" + ");
}
summation += i;
}
System.out.print(" = " + summation);
}
} | mit |
danielesteban/LedNet | firmware/src/config.hpp | 273 | #ifndef __CONFIG_HPP__
#define __CONFIG_HPP__
/* Server config */
#define SERVER_HOST "projects.gatunes.com"
#define SERVER_PATH "/lednet/led/"
#define SERVER_PORT 443
#define SERVER_SSL 1
/* Hardware config */
#define BUTTON 2
#define LED 0
#endif /* __CONFIG_HPP__ */
| mit |
if-Team/__DEPRECATED__ | HmHmmHm/src/pocketmine/command/defaults/SpawnpointCommand.php | 2912 | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\command\defaults;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\level\Position;
use pocketmine\Player;
use pocketmine\utils\TextFormat;
class SpawnpointCommand extends VanillaCommand{
public function __construct($name){
parent::__construct(
$name,
"Sets a player's spawn point",
"/spawnpoint OR /spawnpoint <player> OR /spawnpoint <player> <x> <y> <z>"
);
$this->setPermission("pocketmine.command.spawnpoint");
}
public function execute(CommandSender $sender, $currentAlias, array $args){
if(!$this->testPermission($sender)){
return \true;
}
$target = \null;
if(\count($args) === 0){
if($sender instanceof Player){
$target = $sender;
}else{
$sender->sendMessage(TextFormat::RED . "Please provide a player!");
return \true;
}
}else{
$target = $sender->getServer()->getPlayer($args[0]);
if($target === \null){
$sender->sendMessage(TextFormat::RED . "Can't find player " . $args[0]);
return \true;
}
}
$level = $target->getLevel();
if(\count($args) === 4){
if($level !== \null){
$pos = $sender instanceof Player ? $sender->getPosition() : $level->getSpawnLocation();
$x = (int) $this->getRelativeDouble($pos->x, $sender, $args[1]);
$y = $this->getRelativeDouble($pos->y, $sender, $args[2], 0, 128);
$z = $this->getRelativeDouble($pos->z, $sender, $args[3]);
$target->setSpawn(new Position($x, $y, $z, $level));
Command::broadcastCommandMessage($sender, "Set " . $target->getDisplayName() . "'s spawnpoint to " . $x . ", " . $y . ", " . $z);
return \true;
}
}elseif(\count($args) <= 1){
if($sender instanceof Player){
$pos = new Position((int) $sender->x, (int) $sender->y, (int) $sender->z, $sender->getLevel());
$target->setSpawn($pos);
Command::broadcastCommandMessage($sender, "Set " . $target->getDisplayName() . "'s spawnpoint to " . $pos->x . ", " . $pos->y . ", " . $pos->z);
return \true;
}else{
$sender->sendMessage(TextFormat::RED . "Please provide a player!");
return \true;
}
}
$sender->sendMessage(TextFormat::RED . "Usage: " . $this->usageMessage);
return \true;
}
}
| mit |
DevinLow/DevinLow.github.io | test/scripts/helpers/list_categories.js | 11407 | 'use strict';
const Promise = require('bluebird');
describe('list_categories', () => {
const Hexo = require('../../../lib/hexo');
const hexo = new Hexo(__dirname);
const Post = hexo.model('Post');
const Category = hexo.model('Category');
const ctx = {
config: hexo.config
};
ctx.url_for = require('../../../lib/plugins/helper/url_for').bind(ctx);
const listCategories = require('../../../lib/plugins/helper/list_categories').bind(ctx);
before(() => hexo.init().then(() => Post.insert([
{source: 'foo', slug: 'foo'},
{source: 'bar', slug: 'bar'},
{source: 'baz', slug: 'baz'},
{source: 'boo', slug: 'boo'},
{source: 'bat', slug: 'bat'}
])).then(posts => Promise.each([
['baz'],
['baz', 'bar'],
['foo'],
['baz'],
['bat', ['baz', 'bar']]
], (cats, i) => posts[i].setCategories(cats))).then(() => {
hexo.locals.invalidate();
ctx.site = hexo.locals.toObject();
ctx.page = ctx.site.posts.data[1];
}));
it('default', () => {
const result = listCategories();
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">bar</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('specified collection', () => {
const result = listCategories(Category.find({
parent: {$exists: false}
}));
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('style: false', () => {
const result = listCategories({
style: false
});
result.should.eql([
'<a class="category-link" href="/categories/bat/">bat<span class="category-count">1</span></a>',
'<a class="category-link" href="/categories/baz/">baz<span class="category-count">4</span></a>',
'<a class="category-link" href="/categories/baz/bar/">bar<span class="category-count">2</span></a>',
'<a class="category-link" href="/categories/foo/">foo<span class="category-count">1</span></a>'
].join(', '));
});
it('show_count: false', () => {
const result = listCategories({
show_count: false
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">bar</a>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a>',
'</li>',
'</ul>'
].join(''));
});
it('class', () => {
const result = listCategories({
class: 'test'
});
result.should.eql([
'<ul class="test-list">',
'<li class="test-list-item">',
'<a class="test-list-link" href="/categories/bat/">bat</a><span class="test-list-count">1</span>',
'</li>',
'<li class="test-list-item">',
'<a class="test-list-link" href="/categories/baz/">baz</a><span class="test-list-count">4</span>',
'<ul class="test-list-child">',
'<li class="test-list-item">',
'<a class="test-list-link" href="/categories/baz/bar/">bar</a><span class="test-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="test-list-item">',
'<a class="test-list-link" href="/categories/foo/">foo</a><span class="test-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('depth', () => {
const result = listCategories({
depth: 1
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('orderby', () => {
const result = listCategories({
orderby: 'length'
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">bar</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'</ul>'
].join(''));
});
it('order', () => {
const result = listCategories({
order: -1
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">bar</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('transform', () => {
const result = listCategories({
transform(name) {
return name.toUpperCase();
}
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">BAT</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/">BAZ</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">BAR</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">FOO</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('separator (blank)', () => {
const result = listCategories({
style: false,
separator: ''
});
result.should.eql([
'<a class="category-link" href="/categories/bat/">bat<span class="category-count">1</span></a>',
'<a class="category-link" href="/categories/baz/">baz<span class="category-count">4</span></a>',
'<a class="category-link" href="/categories/baz/bar/">bar<span class="category-count">2</span></a>',
'<a class="category-link" href="/categories/foo/">foo<span class="category-count">1</span></a>'
].join(''));
});
it('separator (non-blank)', () => {
const result = listCategories({
style: false,
separator: '|'
});
result.should.eql([
'<a class="category-link" href="/categories/bat/">bat<span class="category-count">1</span></a>|',
'<a class="category-link" href="/categories/baz/">baz<span class="category-count">4</span></a>|',
'<a class="category-link" href="/categories/baz/bar/">bar<span class="category-count">2</span></a>|',
'<a class="category-link" href="/categories/foo/">foo<span class="category-count">1</span></a>'
].join(''));
});
it('children-indicator', () => {
const result = listCategories({
children_indicator: 'has-children'
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item has-children">',
'<a class="category-list-link" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/baz/bar/">bar</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
it('show-current', () => {
const result = listCategories({
show_current: true
});
result.should.eql([
'<ul class="category-list">',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/bat/">bat</a><span class="category-list-count">1</span>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link current" href="/categories/baz/">baz</a><span class="category-list-count">4</span>',
'<ul class="category-list-child">',
'<li class="category-list-item">',
'<a class="category-list-link current" href="/categories/baz/bar/">bar</a><span class="category-list-count">2</span>',
'</li>',
'</ul>',
'</li>',
'<li class="category-list-item">',
'<a class="category-list-link" href="/categories/foo/">foo</a><span class="category-list-count">1</span>',
'</li>',
'</ul>'
].join(''));
});
});
| mit |
codahale/grump | Godeps/_workspace/src/github.com/Bowery/prompt/output.go | 2651 | // Copyright 2013-2014 Bowery, Inc.
package prompt
import (
"os"
"unicode/utf8"
)
// toBytes converts a slice of runes to its equivalent in bytes.
func toBytes(runes []rune) []byte {
char := make([]byte, utf8.UTFMax)
bytes := make([]byte, 0)
for _, r := range runes {
n := utf8.EncodeRune(char, r)
bytes = append(bytes, char[:n]...)
}
return bytes
}
// Buffer contains state for line editing and writing.
type Buffer struct {
Out *os.File
Prompt string
Echo bool
Cols int
pos int
size int
data []rune
}
// NewBuffer creates a buffer writing to out if echo is true.
func NewBuffer(prompt string, out *os.File, echo bool) *Buffer {
return &Buffer{
Out: out,
Prompt: prompt,
Echo: echo,
data: make([]rune, 0),
}
}
// String returns the data as a string.
func (buf *Buffer) String() string {
return string(buf.data[:buf.size])
}
// Insert inserts characters at the cursors position.
func (buf *Buffer) Insert(rs ...rune) error {
rsLen := len(rs)
total := buf.size + rsLen
if total > len(buf.data) {
buf.data = append(buf.data, make([]rune, rsLen)...)
}
// Shift characters to make room in the correct pos.
if buf.size != buf.pos {
copy(buf.data[buf.pos+rsLen:buf.size+rsLen], buf.data[buf.pos:buf.size])
}
for _, r := range rs {
buf.data[buf.pos] = r
buf.pos++
buf.size++
}
return buf.Refresh()
}
// Start moves the cursor to the start.
func (buf *Buffer) Start() error {
if buf.pos <= 0 {
return nil
}
buf.pos = 0
return buf.Refresh()
}
// End moves the cursor to the end.
func (buf *Buffer) End() error {
if buf.pos >= buf.size {
return nil
}
buf.pos = buf.size
return buf.Refresh()
}
// Left moves the cursor one character left.
func (buf *Buffer) Left() error {
if buf.pos <= 0 {
return nil
}
buf.pos--
return buf.Refresh()
}
// Right moves the cursor one character right.
func (buf *Buffer) Right() error {
if buf.pos >= buf.size {
return nil
}
buf.pos++
return buf.Refresh()
}
// Del removes the character at the cursor position.
func (buf *Buffer) Del() error {
if buf.pos >= buf.size {
return nil
}
// Shift characters after position back one.
copy(buf.data[buf.pos:], buf.data[buf.pos+1:buf.size])
buf.size--
return buf.Refresh()
}
// DelLeft removes the character to the left.
func (buf *Buffer) DelLeft() error {
if buf.pos <= 0 {
return nil
}
// Shift characters from position back one.
copy(buf.data[buf.pos-1:], buf.data[buf.pos:buf.size])
buf.pos--
buf.size--
return buf.Refresh()
}
// EndLine ends the line with CRLF.
func (buf *Buffer) EndLine() error {
_, err := buf.Out.Write(crlf)
return err
}
| mit |
zlsoftdq/Notebook | app/backgrounds/window.js | 1938 | import fs from 'fs'
import path from 'path'
import { app, BrowserWindow, screen } from 'electron'
const dir = app.getPath('userData')
export default (name, options) => {
const stateStoreFile = path.join(dir, 'window-state-' + name + '.json')
const defaultSize = { width: options.width, height: options.height }
let state = {}
let win
const restore = () => {
try {
return Object.assign({}, defaultSize, JSON.parse(fs.readFileSync(stateStoreFile)))
} catch (err) {
return Object.assign({}, defaultSize)
}
}
const getCurrentState = () => {
const position = win.getPosition()
const size = defaultSize.useContentSize ? win.getContentSize() : win.getSize()
return { x: position[0], y: position[1], width: size[0], height: size[1] }
}
const windowWithinBounds = (windowState, bounds) => {
return windowState.x >= bounds.x &&
windowState.y >= bounds.y &&
windowState.x + windowState.width <= bounds.x + bounds.width &&
windowState.y + windowState.height <= bounds.y + bounds.height
}
const resetToDefaults = (windowState) => {
const bounds = screen.getPrimaryDisplay().bounds
return Object.assign({}, defaultSize, {
x: (bounds.width - defaultSize.width) / 2,
y: (bounds.height - defaultSize.height) / 2
})
}
const ensureVisibleOnSomeDisplay = (windowState) => {
const visible = screen.getAllDisplays().some((display) => windowWithinBounds(windowState, display.bounds))
if (!visible) {
return resetToDefaults(windowState)
}
return windowState
}
const saveState = () => {
if (!win.isMinimized() && !win.isMaximized()) {
Object.assign(state, getCurrentState())
}
fs.writeFileSync(stateStoreFile, JSON.stringify(state), 'utf8')
}
state = ensureVisibleOnSomeDisplay(restore())
win = new BrowserWindow(Object.assign({}, options, state))
win.on('close', saveState)
return win
}
| mit |
muskovicsnet/conrate | vendor/engines/pages/lib/conratepages/engine.rb | 98 | module Conratepages
class Engine < ::Rails::Engine
isolate_namespace Conratepages
end
end
| mit |
Bhare8972/LOFAR-LIM | LIM_scripts/stationTimings/autoCorrelator3_stochastic_fitter.py | 58592 | #!/usr/bin/env python3
#python
import time
from os import mkdir, listdir
from os.path import isdir, isfile
from itertools import chain
#from pickle import load
#external
import numpy as np
from scipy.optimize import least_squares, minimize, approx_fprime
#from scipy.signal import hilbert
from matplotlib import pyplot as plt
import h5py
#mine
from LoLIM.prettytable import PrettyTable
from LoLIM.utilities import logger, processed_data_dir, v_air, SId_to_Sname, Sname_to_SId_dict, RTD
#from LoLIM.IO.binary_IO import read_long, write_long, write_double_array, write_string, write_double
#from LoLIM.antenna_response import LBA_ant_calibrator
from LoLIM.porta_code import code_logger, pyplot_emulator
#from LoLIM.signal_processing import parabolic_fit, remove_saturation, data_cut_at_index
from LoLIM.IO.raw_tbb_IO import filePaths_by_stationName, MultiFile_Dal1
#from LoLIM.findRFI import window_and_filter
from LoLIM.stationTimings.autoCorrelator_tools import stationDelay_fitter
#from RunningStat import RunningStat
inv_v_air = 1.0/v_air
#### some random utilities
def none_max(lst):
"""given a list of numbers, return maximum, ignoreing None"""
ret = -np.inf
for a in lst:
if (a is not None) and (a>ret):
ret=a
return ret
def get_radius_ze_az( XYZ ):
radius = np.linalg.norm( XYZ )
ze = np.arccos( XYZ[2]/radius )
az = np.arctan2( XYZ[1], XYZ[0] )
return radius, ze, az
#### main code
class stochastic_fitter:
def __init__(self, source_object_list, initial_guess=None, quick_kill=None):
print("running stochastic fitter")
self.quick_kill = quick_kill
self.source_object_list = source_object_list
## assume globals:
# max_itters_per_loop
# itters_till_convergence
# max_jitter_width
# min_jitter_width
# cooldown
# sorted_antenna_names
self.num_antennas = len(sorted_antenna_names)
self.num_measurments = self.num_antennas*len(source_object_list)
self.num_delays = len(station_order)
#### make guess ####
self.num_DOF = -self.num_delays
self.solution = np.zeros( self.num_delays+4*len(source_object_list) )
self.solution[:self.num_delays] = current_delays_guess
param_i = self.num_delays
for PSE in source_object_list:
self.solution[param_i:param_i+4] = PSE.guess_XYZT
param_i += 4
self.num_DOF += PSE.num_DOF()
if initial_guess is not None: ## use initial guess instead, if given
self.solution = initial_guess
self.initial_guess = np.array( self.solution )
self.rerun()
def objective_fun(self, sol, do_print=False):
workspace_sol = np.zeros(self.num_measurments, dtype=np.double)
delays = sol[:self.num_delays]
ant_i = 0
param_i = self.num_delays
for PSE in self.source_object_list:
PSE.try_location_LS(delays, sol[param_i:param_i+4], workspace_sol[ant_i:ant_i+self.num_antennas])
ant_i += self.num_antennas
param_i += 4
filter = np.logical_not( np.isfinite(workspace_sol) )
workspace_sol[ filter ] = 0.0
if do_print:
print("num func nans:", np.sum(filter))
return workspace_sol
# workspace_sol *= workspace_sol
# return np.sum(workspace_sol)
def objective_jac(self, sol, do_print=False):
workspace_jac = np.zeros((self.num_measurments, self.num_delays+4*len(self.source_object_list)), dtype=np.double)
delays = sol[:self.num_delays]
ant_i = 0
param_i = self.num_delays
for PSE in self.source_object_list:
PSE.try_location_JAC(delays, sol[param_i:param_i+4], workspace_jac[ant_i:ant_i+self.num_antennas, param_i:param_i+4],
workspace_jac[ant_i:ant_i+self.num_antennas, 0:self.num_delays])
filter = np.logical_not( np.isfinite(workspace_jac[ant_i:ant_i+self.num_antennas, param_i+3]) )
workspace_jac[ant_i:ant_i+self.num_antennas, param_i:param_i+4][filter] = 0.0
workspace_jac[ant_i:ant_i+self.num_antennas, 0:self.num_delays][filter] = 0.0
ant_i += self.num_antennas
param_i += 4
if do_print:
print("num jac nans:", np.sum(filter))
return workspace_jac
def get_RMS(self, solution):
total_RMS = 0.0
new_station_delays = solution[:self.num_delays]
param_i = self.num_delays
for PSE in self.source_object_list:
total_RMS += PSE.SSqE_fit( new_station_delays, solution[param_i:param_i+4] )
param_i += 4
return np.sqrt(total_RMS/self.num_DOF)
def rerun(self):
current_guess = np.array( self.solution )
#### first itteration ####
fit_res = least_squares(self.objective_fun, current_guess, jac=self.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# fit_res = least_squares(self.objective_fun, current_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
print("guess RMS:", self.get_RMS(current_guess))
current_guess = fit_res.x
current_fit = fit_res.cost
print("new RMS:", self.get_RMS(current_guess), current_fit, fit_res.status)
current_temperature = max_jitter_width
new_guess = np.array( current_guess )
while current_temperature>min_jitter_width: ## loop over each 'temperature'
print(" stochastic run. Temp:", current_temperature)
itters_since_change = 0
has_improved = False
for run_i in range(max_itters_per_loop):
print(" run:", run_i, ':', itters_since_change, " "*10, end="\r")
# print(" itter", run_i)
## jitter the initial guess ##
new_guess[:self.num_delays] = np.random.normal(scale=current_temperature, size=self.num_delays) + current_guess[:self.num_delays] ## note use of best_solution, allows for translation. Faster convergence?
param_i = self.num_delays
for PSE in self.source_object_list:
new_guess[param_i:param_i+3] = np.random.normal(scale=current_temperature*v_air, size=3) + current_guess[param_i:param_i+3]
# new_guess[param_i+2] = np.abs(new_guess[param_i+2])## Z should be positive
new_guess[param_i+3] = PSE.estimate_T(new_guess[:self.num_delays], new_guess[param_i:param_i+4])
param_i += 4
#### FIT!!! ####
fit_res = least_squares(self.objective_fun, new_guess, jac=self.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# fit_res = least_squares(self.objective_fun, new_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# print(" cost:", fit_res.cost)
if fit_res.cost < current_fit:
current_fit = fit_res.cost
current_guess = fit_res.x
if (fit_res.cost-current_fit)/current_fit > 0.001:
itters_since_change = 0
has_improved = True
else:
itters_since_change += 1
if itters_since_change == itters_till_convergence:
break
print(" "*30,end="\r")
if has_improved:
current_temperature /= cooldown
else:
current_temperature /= strong_cooldown
total_RMS = 0.0
new_station_delays = current_guess[:self.num_delays]
param_i = self.num_delays
for PSE in self.source_object_list:
total_RMS += PSE.SSqE_fit( new_station_delays, current_guess[param_i:param_i+4] )
param_i += 4
total_RMS = np.sqrt(total_RMS/self.num_DOF)
print(" RMS fit", total_RMS, "num runs:", run_i+1, "cost", current_fit)
if self.quick_kill is not None and total_RMS>self.quick_kill:
print(" quick kill exceeded")
break
if run_i+1 == max_itters_per_loop:
print(" not converged!")
self.converged = False
else:
self.converged = True
#### get individual fits per station and PSE
self.PSE_fits = []
self.PSE_RMS_fits = []
new_station_delays = current_guess[:self.num_delays]
param_i = self.num_delays
for source in self.source_object_list:
self.PSE_fits.append( source.RMS_fit_byStation(new_station_delays,
current_guess[param_i:param_i+4]) )
SSQE = source.SSqE_fit(new_station_delays, current_guess[param_i:param_i+4])
# source.SSqE_fitNprint( new_station_delays, current_guess[param_i:param_i+4] )
self.PSE_RMS_fits.append( np.sqrt(SSQE/source.num_DOF()) )
param_i += 4
#### check which stations have fits
self.stations_with_fits = [False]*( len(station_order)+1 )
for stationfits in self.PSE_fits:
for snum, (sname, fit) in enumerate(zip( chain(station_order, [referance_station]), stationfits )):
if fit is not None:
self.stations_with_fits[snum] = True
#### edit solution for stations that don't have guess
for snum, has_fit in enumerate(self.stations_with_fits[:-1]): #ignore last station, as is referance station
if not has_fit:
current_guess[ snum ] = self.initial_guess[ snum ]
#### save results
self.solution = current_guess
self.cost = current_fit
self.RMS = total_RMS
def employ_result(self, source_object_list):
"""set the result to the guess location of the sources, and return the station timing offsets"""
param_i = self.num_delays
for PSE in source_object_list:
PSE.guess_XYZT[:] = self.solution[param_i:param_i+4]
param_i += 4
return self.solution[:self.num_delays]
def print_locations(self, source_object_list):
param_i = self.num_delays
for source, RMSfit in zip(source_object_list, self.PSE_RMS_fits):
print("source", source.ID)
print(" RMS:", RMSfit)
print(" loc:", self.solution[param_i:param_i+4])
param_i += 4
# def print_station_fits(self, source_object_list):
#
# fit_table = PrettyTable()
# fit_table.field_names = ['id'] + station_order + [referance_station] + ['total']
# fit_table.float_format = '.2E'
#
# for source, RMSfit, stationfits in zip(source_object_list, self.PSE_RMS_fits, self.PSE_fits):
# new_row = ['']*len(fit_table.field_names)
# new_row[0] = source.ID
# new_row[-1] = RMSfit
#
# for i,stat_fit in enumerate(stationfits):
# if stat_fit is not None:
# new_row[i+1] = stat_fit
#
# fit_table.add_row( new_row )
#
# print( fit_table )
def print_station_fits(self, source_object_list, num_stat_per_table):
stations_to_print = station_order + [referance_station]
current_station_i = 0
while len(stations_to_print) > 0:
stations_this_run = stations_to_print[:num_stat_per_table]
stations_to_print = stations_to_print[len(stations_this_run):]
fit_table = PrettyTable()
fit_table.field_names = ['id'] + stations_this_run + ['total']
fit_table.float_format = '.2E'
for source, RMSfit, stationfits in zip(source_object_list, self.PSE_RMS_fits, self.PSE_fits):
new_row = ['']*len(fit_table.field_names)
new_row[0] = source.ID
new_row[-1] = RMSfit
for i,stat_fit in enumerate(stationfits[current_station_i:current_station_i+len(stations_this_run)]):
if stat_fit is not None:
new_row[i+1] = stat_fit
fit_table.add_row( new_row )
print( fit_table )
print()
current_station_i += len(stations_this_run)
def print_delays(self, original_delays):
for sname, delay, original in zip(station_order, self.solution[:self.num_delays], original_delays):
print("'"+sname+"' : ",delay,', ## diff to guess:', delay-original)
def get_stations_with_fits(self):
return self.stations_with_fits
class stochastic_fitter_dt:
def __init__(self, source_object_list, initial_guess=None, quick_kill=None):
print("running stochastic fitter")
self.quick_kill = quick_kill
self.source_object_list = source_object_list
## assume globals:
# max_itters_per_loop
# itters_till_convergence
# max_jitter_width
# min_jitter_width
# cooldown
# sorted_antenna_names
self.num_antennas = len(sorted_antenna_names)
self.num_measurments = self.num_antennas*len(source_object_list)
self.num_delays = len(station_order)
self.station_indeces = np.empty( len(ant_locs), dtype=np.int )
for station_index, index_range in enumerate(station_to_antenna_index_list):
first,last = index_range
self.station_indeces[first:last] = station_index
self.fitter = stationDelay_fitter(ant_locs, self.station_indeces, len(self.source_object_list), self.num_delays)
for source in self.source_object_list:
self.fitter.set_event( source.pulse_times )
# self.one_fitter = stationDelay_fitter(ant_locs, self.station_indeces, 1, self.num_delays)
# self.one_fitter.set_event( self.source_object_list[0] )
#### make guess ####
self.num_DOF = -self.num_delays
self.solution = np.zeros( self.num_delays+4*len(source_object_list) )
self.solution[:self.num_delays] = current_delays_guess
param_i = self.num_delays
for PSE in source_object_list:
self.solution[param_i:param_i+4] = PSE.guess_XYZT
param_i += 4
self.num_DOF += PSE.num_DOF()
if initial_guess is not None: ## use initial guess instead, if given
self.solution = initial_guess
self.initial_guess = np.array( self.solution )
self.rerun()
def rerun(self):
current_guess = np.array( self.solution )
# print('D', current_guess)
#### first itteration ####
# fit_res = least_squares(self.fitter.objective_fun, current_guess, jac=self.fitter.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
fit_res = least_squares(self.fitter.objective_fun, current_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# print( self.fitter.objective_jac(current_guess) )
current_guess = fit_res.x
# print('E', fit_res.status, current_guess)
# quit()
current_fit = fit_res.cost
current_temperature = max_jitter_width
new_guess = np.array( current_guess )
while current_temperature>min_jitter_width: ## loop over each 'temperature'
print(" stochastic run. Temp:", current_temperature)
itters_since_change = 0
has_improved = False
for run_i in range(max_itters_per_loop):
print(" run:", run_i, ':', itters_since_change, " "*10, end="\r")
# print(" itter", run_i)
## jitter the initial guess ##
new_guess[:self.num_delays] = np.random.normal(scale=current_temperature, size=self.num_delays) + current_guess[:self.num_delays] ## note use of best_solution, allows for translation. Faster convergence?
param_i = self.num_delays
for PSE in self.source_object_list:
new_guess[param_i:param_i+3] = np.random.normal(scale=current_temperature*v_air, size=3) + current_guess[param_i:param_i+3]
# new_guess[param_i+2] = np.abs(new_guess[param_i+2])## Z should be positive
new_guess[param_i+3] = PSE.estimate_T(new_guess[:self.num_delays], new_guess[param_i:param_i+4])
param_i += 4
#### FIT!!! ####
# fit_res = least_squares(self.fitter.objective_fun, current_guess, jac=self.fitter.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
fit_res = least_squares(self.fitter.objective_fun, current_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# print(" cost:", fit_res.cost)
if fit_res.cost < current_fit:
current_fit = fit_res.cost
current_guess = fit_res.x
if (fit_res.cost-current_fit)/current_fit > 0.001:
itters_since_change = 0
has_improved = True
else:
itters_since_change += 1
if itters_since_change == itters_till_convergence:
break
print(" "*30,end="\r")
if has_improved:
current_temperature /= cooldown
else:
current_temperature /= strong_cooldown
total_RMS = 0.0
new_station_delays = current_guess[:self.num_delays]
param_i = self.num_delays
for PSE in self.source_object_list:
total_RMS += PSE.SSqE_fit( new_station_delays, current_guess[param_i:param_i+4] )
param_i += 4
total_RMS = np.sqrt(total_RMS/self.num_DOF)
print(" RMS fit", total_RMS, "num runs:", run_i+1, "cost", current_fit)
if self.quick_kill is not None and total_RMS>self.quick_kill:
print(" quick kill exceeded")
break
if run_i+1 == max_itters_per_loop:
print(" not converged!")
self.converged = False
else:
self.converged = True
#### get individual fits per station and PSE
self.PSE_fits = []
self.PSE_RMS_fits = []
new_station_delays = current_guess[:self.num_delays]
param_i = self.num_delays
for source in self.source_object_list:
self.PSE_fits.append( source.RMS_fit_byStation(new_station_delays,
current_guess[param_i:param_i+4]) )
SSQE = source.SSqE_fit(new_station_delays, current_guess[param_i:param_i+4])
# source.SSqE_fitNprint( new_station_delays, current_guess[param_i:param_i+4] )
self.PSE_RMS_fits.append( np.sqrt(SSQE/source.num_DOF()) )
param_i += 4
#### check which stations have fits
self.stations_with_fits = [False]*( len(station_order)+1 )
for stationfits in self.PSE_fits:
for snum, (sname, fit) in enumerate(zip( chain(station_order, [referance_station]), stationfits )):
if fit is not None:
self.stations_with_fits[snum] = True
#### edit solution for stations that don't have guess
for snum, has_fit in enumerate(self.stations_with_fits[:-1]): #ignore last station, as is referance station
if not has_fit:
current_guess[ snum ] = self.initial_guess[ snum ]
#### save results
self.solution = current_guess
self.cost = current_fit
self.RMS = total_RMS
def employ_result(self, source_object_list):
"""set the result to the guess location of the sources, and return the station timing offsets"""
param_i = self.num_delays
for PSE in source_object_list:
PSE.guess_XYZT[:] = self.solution[param_i:param_i+4]
param_i += 4
return self.solution[:self.num_delays]
def print_locations(self, source_object_list):
param_i = self.num_delays
for source, RMSfit in zip(source_object_list, self.PSE_RMS_fits):
print("source", source.ID)
print(" RMS:", RMSfit)
print(" loc:", self.solution[param_i:param_i+4])
param_i += 4
def print_station_fits(self, source_object_list, num_stat_per_table):
stations_to_print = station_order + [referance_station]
current_station_i = 0
while len(stations_to_print) > 0:
stations_this_run = stations_to_print[:num_stat_per_table]
stations_to_print = stations_to_print[len(stations_this_run):]
fit_table = PrettyTable()
fit_table.field_names = ['id'] + stations_this_run + ['total']
fit_table.float_format = '.2E'
for source, RMSfit, stationfits in zip(source_object_list, self.PSE_RMS_fits, self.PSE_fits):
new_row = ['']*len(fit_table.field_names)
new_row[0] = source.ID
new_row[-1] = RMSfit
for i,stat_fit in enumerate(stationfits[current_station_i:current_station_i+len(stations_this_run)]):
if stat_fit is not None:
new_row[i+1] = stat_fit
fit_table.add_row( new_row )
print( fit_table )
print()
current_station_i += len(stations_this_run)
def print_delays(self, original_delays):
for sname, delay, original in zip(station_order, self.solution[:self.num_delays], original_delays):
print("'"+sname+"' : ",delay,', ## diff to guess:', delay-original)
def get_stations_with_fits(self):
return self.stations_with_fits
class stochastic_fitter_FitLocs:
def __init__(self, source_object_list, quick_kill=None):
print("running stochastic fitter")
self.quick_kill = quick_kill
self.source_object_list = source_object_list
## assume globals:
# max_itters_per_loop
# itters_till_convergence
# max_jitter_width
# min_jitter_width
# cooldown
# sorted_antenna_names
self.num_antennas = len(sorted_antenna_names)
self.num_measurments = self.num_antennas*len(source_object_list)
self.num_delays = len(station_order)
self.used_delays = np.array(current_delays_guess)
#### make guess ####
self.num_DOF = 0
self.solution = np.zeros( 4*len(source_object_list) )
param_i = 0
for PSE in source_object_list:
self.solution[param_i:param_i+4] = PSE.guess_XYZT
param_i += 4
self.num_DOF += PSE.num_DOF()
self.initial_guess = np.array( self.solution )
self.rerun()
def objective_fun(self, sol, do_print=False):
workspace_sol = np.zeros(self.num_measurments, dtype=np.double)
ant_i = 0
param_i = 0
for PSE in self.source_object_list:
PSE.try_location_LS(self.used_delays, sol[param_i:param_i+4], workspace_sol[ant_i:ant_i+self.num_antennas])
ant_i += self.num_antennas
param_i += 4
filter = np.logical_not( np.isfinite(workspace_sol) )
workspace_sol[ filter ] = 0.0
if do_print:
print("num func nans:", np.sum(filter))
return workspace_sol
# workspace_sol *= workspace_sol
# return np.sum(workspace_sol)
def objective_jac(self, sol, do_print=False):
workspace_jac = np.zeros((self.num_measurments, self.num_delays+4*len(self.source_object_list)), dtype=np.double)
ant_i = 0
param_i = 0
for PSE in self.source_object_list:
PSE.try_location_JAC(self.used_delays, sol[param_i:param_i+4], workspace_jac[ant_i:ant_i+self.num_antennas, param_i:param_i+4],
workspace_jac[ant_i:ant_i+self.num_antennas, 0:self.num_delays])
filter = np.logical_not( np.isfinite(workspace_jac[ant_i:ant_i+self.num_antennas, param_i+3]) )
workspace_jac[ant_i:ant_i+self.num_antennas, param_i:param_i+4][filter] = 0.0
workspace_jac[ant_i:ant_i+self.num_antennas, 0:self.num_delays][filter] = 0.0
ant_i += self.num_antennas
param_i += 4
if do_print:
print("num jac nans:", np.sum(filter))
return workspace_jac[:, self.num_delays:]
def rerun(self):
current_guess = np.array( self.solution )
#### first itteration ####
fit_res = least_squares(self.objective_fun, current_guess, jac=self.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# fit_res = least_squares(self.objective_fun, current_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
current_guess = fit_res.x
current_fit = fit_res.cost
current_fit_obj = fit_res
current_temperature = max_jitter_width
new_guess = np.array( current_guess )
while current_temperature>min_jitter_width: ## loop over each 'temperature'
print(" stochastic run. Temp:", current_temperature)
itters_since_change = 0
has_improved = False
for run_i in range(max_itters_per_loop):
print(" run:", run_i, ':', itters_since_change, " "*10, end="\r")
# print(" itter", run_i)
## jitter the initial guess ##
param_i = 0
for PSE in self.source_object_list:
new_guess[param_i:param_i+3] = np.random.normal(scale=current_temperature*v_air, size=3) + current_guess[param_i:param_i+3]
# new_guess[param_i+2] = np.abs(new_guess[param_i+2])## Z should be positive
new_guess[param_i+3] = PSE.estimate_T(self.used_delays, new_guess[param_i:param_i+4])
param_i += 4
#### FIT!!! ####
fit_res = least_squares(self.objective_fun, new_guess, jac=self.objective_jac, method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# fit_res = least_squares(self.objective_fun, new_guess, jac='2-point', method='lm', xtol=1.0E-15, ftol=1.0E-15, gtol=1.0E-15, x_scale='jac')
# print(" cost:", fit_res.cost)
if fit_res.cost < current_fit:
current_fit = fit_res.cost
current_fit_obj = fit_res
current_guess = fit_res.x
if (fit_res.cost-current_fit)/current_fit > 0.001:
itters_since_change = 0
has_improved = True
else:
itters_since_change += 1
if itters_since_change == itters_till_convergence:
break
print(" "*30,end="\r")
if has_improved:
current_temperature /= cooldown
else:
current_temperature /= strong_cooldown
total_RMS = 0.0
param_i = 0
for PSE in self.source_object_list:
total_RMS += PSE.SSqE_fit( self.used_delays, current_guess[param_i:param_i+4] )
param_i += 4
total_RMS = np.sqrt(total_RMS/self.num_DOF)
print(" RMS fit", total_RMS, "num runs:", run_i+1, "success", current_fit_obj.success)
if self.quick_kill is not None and total_RMS>self.quick_kill:
print(" quick kill exceeded")
break
if run_i+1 == max_itters_per_loop:
print(" not converged!")
self.converged = False
else:
self.converged = True
#### get individual fits per station and PSE
self.PSE_fits = []
self.PSE_RMS_fits = []
param_i = 0
for source in self.source_object_list:
self.PSE_fits.append( source.RMS_fit_byStation(self.used_delays,
current_guess[param_i:param_i+4]) )
SSQE = source.SSqE_fit(self.used_delays, current_guess[param_i:param_i+4])
# source.SSqE_fitNprint( new_station_delays, current_guess[param_i:param_i+4] )
self.PSE_RMS_fits.append( np.sqrt(SSQE/source.num_DOF()) )
param_i += 4
#### check which stations have fits
self.stations_with_fits = [False]*( len(station_order)+1 )
for stationfits in self.PSE_fits:
for snum, (sname, fit) in enumerate(zip( chain(station_order, [referance_station]), stationfits )):
if fit is not None:
self.stations_with_fits[snum] = True
#### save results
self.solution = current_guess
self.cost = current_fit
self.RMS = total_RMS
def employ_result(self, source_object_list):
"""set the result to the guess location of the sources, and return the station timing offsets"""
param_i = 0
for PSE in source_object_list:
PSE.guess_XYZT[:] = self.solution[param_i:param_i+4]
param_i += 4
return self.used_delays
def print_locations(self, source_object_list):
param_i = 0
for source, RMSfit in zip(source_object_list, self.PSE_RMS_fits):
print("source", source.ID)
print(" RMS:", RMSfit)
print(" loc:", self.solution[param_i:param_i+4])
param_i += 4
def print_station_fits(self, source_object_list):
fit_table = PrettyTable()
fit_table.field_names = ['id'] + station_order + [referance_station] + ['total']
fit_table.float_format = '.2E'
for source, RMSfit, stationfits in zip(source_object_list, self.PSE_RMS_fits, self.PSE_fits):
new_row = ['']*len(fit_table.field_names)
new_row[0] = source.ID
new_row[-1] = RMSfit
for i,stat_fit in enumerate(stationfits):
if stat_fit is not None:
new_row[i+1] = stat_fit
fit_table.add_row( new_row )
print( fit_table )
def print_delays(self, original_delays):
for sname, delay, original in zip(station_order, self.used_delays, original_delays):
print("'"+sname+"' : ",delay,', ## diff to guess:', delay-original)
def get_stations_with_fits(self):
return self.stations_with_fits
#### source object ####
## represents a potential source
## keeps track of a stations on the prefered station, and stations on other stations that could correlate and are considered correlated
## contains utilities for fitting, and for finding RMS in total and for each station
## also contains utilities for plotting and saving info
## need to handle inseartion of random error, and that choosen SSPE can change
class source_object():
## assume: guess_location , ant_locs, station_to_antenna_index_list, station_to_antenna_index_dict, referance_station, station_order,
# sorted_antenna_names, station_locations,
# are global
def __init__(self, ID, input_fname, location, stations_to_exclude, antennas_to_exclude ):
self.ID = ID
self.stations_to_exclude = stations_to_exclude
self.antennas_to_exclude = antennas_to_exclude
self.data_file = h5py.File(input_fname, "r")
self.guess_XYZT = np.array( location )
def prep_for_fitting(self, polarization):
self.polarization = polarization
self.pulse_times = np.empty( len(sorted_antenna_names) )
self.pulse_times[:] = np.nan
self.waveforms = [None]*len(self.pulse_times)
self.waveform_startTimes = [None]*len(self.pulse_times)
#### first add times from referance_station
for sname in chain(station_order, [referance_station]):
if sname not in self.stations_to_exclude:
self.add_known_station(sname)
#### setup some temp storage for fitting
self.tmp_LS2_data = np.empty( len(sorted_antenna_names) )
def remove_station(self, sname):
antenna_index_range = station_to_antenna_index_dict[sname]
self.pulse_times[ antenna_index_range[0]:antenna_index_range[1] ] = np.nan
def has_station(self, sname):
antenna_index_range = station_to_antenna_index_dict[sname]
return np.sum(np.isfinite(self.pulse_times[ antenna_index_range[0]:antenna_index_range[1] ])) > 0
def add_known_station(self, sname):
self.remove_station( sname )
if sname in self.data_file:
station_group= self.data_file[sname]
else:
return 0
antenna_index_range = station_to_antenna_index_dict[sname]
for ant_i in range(antenna_index_range[0], antenna_index_range[1]):
ant_name = sorted_antenna_names[ant_i]
if ant_name in station_group:
ant_data = station_group[ant_name]
start_time = ant_data.attrs['starting_index']*5.0E-9
pt = ant_data.attrs['PolE_peakTime'] if self.polarization==0 else ant_data.attrs['PolO_peakTime']
waveform = ant_data[1,:] if self.polarization==0 else ant_data[3,:]
start_time += ant_data.attrs['PolE_timeOffset'] if self.polarization==0 else ant_data.attrs['PolO_timeOffset']
amp = np.max(waveform)
if not np.isfinite(pt):
pt = np.nan
if amp<min_antenna_amplitude or (ant_name in self.antennas_to_exclude) or (ant_name in bad_antennas):
pt = np.nan
self.pulse_times[ ant_i ] = pt
self.waveforms[ ant_i ] = waveform
self.waveform_startTimes[ ant_i ] = start_time
return np.sum(np.isfinite( self.pulse_times[antenna_index_range[0]:antenna_index_range[1]] ) )
def try_location_LS(self, delays, XYZT_location, out):
X,Y,Z,T = XYZT_location
Z = np.abs(Z)
delta_X_sq = ant_locs[:,0]-X
delta_Y_sq = ant_locs[:,1]-Y
delta_Z_sq = ant_locs[:,2]-Z
delta_X_sq *= delta_X_sq
delta_Y_sq *= delta_Y_sq
delta_Z_sq *= delta_Z_sq
out[:] = T - self.pulse_times
##now account for delays
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
out[first:last] += delay ##note the wierd sign
out *= v_air
out *= out ##this is now delta_t^2 *C^2
out -= delta_X_sq
out -= delta_Y_sq
out -= delta_Z_sq
def try_location_JAC(self, delays, XYZT_location, out_loc, out_delays):
X,Y,Z,T = XYZT_location
Z = np.abs(Z)
out_loc[:,0] = X
out_loc[:,0] -= ant_locs[:,0]
out_loc[:,0] *= -2
out_loc[:,1] = Y
out_loc[:,1] -= ant_locs[:,1]
out_loc[:,1] *= -2
out_loc[:,2] = Z
out_loc[:,2] -= ant_locs[:,2]
out_loc[:,2] *= -2
out_loc[:,3] = T - self.pulse_times
out_loc[:,3] *= 2*v_air*v_air
delay_i = 0
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
out_loc[first:last,3] += delay*2*v_air*v_air
out_delays[first:last,delay_i] = out_loc[first:last,3]
delay_i += 1
def try_location_LS2(self, delays, XYZT_location, out):
X,Y,Z,T = XYZT_location
# Z = np.abs(Z)
self.tmp_LS2_data[:] = ant_locs[:,0]
self.tmp_LS2_data[:] -= X
self.tmp_LS2_data[:] *= self.tmp_LS2_data[:]
out[:] = self.tmp_LS2_data
self.tmp_LS2_data[:] = ant_locs[:,1]
self.tmp_LS2_data[:] -= Y
self.tmp_LS2_data[:] *= self.tmp_LS2_data[:]
out[:] += self.tmp_LS2_data
self.tmp_LS2_data[:] = ant_locs[:,2]
self.tmp_LS2_data[:] -= Z
self.tmp_LS2_data[:] *= self.tmp_LS2_data[:]
out[:] += self.tmp_LS2_data
np.sqrt( out, out=out )
out *= inv_v_air
out += T
out -= self.pulse_times
##now account for delays
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
out[first:last] += delay ##note the wierd sign
def try_location_JAC2(self, delays, XYZT_location, out_loc, out_delays):
X,Y,Z,T = XYZT_location
# Z = np.abs(Z)
out_loc[:,0] = X
out_loc[:,0] -= ant_locs[:,0]
out_loc[:,1] = Y
out_loc[:,1] -= ant_locs[:,1]
out_loc[:,2] = Z
out_loc[:,2] -= ant_locs[:,2]
out_delays[:,0] = out_loc[:,0] ## use as temporary storage
out_delays[:,0] *= out_delays[:,0]
out_loc[:,3] = out_delays[:,0] ## also use as temporary storage
out_delays[:,0] = out_loc[:,1] ## use as temporary storage
out_delays[:,0] *= out_delays[:,0]
out_loc[:,3] += out_delays[:,0]
out_delays[:,0] = out_loc[:,2] ## use as temporary storage
out_delays[:,0] *= out_delays[:,0]
out_loc[:,3] += out_delays[:,0]
np.sqrt( out_loc[:,3], out = out_loc[:,3] )
out_loc[:,0] /= out_loc[:,3]
out_loc[:,1] /= out_loc[:,3]
out_loc[:,2] /= out_loc[:,3]
out_loc[:,0] *= inv_v_air
out_loc[:,1] *= inv_v_air
out_loc[:,2] *= inv_v_air
out_loc[:,3] = 1
delay_i = 0
out_delays[:] = 0.0
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
out_delays[first:last,delay_i] = 1
delay_i += 1
def num_DOF(self):
return np.sum( np.isfinite(self.pulse_times) ) - 3 ## minus three or four?
def estimate_T(self, delays, XYZT_location):
X,Y,Z,T = XYZT_location
Z = np.abs(Z)
delta_X_sq = ant_locs[:,0]-X
delta_Y_sq = ant_locs[:,1]-Y
delta_Z_sq = ant_locs[:,2]-Z
delta_X_sq *= delta_X_sq
delta_Y_sq *= delta_Y_sq
delta_Z_sq *= delta_Z_sq
workspace = delta_X_sq+delta_Y_sq
workspace += delta_Z_sq
# print(delta_X_sq)
np.sqrt(workspace, out=workspace)
# print(self.pulse_times)
# print(workspace)
workspace[:] -= self.pulse_times*v_air ## this is now source time
##now account for delays
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
workspace[first:last] += delay*v_air ##note the wierd sign
# print(workspace)
ave_error = np.nanmean( workspace )
return -ave_error/v_air
def SSqE_fit(self, delays, XYZT_location):
X,Y,Z,T = XYZT_location
Z = np.abs(Z)
delta_X_sq = ant_locs[:,0]-X
delta_Y_sq = ant_locs[:,1]-Y
delta_Z_sq = ant_locs[:,2]-Z
delta_X_sq *= delta_X_sq
delta_Y_sq *= delta_Y_sq
delta_Z_sq *= delta_Z_sq
distance = delta_X_sq
distance += delta_Y_sq
distance += delta_Z_sq
np.sqrt(distance, out=distance)
distance *= 1.0/v_air
distance += T
distance -= self.pulse_times
##now account for delays
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
if first is not None:
distance[first:last] += delay ##note the wierd sign
distance *= distance
return np.nansum(distance)
def RMS_fit_byStation(self, delays, XYZT_location):
X,Y,Z,T = XYZT_location
Z = np.abs(Z)
delta_X_sq = ant_locs[:,0]-X
delta_Y_sq = ant_locs[:,1]-Y
delta_Z_sq = ant_locs[:,2]-Z
delta_X_sq *= delta_X_sq
delta_Y_sq *= delta_Y_sq
delta_Z_sq *= delta_Z_sq
distance = delta_X_sq
distance += delta_Y_sq
distance += delta_Z_sq
np.sqrt(distance, out=distance)
distance *= 1.0/v_air
distance += T
distance -= self.pulse_times
##now account for delays
for index_range, delay in zip(station_to_antenna_index_list, delays):
first,last = index_range
if first is not None:
distance[first:last] += delay ##note the wierd sign
distance *= distance
ret = []
for index_range in station_to_antenna_index_list:
first,last = index_range
data = distance[first:last]
nDOF = np.sum( np.isfinite(data) )
if nDOF == 0:
ret.append( None )
else:
ret.append( np.sqrt( np.nansum(data)/nDOF ) )
## need to do referance station
first,last = station_to_antenna_index_dict[ referance_station ]
data = distance[first:last]
nDOF = np.sum( np.isfinite(data) )
if nDOF == 0:
ret.append( None )
else:
ret.append( np.sqrt( np.nansum(data)/nDOF ) )
return ret
def plot_waveforms(self, station_timing_offsets, fname=None):
if fname is None:
plotter = plt
else:
CL = code_logger(fname)
CL.add_statement("import numpy as np")
plotter = pyplot_emulator(CL)
most_min_t = np.inf
snames_not_plotted = []
for sname, offset in zip( chain(station_order,[referance_station]), chain(station_timing_offsets,[0.0]) ):
index_range = station_to_antenna_index_dict[sname]
if sname in self.data_file:
station_data = self.data_file[sname]
else:
continue
min_T = np.inf
max_T = -np.inf
for ant_i in range(index_range[0], index_range[1]):
ant_name = sorted_antenna_names[ant_i]
if ant_name not in station_data:
continue
ant_data = station_data[ant_name]
PolE_peak_time = ant_data.attrs['PolE_peakTime'] - offset
PolO_peak_time = ant_data.attrs['PolO_peakTime'] - offset
PolE_hilbert = ant_data[1,:]
PolO_hilbert = ant_data[3,:]
PolE_trace = ant_data[0,:]
PolO_trace = ant_data[2,:]
PolE_T_array = (np.arange(len(PolE_hilbert)) + ant_data.attrs['starting_index'] )*5.0E-9 + ant_data.attrs['PolE_timeOffset']
PolO_T_array = (np.arange(len(PolO_hilbert)) + ant_data.attrs['starting_index'] )*5.0E-9 + ant_data.attrs['PolO_timeOffset']
PolE_T_array -= offset
PolO_T_array -= offset
PolE_amp = np.max(PolE_hilbert)
PolO_amp = np.max(PolO_hilbert)
amp = max(PolE_amp, PolO_amp)
PolE_hilbert = PolE_hilbert/(amp*3.0)
PolO_hilbert = PolO_hilbert/(amp*3.0)
PolE_trace = PolE_trace/(amp*3.0)
PolO_trace = PolO_trace/(amp*3.0)
if PolE_amp < min_antenna_amplitude:
PolE_peak_time = np.inf
if PolO_amp < min_antenna_amplitude:
PolO_peak_time = np.inf
plotter.plot( PolE_T_array, ant_i+PolE_hilbert, 'g' )
plotter.plot( PolE_T_array, ant_i+PolE_trace, 'g' )
plotter.plot( [PolE_peak_time, PolE_peak_time], [ant_i, ant_i+2.0/3.0], 'g')
plotter.plot( PolO_T_array, ant_i+PolO_hilbert, 'm' )
plotter.plot( PolO_T_array, ant_i+PolO_trace, 'm' )
plotter.plot( [PolO_peak_time, PolO_peak_time], [ant_i, ant_i+2.0/3.0], 'm')
plotter.annotate( ant_name, xy=[PolO_T_array[-1], ant_i], size=7)
max_T = max(max_T, PolE_T_array[-1], PolO_T_array[-1])
min_T = min(min_T, PolE_T_array[0], PolO_T_array[0])
most_min_t = min(most_min_t, min_T)
if min_T<np.inf:
plotter.annotate( sname, xy=[min_T, np.average(index_range)], size=15)
else:
snames_not_plotted.append( sname )
for sname in snames_not_plotted:
index_range = station_to_antenna_index_dict[sname]
plotter.annotate( sname, xy=[most_min_t, np.average(index_range)], size=15)
plotter.show()
if fname is not None:
CL.save()
def plot_selected_waveforms(self, station_timing_offsets, fname=None):
if fname is None:
plotter = plt
else:
CL = code_logger(fname)
CL.add_statement("import numpy as np")
plotter = pyplot_emulator(CL)
most_min_t = np.inf
snames_not_plotted = []
for sname, offset in zip( chain(station_order,[referance_station]), chain(station_timing_offsets,[0.0]) ):
index_range = station_to_antenna_index_dict[sname]
min_T = np.inf
max_T = -np.inf
for ant_i in range(index_range[0], index_range[1]):
ant_name = sorted_antenna_names[ant_i]
pulse_time = self.pulse_times[ ant_i ]
waveform = self.waveforms[ ant_i ]
startTime = self.waveform_startTimes[ ant_i ]
if not np.isfinite( pulse_time ):
continue
T_array = np.arange(len(waveform))*5.0E-9 + (startTime - offset)
amp = np.max(waveform)
waveform = waveform/(amp*3.0)
plotter.plot( T_array, ant_i+waveform, 'g' )
plotter.plot( [pulse_time-offset, pulse_time-offset], [ant_i, ant_i+2.0/3.0], 'm')
plotter.annotate( ant_name, xy=[T_array[-1], ant_i], size=7)
max_T = max(max_T, T_array[-1])
min_T = min(min_T, T_array[0])
most_min_t = min(most_min_t, min_T)
if min_T<np.inf:
plotter.annotate( sname, xy=[min_T, np.average(index_range)], size=15)
else:
snames_not_plotted.append( sname )
for sname in snames_not_plotted:
index_range = station_to_antenna_index_dict[sname]
plotter.annotate( sname, xy=[most_min_t, np.average(index_range)], size=15)
plotter.show()
if fname is not None:
CL.save()
class Part1_input_manager:
def __init__(self, input_files):
self.max_num_input_files = 10
if len(input_files) > self.max_num_input_files:
print("TOO MANY INPUT FOLDERS!!!")
quit()
self.input_files = input_files
self.input_data = []
for folder_i, folder in enumerate(input_files):
input_folder = processed_data_folder + "/" + folder +'/'
file_list = [(int(f.split('_')[1][:-3])*self.max_num_input_files+folder_i ,input_folder+f) for f in listdir(input_folder) if f.endswith('.h5')] ## get all file names, and get the 'ID' for the file name
file_list.sort( key=lambda x: x[0] ) ## sort according to ID
self.input_data.append( file_list )
def known_source(self, ID):
file_i = int(ID/self.max_num_input_files)
folder_i = ID - file_i*self.max_num_input_files
file_list = self.input_data[ folder_i ]
return [info for info in file_list if info[0]==ID][0]
np.set_printoptions(precision=10, threshold=np.inf)
## some global settings
num_stat_per_table = 10
#### these globals are holdovers
#station_locations = None ## to be set
#station_to_antenna_index_list = None## to be set
#stations_with_fits = None## to be set
#station_to_antenna_index_dict = None
def run_fitter(timeID, output_folder, pulse_input_folders, guess_timings, souces_to_fit, guess_source_locations,
source_polarizations, source_stations_to_exclude, source_antennas_to_exclude, bad_ants,
ref_station="CS002", min_ant_amplitude=10, max_stoch_loop_itters = 2000, min_itters_till_convergence = 100,
initial_jitter_width = 100000E-9, final_jitter_width = 1E-9, cooldown_fraction = 10.0, strong_cooldown_fraction = 100.0,
fitter = "dt"):
##### holdovers. These globals need to be fixed, so not global....
global station_locations, station_to_antenna_index_list, stations_with_fits, station_to_antenna_index_dict
global referance_station, station_order, sorted_antenna_names, min_antenna_amplitude, ant_locs, bad_antennas
global max_itters_per_loop, itters_till_convergence, min_jitter_width, max_jitter_width, cooldown, strong_cooldown
global current_delays_guess, processed_data_folder
referance_station = ref_station
min_antenna_amplitude = min_ant_amplitude
bad_antennas = bad_ants
max_itters_per_loop = max_stoch_loop_itters
itters_till_convergence = min_itters_till_convergence
max_jitter_width = initial_jitter_width
min_jitter_width = final_jitter_width
cooldown = cooldown_fraction
strong_cooldown = strong_cooldown_fraction
if referance_station in guess_timings:
ref_T = guess_timings[referance_station]
guess_timings = {station:T-ref_T for station,T in guess_timings.items() if station != referance_station}
processed_data_folder = processed_data_dir(timeID)
data_dir = processed_data_folder + "/" + output_folder
if not isdir(data_dir):
mkdir(data_dir)
logging_folder = data_dir + '/logs_and_plots'
if not isdir(logging_folder):
mkdir(logging_folder)
#Setup logger and open initial data set
log = logger()
log.set(logging_folder + "/log_out.txt") ## TODo: save all output to a specific output folder
log.take_stderr()
log.take_stdout()
print("timeID:", timeID)
print("date and time run:", time.strftime("%c") )
print("input folders:", pulse_input_folders)
print("source IDs to fit:", souces_to_fit)
print("guess locations:", guess_source_locations)
print("polarization to use:", source_polarizations)
print("source stations to exclude:", source_stations_to_exclude)
print("source antennas to exclude:", source_antennas_to_exclude)
print("bad antennas:", bad_ants)
print("referance station:", ref_station)
print("fitter type:", fitter)
print("guess delays:", guess_timings)
print()
print()
#### open data and data processing stuff ####
print("loading data")
raw_fpaths = filePaths_by_stationName(timeID)
raw_data_files = {sname:MultiFile_Dal1(fpaths, force_metadata_ant_pos=True) for sname,fpaths in raw_fpaths.items() if sname in chain(guess_timings.keys(), [referance_station]) }
#### sort antennas and stations ####
station_order = list(guess_timings.keys())## note this doesn't include reference station
sorted_antenna_names = []
station_to_antenna_index_dict = {}
ant_loc_dict = {}
for sname in station_order + [referance_station]:
first_index = len(sorted_antenna_names)
stat_data = raw_data_files[sname]
even_ant_names = stat_data.get_antenna_names()[::2]
even_ant_locs = stat_data.get_LOFAR_centered_positions()[::2]
sorted_antenna_names += even_ant_names
for ant_name, ant_loc in zip(even_ant_names,even_ant_locs):
ant_loc_dict[ant_name] = ant_loc
station_to_antenna_index_dict[sname] = (first_index, len(sorted_antenna_names))
ant_locs = np.zeros( (len(sorted_antenna_names), 3))
for i, ant_name in enumerate(sorted_antenna_names):
ant_locs[i] = ant_loc_dict[ant_name]
station_locations = {sname:ant_locs[station_to_antenna_index_dict[sname][0]] for sname in station_order + [referance_station]}
station_to_antenna_index_list = [station_to_antenna_index_dict[sname] for sname in station_order + [referance_station]]
#### sort the delays guess, and account for station locations ####
current_delays_guess = np.array([guess_timings[sname] for sname in station_order])
original_delays = np.array( current_delays_guess )
#### open info from part 1 ####
input_manager = Part1_input_manager( pulse_input_folders )
#### first we fit the known sources ####
current_sources = []
# next_source = 0
for knownID in souces_to_fit:
source_ID, input_name = input_manager.known_source( knownID )
print("prep fitting:", source_ID)
location = guess_source_locations[source_ID]
## make source
source_to_add = source_object(source_ID, input_name, location, source_stations_to_exclude[source_ID], source_antennas_to_exclude[source_ID] )
current_sources.append( source_to_add )
polarity = source_polarizations[source_ID]
source_to_add.prep_for_fitting(polarity)
print()
print("fitting known sources")
if fitter=='dt':
fitter = stochastic_fitter_dt(current_sources)
elif fitter=='dt2':
fitter = stochastic_fitter(current_sources)
elif fitter=='locs':
fitter = stochastic_fitter_FitLocs(current_sources)
elif fitter=="solve":
print("Pro tip: you shouldn't take advice from bad error messages. Would you have typed in your password if I asked?")
return
else:
print("you choose a bad fitter. Now the fit will be bad. Guess I shouldn't even try. Do better next time, please. 'fitter' can be 'dt', 'dt2', 'locs', or 'solve'")
return
fitter.employ_result( current_sources )
stations_with_fits = fitter.get_stations_with_fits()
print()
fitter.print_locations( current_sources )
print()
fitter.print_station_fits( current_sources, num_stat_per_table )
print()
fitter.print_delays( original_delays )
print()
print()
print("locations")
for source in current_sources:
print(source.ID,':[', source.guess_XYZT[0], ',', source.guess_XYZT[1], ',', source.guess_XYZT[2], ',', source.guess_XYZT[3], '],')
print()
print()
print("REL LOCS")
rel_loc = current_sources[0].guess_XYZT
for source in current_sources:
print(source.ID, rel_loc-source.guess_XYZT)
| mit |
ginach/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WorkbookFunctionsBesselKRequestBody.cs | 1423 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsBesselKRequestBody.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WorkbookFunctionsBesselKRequestBody
{
/// <summary>
/// Gets or sets X.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "x", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken X { get; set; }
/// <summary>
/// Gets or sets N.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "n", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken N { get; set; }
}
}
| mit |
ginfuru/vscode-onedark-raincoat | node_modules/vso-node-api/HttpClient.js | 15454 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
const url = require("url");
const http = require("http");
const https = require("https");
const tunnel = require("tunnel");
http.globalAgent.maxSockets = 100;
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
HttpCodes[HttpCodes["MovedPermanantly"] = 301] = "MovedPermanantly";
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
class HttpClientResponse {
constructor(message) {
this.message = message;
}
readBody() {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
let output = '';
this.message.on('data', (chunk) => {
output += chunk;
});
this.message.on('end', () => {
resolve(output);
});
}));
}
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
let parsedUrl = url.parse(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, socketTimeout) {
this.userAgent = userAgent;
this.handlers = handlers;
this.socketTimeout = socketTimeout ? socketTimeout : 3 * 60000;
}
get(requestUrl, additionalHeaders) {
return this.request('GET', requestUrl, null, additionalHeaders || {});
}
del(requestUrl, additionalHeaders) {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
}
post(requestUrl, data, additionalHeaders) {
return this.request('POST', requestUrl, data, additionalHeaders || {});
}
patch(requestUrl, data, additionalHeaders) {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
}
put(requestUrl, data, additionalHeaders) {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return this.request(verb, requestUrl, stream, additionalHeaders);
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
request(verb, requestUrl, data, headers) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
try {
var info = this._prepareRequest(verb, requestUrl, headers);
let res = yield this._requestRaw(info, data);
// TODO: check 401 if handled
// TODO: retry support
resolve(res);
}
catch (err) {
// only throws in truly exceptional cases (connection, can't resolve etc...)
// responses from the server do not throw
reject(err);
}
}));
}
_requestRaw(info, data) {
return new Promise((resolve, reject) => {
let socket;
let isDataString = typeof (data) === 'string';
if (typeof (data) === 'string') {
info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
}
let req = info.httpModule.request(info.options, (msg) => {
let res = new HttpClientResponse(msg);
resolve(res);
});
req.on('socket', (sock) => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this.socketTimeout, () => {
if (socket) {
socket.end();
}
reject(new Error('Request timeout: ' + info.options.path));
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
reject(err);
});
if (data && typeof (data) === 'string') {
req.write(data, 'utf8');
}
if (data && typeof (data) !== 'string') {
data.on('close', function () {
req.end();
});
data.pipe(req);
}
else {
req.end();
}
});
}
_prepareRequest(method, requestUrl, headers) {
let info = {};
info.parsedUrl = url.parse(requestUrl);
let usingSsl = info.parsedUrl.protocol === 'https:';
info.httpModule = usingSsl ? https : http;
var defaultPort = usingSsl ? 443 : 80;
var proxyUrl;
if (process.env.HTTPS_PROXY && usingSsl) {
proxyUrl = url.parse(process.env.HTTPS_PROXY);
}
else if (process.env.HTTP_PROXY) {
proxyUrl = url.parse(process.env.HTTP_PROXY);
}
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort;
info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method;
info.options.headers = headers || {};
info.options.headers["User-Agent"] = this.userAgent;
let useProxy = proxyUrl && proxyUrl.hostname;
if (useProxy) {
var agentOptions = {
maxSockets: http.globalAgent.maxSockets,
proxy: {
// TODO: support proxy-authorization
//proxyAuth: "user:password",
host: proxyUrl.hostname,
port: proxyUrl.port
}
};
var tunnelAgent;
var overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
info.options.agent = tunnelAgent(agentOptions);
}
// gives handlers an opportunity to participate
if (this.handlers) {
this.handlers.forEach((handler) => {
handler.prepareRequest(info.options);
});
}
return info;
}
}
exports.HttpClient = HttpClient;
//
// Legacy callback client. Will delete.
//
class HttpCallbackClient {
constructor(userAgent, handlers, socketTimeout) {
this.userAgent = userAgent;
this.handlers = handlers;
this.socketTimeout = socketTimeout ? socketTimeout : 3 * 60000;
}
get(verb, requestUrl, headers, onResult) {
var options = this._getOptions(verb, requestUrl, headers);
this.request(options.protocol, options.options, null, onResult);
}
// POST, PATCH, PUT
send(verb, requestUrl, data, headers, onResult) {
var options = this._getOptions(verb, requestUrl, headers);
this.request(options.protocol, options.options, data, onResult);
}
sendStream(verb, requestUrl, stream, headers, onResult) {
var options = this._getOptions(verb, requestUrl, headers);
var req = options.protocol.request(options.options, (res) => {
let output = '';
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function () {
// res has statusCode and headers
onResult(null, res, output);
});
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
onResult(err, null, null);
});
stream.on('close', function () {
req.end();
});
stream.pipe(req);
}
getStream(requestUrl, accept, onResult) {
let headers = {};
headers['ACCEPT'] = accept;
var options = this._getOptions('GET', requestUrl, headers);
var req = options.protocol.request(options.options, (res) => {
onResult(null, res.statusCode, res);
});
req.on('error', (err) => {
onResult(err, err.statusCode, null);
});
req.end();
}
/**
* Makes an http request delegating authentication to handlers.
* returns http result as contents buffer
* All other methods such as get, post, and patch ultimately call this.
*/
request(protocol, options, data, onResult) {
// Set up a callback to pass off 401s to an authentication handler that can deal with it
var callback = (err, res, contents) => {
var authHandler;
if (this.handlers) {
this.handlers.some(function (handler, index, handlers) {
// Find the first one that can handle the auth based on the response
if (handler.canHandleAuthentication(res)) {
authHandler = handler;
return true;
}
return false;
});
}
if (authHandler !== undefined) {
authHandler.handleAuthentication(this, protocol, options, data, onResult);
}
else {
// No auth handler found, call onResult normally
onResult(err, res, contents);
}
};
this.requestRaw(protocol, options, data, callback);
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
*/
requestRaw(protocol, options, data, onResult) {
var socket;
if (data) {
options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
}
var callbackCalled = false;
var handleResult = (err, res, contents) => {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res, contents);
}
};
var req = protocol.request(options, (res) => {
let output = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
output += chunk;
});
res.on('end', () => {
// res has statusCode and headers
handleResult(null, res, output);
});
});
req.on('socket', (sock) => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this.socketTimeout, function () {
if (socket) {
socket.end();
}
handleResult(new Error('Request timeout: ' + options.path), null, null);
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err, null, null);
});
if (data) {
req.write(data, 'utf8');
}
req.end();
}
_getOptions(method, requestUrl, headers) {
var parsedUrl = url.parse(requestUrl);
var usingSsl = parsedUrl.protocol === 'https:';
var prot = usingSsl ? https : http;
var defaultPort = usingSsl ? 443 : 80;
this.isSsl = usingSsl;
var proxyUrl;
if (process.env.HTTPS_PROXY && usingSsl) {
proxyUrl = url.parse(process.env.HTTPS_PROXY);
}
else if (process.env.HTTP_PROXY) {
proxyUrl = url.parse(process.env.HTTP_PROXY);
}
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var options = {
host: parsedUrl.hostname,
port: parsedUrl.port || defaultPort,
path: (parsedUrl.pathname || '') + (parsedUrl.search || ''),
method: method,
headers: headers || {}
};
options.headers["User-Agent"] = this.userAgent;
var useProxy = proxyUrl && proxyUrl.hostname;
if (useProxy) {
var agentOptions = {
maxSockets: http.globalAgent.maxSockets,
proxy: {
// TODO: support proxy-authorization
//proxyAuth: "user:password",
host: proxyUrl.hostname,
port: proxyUrl.port
}
};
var tunnelAgent;
var overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
options.agent = tunnelAgent(agentOptions);
}
if (this.handlers) {
this.handlers.forEach((handler) => {
handler.prepareRequest(options);
});
}
return {
protocol: prot,
options: options,
};
}
}
exports.HttpCallbackClient = HttpCallbackClient;
| mit |
dawikur/c8 | include/chip/executor.hpp | 584 | // Copyright 2016 Dawid Kurek. All Rights Reserved.
#ifndef INCLUDE_CHIP_EXECUTOR_HPP_
#define INCLUDE_CHIP_EXECUTOR_HPP_
#include "callbacks.hpp"
#include "chip/memory.hpp"
#include "chip/opcode.hpp"
namespace chip {
class Executor {
public:
Executor();
void operator()(Opcode const &, Memory &, GetKey const &, UpdateDisplay &);
private:
void (*_lookupTable[16])(Opcode const &,
Memory &,
GetKey const &,
UpdateDisplay &);
};
} // namespace chip
#endif // INCLUDE_CHIP_EXECUTOR_HPP_
| mit |
josegonzalez/php-queuesadilla | src/josegonzalez/Queuesadilla/Event/EventListenerInterface.php | 1066 | <?php
namespace josegonzalez\Queuesadilla\Event;
/**
* Objects implementing this interface should declare the `implementedEvents` function
* to notify the event manager what methods should be called when an event is triggered.
*
*/
interface EventListenerInterface
{
/**
* Returns a list of events this object is implementing. When the class is registered
* in an event manager, each individual method will be associated with the respective event.
*
* ### Example:
*
* {{{
* public function implementedEvents() {
* return array(
* 'Order.complete' => 'sendEmail',
* 'Article.afterBuy' => 'decrementInventory',
* 'User.onRegister' => array('callable' => 'logRegistration', 'priority' => 20, 'passParams' => true)
* );
* }
* }}}
*
* @return array associative array or event key names pointing to the function
* that should be called in the object when the respective event is fired
*/
public function implementedEvents();
}
| mit |
terut/ltsv-logger | spec/ltsv-logger_spec.rb | 646 | # coding: utf-8
require 'spec_helper'
describe LTSV do
context 'shortcut method' do
context '.logger' do
before do
LTSV::Logger.open(RSpec.configuration.test_log_path)
end
it 'module has logger instance' do
LTSV.logger.should be_an_instance_of(LTSV::Logger::Logger)
end
end
end
end
describe LTSV::Logger do
context 'logger method' do
context '.open' do
before do
LTSV::Logger.open(RSpec.configuration.test_log_path)
end
it 'module has logger instance' do
LTSV::Logger.logger.should be_an_instance_of(LTSV::Logger::Logger)
end
end
end
end
| mit |
hakatashi/esolang-battle | contests/5.js | 4427 | const random = require('lodash/random');
const printableRegex = /[a-z0-9!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~-]/gi;
module.exports.getPrecedingIndices = (cellIndex) => {
const x = cellIndex % 24;
const y = Math.floor(cellIndex / 24);
const isOdd = Math.floor(y / 2) % 2 === 0;
const dx = x % 4;
const dy = y % 2;
const type = dy * 4 + dx;
let cells = null;
if (type === 0) {
cells = [
{x: x - 1, y},
{x: x + 1, y},
{x, y: y + 1},
];
} else if (type === 1) {
cells = [
{x: x - 1, y},
{x: x + 1, y},
{x: isOdd ? x : x - 4, y: y - 1},
{x, y: y + 1},
];
} else if (type === 2) {
cells = [
{x: x - 1, y},
{x: x + 1, y},
{x: isOdd ? x + 2 : x - 2, y: y - 1},
];
} else if (type === 3) {
cells = [
{x: x - 1, y},
{x: x + 1, y},
{x: isOdd ? x + 2 : x - 2, y: y - 1},
{x: x - 2, y: y + 1},
];
} else if (type === 4) {
cells = [
{x: x - 3, y},
{x: x + 1, y},
{x, y: y - 1},
{x: isOdd ? x + 2 : x - 2, y: y + 1},
];
} else if (type === 5) {
cells = [
{x: x - 1, y},
{x: x + 3, y},
{x, y: y - 1},
{x: x + 2, y: y - 1},
{x: isOdd ? x + 2 : x - 2, y: y + 1},
{x: isOdd ? x + 4 : x, y: y + 1},
];
} else {
return [];
}
const portals = [
[32, 55, 57, 257, 259, 280],
[165, 188, 211, 147, 172, 193],
[245, 247, 272, 36, 63, 65],
];
const precedings = cells
.filter((c) => c.x >= 0 && c.x < 24 && c.y >= 0 && c.y < 14)
.map((c) => c.y * 24 + c.x);
const portal = portals.find((p) => p.includes(cellIndex));
if (portal) {
return Array.from(
new Set([...precedings, ...portal.filter((c) => c !== cellIndex)]),
);
}
return precedings;
};
module.exports.generateInput = () => {
const tokyoX = random(10, 49);
const kyotoX = random(0, tokyoX - 3);
const height = random(3, 50);
const lines = Array(height).fill(' '.repeat(50));
lines[0] = Array(50)
.fill()
.map((_, i) => (i === tokyoX ? 'T' : ' '))
.join('');
lines[height - 1] = Array(50)
.fill()
.map((_, i) => (i === kyotoX ? 'K' : ' '))
.join('');
return `${lines.join('\n')}\n`;
};
module.exports.isValidAnswer = (input, output) => {
if (process.env.NODE_ENV !== 'production') {
// return true;
}
const inputLines = input.split('\n').filter((line) => line);
const tokyoX = inputLines[0].indexOf('T');
const kyotoX = inputLines[inputLines.length - 1].indexOf('K');
const outputLines = output.toString().split('\n');
for (const [index, line] of outputLines.entries()) {
if (line.slice(50).match(/\S/)) {
console.log(`info: line ${index} exceeds permit output range`);
return false;
}
if (index >= inputLines.length && line.match(/\S/)) {
console.log(`info: line ${index} exceeds permit output range`);
return false;
}
}
const normalizedOutputLines = Array(inputLines.length)
.fill()
.map((_, i) => ((outputLines[i] || '') + ' '.repeat(50)).slice(0, 50));
const printableCounts = (
normalizedOutputLines.join('').match(printableRegex) || []
).length;
if (printableCounts > Math.abs(tokyoX - kyotoX) + inputLines.length) {
console.log(
`info: printable character counts ${printableCounts} exceeds limit`,
);
return false;
}
if (!normalizedOutputLines[0][tokyoX].match(printableRegex)) {
console.log('info: start point is not reachable');
return false;
}
const visited = new Set();
const queue = [];
let isReachable = false;
visited.add(tokyoX);
queue.push({x: tokyoX, y: 0});
const isPrintable = (x, y) => normalizedOutputLines[y][x].match(printableRegex);
while (queue.length > 0) {
const {x, y} = queue.pop();
if (x === kyotoX && y === inputLines.length - 1) {
isReachable = true;
break;
}
if (x - 1 >= 0 && !visited.has(y * 50 + x - 1) && isPrintable(x - 1, y)) {
visited.add(y * 50 + x - 1);
queue.push({x: x - 1, y});
}
if (x + 1 <= 49 && !visited.has(y * 50 + x + 1) && isPrintable(x + 1, y)) {
visited.add(y * 50 + x + 1);
queue.push({x: x + 1, y});
}
if (y - 1 >= 0 && !visited.has((y - 1) * 50 + x) && isPrintable(x, y - 1)) {
visited.add((y - 1) * 50 + x);
queue.push({x, y: y - 1});
}
if (
y + 1 < inputLines.length &&
!visited.has((y + 1) * 50 + x) &&
isPrintable(x, y + 1)
) {
visited.add((y + 1) * 50 + x);
queue.push({x, y: y + 1});
}
}
if (!isReachable) {
console.log('info: kyoto is unreachable');
return false;
}
console.log('info:', {input, output});
return true;
};
| mit |
cdubuc/arakey | src/AppBundle/Controller/Car.php | 10188 | <?php
/**
* Created by IntelliJ IDEA.
* User: c.dubuc
* Date: 06/11/2016
* Time: 23:56
*/
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\Annotations\Patch;
use FOS\RestBundle\Controller\Annotations\Delete;
use AppBundle\Entity\Cars;
use Symfony\Component\HttpFoundation\Request;
/**
* Class Cars
* @package AppBundle\Controller
* @RouteResource("car",pluralize=true)
*/
class Car extends FOSRestController
{
private $oEM = null;
/**
* @Get("/api/getAllCars", name="AllCars", defaults={"_format"="json"})
*/
function getAllCars() {
// ToDo : write custom query or tune many to many association to avoid loops on get and loading useless data.
$this->oEM = $this->getDoctrine()->getManager();
$mRes = $this->oEM->getRepository('AppBundle:Cars')->findAll();
if (true === empty($mRes)) {
throw $this->createNotFoundException('Not Found');
}
return $mRes;
}
/**
* @Get("/api/getCar/{iCarId}", name="getCar", defaults={"_format"="json"})
*/
function getCar($iCarId) {
$iCarId = intval($iCarId);
if (0 >= $iCarId) {
throw $this->createAccessDeniedException('Invalid Params');
}
$this->oEM = $this->getDoctrine()->getManager();
return $this->oEM->getRepository('AppBundle:Cars')->find($iCarId);
}
/**
* @Delete("/api/deleteCar/{iCarId}", name="deleteCar", defaults={"_format"="json"})
*/
function deleteCar($iCarId) {
$iCarId = intval($iCarId);
if (0 >= $iCarId) {
throw $this->createNotFoundException('Invalid Params');
}
$this->oEM = $this->getDoctrine()->getManager();
$oCar = $this->oEM->getRepository('AppBundle:Cars')->find($iCarId);
if (true === is_null($oCar)) {
throw $this->createNotFoundException('Not Found');
}
$this->oEM->remove($oCar);
$this->oEM->flush();
$aData = array('OK');
$aReturn['code'] = 200;
$aReturn['status'] = 'OK';
$aReturn['message'] = '';
$aReturn['data'] = $aData;
return $aReturn;
}
/**
* @Post("/api/postCar", name="newCar", defaults={"_format"="json"})
*/
function postCar() {
$this->oEM = $this->getDoctrine()->getManager();
$oRequest = Request::createFromGlobals();
$oParams = json_decode($oRequest->getContent());
try {
if (false === empty($oParams)) {
$aEquip = array();
$aOptions = array();
if (true === is_array($oParams->equip)) {
foreach ($oParams->equip as $iEquip) {
$aEquip[] = $this->oEM->getRepository('AppBundle:Equipments')->find($iEquip);
}
}
if (true === is_array($oParams->options)) {
foreach ($oParams->options as $iOption) {
$aOptions[] = $this->oEM->getRepository('AppBundle:Equipments')->find($iOption);
}
}
$this->entityNotExists(new Cars($oParams->maker, $oParams->model, $oParams->price, $aEquip, $aOptions));
$this->oEM->flush();
$aData = array('OK');
$aReturn['code'] = 200;
$aReturn['status'] = 'OK';
$aReturn['message'] = '';
$aReturn['data'] = $aData;
} else {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = 'Params Error.';
$aReturn['data'] = '';
}
} catch (Exception $e) {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = $e->getMessage();
$aReturn['data'] = '';
}
return $aReturn;
}
/**
* @Put("/api/putCar", name="updateCar", defaults={"_format"="json"})
*/
function putCar() {
$this->oEM = $this->getDoctrine()->getManager();
$oRequest = Request::createFromGlobals();
$oParams = json_decode($oRequest->getContent());
try {
if (false === empty($oParams)) {
if (false === isset($oParams->id) || 0 >= intval($oParams->id)) {
throw $this->createNotFoundException('Not Found');
}
$iCarId = $oParams->id;
$oCar = $this->oEM->getRepository('AppBundle:Cars')->find($iCarId);
if (true === is_null($oCar)) {
throw $this->createNotFoundException('Not Found');
}
$oCar->resetEquip();
$oCar->resetOption();
if (true === isset($oParams->equip) && true === is_array($oParams->equip)) {
foreach ($oParams->equip as $iEquip) {
$oCar->addEquip($this->oEM->getRepository('AppBundle:Equipments')->find($iEquip));
}
}
if (true === isset($oParams->options) && true === is_array($oParams->options)) {
foreach ($oParams->options as $iOption) {
$oCar->addOption($this->oEM->getRepository('AppBundle:Equipments')->find($iOption));
}
}
if (true === isset($oParams->maker)) {
$oCar->setMaker($oParams->maker);
} else {
$oCar->setMaker(null);
}
if (true === isset($oParams->model)) {
$oCar->setModel($oParams->model);
} else {
$oCar->setModel(null);
}
if (true === isset($oParams->price)) {
$oCar->setPrice($oParams->price);
} else {
$oCar->setPrice(null);
}
$this->oEM->flush();
$aData = array('OK');
$aReturn['code'] = 200;
$aReturn['status'] = 'OK';
$aReturn['message'] = '';
$aReturn['data'] = $aData;
} else {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = 'Params Error.';
$aReturn['data'] = '';
}
} catch (Exception $e) {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = $e->getMessage();
$aReturn['data'] = '';
}
return $aReturn;
}
/**
* @Patch("/api/patchCar", name="patchCar", defaults={"_format"="json"})
*/
function patchCar() {
$this->oEM = $this->getDoctrine()->getManager();
$oRequest = Request::createFromGlobals();
$oParams = json_decode($oRequest->getContent());
try {
if (false === empty($oParams)) {
if (false === isset($oParams->id) || 0 >= intval($oParams->id)) {
throw $this->createNotFoundException('Not Found');
}
$iCarId = $oParams->id;
$oCar = $this->oEM->getRepository('AppBundle:Cars')->find($iCarId);
if (true === is_null($oCar)) {
throw $this->createNotFoundException('Not Found');
}
if (true === isset($oParams->equip) && true === is_array($oParams->equip)) {
$oCar->resetEquip();
foreach ($oParams->equip as $iEquip) {
$oCar->addEquip($this->oEM->getRepository('AppBundle:Equipments')->find($iEquip));
}
}
if (true === isset($oParams->options) && true === is_array($oParams->options)) {
$oCar->resetOption();
foreach ($oParams->options as $iOption) {
$oCar->addOption($this->oEM->getRepository('AppBundle:Equipments')->find($iOption));
}
}
if (true === isset($oParams->maker)) {
$oCar->setMaker($oParams->maker);
}
if (true === isset($oParams->model)) {
$oCar->setModel($oParams->model);
}
if (true === isset($oParams->price)) {
$oCar->setPrice($oParams->price);
}
$this->oEM->flush();
$aData = array('OK');
$aReturn['code'] = 200;
$aReturn['status'] = 'OK';
$aReturn['message'] = '';
$aReturn['data'] = $aData;
} else {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = 'Params Error.';
$aReturn['data'] = '';
}
} catch (Exception $e) {
$aReturn['code'] = 503;
$aReturn['status'] = 'NOK';
$aReturn['message'] = $e->getMessage();
$aReturn['data'] = '';
}
return $aReturn;
}
/**
* Check for duplicate
* @param Cars $oCars
* @return bool
* @throws \Exception
*/
public function entityNotExists(Cars $oCars)
{
try {
$aFindAssociation = $this->oEM->getRepository('AppBundle:Cars')->findOneBy(
array(
'maker' => $oCars->getMaker(),
'model' => $oCars->getModel(),
'price' => $oCars->getPrice()
)
);
} catch (Exception $e) {
throw $e;
}
if (count($aFindAssociation) > 0) {
return FALSE;
} else {
return $this->oEM->persist($oCars);
}
}
} | mit |
Haacked/Rothko | src/Rothko/Infrastructure/IFileFacade.cs | 28116 | using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Text;
namespace Rothko
{
public interface IFileFacade
{
/// <summary>
/// Creates or overwrites the specified file with the specified buffer size,
/// file options, and file security.
/// </summary>
/// <param name="path">The name of the file.</param>
/// <returns>
/// A new file with the specified buffer size, file options, and file security.
/// </returns>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.-or-System.IO.FileOptions.Encrypted is specified for options
/// and file encryption is not supported on the current platform.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by System.IO.Path.InvalidPathChars.
/// </exception>
/// <exception cref="System.ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than
/// 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="System.IO.IOException">An I/O error occurred while creating the file.</exception>
/// <exception cref="System.NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.
/// </exception>
FileStream Create(string path);
/// <summary>
/// Creates or overwrites the specified file with the specified buffer size,
/// file options, and file security.
/// </summary>
/// <param name="path">The name of the file.</param>
/// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
/// <returns>
/// A new file with the specified buffer size, file options, and file security.
/// </returns>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.-or-System.IO.FileOptions.Encrypted is specified for options
/// and file encryption is not supported on the current platform.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by System.IO.Path.InvalidPathChars.
/// </exception>
/// <exception cref="System.ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than
/// 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="System.IO.IOException">An I/O error occurred while creating the file.</exception>
/// <exception cref="System.NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.
/// </exception>
FileStream Create(string path, int bufferSize);
/// <summary>
/// Creates or overwrites the specified file with the specified buffer size,
/// file options, and file security.
/// </summary>
/// <param name="path">The name of the file.</param>
/// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
/// <param name="options">
/// One of the <see cref="System.IO.FileOptions"/> values that describes how to create or overwrite
/// the file
/// </param>
/// <returns>
/// A new file with the specified buffer size, file options, and file security.
/// </returns>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.-or-System.IO.FileOptions.Encrypted is specified for options
/// and file encryption is not supported on the current platform.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by System.IO.Path.InvalidPathChars.
/// </exception>
/// <exception cref="System.ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than
/// 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="System.IO.IOException">An I/O error occurred while creating the file.</exception>
/// <exception cref="System.NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.
/// </exception>
FileStream Create(string path, int bufferSize, FileOptions options);
/// <summary>
/// Creates or overwrites the specified file with the specified buffer size,
/// file options, and file security.
/// </summary>
/// <param name="path">The name of the file.</param>
/// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
/// <param name="options">
/// One of the <see cref="System.IO.FileOptions"/> values that describes how to create or overwrite
/// the file
/// </param>
/// <param name="fileSecurity">
/// One of the <see cref="System.Security.AccessControl.FileSecurity"/> values that determines
/// the access control and audit security for the file.
/// </param>
/// <returns>
/// A new file with the specified buffer size, file options, and file security.
/// </returns>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.-or-System.IO.FileOptions.Encrypted is specified for options
/// and file encryption is not supported on the current platform.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by System.IO.Path.InvalidPathChars.
/// </exception>
/// <exception cref="System.ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum
/// length. For example, on Windows-based platforms, paths must be less than
/// 248 characters, and file names must be less than 260 characters.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="System.IO.IOException">An I/O error occurred while creating the file.</exception>
/// <exception cref="System.NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The caller does not have the required permission.-or- <paramref name="path"/> specified a file
/// that is read-only.
/// </exception>
FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
/// <summary>Determines whether the specified file exists.</summary>
/// <param name="path">The file to check.</param>
/// <return>
/// true if the caller has the required permissions and path contains the name
/// of an existing file; otherwise, false. This method also returns false if
/// path is null, an invalid path, or a zero-length string. If the caller does
/// not have sufficient permissions to read the specified file, no exception
/// is thrown and the method returns false regardless of the existence of path.
/// </return>
bool Exists(string path);
/// <summary>Gets a <see cref="T:Rothko.IFileInfo"/> representing the specified path.</summary>
/// <param name="path">The path of the file to get.</param>
/// <returns>An object that represents the file for the specified path.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null. </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> contains invalid characters such as ", >, <, or |.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
IFileInfo GetFile(string path);
/// <summary>
/// Gets a <see cref="T:Rothko.IFileInfo"/> representing the specified path.
/// </summary>
/// <param name="path">The path of the file to get.</param>
/// <param name="contents">The string to write to the file.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null or <paramref name="contents"/> is null. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> contains invalid characters such as ", >, <, or |.
/// </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// An I/O error occurred while opening the file.
/// </exception>
/// <exception cref="T:System.UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.-or- This operation is not supported
/// on the current platform.-or- path specified a directory.-or- The caller does
/// not have the required permission.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
void WriteAllText(string path, string contents);
/// <summary>
/// Gets a <see cref="T:Rothko.IFileInfo"/> representing the specified path.
/// </summary>
/// <param name="path">The path of the file to get.</param>
/// <param name="contents">The string to write to the file.</param>
/// <param name="encoding">The encoding that is applied to the contents of the file.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null or <paramref name="contents"/> is null. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> contains invalid characters such as ", >, <, or |.
/// </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// An I/O error occurred while opening the file.
/// </exception>
/// <exception cref="T:System.UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.-or- This operation is not supported
/// on the current platform.-or- path specified a directory.-or- The caller does
/// not have the required permission.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
void WriteAllText(string path, string contents, Encoding encoding);
/// <summary>
/// Copies an existing file to a new file. Overwriting a file of the same name
/// is allowed.
/// </summary>
/// <param name="sourceFileName">The file to copy.</param>
/// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
/// <param name="overwrite">true if the destination file can be overwritten; otherwise, false.</param>
/// <exception cref="T:System.UnauthorizedAccessException">
/// The caller does not have the required permission. -or-destFileName is read-only.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is a zero-length string,
/// contains only white space, or contains one or more invalid characters as defined by
/// System.IO.Path.InvalidPathChars.-or- sourceFileName or destFileName specifies a directory.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> sourceFileName or destFileName is null.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The path specified in <paramref name="sourceFileName" /> or <paramref name="destFileName" />, file name,
/// or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be
/// less than 248 characters, and file names must be less than 260 characters. The specified path, file
/// name, or both are too long.
/// </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The path specified in <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is invalid
/// (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.FileNotFoundException">
/// <paramref name="sourceFileName" /> was not found.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// <paramref name="destFileName" /> exists and overwrite is false.-or- An I/O error has occurred.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
void Copy(string sourceFileName, string destFileName, bool overwrite);
/// <summary>
/// Moves a specified file to a new location, providing the option to specify
/// a new file name.
/// </summary>
/// <param name="sourceFileName">The file to copy.</param>
/// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
/// <exception cref="T:System.UnauthorizedAccessException">
/// The caller does not have the required permission. -or-destFileName is read-only.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is a zero-length string,
/// contains only white space, or contains one or more invalid characters as defined by
/// System.IO.Path.InvalidPathChars.-or- sourceFileName or destFileName specifies a directory.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> sourceFileName or destFileName is null.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The path specified in <paramref name="sourceFileName" /> or <paramref name="destFileName" />, file name,
/// or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be
/// less than 248 characters, and file names must be less than 260 characters. The specified path, file
/// name, or both are too long.
/// </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The path specified in <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is invalid
/// (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.FileNotFoundException">
/// <paramref name="sourceFileName" /> was not found.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// <paramref name="destFileName" /> exists and overwrite is false.-or- An I/O error has occurred.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
void Move(string sourceFileName, string destFileName);
/// <summary>
/// Read the lines of a file that has a specified encoding.
/// </summary>
/// <param name="path">The file to check.</param>
/// <param name="encoding">The encoding that is applied to the contents of the file.</param>
/// <returns>
/// All the lines of the file, or the lines that are the result of a query.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by the System.IO.Path.GetInvalidPathChars()
/// method.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null. </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.FileNotFoundException">
/// <paramref name="path" /> was not found.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// An I/O error occurred while opening the file.
/// </exception>
/// <exception cref="T:System.UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.-or- This operation is not supported
/// on the current platform.-or- path specified a directory.-or- The caller does
/// not have the required permission.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
IEnumerable<string> ReadLines(string path, Encoding encoding);
/// <summary>
/// Opens a file, reads all lines of the file with the specified encoding, and
/// then closes the file.
/// </summary>
/// <param name="path">The file to check.</param>
/// <param name="encoding">The encoding that is applied to the contents of the file.</param>
/// <returns>
/// All the lines of the file, or the lines that are the result of a query.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by the System.IO.Path.GetInvalidPathChars()
/// method.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null. </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.FileNotFoundException">
/// <paramref name="path" /> was not found.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// An I/O error occurred while opening the file.
/// </exception>
/// <exception cref="T:System.UnauthorizedAccessException">
/// <paramref name="path"/> specified a file that is read-only.-or- This operation is not supported
/// on the current platform.-or- path specified a directory.-or- The caller does
/// not have the required permission.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
string ReadAllText(string path, Encoding encoding);
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="path">The file to check.</param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="path"/> is a zero-length string, contains only white space, or contains one
/// or more invalid characters as defined by the System.IO.Path.GetInvalidPathChars()
/// method.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path"/> is null. </exception>
/// <exception cref="T:System.DirectoryNotFoundException">
/// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="T:System.IO.FileNotFoundException">
/// <paramref name="path" /> was not found.
/// </exception>
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than
/// 260 characters. The specified path, file name, or both are too long.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// The specified file is in use. -or-There is an open handle on the file, and
/// the operating system is Windows XP or earlier. This open handle can result
/// from enumerating directories and files. For more information, see How to:
/// Enumerate Directories and Files.
/// </exception>
/// <exception cref="T:System.UnauthorizedAccessException">
// The caller does not have the required permission.-or- <paramref name="path"/> is a directory.-or-
// path specified a read-only file.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// <paramref name="path"/> is in an invalid format.
/// </exception>
/// <exception cref="T:System.Security.SecurityException">
/// The caller does not have the required permission.
/// </exception>
void Delete(string path);
}
}
| mit |
sproutcoin/sprouts | src/qt/locale/bitcoin_da.ts | 127726 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="da">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="75"/>
<source><html><head/><body><p><span style=" font-weight:600;">Sprouts</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="113"/>
<source>Copyright © 2014 Sprouts Developers</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="120"/>
<source>Copyright © 2011-2014 Sprouts Developers</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="133"/>
<source>Copyright © 2009-2014 Bitcoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Adressebog</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your Sprouts 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 type="unfinished"></translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklik for at redigere adresse eller mærkat</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>Opret en ny adresse</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&Ny adresse ...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adresse til systemets udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&Kopier til Udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Show &QR Code</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="96"/>
<source>Sign a message to prove you own this address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="99"/>
<source>&Sign Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="110"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Slet den valgte adresse fra listen. Kun adresser brugt til afsendelse kan slettes.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="113"/>
<source>&Delete</source>
<translation>&Slet</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="65"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="66"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="67"/>
<source>Edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="68"/>
<source>Delete</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="273"/>
<source>Export Address Book Data</source>
<translation>Eksporter Adressekartoteketsdata</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="274"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="287"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="287"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="79"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="79"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="115"/>
<source>(no label)</source>
<translation>(ingen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="94"/>
<source>TextLabel</source>
<translation>TekstEtiket</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>Indtast adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>Ny adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>Gentag ny adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="114"/>
<source>Toggle Keyboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="37"/>
<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>Indtast den nye adgangskode til tegnebogen.<br/>Brug venligst en adgangskode på <b>10 eller flere tilfældige tegn</b>, eller <b>otte eller flere ord</b>.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>Encrypt wallet</source>
<translation>Krypter tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="41"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at låse tegnebogen op.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>Unlock wallet</source>
<translation>Lås tegnebog op</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="49"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at dekryptere tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Decrypt wallet</source>
<translation>Dekryptér tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="57"/>
<source>Change passphrase</source>
<translation>Skift adgangskode</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="58"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Indtast den gamle og nye adgangskode til tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="106"/>
<source>Confirm wallet encryption</source>
<translation>Bekræft tegnebogskryptering</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="116"/>
<location filename="../askpassphrasedialog.cpp" line="165"/>
<source>Wallet encrypted</source>
<translation>Tegnebog krypteret</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="213"/>
<location filename="../askpassphrasedialog.cpp" line="237"/>
<source>Warning: The Caps Lock key is on.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="122"/>
<location filename="../askpassphrasedialog.cpp" line="129"/>
<location filename="../askpassphrasedialog.cpp" line="171"/>
<location filename="../askpassphrasedialog.cpp" line="177"/>
<source>Wallet encryption failed</source>
<translation>Tegnebogskryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="107"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PEERCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<source>Sprouts will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Sproutss from being stolen by malware infecting your computer.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="123"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Tegnebogskryptering mislykkedes på grund af en intern fejl. Din tegnebog blev ikke krypteret.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="130"/>
<location filename="../askpassphrasedialog.cpp" line="178"/>
<source>The supplied passphrases do not match.</source>
<translation>De angivne kodeord stemmer ikke overens.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="141"/>
<source>Wallet unlock failed</source>
<translation>Tegnebogsoplåsning mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="142"/>
<location filename="../askpassphrasedialog.cpp" line="153"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Det angivne kodeord for tegnebogsdekrypteringen er forkert.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="152"/>
<source>Wallet decryption failed</source>
<translation>Tegnebogsdekryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Tegnebogskodeord blev ændret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="191"/>
<source>&Overview</source>
<translation>&Oversigt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="192"/>
<source>Show general overview of wallet</source>
<translation>Vis generel oversigt over tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="197"/>
<source>&Transactions</source>
<translation>&Transaktioner</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="198"/>
<source>Browse transaction history</source>
<translation>Gennemse transaktionshistorik</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="203"/>
<source>&Minting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>Show your minting capacity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="209"/>
<source>&Address Book</source>
<translation>&Adressebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediger listen over gemte adresser og etiketter</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>&Receive coins</source>
<translation>&Modtag coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="216"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for at modtage betalinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="221"/>
<source>&Send coins</source>
<translation>&Send coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="227"/>
<source>Sign/Verify &message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="228"/>
<source>Prove you control an address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>E&xit</source>
<translation>&Luk</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="250"/>
<source>Quit application</source>
<translation>Afslut program</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="254"/>
<source>Show information about Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="256"/>
<source>About &Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="257"/>
<source>Show information about Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="259"/>
<source>&Options...</source>
<translation>&Indstillinger ...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="264"/>
<source>&Export...</source>
<translation>&Eksporter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="265"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="266"/>
<source>&Encrypt Wallet</source>
<translation>&Kryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="267"/>
<source>Encrypt or decrypt wallet</source>
<translation>Kryptér eller dekryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="269"/>
<source>&Unlock Wallet for Minting Only</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="270"/>
<source>Unlock wallet only for minting. Sending coins will still require the passphrase.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="272"/>
<source>&Backup Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="273"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="274"/>
<source>&Change Passphrase</source>
<translation>&Skift adgangskode</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="275"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Skift kodeord anvendt til tegnebogskryptering</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="276"/>
<source>&Debug window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="277"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="301"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="310"/>
<source>&Settings</source>
<translation>&Indstillinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="317"/>
<source>&Help</source>
<translation>&Hjælp</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="326"/>
<source>Tabs toolbar</source>
<translation>Faneværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="338"/>
<source>Actions toolbar</source>
<translation>Handlingsværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="350"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="658"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1. Do you want to pay the fee?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="76"/>
<source>Sprouts Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="222"/>
<source>Send coins to a Sprouts address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="253"/>
<source>&About Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="260"/>
<source>Modify configuration options for Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Show/Hide &Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="263"/>
<source>Show or hide the Sprouts window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="415"/>
<source>Sprouts client</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="443"/>
<source>p-qt</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="507"/>
<source>%n active connection(s) to Sprouts network</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="531"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med netværk ...</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="533"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished">
<numerusform>~%n block remaining</numerusform>
<numerusform>~%n blocks remaining</numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="544"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="556"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Downloadet %1 blokke af transaktionshistorie.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="571"/>
<source>%n second(s) ago</source>
<translation type="unfinished">
<numerusform>%n sekund(er) siden</numerusform>
<numerusform>%n sekund(er) siden</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="575"/>
<source>%n minute(s) ago</source>
<translation type="unfinished">
<numerusform>%n minut(ter) siden</numerusform>
<numerusform>%n minut(ter) siden</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="579"/>
<source>%n hour(s) ago</source>
<translation type="unfinished">
<numerusform>%n time(r) siden</numerusform>
<numerusform>%n time(r) siden</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="583"/>
<source>%n day(s) ago</source>
<translation type="unfinished">
<numerusform>%n dag(e) siden</numerusform>
<numerusform>%n dag(e) siden</numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="589"/>
<source>Up to date</source>
<translation>Opdateret</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="594"/>
<source>Catching up...</source>
<translation>Indhenter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="602"/>
<source>Last received block was generated %1.</source>
<translation>Sidst modtagne blok blev genereret %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="661"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="688"/>
<source>Sent transaction</source>
<translation>Afsendt transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="689"/>
<source>Incoming transaction</source>
<translation>Indgående transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="690"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløb: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="821"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked for block minting only</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="821"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>ulåst</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="831"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="888"/>
<source>Backup Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="888"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="891"/>
<source>Backup Failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="891"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="128"/>
<source>A fatal error occured. Sprouts can no longer continue safely and will quit.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="14"/>
<source>Coin Control</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="45"/>
<source>Quantity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="64"/>
<location filename="../forms/coincontroldialog.ui" line="96"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="77"/>
<source>Bytes:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="125"/>
<source>Amount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="144"/>
<location filename="../forms/coincontroldialog.ui" line="224"/>
<location filename="../forms/coincontroldialog.ui" line="310"/>
<location filename="../forms/coincontroldialog.ui" line="348"/>
<source>0.00 BTC</source>
<translation>123.456 BTC {0.00 ?}</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="157"/>
<source>Priority:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="205"/>
<source>Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="240"/>
<source>Low Output:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="262"/>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>no</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="291"/>
<source>After Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="326"/>
<source>Change:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="395"/>
<source>(un)select all</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="408"/>
<source>Tree mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="424"/>
<source>List mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="469"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="479"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="484"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="489"/>
<source>Confirmations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="492"/>
<source>Confirmed</source>
<translation>Bekræftet</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="497"/>
<source>Coin days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="502"/>
<source>Priority</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="36"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="37"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="38"/>
<location filename="../coincontroldialog.cpp" line="64"/>
<source>Copy amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="39"/>
<source>Copy transaction ID</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="63"/>
<source>Copy quantity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="65"/>
<source>Copy fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="66"/>
<source>Copy after fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="67"/>
<source>Copy bytes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="68"/>
<source>Copy priority</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="69"/>
<source>Copy low output</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="70"/>
<source>Copy change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="388"/>
<source>highest</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="389"/>
<source>high</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="390"/>
<source>medium-high</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="391"/>
<source>medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="395"/>
<source>low-medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="396"/>
<source>low</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="397"/>
<source>lowest</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>DUST</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>yes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="582"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="583"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="584"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="585"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="622"/>
<location filename="../coincontroldialog.cpp" line="688"/>
<source>(no label)</source>
<translation>(ingen etiket)</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="679"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="680"/>
<source>(change)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="275"/>
<source>&Unit to show amounts in: </source>
<translation>&Enhed at vise beløb i: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="279"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Vælg den standard underopdelingsenhed som skal vises i brugergrænsefladen, og når du sender coins</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="286"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="287"/>
<source>Whether to show Sprouts addresses in the transaction list</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="290"/>
<source>Display coin control features (experts only!)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="291"/>
<source>Whether to show coin control features or not</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Rediger Adresse</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Etiketten forbundet med denne post i adressekartoteket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adressen tilknyttet til denne post i adressekartoteket. Dette kan kun ændres for afsendelsesadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Ny modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Ny afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Rediger modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Rediger afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den indtastede adresse "%1" er allerede i adressebogen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid Sprouts address.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse tegnebog op.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Ny nøglegenerering mislykkedes.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="177"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systembakken i stedet for proceslinjen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="178"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Vis kun et systembakkeikon efter minimering af vinduet</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<source>Map port using &UPnP</source>
<translation>Konfigurer port vha. &UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="182"/>
<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>Minimer i stedet for at afslutte programmet når vinduet lukkes. Når denne indstilling er valgt vil programmet kun blive lukket når du har valgt Afslut i menuen.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="187"/>
<source>Automatically open the Sprouts client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>&Forbind gennem SOCKS4 proxy:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Opret forbindelse til Bitconnetværket via en SOCKS4 proxy (f.eks. ved tilslutning gennem Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>Proxy-&IP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adressen på proxyen (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>&Port:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Porten på proxyen (f.eks. 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<source>Mandatory network transaction fee per kB transferred. Most transactions are 1 kB and incur a 0.01 SPRTS fee. Note: transfer size may increase depending on the number of input transactions required to be added together to fund the payment.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Additional network &fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="234"/>
<source>Detach databases at shutdown</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="235"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="172"/>
<source>&Start Sprouts on window system startup</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="173"/>
<source>Automatically start Sprouts after the computer is turned on</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MintingTableModel</name>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Age</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>CoinDay</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>MintProbability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="284"/>
<source>minutes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="291"/>
<source>hours</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="295"/>
<source>days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="298"/>
<source>You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="418"/>
<source>Destination address of the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="420"/>
<source>Original transaction id.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="422"/>
<source>Age of the transaction in days.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="424"/>
<source>Balance of the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="426"/>
<source>Coin age in the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="428"/>
<source>Chance to mint a block within given time interval.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MintingView</name>
<message>
<location filename="../mintingview.cpp" line="33"/>
<source>transaction is too young</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="40"/>
<source>transaction is mature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="47"/>
<source>transaction has reached maximum probability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="60"/>
<source>Display minting probability within : </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="62"/>
<source>10 min</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="63"/>
<source>24 hours</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="64"/>
<source>30 days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="65"/>
<source>90 days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="162"/>
<source>Export Minting Data</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="163"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*.csv)</translation>
</message>
<message>
<location filename="../mintingview.cpp" line="171"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../mintingview.cpp" line="172"/>
<source>Transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="173"/>
<source>Age</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="174"/>
<source>CoinDay</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="175"/>
<source>Balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="176"/>
<source>MintingProbability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="180"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../mintingview.cpp" line="180"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="81"/>
<source>Main</source>
<translation>Generelt</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="86"/>
<source>Display</source>
<translation>Visning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="106"/>
<source>Options</source>
<translation>Indstillinger</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>Antal transaktioner:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>Ubekræftede:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source>Stake:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="102"/>
<source>Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="138"/>
<source><b>Recent transactions</b></source>
<translation><b>Nyeste transaktioner</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="104"/>
<source>Your current balance</source>
<translation>Din nuværende saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="109"/>
<source>Your current stake</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="114"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Summen af transaktioner, der endnu ikke er bekræftet, og endnu ikke er inkluderet i den nuværende saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="117"/>
<source>Total number of transactions in wallet</source>
<translation>Samlede antal transaktioner i tegnebogen</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="55"/>
<source>Request Payment</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="70"/>
<source>Amount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="105"/>
<source>SPRTS</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="121"/>
<source>Label:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="144"/>
<source>Message:</source>
<translation>Besked:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="186"/>
<source>&Save As...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="46"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="64"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="121"/>
<source>Save Image...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="121"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="14"/>
<source>Sprouts (Sprouts) debug window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="24"/>
<source>Information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="33"/>
<source>Client name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="40"/>
<location filename="../forms/rpcconsole.ui" line="60"/>
<location filename="../forms/rpcconsole.ui" line="106"/>
<location filename="../forms/rpcconsole.ui" line="156"/>
<location filename="../forms/rpcconsole.ui" line="176"/>
<location filename="../forms/rpcconsole.ui" line="196"/>
<location filename="../forms/rpcconsole.ui" line="229"/>
<location filename="../rpcconsole.cpp" line="338"/>
<source>N/A</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="53"/>
<source>Client version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="79"/>
<source>Version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="92"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="99"/>
<source>Number of connections</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="119"/>
<source>On testnet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="142"/>
<source>Block chain</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="149"/>
<source>Current number of blocks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="169"/>
<source>Estimated total blocks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="189"/>
<source>Last block time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="222"/>
<source>Build date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="237"/>
<source>Console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="270"/>
<source>></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="286"/>
<source>Clear console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="306"/>
<source>Welcome to the Sprouts RPC console.<br>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.<br>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="176"/>
<location filename="../sendcoinsdialog.cpp" line="181"/>
<location filename="../sendcoinsdialog.cpp" line="186"/>
<location filename="../sendcoinsdialog.cpp" line="191"/>
<location filename="../sendcoinsdialog.cpp" line="197"/>
<location filename="../sendcoinsdialog.cpp" line="202"/>
<location filename="../sendcoinsdialog.cpp" line="207"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="90"/>
<source>Coin Control Features</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="110"/>
<source>Inputs...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="117"/>
<source>automatically selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="136"/>
<source>Insufficient funds!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="213"/>
<source>Quantity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="235"/>
<location filename="../forms/sendcoinsdialog.ui" line="270"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="251"/>
<source>Bytes:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="302"/>
<source>Amount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="324"/>
<location filename="../forms/sendcoinsdialog.ui" line="410"/>
<location filename="../forms/sendcoinsdialog.ui" line="496"/>
<location filename="../forms/sendcoinsdialog.ui" line="528"/>
<source>0.00 BTC</source>
<translation>123.456 BTC {0.00 ?}</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="337"/>
<source>Priority:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="356"/>
<source>medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="388"/>
<source>Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="423"/>
<source>Low Output:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="442"/>
<source>no</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="474"/>
<source>After Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="509"/>
<source>Change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="559"/>
<source>custom change address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="665"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere modtagere på én gang</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="668"/>
<source>&Add recipient...</source>
<translation>&Tilføj modtager...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="685"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="688"/>
<source>Clear all</source>
<translation>Ryd alle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="707"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="714"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="745"/>
<source>Confirm the send action</source>
<translation>Bekræft afsendelsen</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="748"/>
<source>&Send</source>
<translation>&Afsend</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="51"/>
<source>Copy quantity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="52"/>
<source>Copy amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="53"/>
<source>Copy fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="54"/>
<source>Copy after fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="55"/>
<source>Copy bytes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="56"/>
<source>Copy priority</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="57"/>
<source>Copy low output</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="58"/>
<source>Copy change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Confirm send coins</source>
<translation>Bekræft afsendelse af coins</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="150"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="150"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="182"/>
<source>The amount to pay must be at least one cent (0.01).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="457"/>
<source>Warning: Invalid Bitcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="466"/>
<source>Warning: Unknown change address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="477"/>
<source>(no label)</source>
<translation>(ingen etiket)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="187"/>
<source>Amount exceeds your balance</source>
<translation>Beløbet overstiger din saldo</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="36"/>
<source>Enter a Sprouts address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="177"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="192"/>
<source>Total exceeds your balance when the %1 transaction fee is included</source>
<translation>Totalen overstiger din saldo når %1 transaktionsgebyr er inkluderet</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="198"/>
<source>Duplicate address found, can only send to each address once in one send operation</source>
<translation>Duplikeret adresse fundet. Du kan kun sende til hver adresse en gang pr. afsendelse.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="203"/>
<source>Error: Transaction creation failed </source>
<translation>Fejl: Oprettelse af transaktionen mislykkedes </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="208"/>
<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>Fejl: Transaktionen blev afvist. Dette kan ske hvis nogle af dine coins i din tegnebog allerede var brugt, som hvis du brugte en kopi af wallet.dat og dine coins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>B&eløb:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Indtast en etiket for denne adresse for at føje den til din adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Vælg adresse fra adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Indsæt adresse fra udklipsholderen</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Fjern denne modtager</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a Sprouts address</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="24"/>
<source>&Sign Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="30"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="48"/>
<source>The address to sign the message with</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="55"/>
<location filename="../forms/signverifymessagedialog.ui" line="265"/>
<source>Choose previously used address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="65"/>
<location filename="../forms/signverifymessagedialog.ui" line="275"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="75"/>
<source>Paste address from clipboard</source>
<translation>Indsæt adresse fra udklipsholderen</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="85"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="97"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="104"/>
<source>Signature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="131"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="152"/>
<source>Sign the message to prove you own this Sprouts address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="155"/>
<source>Sign &Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="169"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="172"/>
<location filename="../forms/signverifymessagedialog.ui" line="315"/>
<source>Clear &All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="231"/>
<source>&Verify Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="237"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="258"/>
<source>The address the message was signed with</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="295"/>
<source>Verify the message to ensure it was signed with the specified Sprouts address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="298"/>
<source>Verify &Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="312"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="29"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="30"/>
<source>Enter the signature of the message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="31"/>
<location filename="../signverifymessagedialog.cpp" line="32"/>
<source>Enter a Sprouts address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="115"/>
<location filename="../signverifymessagedialog.cpp" line="195"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="115"/>
<location filename="../signverifymessagedialog.cpp" line="123"/>
<location filename="../signverifymessagedialog.cpp" line="195"/>
<location filename="../signverifymessagedialog.cpp" line="203"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="123"/>
<location filename="../signverifymessagedialog.cpp" line="203"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="131"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="139"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="151"/>
<source>Message signing failed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="156"/>
<source>Message signed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="214"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="214"/>
<location filename="../signverifymessagedialog.cpp" line="227"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="227"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="234"/>
<source>Message verification failed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="239"/>
<source>Message verified.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="21"/>
<source>Open for %1 blocks</source>
<translation>Åben for %1 blokke</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="23"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="29"/>
<source>%1/offline?</source>
<translation>%1/offline?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="31"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekræftet</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="33"/>
<source>%1 confirmations</source>
<translation>%1 bekræftelser</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="51"/>
<source><b>Status:</b> </source>
<translation><b>Status:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, has not been successfully broadcast yet</source>
<translation>, er ikke blevet transmitteret endnu</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="58"/>
<source>, broadcast through %1 node</source>
<translation>, transmitteret via %1 node</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source>, broadcast through %1 nodes</source>
<translation>, transmitteret via %1 noder</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="64"/>
<source><b>Date:</b> </source>
<translation><b>Dato:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="71"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Kilde:</b> Genereret<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="77"/>
<location filename="../transactiondesc.cpp" line="94"/>
<source><b>From:</b> </source>
<translation><b>Fra:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source>unknown</source>
<translation>ukendt</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="95"/>
<location filename="../transactiondesc.cpp" line="118"/>
<location filename="../transactiondesc.cpp" line="178"/>
<source><b>To:</b> </source>
<translation><b>Til:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="98"/>
<source> (yours, label: </source>
<translation> (din, etiket:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="100"/>
<source> (yours)</source>
<translation> (din)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="136"/>
<location filename="../transactiondesc.cpp" line="150"/>
<location filename="../transactiondesc.cpp" line="195"/>
<location filename="../transactiondesc.cpp" line="212"/>
<source><b>Credit:</b> </source>
<translation><b>Kredit:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="138"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 modnes i %2 blokke mere)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="142"/>
<source>(not accepted)</source>
<translation>(ikke accepteret)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="186"/>
<location filename="../transactiondesc.cpp" line="194"/>
<location filename="../transactiondesc.cpp" line="209"/>
<source><b>Debit:</b> </source>
<translation><b>Debet:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="200"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Transaktionsgebyr:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="218"/>
<source><b>Net amount:</b> </source>
<translation><b>Nettobeløb:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="220"/>
<source><b>Retained amount:</b> %1 until %2 more blocks<br></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="227"/>
<source>Message:</source>
<translation>Besked:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="229"/>
<source>Comment:</source>
<translation>Kommentar:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="231"/>
<source>Transaction ID:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="234"/>
<source>Generated coins must wait 520 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, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Genererede coins skal vente 120 blokke, før de kan blive brugt. Da du genererede denne blok blev det transmitteret til netværket, for at blive føjet til blokkæden. Hvis det mislykkes at komme ind i kæden, vil den skifte til "ikke godkendt", og ikke blive kunne bruges. Dette kan lejlighedsvis ske, hvis en anden node genererer en blok inden for få sekunder af din. {520 ?}</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="236"/>
<source>Staked coins must wait 520 blocks before they can return to balance and be spent. When you generated this proof-of-stake block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be a valid stake. This may occasionally happen if another node generates a proof-of-stake block within a few seconds of yours.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Transaktionsdetaljer</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Denne rude viser en detaljeret beskrivelse af transaktionen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="281"/>
<source>Open for %n block(s)</source>
<translation>
<numerusform>Åben for %n blok(ke)</numerusform>
<numerusform>Åben for %n blok(ke)</numerusform>
</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="284"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="287"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="290"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekræftet (%1 af %2 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="293"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekræftet (%1 bekræftelser)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>Mined balance will be available in %n more blocks</source>
<translation>
<numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform>
<numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform>
</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="307"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blok blev ikke modtaget af nogen andre noder, og vil formentlig ikke blive accepteret!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="310"/>
<source>Generated but not accepted</source>
<translation>Genereret, men ikke accepteret</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Received from</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="358"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="360"/>
<source>Payment to yourself</source>
<translation>Betaling til dig selv</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="362"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="364"/>
<source>Mint by stake</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="403"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="603"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactionsstatus. Hold musen over dette felt for at vise antallet af bekræftelser.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="605"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for at transaktionen blev modtaget.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="607"/>
<source>Type of transaction.</source>
<translation>Type af transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="609"/>
<source>Destination address of transaction.</source>
<translation>Destinationsadresse for transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="611"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløb fjernet eller tilføjet balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Denne uge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Denne måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Sidste måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Dette år</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Interval...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Til dig selv</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Mint by stake</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactionview.cpp" line="79"/>
<source>Other</source>
<translation>Andet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="85"/>
<source>Enter address or label to search</source>
<translation>Indtast adresse eller etiket for at søge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="91"/>
<source>Min amount</source>
<translation>Min. beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Copy amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Edit label</source>
<translation>Rediger etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="129"/>
<source>Show details...</source>
<translation>Vis detaljer...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="130"/>
<source>Clear orphans</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactionview.cpp" line="273"/>
<source>Export Transaction Data</source>
<translation>Eksportér Transaktionsdata</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="274"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Confirmed</source>
<translation>Bekræftet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="284"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="285"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="286"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="288"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="292"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="292"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="400"/>
<source>Range:</source>
<translation>Interval:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="408"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="164"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Warning: Disk space is low </source>
<translation>Advarsel: Diskplads er lav </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Usage:</source>
<translation>Anvendelse:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Unable to bind to port %d on this computer. Sprouts is probably already running.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>Sprouts version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Send command to -server or sproutsd</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>List commands</source>
<translation>Liste over kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Get help for a command</source>
<translation>Få hjælp til en kommando
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Options:</source>
<translation>Indstillinger:
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Specify configuration file (default: sprouts.conf)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Specify pid file (default: sproutsd.pid)</source>
<translation>Angiv pid-fil (default: sproutsd.pid)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Generate coins</source>
<translation>Generér coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Don't generate coins</source>
<translation>Generér ikke coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Start minimized</source>
<translation>Start minimeret
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Specify data directory</source>
<translation>Angiv databibliotek
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="26"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="27"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Angiv tilslutningstimeout (i millisekunder)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Connect through socks4 proxy</source>
<translation>Tilslut via SOCKS4 proxy
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Allow DNS lookups for addnode and connect</source>
<translation>Tillad DNS-opslag for addnode og connect
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Listen for connections on <port> (default: 9901 or testnet: 9903)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Connect only to the specified node</source>
<translation>Tilslut kun til den angivne node
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Accept connections from outside (default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="39"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Use Universal Plug and Play to map the listening port (default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Use Universal Plug and Play to map the listening port (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter kommandolinje- og JSON-RPC-kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kør i baggrunden som en service, og acceptér kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Use the test network</source>
<translation>Brug test-netværket
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Output extra debugging information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="54"/>
<source>Username for JSON-RPC connections</source>
<translation>Brugernavn til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Password for JSON-RPC connections</source>
<translation>Password til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Listen for JSON-RPC connections on <port> (default: 9902)</source>
<translation>Lyt til JSON-RPC-forbindelser på <port> (standard: 8332)
{9902)?}</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillad JSON-RPC-forbindelser fra bestemt IP-adresse
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node, der kører på <ip> (standard: 127.0.0.1)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Sæt nøglepoolstørrelse til <n> (standard: 100)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Gennemsøg blokkæden for manglende tegnebogstransaktioner
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>
SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Brug OpenSSL (https) for JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servercertifikat-fil (standard: server.cert)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private nøgle (standard: server.pem)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptabele ciphers (standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>This help message</source>
<translation>Denne hjælpebesked
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Usage</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Cannot obtain a lock on data directory %s. Sprouts is probably already running.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Error loading wallet.dat: Wallet requires newer version of Sprouts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="89"/>
<source>Wallet needed to be rewritten: restart Sprouts to complete</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="103"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=peercoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="119"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong Sprouts will not work properly.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Loading addresses...</source>
<translation>Indlæser adresser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>Error loading addr.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>Loading block index...</source>
<translation>Indlæser blok-indeks...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Loading wallet...</source>
<translation>Indlæser tegnebog...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="90"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Cannot write default address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Rescanning...</source>
<translation>Genindlæser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>Done loading</source>
<translation>Indlæsning gennemført</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source>Invalid -proxy address</source>
<translation>Ugyldig -proxy adresse</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>Ugyldigt beløb for -paytxfee=<amount></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel:-paytxfee er sat meget højt. Dette er det gebyr du vil betale, hvis du sender en transaktion.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="101"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>Fejl: CreateThread(StartNode) mislykkedes</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="102"/>
<source>To use the %s option</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="113"/>
<source>An error occured while setting up the RPC port %i for listening: %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="114"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="122"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="123"/>
<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 type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>Error: Transaction creation failed </source>
<translation>Fejl: Oprettelse af transaktionen mislykkedes </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<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>Fejl: Transaktionen blev afvist. Dette kan ske hvis nogle af dine coins i din tegnebog allerede var brugt, som hvis du brugte en kopi af wallet.dat og dine coins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>Invalid amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source>Insufficient funds</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| mit |
cuckata23/wurfl-data | data/sonyericsson_x1i_ver1_subr1aa.php | 579 | <?php
return array (
'id' => 'sonyericsson_x1i_ver1_subr1aa',
'fallback' => 'sonyericsson_x1i_ver1',
'capabilities' =>
array (
'mobile_browser_version' => '7.11',
'uaprof' => 'http://wap.sonyericsson.com/uaprof/X1iR101.xml',
'release_date' => '2008_november',
'columns' => '16',
'rows' => '36',
'resolution_width' => '480',
'resolution_height' => '800',
'colors' => '65536',
'max_deck_size' => '3000',
'mms_max_size' => '614400',
'mms_max_width' => '1600',
'mms_max_height' => '1600',
'oma_support' => 'true',
),
);
| mit |
vesln/tryc | karma.conf.js | 227 | module.exports = function(config) {
config.set({
files: [
'build/build.js',
'test/support/index.js',
'test/index.js'
],
browsers: ['PhantomJS', 'Chrome', 'Firefox'],
singleRun: true
});
};
| mit |
kosua20/GL_Template | docs/theme/process-glsl.py | 3542 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# If no documentation is generated, make sure that this file is executable.
import sys
import os
def printout(text):
sys.stdout.write(text)
doxyFullNames = {"vert" : "vertex", "frag" : "fragment", "geom" : "geometry", "glsl" : "general", "tessc" : "tesselation control", "tesse" : "tesselation evaluation" }
doxySubNamespaces = {"vert" : "Vert", "frag" : "Frag", "geom" : "Geom", "glsl" : "Common", "tesse" : "TessEval", "tessc" : "TessControl" }
structAddKeyword = {"vert" : "out", "frag" : "in", "geom" : "in", "glsl" : "", "tessc" : "in", "tesse" : "out" }
if len(sys.argv) != 2:
sys.exit(1)
# Get the file infos.
filePath = sys.argv[1]
fileSubpath, fileExt = os.path.splitext(filePath)
fileDir, fileName = os.path.split(fileSubpath)
fileExt = fileExt
fileName = fileName
fileType = fileExt.lower()[1:]
# Get the file content.
fileHandle = open(filePath)
fileLines = fileHandle.readlines()
fileHandle.close()
# Doxygen infos.
doxyNamespace = "GPUShaders"
doxyGroup = "Shaders"
subNamespace = doxySubNamespaces[fileType]
descripName = doxyFullNames[fileType]
structKeyword = structAddKeyword[fileType]
className = fileName.capitalize().replace("-", "_")
classDetails = className.replace("_", " ")
# Start by parsing the body of the shader and wrapping it into a C++ class.
# We adjust include, layout and blocks keywords to avoid issues with Doxygen.
# We do this first so that we can reference included shaders afterwards.
bodyStr = "public class " + className + " {" + "\n"
bodyStr += "public:" + "\n"
inInterfaceBlock = False
inUniformBlock = False
referencedFiles = []
# Content of the shader
for line in fileLines:
printLine = True
# Detect layout keyword at beginning and remove layout block that make Doxygen think it's a function.
if line.lstrip().startswith("layout"):
line = line[line.find(")")+1:].lstrip()
if line.find("INTERFACE")>=0:
printLine = False
inInterfaceBlock = True
if line.find("uniform")>=0 and line.find("sampler")<0:
printLine = False
inUniformBlock = True
if (inInterfaceBlock or inUniformBlock) and line.find("}") >= 0:
printLine = False
inInterfaceBlock = False
inUniformBlock = False
if inInterfaceBlock and len(line) > 0:
line = structKeyword + " " + line.lstrip()
if inUniformBlock and len(line) > 0:
line = "uniform" + " " + line.lstrip()
# Skip our include system directives, but keep track
# of them so that we can reference them in the description.
incPos = line.find("#include")
if incPos>=0:
nameStart = line.find("\"", incPos)
nameEnd = line.find(".glsl\"", nameStart)
name = line[(nameStart+1):(nameEnd)]
referencedFiles += [name]
printLine = False
if printLine:
bodyStr += line
# Close the class.
bodyStr += "\n};"
# C++ namespaces
headerStr = "namespace " + doxyNamespace + " {\n"
headerStr += "namespace " + subNamespace + " {\n"
# Class description
headerStr += "/** \\class " + className + "\n"
headerStr += " * \\brief " + classDetails + " " + descripName + " shader." + "\n"
# Reference included shaders
if(len(referencedFiles) > 0):
headerStr += " * \\sa "
firstSA = True
for refFile in referencedFiles:
if not firstSA:
headerStr += ", "
else:
firstSA = False
refName = refFile.capitalize().replace("-", "_")
headerStr += doxyNamespace + "::" + doxySubNamespaces["glsl"] + "::" + refName
headerStr += "\n"
headerStr += " * \\ingroup " + doxyGroup + "\n*/\n"
# Close the namespaces
bodyStr += "\n}\n}\n"
printout(headerStr)
printout(bodyStr)
sys.exit(0)
| mit |
togusafish/app2641-_-hacker-bookmark | config/routes.rb | 1591 | Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'index#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
resources :skills
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| mit |
CyclopsMC/IntegratedDynamics | src/main/java/org/cyclops/integrateddynamics/block/BlockMenrilSlabConfig.java | 1237 | package org.cyclops.integrateddynamics.block;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.SlabBlock;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialColor;
import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig;
import org.cyclops.cyclopscore.helper.BlockHelpers;
import org.cyclops.integrateddynamics.IntegratedDynamics;
import org.cyclops.integrateddynamics.RegistryEntries;
/**
* Config for the Menril Slab.
* @author rubensworks
*
*/
public class BlockMenrilSlabConfig extends BlockConfig {
public BlockMenrilSlabConfig() {
super(
IntegratedDynamics._instance,
"menril_slab",
eConfig -> new SlabBlock(AbstractBlock.Properties.create(Material.WOOD, MaterialColor.CYAN)
.hardnessAndResistance(2.0F, 3.0F)
.sound(SoundType.WOOD)),
getDefaultItemConstructor(IntegratedDynamics._instance)
);
}
@Override
public void onForgeRegistered() {
super.onForgeRegistered();
BlockHelpers.setFireInfo(getInstance(), 5, 20);
}
}
| mit |
trentm/node-bunyan | test/safe-json-stringify.test.js | 2150 | /*
* Copyright 2020 Trent Mick
*
* If available, use `safe-json-stringfy` as a fallback stringifier.
* This covers the case where an enumerable property throws an error
* in its getter.
*
* See <https://github.com/trentm/node-bunyan/pull/182>
*/
var exec = require('child_process').exec;
var test = require('tap').test;
test('__defineGetter__ boom', function (t) {
var cmd = process.execPath + ' ' + __dirname + '/safe-json-stringify-1.js';
exec(cmd, function (err, stdout, stderr) {
t.ifError(err, err);
var rec = JSON.parse(stdout.trim());
t.equal(rec.obj.boom, '[Throws: __defineGetter__ ouch!]');
t.end();
});
});
test('__defineGetter__ boom, without safe-json-stringify', function (t) {
var cmd = process.execPath + ' ' + __dirname + '/safe-json-stringify-2.js';
exec(cmd, function (err, stdout, stderr) {
t.ifError(err, err);
t.ok(stdout.indexOf('Exception in JSON.stringify') !== -1);
t.ok(stderr.indexOf(
'You can install the "safe-json-stringify" module') !== -1);
t.end();
});
});
test('defineProperty boom', function (t) {
var cmd = process.execPath + ' ' + __dirname + '/safe-json-stringify-3.js';
exec(cmd, function (err, stdout, stderr) {
t.ifError(err, err);
var recs = stdout.trim().split(/\n/g);
t.equal(recs.length, 2);
var rec = JSON.parse(recs[0]);
t.equal(rec.obj.boom, '[Throws: defineProperty ouch!]');
t.end();
});
});
test('defineProperty boom, without safe-json-stringify', function (t) {
var cmd = process.execPath + ' ' + __dirname + '/safe-json-stringify-4.js';
exec(cmd, function (err, stdout, stderr) {
t.ifError(err, err);
t.ok(stdout.indexOf('Exception in JSON.stringify') !== -1);
t.equal(stdout.match(/Exception in JSON.stringify/g).length, 2);
t.ok(stderr.indexOf(
'You can install the "safe-json-stringify" module') !== -1);
t.equal(stderr.match(
/* JSSTYLED */
/You can install the "safe-json-stringify" module/g).length, 1);
t.end();
});
});
| mit |
charlielor/blt2 | web/js/blocks/package.block.js | 17741 | $(document).ready(function() {
// Get the modal for Package
var packageModal = $("#packageModal");
// Get the id for the each of the select2 dropdown boxes
var select2Shipper = $("#select2-Shipper");
var select2Vendor = $("#select2-Vendor");
var select2Receiver = $("#select2-Receiver");
// Get the input text box for number of packages
var numberOfPackages = $('#numberOfPackages');
// Get the input file
var uploadFiles = $("#uploadFiles");
// Set up the deleted packing slips array
var deletedPackingSlips = [];
// Get the div for existing packing slips
var listOfExistingPackingSlips = $("#listOfExistingPackingSlips");
// Set up noty
var n = null;
// Set up the form data
var formData = null;
// Set the dropdownParent for all select2 on this page to the package modal
$.fn.select2.defaults.set("dropdownParent", $("#packageModal"));
// When the select2 items are selected
select2Shipper.on("select2:select", function() {
select2Vendor.select2("open");
});
select2Vendor.on("select2:select", function() {
select2Receiver.select2("open");
});
packageModal.on("show.bs.modal", function() {
// When the dialogForm opens, check to see if it is an existing packageObject.
// If so then show the shipper select2 div, create a new packageObject and fill the information
if (window.newPackage === false) {
// Display the shipper select2
$(".existingPackage").show();
// Hide the currently selected shipper
$(".newPackage").hide();
// Set the tracking number
$("#packageTrackingNumber").text(window.existingPackageObject.trackingNumber);
// Fill in the select2 inputs
var shipperOption = new Option(window.existingPackageObject.shipper.name, window.existingPackageObject.shipper.id);
select2Shipper.html(shipperOption).trigger("change");
var vendorOption = new Option(window.existingPackageObject.vendor.name, window.existingPackageObject.vendor.id);
select2Vendor.html(vendorOption).trigger("change");
var receiverOption = new Option(window.existingPackageObject.receiver.name + ' | ' + window.existingPackageObject.receiver.deliveryRoom, window.existingPackageObject.receiver.id);
select2Receiver.html(receiverOption).trigger("change");
// Set the number of packageObjects
numberOfPackages.val(window.existingPackageObject.numberOfPackages);
// If the packageObject has packing slips, set up preview links
if (window.existingPackageObject.packingSlips.length > 0) {
window.existingPackageObject.packingSlips.forEach(function (element, index, array) {
listOfExistingPackingSlips.append(
'<div id="' + element['id']+ '" class="form-control-static input-group col-md-3">' +
'<a class="btn btn-default btn-xs" data-id="'+ element['id'] + '" role="button" href="preview/' + element['downloadLink'] + '" target="_blank" tabindex="-1">Link</a>' +
'<div class="input-group-btn">' +
'<button type="button" data-id="' + element['id'] + '" class="btn btn-danger btn-xs deleteExistingPackingSlip" tabindex="-1">X</button>' +
'</div>' +
'</div>'
);
});
} else {
// Hide the shipper select2 input
$("#existingPackingSlips").hide();
}
} else { // Package being edited is a new package
// Hide the shipper select2 input
$(".existingPackage").hide();
// Show the currently selected shipper
$(".newPackage").show();
// Get the tracking number
var trackingNumber = $("#trackingNumberInput").val();
var shipperSpan = $("#shipperSpan");
$("#packageShipper").text(shipperSpan.text());
// Set the tracking number in form
$("#packageTrackingNumber").text(trackingNumber);
}
});
packageModal.on("shown.bs.modal", function() {
if (!window.newPackage) {
select2Shipper.select2("open");
} else {
select2Vendor.select2("open");
}
});
packageModal.on("hidden.bs.modal", function() {
clearForm();
var location = window.location.href.toString().split("/");
if (location[location.length - 1] == "receiving" || location[location.length - 1] == "receiving#") {
$("#trackingNumberInput").val("");
$("#trackingNumberInput").focus();
}
});
$("#noPackingSlipsModal").on("shown.bs.modal", function() {
// If new package modal is shown, increase the z-index so that this modal is on top of the new package modal
if ($("#packageModal").hasClass("in")) {
$("#noPackingSlipsModal").css("z-index", parseInt($("#packageModal").css("z-index")) + 30);
}
});
$("#submitPackage").on("click", function() {
// Get the elements
var shipperSpan = $("#shipperSpan");
formData = new FormData(document.getElementById('uploadFiles'));
if (!window.newPackage) {
if (select2Shipper.val() === null) {
addError("shipper");
select2Shipper.select2('open');
return;
} else {
formData.append("shipperId", select2Shipper.val());
deletedPackingSlips.forEach(function(val, index) {
formData.append("deletePackingSlipIds[]", val);
});
}
} else {
formData.append("trackingNumber", $("#packageTrackingNumber").text());
formData.append("shipperId", shipperSpan.attr('value'));
}
if (select2Vendor.val() === null) {
addError("vendor");
select2Vendor.select2('open');
return;
} else {
formData.append("vendorId", select2Vendor.val());
}
if (select2Receiver.val() === null) {
addError("receiver");
select2Receiver.select2('open');
return;
} else {
formData.append("receiverId", select2Receiver.val());
}
if (parseInt($("#numberOfPackages").val()) < 0) {
$("#addAPackage").focus();
return;
} else {
formData.append("numberOfPackages", parseInt($("#numberOfPackages").val()));
}
// Get all pictures
var picturesTaken = document.getElementsByClassName("thumbnail");
if (picturesTaken.length > 0) {
for (var i = 0; i < picturesTaken.length; i++) {
formData.append("packingSlipPictures[]", picturesTaken[i].src);
}
}
var emptyPackingSlips = false;
var packingSlips = $("#attachedPackingSlips");
var numberOfAttachedPackingSlips = packingSlips[0]['files'].length;
if (numberOfAttachedPackingSlips < 1 && picturesTaken.length < 1) {
emptyPackingSlips = true;
}
if (emptyPackingSlips) {
$("#noPackingSlipsModal").modal({
backdrop: "static"
});
} else {
sendFormData();
}
});
$("#confirmedNoPackingSlipsIsOkay").on("click", function() {
sendFormData();
});
// When the user clicks on the "-" next to the number of packageObjects text input box, decrease the number in the text box by one
$("#minusAPackage").click(function() {
var numberOfPackages = document.getElementById("numberOfPackages");
var numValue = parseInt(numberOfPackages.value, 10);
if (numValue > 1) {
numberOfPackages.value = numValue - 1;
}
});
// When the user clicks on the "+" next to the number of packageObjects text input box, increase the number in the text box by one
$("#addAPackage").click(function() {
var numberOfPackages = document.getElementById("numberOfPackages");
var numValue = parseInt(numberOfPackages.value, 10);
numberOfPackages.value = numValue + 1;
});
/*
* Remove the selected input type file. If it's the only one, then just remove the input element and add a new one.
*/
$(document).on("click", "#clearAttachedPackingSlips", function() {
$("#attachedPackingSlips").val("");
});
/*
* Delete existing packing slip
*/
$(document).on("click", ".deleteExistingPackingSlip", function() {
var idOfPackingSlip = $(this).data('id');
$("#" + idOfPackingSlip).remove();
deletedPackingSlips.push(idOfPackingSlip);
// If the list is empty, hide the label/div
if ($(".deleteExistingPackingSlip").length == 0) {
// Hide the shipper select2 input
$("#existingPackingSlips").hide();
}
});
/**
* Clear the form
*/
function clearForm() {
// Remove any highlighted errors
removeFormErrors();
// Reset select2 hidden inputs
select2Shipper.val(null).trigger("change");
select2Vendor.val(null).trigger("change");
select2Receiver.val(null).trigger("change");
formData = null;
// Set the number of packageObjects to 1
numberOfPackages.val(1);
// Remove all existing packing slips from the previous packageObject, if any
$("#listOfExistingPackingSlips").empty();
// Clear imput type file
$("#attachedPackingSlips").val("");
// Remove all images
$('.thumbnail').remove();
$("#image").src = '';
$("#thumbnailsDiv").empty();
// Change newPackage flag to true
window.newPackage = true;
// Clear any deleted packing slips from updates
deletedPackingSlips = [];
}
// If the up/down arrow keys are pressed, add or subtract the number of packageObjects
$(document).keyup(function(e) {
if (!($(".select2-input").is(":visible"))) {
if (e.keyCode == 38) {
$("#addAPackage").click();
} else if (e.keyCode == 40) {
$("#minusAPackage").click();
}
}
});
function sendFormData() {
if (window.newPackage) {
// Upload form VIA AJAX POST
$.ajax({
url: 'packages/new',
type: 'POST',
data: formData,
contentType: false,
processData: false
})
.done(function (results) {
// If the result is an error, display the error and close the form as the form has already been submitted
if (results['result'] == 'error') {
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "error",
text: results['message'],
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
} else {
if ((results['result'] == 'success') && (results['object'] !== null)) {
// Add a row to the current table with the last uploaded packageObject information
$('#datatable-Receiving').DataTable().row.add(results['object']).draw();
// Display a noty notification towards the bottom telling the user that the packageObject information was submitted successfully
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "success",
text: "Package information sent successfully!",
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
}
}
})
.fail(function () {
// Display a noty telling the user that there was an issue submitting the packageObject information
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "error",
text: "Connection error; please try again",
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
});
} else { // Update package VIA POST
$.ajax({
url: 'packages/' + window.existingPackageObject.trackingNumber + '/update',
type: 'POST',
data: formData,
contentType: false,
processData: false
})
.done(function (results) {
// If the result is an error, display the error and close the form as the form has already been submitted
if (results['result'] == 'error') {
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "error",
text: results['message'],
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
} else {
if ((results['result'] == 'success') && (results['object'] !== null)) {
// Display a noty notification towards the bottom telling the user that the packageObject information was submitted successfully
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "success",
text: results['message'],
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
var location = window.location.href.toString().split("/");
if (location[location.length - 1] == "receiving" || location[location.length - 1] == "receiving#") {
// Depending on the returned object, either update the dataTable or ignore
var trackingNumberUpdated = results["object"]["trackingNumber"];
// Get the row index the row is on if any
// NOTICE: The DataTable constructor used here is "Hungarian" casing to use
// legacy plugins created for 1.9 and lower
var row = $('#datatable-Receiving').dataTable().fnFindCellRowIndexes(trackingNumberUpdated, 0);
if (row.length != 0) {
$('#datatable-Receiving').DataTable().row(row).remove().row.add(results["object"]).draw();
}
}
}
}
})
.fail(function () {
// Display a noty telling the user that there was an issue submitting the packageObject information
n = noty({
layout: "top",
theme: "bootstrapTheme",
type: "error",
text: "Connection error; please try again",
maxVisible: 2,
timeout: 2000,
killer: true,
buttons: false
});
});
}
// Close the form
packageModal.modal("hide");
}
/**
* Remove all form errors
*/
function removeFormErrors() {
$('#packageVendorDiv').removeClass('has-error');
$('#packageReceiverDiv').removeClass('has-error');
$('#packageShipperDiv').removeClass('has-error');
}
/**
* When the user clicks on a thumbnail, ask the user to see if he/she wants to delete this image. If so, delete the
* thumbnail and the hidden image.
*/
$(document).on("click", ".thumbnail", function() {
var confirmDelete = confirm("Are you sure you want to delete this image?");
if (confirmDelete) {
this.remove();
var allThumbnails = document.getElementsByClassName("thumbnail").length;
if (allThumbnails === 0) {
$("#thumbnails").css("display", "none");
}
}
});
function addError(error) {
if (error == "vendor") {
$('#packageVendorDiv').addClass('has-error');
} else if (error == "receiver") {
$('#packageReceiverDiv').addClass('error');
} else if (error == "shipper") {
$('#packageShipperDiv').addClass('error');
}
}
}); | mit |
montanaflynn/phpjs | _unported/xdiff/xdiff_string_bpatch.js | 37 | function xdiff_string_bpatch () {
}
| mit |
roderickwang/apollo-menu-static | src/js/lib/DateConflict.js | 116 | /**
* Created by pengfei on 2015/8/2.
*/
export default class DateConflict{
constructor(schemeData){
}
}
| mit |
k2works/baukis-kai | app/presenters/confirming_user_form_presenter.rb | 401 | class ConfirmingUserFormPresenter < ConfirmingFormPresenter
def full_name_block(name1, name2, label_text, options = {})
markup(:div, class: 'AppForm__input-block') do |m|
m << decorated_label(name1, label_text, options)
m.div(object.send(name1) + ' ' + object.send(name2), class: 'AppForm--field-value')
m << hidden_field(name1)
m << hidden_field(name2)
end
end
end | mit |
coveord/Blitz2016-Server | sample-clients/java-client/src/main/java/com/coveo/blitz/client/bot/SimpleBot.java | 860 | package com.coveo.blitz.client.bot;
import com.coveo.blitz.client.dto.GameState;
/**
* Most basic interface for a bot
* <p/>
* The SimpleBot gets a GameState and is expected to return a BotMove. The response to the server is a Move,
* but since a SimpleBot does not know its API key, it returns a BotMove to indicate the direction and allows the framework
* to take care of building a Move response.
* <p/>
* The bot must handle its own map parsing, threading, timing, etc.
*/
public interface SimpleBot {
/**
* Method that plays each move
*
* @param gameState the current game state
* @return the decided move
*/
public BotMove move(GameState gameState);
/**
* Called before the game is started
*/
public void setup();
/**
* Called after the game
*/
public void shutdown();
}
| mit |
brewhk/follower | server/index.js | 121 | import Followers from '../lib/collections.js';
import './methods.js';
import './publications.js';
export { Followers };
| mit |
fujaru/lasku | www/install/actions/test.php | 7136 | <?php defined('SYSPATH') or die('No direct script access.');
/* BEGIN TESTING */
$tests = array();
$releases = include INSTPATH.'releases'.EXT;
$ver_exists = false;
// Current Lasku Version
$tests['version'] = array(
'label' => "Existing Lasku Installation",
);
if(!file_exists(APPPATH.'config/lasku.version'.EXT)) {
$tests['version']['value'] = 'Not Found';
}
elseif(version_compare(include APPPATH.'config/lasku.version'.EXT, end($releases), '<=')) {
$ver_exists = true;
$ver_now = include APPPATH.'config/lasku.version'.EXT;
$ver_new = end($releases);
if($ver_now == $ver_new) {
$tests['version']['value'] = "{$ver_now} to be reinstalled with the same version";
}
else {
$tests['version']['value'] = "{$ver_now} to be upgraded to {$ver_new}";
}
}
else {
$ver_now = include APPPATH.'config/lasku.version'.EXT;
$ver_new = end($releases);
$tests['version']['error'] = true;
$tests['version']['value'] = "Currently installed version {$ver_now} is newer than the latest version provided by this installer {$ver_new}";
}
// PHP version
$tests['php'] = array(
'label' => "PHP Version",
);
if(version_compare(PHP_VERSION, '5.3.3', '>=')) {
$tests['php']['value'] = PHP_VERSION;
}
else {
$tests['php']['error'] = true;
$tests['php']['value'] = "Lasku requires PHP version 5.3.3 or newer, this version is ".PHP_VERSION;
}
// Installer file
$tests['installer'] = array(
'label' => "Installer Script",
);
if(is_dir(DOCROOT) AND is_writable(DOCROOT)) {
$tests['installer']['value'] = "The installer script can be automatically disabled after installation.";
}
else {
$tests['installer']['warning'] = true;
$tests['installer']['value'] = "After installation finishes, please manually disable the installer script.";
}
// Config dir
$tests['config'] = array(
'label' => "Config Directory",
);
if(is_dir(APPPATH) AND is_dir(APPPATH.'config') AND is_writable(APPPATH.'config')) {
$tests['config']['value'] = APPPATH.'config';
}
else {
$tests['config']['error'] = true;
$tests['config']['value'] = "Directory <code>".APPPATH.'config'."</code> is not writable.";
}
// Cache dir
$tests['cache'] = array(
'label' => "Cache Directory",
);
if(is_dir(APPPATH) AND is_dir(APPPATH.'cache') AND is_writable(APPPATH.'cache')) {
$tests['cache']['value'] = APPPATH.'cache';
}
else {
$tests['cache']['error'] = true;
$tests['cache']['value'] = "Directory <code>".APPPATH.'cache'."</code> is not writable.";
}
// Logs dir
$tests['logs'] = array(
'label' => "Logs Directory",
);
if(is_dir(APPPATH) AND is_dir(APPPATH.'logs') AND is_writable(APPPATH.'logs')) {
$tests['logs']['value'] = APPPATH.'logs';
}
else {
$tests['logs']['error'] = true;
$tests['logs']['value'] = "Directory <code>".APPPATH.'logs'."</code> is not writable.";
}
// PCRE UTF-8
$tests['pcre'] = array(
'label' => "PCRE UTF-8",
);
if(! @preg_match('/^.$/u', 'ñ')) {
$tests['pcre']['error'] = true;
$tests['pcre']['value'] = '<a href="http://php.net/pcre">PCRE</a> has not been compiled with UTF-8 support.';
}
elseif (! @preg_match('/^\pL$/u', 'ñ')) {
$tests['pcre']['error'] = true;
$tests['pcre']['value'] = '<a href="http://php.net/pcre">PCRE</a> has not been compiled with Unicode support.';
}
else {
$tests['pcre']['value'] = 'Enabled';
}
// MySQLi
$tests['mysqli'] = array(
'label' => "MySQLi Extension",
);
if(function_exists('mysqli_connect')) {
$tests['mysqli']['value'] = 'Loaded';
}
else {
$tests['mysqli']['error'] = true;
$tests['mysqli']['value'] = 'The <a href="http://php.net/mysqli">MySQLi</a> extension is either not loaded or not compiled in.';
}
// SPL
$tests['spl'] = array(
'label' => "SPL",
);
if(function_exists('spl_autoload_register')) {
$tests['spl']['value'] = 'Loaded';
}
else {
$tests['spl']['error'] = true;
$tests['spl']['value'] = 'PHP <a href="http://www.php.net/spl">SPL</a> is either not loaded or not compiled in.';
}
// Reflection
$tests['reflection'] = array(
'label' => "Reflection Class",
);
if(class_exists('ReflectionClass')) {
$tests['reflection']['value'] = 'Loaded';
}
else {
$tests['reflection']['error'] = true;
$tests['reflection']['value'] = 'PHP <a href="http://www.php.net/reflection">reflection</a> is either not loaded or not compiled in.';
}
// Filters
$tests['filter'] = array(
'label' => "Filters",
);
if(function_exists('filter_list')) {
$tests['filter']['value'] = 'Loaded';
}
else {
$tests['filter']['error'] = true;
$tests['filter']['value'] = 'The <a href="http://www.php.net/filter">filter</a> extension is either not loaded or not compiled in.';
}
// Iconv
$tests['iconv'] = array(
'label' => "Iconv Extension",
);
if(extension_loaded('iconv')) {
$tests['iconv']['value'] = 'Loaded';
}
else {
$tests['iconv']['error'] = true;
$tests['iconv']['value'] = 'The <a href="http://php.net/iconv">iconv</a> extension is not loaded.';
}
// Mbstring not overloaded
if (extension_loaded('mbstring')) {
$tests['mbstring'] = array(
'label' => "Mbstring Not Overloaded",
);
if(ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING) {
$tests['mbstring']['error'] = true;
$tests['mbstring']['value'] = 'The <a href="http://php.net/mbstring">mbstring</a> extension is overloading PHP\'s native string functions.';
}
else {
$tests['mbstring']['value'] = 'Pass';
}
}
// Ctype
$tests['ctype'] = array(
'label' => "Character Type (CTYPE) Extension",
);
if(! function_exists('ctype_digit')) {
$tests['ctype']['error'] = true;
$tests['ctype']['value'] = 'The <a href="http://php.net/ctype">ctype</a> extension is not enabled.';
}
else {
$tests['ctype']['value'] = 'Enabled';
}
// URI Determination
$tests['uri'] = array(
'label' => "URI Determination",
);
if(isset($_SERVER['REQUEST_URI']) OR isset($_SERVER['PHP_SELF']) OR isset($_SERVER['PATH_INFO'])) {
$tests['uri']['value'] = 'Pass';
}
else {
$tests['uri']['error'] = true;
$tests['uri']['value'] = "Neither <code>\$_SERVER['REQUEST_URI']</code>, <code>\$_SERVER['PHP_SELF']</code>, or <code>\$_SERVER['PATH_INFO']</code> is available.";
}
/* CONFIGURATIONS */
$init_defaults = array(
'base_url' => BASEURL,
'index_file' => 'index.php',
);
if($ver_exists AND file_exists(APPPATH.'config/bootstrap.init'.EXT)) {
$init_own = include APPPATH.'config/bootstrap.init'.EXT;
$init_defaults = array_merge($init_defaults, $init_own);
}
$init = array_merge($init_defaults, @isset($_POST['init']) ? $_POST['init'] : array());
$database_defaults = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'lasku',
);
if($ver_exists AND file_exists(APPPATH.'config/database'.EXT)) {
$database_own = include APPPATH.'config/database'.EXT;
$database_defaults = array_merge($database_defaults, $database_own['default']['connection']);
}
$database = array_merge($database_defaults, @isset($_POST['database']) ? $_POST['database'] : array());
$timezone = include INSTPATH.'defaults/bootstrap.timezone'.EXT;
if($ver_exists AND file_exists(APPPATH.'config/bootstrap.timezone'.EXT)) {
$timezone = include APPPATH.'config/bootstrap.timezone'.EXT;
}
// Get timezone lise
$timezones = include INSTPATH.'defaults/timezones'.EXT;
// Render
include INSTPATH.'views/test'.EXT;
| mit |
contentful/contentful-management.js | lib/enhance-with-methods.ts | 1091 | /**
* This method enhances a base object which would normally contain data, with
* methods from another object that might work on manipulating that data.
* All the added methods are set as non enumerable, non configurable, and non
* writable properties. This ensures that if we try to clone or stringify the
* base object, we don't have to worry about these additional methods.
* @private
* @param {object} baseObject - Base object with data
* @param {object} methodsObject - Object with methods as properties. The key
* values used here will be the same that will be defined on the baseObject.
*/
export default function enhanceWithMethods<
B extends Record<string, unknown>,
M extends Record<string, Function>
>(baseObject: B, methodsObject: M): M & B {
// @ts-expect-error
return Object.keys(methodsObject).reduce((enhancedObject, methodName) => {
Object.defineProperty(enhancedObject, methodName, {
enumerable: false,
configurable: true,
writable: false,
value: methodsObject[methodName],
})
return enhancedObject
}, baseObject)
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.