repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
think-01/oauth | examples/laravel5.php | 804 | <?php
// Add the ServiceProvider
// Create the oauth-providers config file
// Create a route:
Route::get('login/{provider}', ['uses' => 'SocialController@login']);
// Create a controller:
use CodeZero\OAuth\Contracts\Authenticator;
use Illuminate\Routing\Controller;
class SocialController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function login($provider, Authenticator $auth)
{
$details = $auth->request($provider);
if ($details) {
var_dump($details->getEmail());
var_dump($details->getFirstName());
var_dump($details->getLastName());
} else {
echo 'User canceled!';
}
die();
return redirect()->intended('/');
}
}
| mit |
ezekielthao/mozu-dotnet | Mozu.Api/Contracts/ProductRuntime/ProductSearchResult.cs | 1578 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Codezu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace Mozu.Api.Contracts.ProductRuntime
{
///
/// The result of a product search.
///
public class ProductSearchResult
{
///
///The facets applied to index products in the product search result.
///
public List<Facet> Facets { get; set; }
///
///An array list of objects in the returned collection.
///
public List<Product> Items { get; set; }
///
///The number of pages returned based on the startIndex and pageSize values specified. This value is system-supplied and read-only.
///
public int PageCount { get; set; }
///
///The number of results to display on each page when creating paged results from a query. The maximum value is 200.
///
public int PageSize { get; set; }
///
///Mozu.ProductRuntime.Contracts.ProductSearchResult solrDebugInfo ApiTypeMember DOCUMENT_HERE
///
public SolrDebugInfo SolrDebugInfo { get; set; }
public int StartIndex { get; set; }
///
///The number of results listed in the query collection, represented by a signed 64-bit (8-byte) integer. This value is system-supplied and read-only.
///
public int TotalCount { get; set; }
}
} | mit |
souman/baseapp | app/controllers/application_controller.rb | 615 | class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :require_login
def render404
render :file => File.join(Rails.root, 'public', '404.html'), :status => 404, :layout => false
return true
end
private
def require_login
unless (current_user || logging_in_or_signing_up)
redirect_to new_user_session_path
end
end
def logging_in_or_signing_up
request.env['PATH_INFO'] == new_user_session_path || request.env['PATH_INFO'] == new_user_registration_path || (request.env['PATH_INFO'] == '/users' && params[:"commit"] == "Sign up")
end
end
| mit |
kevinzhwl/ObjectARXMod | 2000/IESDK/INCLUDE/IEAPIENC.H | 2193 | //
// Copyright (C) 1992-1997 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// Definition of image data compression and decompression filters for the
// Image Engine.
/*
* Begin multiple inclusion protection...
*/
#ifndef _ieapienc_h
#define _ieapienc_h
#pragma pack (push, 8)
/*
* Required header files.
*/
#ifndef _csdefs_h
#include <csdefs.h> // required for typedefs
#endif /* _csdefs_h */
#include "cs.h" // for CsSpace
enum IeCodecType {
IE_ENCODER,
IE_DECODER
};
class IeCodecInterface {
public:
virtual ~IeCodecInterface() {}
virtual void preProcessChunk(Int pixelWidth, Int bitsInPixel) = 0;
virtual AiBoolean processRow(void *pDecData) = 0;
virtual void postProcessChunk() = 0;
virtual void setEncBuffer(void IE_HUGE *pEncData, UInt encBufSize) = 0;
virtual Int getNumBytesRemaining() const = 0;
virtual char const *getCodecName() const = 0;
virtual IeCodecType const getCodecType() const = 0;
virtual Int getMaxEncRowSize(Int bytesWide) const = 0;
virtual AiBoolean isBitsPerPixelCompatible(unsigned long ulBitsPerPixel) const = 0;
virtual IeCodecInterface *duplicate() = 0;
};
#pragma pack (pop)
#endif /* _ieapienc_h */
| mit |
reidsteven75/test2 | app/routes/activitys.js | 129 | // routes/activitys.js
export default Ember.Route.extend({
model: function() {
return this.store.find('activity');
}
});
| mit |
EvgeniiVoskoboinik/arendahashtag-client | src/app/shared/gallery/ngx-gallery-animation.model.ts | 147 | export class NgxGalleryAnimation {
static Fade = 'fade';
static Slide = 'slide';
static Rotate = 'rotate';
static Zoom = 'zoom';
}
| mit |
unixcharles/refinerycms-blog | app/models/blog_mailer.rb | 887 | class BlogMailer < ActionMailer::Base
def notification(comment, request)
subject "New comment on #{comment.blog.title}"
recipients BlogSetting.notification_email
from from_address(request)
sent_on Time.now
body :comment => comment
end
def confirmation(comment, request)
subject "#{site_name} - comment confirmation"
recipients comment.email
from from_address(request)
sent_on Time.now
content_type "text/html"
body :comment => comment,
:site_domain => site_domain(request)
end
protected
def from_address(request)
"\"#{site_name}\" <no-reply@#{site_domain(request)}>"
end
def site_domain(request)
@domain ||= request.domain(RefinerySetting.find_or_set(:tld_length, 1))
end
def site_name
RefinerySetting[:site_name]
end
end
| mit |
gterzian/exam | tests/test_decorators.py | 2217 | from tests import TestCase
from exam.decorators import fixture
class Outer(object):
@classmethod
def meth(cls):
return cls, 'from method'
@classmethod
def reflective_meth(cls, arg):
return cls, arg
class Dummy(object):
outside = 'value from outside'
@fixture
def number(self):
return 42
@fixture
def obj(self):
return object()
inline = fixture(int, 5)
inline_func = fixture(lambda self: self.outside)
inline_func_with_args = fixture(lambda *a, **k: (a, k), 1, 2, a=3)
inline_from_method = fixture(Outer.meth)
inline_from_method_with_arg_1 = fixture(Outer.reflective_meth, 1)
inline_from_method_with_arg_2 = fixture(Outer.reflective_meth, 2)
class ExtendedDummy(Dummy):
@fixture
def number(self):
return 42 + 42
class TestFixture(TestCase):
def test_converts_method_to_property(self):
self.assertEqual(Dummy().number, 42)
def test_caches_property_on_same_instance(self):
instance = Dummy()
self.assertEqual(instance.obj, instance.obj)
def test_gives_different_object_on_separate_instances(self):
self.assertNotEqual(Dummy().obj, Dummy().obj)
def test_can_be_used_inline_with_a_function(self):
self.assertEqual(Dummy().inline_func, 'value from outside')
def test_can_be_used_with_a_callable_that_takes_args(self):
inst = Dummy()
self.assertEqual(inst.inline_func_with_args, ((inst, 1, 2), dict(a=3)))
def test_can_be_used_with_class_method(self):
self.assertEqual(Dummy().inline_from_method, (Outer, 'from method'))
def test_if_passed_type_builds_new_object(self):
self.assertEqual(Dummy().inline, 5)
def test_override_in_subclass_overrides_value(self):
self.assertEqual(ExtendedDummy().number, 42 + 42)
def test_captures_identical_funcs_with_args_separatly(self):
instance = Dummy()
first = instance.inline_from_method_with_arg_1
second = instance.inline_from_method_with_arg_2
self.assertNotEqual(first, second)
def test_clas_access_returns_fixture_itself(self):
self.assertEqual(getattr(Dummy, 'number'), Dummy.number)
| mit |
NadzwyczajnaGrupaRobocza/papuc_exercises | lm/game01/World.hpp | 876 | #pragma once
#include <SFML/Graphics.hpp>
#include "Board.hpp"
#include <vector>
namespace lmg01
{
class World
{
public:
World(sf::View);
void advance(const sf::Time& tick, const sf::Vector2f& playerMove);
void draw(sf::RenderTarget&);
private:
std::vector<sf::CircleShape> createObstacles();
void drawObstacles(sf::RenderTarget&);
void drawPlayer(sf::RenderTarget&);
void movePlayer(const sf::Vector2f&);
sf::Vector2f validMovement(const sf::Vector2f&, const sf::CircleShape& obstacle) const;
sf::View current_view;
Board b;
sf::CircleShape player;
sf::Vector2f player_position;
std::vector<sf::CircleShape> obstacle_container;
};
float dist_sqr(const sf::Vector2f& a, const sf::Vector2f b);
sf::Vector2f center(const sf::Shape& s);
float compute_scaling_factor(const sf::Vector2f& b, const sf::Vector2f& c, float d);
}
| mit |
ceolter/ag-grid | charts-packages/ag-charts-community/dist/cjs/util/equal.test.js | 1246 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var equal_1 = require("./equal");
describe('equal', function () {
test('strings', function () {
expect(equal_1.equal(['a', 'b'], ['a', 'b'])).toBe(true);
expect(equal_1.equal(['a', 'b'], ['a', 'b', 'c'])).toBe(false);
expect(equal_1.equal(['b', 'a'], ['a', 'b'])).toBe(false);
expect(equal_1.equal([], ['a', 'b'])).toBe(false);
expect(equal_1.equal(null, ['a', 'b'])).toBe(false);
expect(equal_1.equal(undefined, ['a', 'b'])).toBe(false);
expect(equal_1.equal({}, ['a', 'b'])).toBe(false);
expect(equal_1.equal(42, ['a', 'b'])).toBe(false);
});
test('objects', function () {
expect(equal_1.equal([{ a: 42, b: ['a', 'b'] }], [{ a: 42, b: ['a', 'b'] }])).toBe(true);
expect(equal_1.equal([{ a: 17, b: ['a', 'b'] }], [{ a: 42, b: ['a', 'b'] }])).toBe(false);
expect(equal_1.equal([{ a: 42, b: ['b', 'a'] }], [{ a: 42, b: ['a', 'b'] }])).toBe(false);
});
test('mixed', function () {
expect(equal_1.equal([{ a: 42, b: [{ c: 13, d: 17 }, 'b'] }, {}], [{ a: 42, b: [{ c: 13, d: 17 }, 'b'] }, {}])).toBe(true);
});
});
//# sourceMappingURL=equal.test.js.map | mit |
oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/LockClock.js | 522 | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m14.5 14.2 2.9 1.7-.8 1.3L13 15v-5h1.5v4.2zM22 14c0 4.41-3.59 8-8 8-2.02 0-3.86-.76-5.27-2H4c-1.15 0-2-.85-2-2V9c0-1.12.89-1.96 2-2v-.5C4 4.01 6.01 2 8.5 2c2.34 0 4.24 1.79 4.46 4.08.34-.05.69-.08 1.04-.08 4.41 0 8 3.59 8 8zM6 7h5v-.74C10.88 4.99 9.8 4 8.5 4 7.12 4 6 5.12 6 6.5V7zm14 7c0-3.31-2.69-6-6-6s-6 2.69-6 6 2.69 6 6 6 6-2.69 6-6z"
}), 'LockClock'); | mit |
TakayukiHoshi1984/DeviceConnect-JS | dConnectSDKForJavascriptTest/tests/profiles/setting_abnormal.js | 28012 | QUnit.module('Setting Profile Abnormal Test', {
before: function() {
init();
}
});
/**
* Settingプロファイルの異常系テストを行うクラス。
* @class
*/
let SettingProfileAbnormalTest = {};
/**
* 定義されていないkindのボリュームを取得するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: GET<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=-1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest001 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: -1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest001(get)(kind is -1)', SettingProfileAbnormalTest.volumeAbnormalTest001);
/**
* kindを文字列(this is a test.)でボリュームを取得するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: GET<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind='this is a test.'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest002 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 'this is a test.'
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest002(get)(kind is string)',
SettingProfileAbnormalTest.volumeAbnormalTest002);
/**
* kindを指定しないでボリュームを取得するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: GET<br/>
* Path: /setting/displayvolume?serviceId=xxxx<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest003 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId()
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest003(get)(omitted kind.)',
SettingProfileAbnormalTest.volumeAbnormalTest003);
/**
* kindに特殊文字を指定してボリュームを取得するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: GET<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind='!\"#$%&'()0=~|'{}@`*+;<,.>/_'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest004 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: "!\"#$%&'()0=~|'{}@`*+;<,.>/_"
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest004(get)(kind is special characters.)', SettingProfileAbnormalTest.volumeAbnormalTest004);
/**
* kindに大きな数値を指定してボリュームを取得するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: GET<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=10000000<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest005 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 10000000
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest005(get)(kind is big number.)', SettingProfileAbnormalTest.volumeAbnormalTest005);
/**
* kindに-1を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=-1&level=1.0<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest006 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: -1,
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest006(put)(kind is -1.)', SettingProfileAbnormalTest.volumeAbnormalTest006);
/**
* kindに文字列(this is a test.)を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind='this is a test.'&level=1.0<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest007 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 'this is a test.',
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest007(put)(kind is string.)', SettingProfileAbnormalTest.volumeAbnormalTest007);
/**
* kindに特殊文字を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind='!\"#$%&'()0=~|'{}@`*+;<,.>/_'&level=1.0<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest008 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: "!\"#$%&'()0=~|'{}@`*+;<,.>/_",
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest008(put)(kind is special characters.)', SettingProfileAbnormalTest.volumeAbnormalTest008);
/**
* kindに大きな数値を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=10000000&level=1.0<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest009 = function(assert) {
let done = assert.async();
sdk.get({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 10000000,
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest009(put)(kind is big number.)', SettingProfileAbnormalTest.volumeAbnormalTest009);
/**
* levelに-1を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level=-1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest010 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: -1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest010(put)(level is -1.)', SettingProfileAbnormalTest.volumeAbnormalTest010);
/**
* levelに100を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level=100<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest011 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: 100
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest011(put)(level is 100.)', SettingProfileAbnormalTest.volumeAbnormalTest011);
/**
* levelに文字列を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level='this is test.'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest012 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: 'this is a test.'
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest012(put)(level is string.)', SettingProfileAbnormalTest.volumeAbnormalTest012);
/**
* levelに特殊文字を指定してボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level='this is test.'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest013 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: "!\"#$%&'()0=~|'{}@`*+;<,.>/_"
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest013(put)(level is special characters.)', SettingProfileAbnormalTest.volumeAbnormalTest013);
/**
* levelを指定しないでボリュームを設定するテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest014 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('volumeAbnormalTest014(put)(level is special characters.)', SettingProfileAbnormalTest.volumeAbnormalTest014);
/**
* 定義されていないPOSTメソッドでvolumeにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: POST<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level=1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest015 = function(assert) {
let done = assert.async();
sdk.post({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('volumeAbnormalTest015(Calling a post method that does not support.)', SettingProfileAbnormalTest.volumeAbnormalTest015);
/**
* 定義されていないDELETEメソッドでvolumeにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: DELETE<br/>
* Path: /setting/displayvolume?serviceId=xxxx&accessToken=xxxx&kind=1&level=1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.volumeAbnormalTest016 = function(assert) {
let done = assert.async();
sdk.delete({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_SOUND,
attribute: dConnectSDK.constants.setting.ATTR_VOLUME,
params: {
serviceId: getCurrentServiceId(),
kind: 1,
level: 1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('volumeAbnormalTest016(Calling a delete method that does not support.)', SettingProfileAbnormalTest.volumeAbnormalTest016);
/**
* 定義されていないPOSTメソッドでdateにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: POST<br/>
* Path: /setting/displaydate?serviceId=xxxx&accessToken=xxxx&date=''<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.dateAbnormalTest001 = function(assert) {
let done = assert.async();
sdk.post({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
attribute: dConnectSDK.constants.setting.ATTR_DATE,
params: {
serviceId: getCurrentServiceId(),
date: ''
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('dateAbnormalTest001(Calling a post method that does not support.)', SettingProfileAbnormalTest.dateAbnormalTest001);
/**
* 定義されていないDELETEメソッドでdateにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: DELETE<br/>
* Path: /setting/displaydate?serviceId=xxxx&accessToken=xxxx&date=''<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.dateAbnormalTest002 = function(assert) {
let done = assert.async();
sdk.delete({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
attribute: dConnectSDK.constants.setting.ATTR_DATE,
params: {
serviceId: getCurrentServiceId(),
date: ''
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('dateAbnormalTest002(Calling a delete method that does not support.)', SettingProfileAbnormalTest.dateAbnormalTest002);
/**
* levelに-1を指定して、ライト点灯のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaylight?serviceId=xxxx&accessToken=xxxx&level=-1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.lightAbnormalTest001 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_BRIGHTNESS,
params: {
serviceId: getCurrentServiceId(),
level: -1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('lightAbnormalTest001(level is -1)', SettingProfileAbnormalTest.lightAbnormalTest001);
/**
* levelに文字を指定して、ライト点灯のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaylight?serviceId=xxxx&accessToken=xxxx&level='this is a test'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.lightAbnormalTest002 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_BRIGHTNESS,
params: {
serviceId: getCurrentServiceId(),
level: 'this is a test.'
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('lightAbnormalTest002(level is string)', SettingProfileAbnormalTest.lightAbnormalTest002);
/**
* levelに特殊文字を指定して、ライト点灯のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaylight?serviceId=xxxx&accessToken=xxxx&level="!\"#$%&'()0=~|'{}@`*+;<,.>/_"<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.lightAbnormalTest003 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_BRIGHTNESS,
params: {
serviceId: getCurrentServiceId(),
level: "!\"#$%&'()0=~|'{}@`*+;<,.>/_"
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('lightAbnormalTest003(level is special characters.)', SettingProfileAbnormalTest.lightAbnormalTest003);
/**
* levelに最大値を超える数値を指定して、ライト点灯のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaylight?serviceId=xxxx&accessToken=xxxx&level=100000<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.lightAbnormalTest004 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_BRIGHTNESS,
params: {
serviceId: getCurrentServiceId(),
level: 100000
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('lightAbnormalTest004(level is big number.)', SettingProfileAbnormalTest.lightAbnormalTest004);
/**
* timeに-1を指定して、スリープ時間設定のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaysleep?serviceId=xxxx&accessToken=xxxx&time=-1<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.sleepAbnormalTest001 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_SLEEP,
params: {
serviceId: getCurrentServiceId(),
time: -1
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('sleepAbnormalTest001(time is -1)', SettingProfileAbnormalTest.sleepAbnormalTest001);
/**
* sleepに文字を指定して、スリープ時間設定のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaysleep?serviceId=xxxx&accessToken=xxxx&time='this is a test'<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.sleepAbnormalTest002 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_SLEEP,
params: {
serviceId: getCurrentServiceId(),
time: 'this is a test'
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('sleepAbnormalTest002(time is string)', SettingProfileAbnormalTest.sleepAbnormalTest002);
/**
* sleepに特殊文字を指定して、スリープ時間設定のテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: PUT<br/>
* Path: /setting/displaysleep?serviceId=xxxx&accessToken=xxxx&time="!\"#$%&'()0=~|'{}@`*+;<,.>/_"<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.sleepAbnormalTest003 = function(assert) {
let done = assert.async();
sdk.put({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_SLEEP,
params: {
serviceId: getCurrentServiceId(),
time: "!\"#$%&'()0=~|'{}@`*+;<,.>/_"
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 10);
done();
});
};
QUnit.test('sleepAbnormalTest003(time is special characters.)', SettingProfileAbnormalTest.sleepAbnormalTest003);
/**
* 定義されていないPOSTメソッドで、sleepにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: POST<br/>
* Path: /setting/displaysleep?serviceId=xxxx&accessToken=xxxx&time=1000<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.sleepAbnormalTest004 = function(assert) {
let done = assert.async();
sdk.post({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_SLEEP,
params: {
serviceId: getCurrentServiceId(),
time: 1000
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('sleepAbnormalTest004(Calling a post method that does not support.)', SettingProfileAbnormalTest.sleepAbnormalTest004);
/**
* 定義されていないDELETEメソッドで、sleepにアクセスするテストを行う。
* <h3>【HTTP通信】</h3>
* <p id="test">
* Method: DELETE<br/>
* Path: /setting/displaysleep?serviceId=xxxx&accessToken=xxxx&time=1000<br/>
* </p>
* <h3>【期待する動作】</h3>
* <p id="expected">
* ・resultに1が返ってくること。<br/>
* </p>
*/
SettingProfileAbnormalTest.sleepAbnormalTest005 = function(assert) {
let done = assert.async();
sdk.delete({
profile: dConnectSDK.constants.setting.PROFILE_NAME,
interface: dConnectSDK.constants.setting.INTERFACE_DISPLAY,
attribute: dConnectSDK.constants.setting.ATTR_SLEEP,
params: {
serviceId: getCurrentServiceId(),
time: 1000
}
}).then(json => {
assert.ok(false, 'json: ' + JSON.stringify(json));
done();
}).catch(e => {
checkSuccessErrorCode(assert, e, 3);
done();
});
};
QUnit.test('sleepAbnormalTest005(Calling a delete method that does not support.)', SettingProfileAbnormalTest.sleepAbnormalTest005);
| mit |
enettolima/magento-training | magento2ce/app/code/Magento/Theme/Console/Command/ThemeUninstallCommand.php | 12060 | <?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Theme\Console\Command;
use Magento\Framework\App\Area;
use Magento\Framework\App\Cache;
use Magento\Framework\App\MaintenanceMode;
use Magento\Framework\App\State\CleanupFiles;
use Magento\Framework\Composer\ComposerInformation;
use Magento\Framework\Composer\DependencyChecker;
use Magento\Theme\Model\Theme\Data\Collection;
use Magento\Theme\Model\Theme\ThemePackageInfo;
use Magento\Theme\Model\Theme\ThemeUninstaller;
use Magento\Theme\Model\Theme\ThemeDependencyChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Magento\Framework\Setup\BackupRollbackFactory;
use Magento\Theme\Model\ThemeValidator;
/**
* Command for uninstalling theme and backup-code feature
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
class ThemeUninstallCommand extends Command
{
/**
* Names of input arguments or options
*/
const INPUT_KEY_BACKUP_CODE = 'backup-code';
const INPUT_KEY_THEMES = 'theme';
const INPUT_KEY_CLEAR_STATIC_CONTENT = 'clear-static-content';
/**
* Maintenance Mode
*
* @var MaintenanceMode
*/
private $maintenanceMode;
/**
* Composer general dependency checker
*
* @var DependencyChecker
*/
private $dependencyChecker;
/**
* Root composer.json information
*
* @var ComposerInformation
*/
private $composer;
/**
* Theme collection in filesystem
*
* @var Collection
*/
private $themeCollection;
/**
* System cache model
*
* @var Cache
*/
private $cache;
/**
* Cleaning up application state service
*
* @var CleanupFiles
*/
private $cleanupFiles;
/**
* BackupRollback factory
*
* @var BackupRollbackFactory
*/
private $backupRollbackFactory;
/**
* Theme Validator
*
* @var ThemeValidator
*/
private $themeValidator;
/**
* Package name finder
*
* @var ThemePackageInfo
*/
private $themePackageInfo;
/**
* Theme Uninstaller
*
* @var ThemeUninstaller
*/
private $themeUninstaller;
/**
* Theme Dependency Checker
*
* @var ThemeDependencyChecker
*/
private $themeDependencyChecker;
/**
* Constructor
*
* @param Cache $cache
* @param CleanupFiles $cleanupFiles
* @param ComposerInformation $composer
* @param MaintenanceMode $maintenanceMode
* @param DependencyChecker $dependencyChecker
* @param Collection $themeCollection
* @param BackupRollbackFactory $backupRollbackFactory
* @param ThemeValidator $themeValidator
* @param ThemePackageInfo $themePackageInfo
* @param ThemeUninstaller $themeUninstaller
* @param ThemeDependencyChecker $themeDependencyChecker
*/
public function __construct(
Cache $cache,
CleanupFiles $cleanupFiles,
ComposerInformation $composer,
MaintenanceMode $maintenanceMode,
DependencyChecker $dependencyChecker,
Collection $themeCollection,
BackupRollbackFactory $backupRollbackFactory,
ThemeValidator $themeValidator,
ThemePackageInfo $themePackageInfo,
ThemeUninstaller $themeUninstaller,
ThemeDependencyChecker $themeDependencyChecker
) {
$this->cache = $cache;
$this->cleanupFiles = $cleanupFiles;
$this->composer = $composer;
$this->maintenanceMode = $maintenanceMode;
$this->dependencyChecker = $dependencyChecker;
$this->themeCollection = $themeCollection;
$this->backupRollbackFactory = $backupRollbackFactory;
$this->themeValidator = $themeValidator;
$this->themePackageInfo = $themePackageInfo;
$this->themeUninstaller = $themeUninstaller;
$this->themeDependencyChecker = $themeDependencyChecker;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('theme:uninstall');
$this->setDescription('Uninstalls theme');
$this->addOption(
self::INPUT_KEY_BACKUP_CODE,
null,
InputOption::VALUE_NONE,
'Take code backup (excluding temporary files)'
);
$this->addArgument(
self::INPUT_KEY_THEMES,
InputArgument::IS_ARRAY | InputArgument::REQUIRED,
'Path of the theme. Theme path should be specified as full path which is area/vendor/name.'
. ' For example, frontend/Magento/blank'
);
$this->addOption(
self::INPUT_KEY_CLEAR_STATIC_CONTENT,
'c',
InputOption::VALUE_NONE,
'Clear generated static view files.'
);
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$messages = [];
$themePaths = $input->getArgument(self::INPUT_KEY_THEMES);
$messages = array_merge($messages, $this->validate($themePaths));
if (!empty($messages)) {
$output->writeln($messages);
// we must have an exit code higher than zero to indicate something was wrong
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
}
$messages = array_merge(
$messages,
$this->themeValidator->validateIsThemeInUse($themePaths),
$this->themeDependencyChecker->checkChildTheme($themePaths),
$this->checkDependencies($themePaths)
);
if (!empty($messages)) {
$output->writeln(
'<error>Unable to uninstall. Please resolve the following issues:</error>'
. PHP_EOL . implode(PHP_EOL, $messages)
);
// we must have an exit code higher than zero to indicate something was wrong
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
}
try {
$output->writeln('<info>Enabling maintenance mode</info>');
$this->maintenanceMode->set(true);
if ($input->getOption(self::INPUT_KEY_BACKUP_CODE)) {
$time = time();
$codeBackup = $this->backupRollbackFactory->create($output);
$codeBackup->codeBackup($time);
}
$this->themeUninstaller->uninstallRegistry($output, $themePaths);
$this->themeUninstaller->uninstallCode($output, $themePaths);
$this->cleanup($input, $output);
$output->writeln('<info>Disabling maintenance mode</info>');
$this->maintenanceMode->set(false);
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage() . '</error>');
$output->writeln('<error>Please disable maintenance mode after you resolved above issues</error>');
// we must have an exit code higher than zero to indicate something was wrong
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
}
}
/**
* Validate given full theme paths
*
* @param string[] $themePaths
* @return string[]
*/
private function validate($themePaths)
{
$messages = [];
$incorrectThemes = $this->getIncorrectThemes($themePaths);
if (!empty($incorrectThemes)) {
$text = 'Theme path should be specified as full path which is area/vendor/name.';
$messages[] = '<error>Incorrect theme(s) format: ' . implode(', ', $incorrectThemes)
. '. ' . $text . '</error>';
return $messages;
}
$unknownPackages = $this->getUnknownPackages($themePaths);
$unknownThemes = $this->getUnknownThemes($themePaths);
$unknownPackages = array_diff($unknownPackages, $unknownThemes);
if (!empty($unknownPackages)) {
$text = count($unknownPackages) > 1 ?
' are not installed Composer packages' : ' is not an installed Composer package';
$messages[] = '<error>' . implode(', ', $unknownPackages) . $text . '</error>';
}
if (!empty($unknownThemes)) {
$messages[] = '<error>Unknown theme(s): ' . implode(', ', $unknownThemes) . '</error>';
}
return $messages;
}
/**
* Retrieve list of themes with wrong name format
*
* @param string[] $themePaths
* @return string[]
*/
protected function getIncorrectThemes($themePaths)
{
$result = [];
foreach ($themePaths as $themePath) {
if (!preg_match('/^[^\/]+\/[^\/]+\/[^\/]+$/', $themePath)) {
$result[] = $themePath;
continue;
}
}
return $result;
}
/**
* Retrieve list of unknown packages
*
* @param string[] $themePaths
* @return string[]
*/
protected function getUnknownPackages($themePaths)
{
$installedPackages = $this->composer->getRootRequiredPackages();
$result = [];
foreach ($themePaths as $themePath) {
if (array_search($this->themePackageInfo->getPackageName($themePath), $installedPackages) === false) {
$result[] = $themePath;
}
}
return $result;
}
/**
* Retrieve list of unknown themes
*
* @param string[] $themePaths
* @return string[]
*/
protected function getUnknownThemes($themePaths)
{
$result = [];
foreach ($themePaths as $themePath) {
if (!$this->themeCollection->hasTheme($this->themeCollection->getThemeByFullPath($themePath))) {
$result[] = $themePath;
}
}
return $result;
}
/**
* Check dependencies to given full theme paths
*
* @param string[] $themePaths
* @return string[]
*/
private function checkDependencies($themePaths)
{
$messages = [];
$packageToPath = [];
foreach ($themePaths as $themePath) {
$packageToPath[$this->themePackageInfo->getPackageName($themePath)] = $themePath;
}
$dependencies = $this->dependencyChecker->checkDependencies(array_keys($packageToPath), true);
foreach ($dependencies as $package => $dependingPackages) {
if (!empty($dependingPackages)) {
$messages[] =
'<error>' . $packageToPath[$package] .
" has the following dependent package(s):</error>" .
PHP_EOL . "\t<error>" . implode('</error>' . PHP_EOL . "\t<error>", $dependingPackages)
. "</error>";
}
}
return $messages;
}
/**
* Cleanup after updated modules status
*
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
private function cleanup(InputInterface $input, OutputInterface $output)
{
$this->cache->clean();
$output->writeln('<info>Cache cleared successfully.</info>');
if ($input->getOption(self::INPUT_KEY_CLEAR_STATIC_CONTENT)) {
$this->cleanupFiles->clearMaterializedViewFiles();
$output->writeln('<info>Generated static view files cleared successfully.</info>');
} else {
$output->writeln(
'<error>Alert: Generated static view files were not cleared.'
. ' You can clear them using the --' . self::INPUT_KEY_CLEAR_STATIC_CONTENT . ' option.'
. ' Failure to clear static view files might cause display issues in the Admin and storefront.</error>'
);
}
}
}
| mit |
darshanhs90/Java-InterviewPrep | src/May2021GoogLeetcode/_0428SerializeAndDeserializeNaryTree.java | 3349 | package May2021GoogLeetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _0428SerializeAndDeserializeNaryTree {
public static void main(String[] args) {
Codec codec = new Codec();
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
n1.children = new ArrayList<Node>(Arrays.asList(n3, n2, n4));
n3.children = new ArrayList<Node>(Arrays.asList(n5, n6));
printNodes(n1);
System.out.println();
System.out.println(codec.serialize(n1));
printNodes(codec.deserialize(codec.serialize(n1)));
System.out.println();
n1 = new Node(1);
n2 = new Node(2);
n3 = new Node(3);
n4 = new Node(4);
n5 = new Node(5);
n6 = new Node(6);
Node n7 = new Node(7);
Node n8 = new Node(8);
Node n9 = new Node(9);
Node n10 = new Node(10);
Node n11 = new Node(11);
Node n12 = new Node(12);
Node n13 = new Node(13);
Node n14 = new Node(14);
n1.children = new ArrayList<Node>(Arrays.asList(n2, n3, n4, n5));
n3.children = new ArrayList<Node>(Arrays.asList(n6, n7));
n7.children = new ArrayList<Node>(Arrays.asList(n11));
n11.children = new ArrayList<Node>(Arrays.asList(n14));
n4.children = new ArrayList<Node>(Arrays.asList(n8));
n8.children = new ArrayList<Node>(Arrays.asList(n12));
n5.children = new ArrayList<Node>(Arrays.asList(n9, n10));
n9.children = new ArrayList<Node>(Arrays.asList(n13));
printNodes(n1);
System.out.println();
System.out.println(codec.serialize(n1));
printNodes(codec.deserialize(codec.serialize(n1)));
System.out.println();
}
static void printNodes(Node n1) {
if (n1 != null) {
System.out.print(n1.val + "->");
if (n1.children != null) {
for (int i = 0; i < n1.children.size(); i++) {
printNodes(n1.children.get(i));
}
}
}
}
static class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
static class Codec {
// Encodes a tree to a single string.
public String serialize(Node root) {
if (root == null)
return "";
List<String> out = new ArrayList<String>();
serHelper(root, out);
return String.join(",", out);
}
public void serHelper(Node root, List<String> list) {
if (root == null) {
list.add("#");
return;
}
list.add(root.val + "");
int noOFchildrens = root.children != null ? root.children.size() : 0;
list.add(noOFchildrens + "");
for (int i = 0; i < noOFchildrens; i++) {
serHelper(root.children.get(i), list);
}
}
// Decodes your encoded data to tree.
public Node deserialize(String data) {
if (data.isEmpty())
return null;
return deserHelper(new LinkedList<String>(Arrays.asList(data.split(","))));
}
public Node deserHelper(Queue<String> q) {
if (q.isEmpty())
return null;
if (q.peek().equals("#")) {
q.poll();
return null;
}
Node node = new Node(Integer.parseInt(q.poll()), new ArrayList<Node>());
int noOfChildrens = Integer.parseInt(q.poll());
for (int i = 0; i < noOfChildrens; i++) {
node.children.add(deserHelper(q));
}
return node;
}
}
}
| mit |
juniorgasparotto/MarkdownMerge | src/MarkdownGenerator/Dependences/Markdig/Extensions/SmartyPants/SmartyPantsExtension.cs | 1681 | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Parsers.Inlines;
using Markdig.Renderers;
namespace Markdig.Extensions.SmartyPants
{
/// <summary>
/// Extension to enable SmartyPants.
/// </summary>
public class SmartyPantsExtension : IMarkdownExtension
{
/// <summary>
/// Initializes a new instance of the <see cref="SmartyPantsExtension"/> class.
/// </summary>
/// <param name="options">The options.</param>
public SmartyPantsExtension(SmartyPantOptions options)
{
Options = options ?? new SmartyPantOptions();
}
/// <summary>
/// Gets the options.
/// </summary>
public SmartyPantOptions Options { get; }
public void Setup(MarkdownPipelineBuilder pipeline)
{
if (!pipeline.InlineParsers.Contains<SmartyPantsInlineParser>())
{
// Insert the parser after the code span parser
pipeline.InlineParsers.InsertAfter<CodeInlineParser>(new SmartyPantsInlineParser());
}
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
var htmlRenderer = renderer as HtmlRenderer;
if (htmlRenderer != null)
{
if (!htmlRenderer.ObjectRenderers.Contains<HtmlSmartyPantRenderer>())
{
htmlRenderer.ObjectRenderers.Add(new HtmlSmartyPantRenderer(Options));
}
}
}
}
} | mit |
Zarel/Pokemon-Showdown | test/sim/moves/focuspunch.js | 5589 | 'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Focus Punch', function () {
afterEach(function () {
battle.destroy();
});
it(`should cause the user to lose focus if hit by an attacking move`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf']},
]]);
battle.makeChoices();
assert.fullHP(battle.p2.active[0]);
});
it(`should not cause the user to lose focus if hit by a status move`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['growl']},
]]);
battle.makeChoices();
assert.false.fullHP(battle.p2.active[0]);
});
it(`should not cause the user to lose focus if hit while behind a substitute`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['substitute', 'focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf']},
]]);
battle.makeChoices();
battle.makeChoices('move focuspunch', 'auto');
assert.false.fullHP(battle.p2.active[0]);
});
it(`should cause the user to lose focus if hit by a move called by Nature Power`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['naturepower']},
]]);
battle.makeChoices();
assert.fullHP(battle.p2.active[0]);
});
it(`should not cause the user to lose focus on later uses of Focus Punch if hit`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf', 'growl']},
]]);
battle.makeChoices();
assert.fullHP(battle.p2.active[0]);
battle.makeChoices('auto', 'move growl');
assert.false.fullHP(battle.p2.active[0]);
});
it(`should cause the user to lose focus if hit by an attacking move followed by a status move in one turn`, function () {
battle = common.createBattle({gameType: 'doubles'}, [
[{species: 'Chansey', ability: 'naturalcure', moves: ['focuspunch']}, {species: 'Blissey', ability: 'naturalcure', moves: ['softboiled']}],
[{species: 'Venusaur', ability: 'overgrow', moves: ['magicalleaf']}, {species: 'Ivysaur', ability: 'overgrow', moves: ['toxic']}],
]);
battle.makeChoices('move focuspunch 1, move softboiled', 'move magicalleaf 1, move toxic 1');
assert.equal(battle.p1.active[0].status, 'tox');
assert.equal(battle.p2.active[0].hp, battle.p2.active[0].maxhp);
});
it(`should not deduct PP if the user lost focus`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf', 'growl']},
]]);
const move = battle.p1.active[0].getMoveData(Dex.moves.get('focuspunch'));
battle.makeChoices();
assert.equal(move.pp, move.maxpp);
battle.makeChoices('auto', 'move growl');
assert.equal(move.pp, move.maxpp - 1);
});
it(`should deduct PP if the user lost focus before Gen 5`, function () {
battle = common.gen(4).createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf', 'growl']},
]]);
const move = battle.p1.active[0].getMoveData(Dex.moves.get('focuspunch'));
battle.makeChoices();
assert.equal(move.pp, move.maxpp - 1);
battle.makeChoices('auto', 'move growl');
assert.equal(move.pp, move.maxpp - 2);
});
it(`should display a message indicating the Pokemon is tightening focus`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf']},
]]);
battle.makeChoices();
const tighteningFocusMessage = battle.log.indexOf('|-singleturn|p1a: Chansey|move: Focus Punch');
assert(tighteningFocusMessage > 0);
});
it(`should not tighten the Pokemon's focus when Dynamaxing or already Dynamaxed`, function () {
battle = common.createBattle([[
{species: 'Chansey', moves: ['focuspunch']},
], [
{species: 'Venusaur', moves: ['magicalleaf']},
]]);
battle.makeChoices('move focuspunch dynamax', 'auto');
battle.makeChoices('move focuspunch', 'auto');
const tighteningFocusMessage = battle.log.indexOf('|-singleturn|p1a: Chansey|move: Focus Punch');
assert(tighteningFocusMessage < 0);
});
it.skip(`should tighten focus after switches in Gen 5+`, function () {
battle = common.createBattle([[
{species: 'salamence', moves: ['focuspunch']},
], [
{species: 'mew', moves: ['sleeptalk']},
{species: 'wynaut', moves: ['sleeptalk']},
]]);
battle.makeChoices('move focuspunch', 'switch 2');
const log = battle.getDebugLog();
const focusPunchChargeIndex = log.indexOf('|-singleturn|');
const switchIndex = log.indexOf('|switch|p2a: Wynaut');
assert(focusPunchChargeIndex > switchIndex, `Focus Punch's charge message should occur after switches in Gen 5+`);
});
it(`should tighten focus before switches in Gens 3-4`, function () {
battle = common.gen(4).createBattle([[
{species: 'salamence', moves: ['focuspunch']},
], [
{species: 'mew', moves: ['sleeptalk']},
{species: 'wynaut', moves: ['sleeptalk']},
]]);
battle.makeChoices('move focuspunch', 'switch 2');
const log = battle.getDebugLog();
const focusPunchChargeIndex = log.indexOf('|-singleturn|');
const switchIndex = log.indexOf('|switch|p2a: Wynaut');
assert(focusPunchChargeIndex < switchIndex, `Focus Punch's charge message should occur before switches in Gens 3-4`);
});
});
| mit |
am-kantox/forkforge | lib/forkforge/internal/unicode_data.rb | 2929 | # encoding: utf-8
require 'forkforge/internal/monkeypatches'
require 'forkforge/internal/unicode_org_file'
require 'forkforge/internal/code_point'
require 'forkforge/internal/character_decomposition_mapping'
module Forkforge
module UnicodeData
include UnicodeOrgFileFormat
LOCAL = 'data'
REMOTE = 'Public/UCD/latest/ucd'
FILE = 'UnicodeData.txt'
@cdm = {}
def hash
i_hash(REMOTE, LOCAL, FILE, CodePoint::UNICODE_FIELDS, false)
end
def code_points
@codepoints ||= CodePoints.new hash
end
def info cp
cp = cp.codepoints.first if String === cp && cp.length == 1
hash[__to_code_point(cp)]
end
def infos string
string.codepoints.map { |cp| hash[__to_code_point(cp)] }
end
# TODO return true/false whether the normalization was done?
def to_char cp, action = :code_point
elem = hash[__to_code_point(cp)]
__to_char(elem[action].vacant? ? elem[:code_point] : elem[action])
end
def to_codepoint cp
Forkforge::CodePoint.new info cp
end
# get_code_point '00A0' | get_character_decomposition_mapping 0xA0 | ...
# all_code_point /00[A-C]\d/ | get_character_decomposition_mapping /00A*/ | ...
CodePoint::UNICODE_FIELDS.each { |method|
define_method("get_#{method}") { |cp|
ncp = __to_code_point cp
return hash[ncp] ? hash[ncp][method.to_sym] : nil
}
define_method("all_#{method}") { |pattern = nil|
pattern = Regexp.new(pattern) unless pattern.nil? || Regexp === pattern
hash.select { |k, v|
pattern.nil? ? !v[method.to_sym].vacant? : !pattern.match(v[method.to_sym]).nil?
}
}
}
def compose_cp cp, tag = :font, thorough = true
cp = __to_code_point cp
return Forkforge::CodePoint.new(hash[cp]) unless (t = CharacterDecompositionMapping::Tag.tag(tag)).valid?
@cdm[tag] = all_character_decomposition_mapping(/#{t.tag}/).values if @cdm[tag].nil?
# FIXME Could we distinguish “<wide> 0ABC” and “0A00 0ABC” in more elegant way?
lmbd = ->(v) { v[:character_decomposition_mapping] =~ /[^\dA-Fa-f]\s+#{cp}\Z/ }
thorough ? \
@cdm[tag].select(&lmbd).map { |cp| Forkforge::CodePoint.new(cp) } :
Forkforge::CodePoint.new(@cdm[tag].find(&lmbd) || hash[cp])
end
def decompose_cp cp, tags = []
normalized = __to_code_point cp
mapping = get_character_decomposition_mapping cp
return normalized if mapping.vacant?
cps = mapping.split ' '
return normalized if ![*tags].vacant? && \
cps.inject(false) { |memo, cp|
memo || (CharacterDecompositionMapping::Tag::tag?(cp) && ![*tags].include?(CharacterDecompositionMapping::Tag::tag(cp).sym))
}
cps.reject { |cp|
Forkforge::CharacterDecompositionMapping::Tag::tag? cp
}.map { |cp| decompose_cp cp, tags }
end
extend self
end
end
| mit |
jamemackson/lux | flow-typed/npm/rollup-plugin-node-resolve_vx.x.x.js | 1774 | // flow-typed signature: 2ef7f48018e4a4117b5a5d0da443e442
// flow-typed version: <<STUB>>/rollup-plugin-node-resolve_v3.0.0/flow_v0.46.0
/**
* This is an autogenerated libdef stub for:
*
* 'rollup-plugin-node-resolve'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'rollup-plugin-node-resolve' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.cjs' {
declare module.exports: any;
}
declare module 'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.es' {
declare module.exports: any;
}
declare module 'rollup-plugin-node-resolve/src/empty' {
declare module.exports: any;
}
declare module 'rollup-plugin-node-resolve/src/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.cjs.js' {
declare module.exports: $Exports<'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.cjs'>;
}
declare module 'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.es.js' {
declare module.exports: $Exports<'rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.es'>;
}
declare module 'rollup-plugin-node-resolve/src/empty.js' {
declare module.exports: $Exports<'rollup-plugin-node-resolve/src/empty'>;
}
declare module 'rollup-plugin-node-resolve/src/index.js' {
declare module.exports: $Exports<'rollup-plugin-node-resolve/src/index'>;
}
| mit |
mrkeng/aurora | aurora_app/deployments/models.py | 2946 | import time
import os
from datetime import datetime
from flask import url_for, current_app
from ..extensions import db
from ..tasks.models import Task
from .constants import STATUSES, BOOTSTRAP_ALERTS
deployments_tasks_table = db.Table('deployments_tasks', db.Model.metadata,
db.Column('deployment_id', db.Integer,
db.ForeignKey('deployments.id')),
db.Column('task_id', db.Integer,
db.ForeignKey('tasks.id')))
class Deployment(db.Model):
__tablename__ = "deployments"
id = db.Column(db.Integer, primary_key=True)
status = db.Column(db.SmallInteger, default=STATUSES['READY'])
branch = db.Column(db.String(32), default='master')
commit = db.Column(db.String(128))
started_at = db.Column(db.DateTime(), default=datetime.now)
finished_at = db.Column(db.DateTime())
code = db.Column(db.Text())
log = db.Column(db.Text())
# Relations
stage_id = db.Column(db.Integer(),
db.ForeignKey('stages.id'), nullable=False)
user_id = db.Column(db.Integer(),
db.ForeignKey('users.id'), nullable=False)
tasks = db.relationship(Task,
secondary=deployments_tasks_table,
backref="deployments")
def get_tmp_path(self):
return os.path.join(current_app.config['AURORA_TMP_DEPLOYMENTS_PATH'],
'{0}'.format(self.id))
def bootstrap_status(self):
return BOOTSTRAP_ALERTS[self.status]
def show_status(self):
for status, number in STATUSES.iteritems():
if number == self.status:
return status
def is_running(self):
return self.status == STATUSES['RUNNING']
def show_tasks_list(self):
template = '<a href="{0}">{1}</a>'
return ', '.join([template.format(url_for('tasks.view', id=task.id),
task.name) for task in self.tasks])
def get_log_path(self):
return os.path.join(self.get_tmp_path(), 'log')
def get_log_lines(self):
if self.log:
return self.log.split('\n')
path = os.path.join(self.get_tmp_path(), 'log')
if os.path.exists(path):
return open(path).readlines()
return []
def show_duration(self):
delta = self.finished_at - self.started_at
return time.strftime("%H:%M:%S", time.gmtime(delta.seconds))
def show_commit(self):
return "{0}".format(self.commit[:10]) if self.commit else ''
def __init__(self, *args, **kwargs):
super(Deployment, self).__init__(*args, **kwargs)
self.code = [self.stage.project.code, self.stage.code]
for task in self.stage.tasks:
self.code.append(task.code)
self.code = '\n'.join(self.code)
| mit |
patricklodder/blockio-java | src/main/java/io/block/api/utils/Constants.java | 2832 | package io.block.api.utils;
public class Constants {
public static final String BASE_URL = "https://block.io/api/v";
public static final String API_VERSION = "2";
public static class Methods {
public static final String GET_NEW_ADDRESS = "get_new_address";
public static final String GET_ACCOUNT_BALANCE = "get_balance";
public static final String GET_MY_ADDRESSES = "get_my_addresses";
public static final String GET_ADDR_BALANCE = "get_address_balance";
public static final String GET_ADDR_BY_LABEL = "get_address_by_label";
public static final String WITHDRAW_FROM_ANY = "withdraw";
public static final String WITHDRAW_FROM_LABELS = "withdraw_from_labels";
public static final String WITHDRAW_FROM_ADDRS = "withdraw_from_addresses";
public static final String WITHDRAW_FROM_USERIDS = "withdraw_from_user_ids";
public static final String WITHDRAW_DO_FINAL = "sign_and_finalize_withdrawal";
public static final String GET_PRICES = "get_current_price";
public static final String IS_GREEN_ADDR = "is_green_address";
public static final String IS_GREEN_TX = "is_green_transaction";
public static final String GET_TXNS = "get_transactions";
}
public static class Params {
public static final String API_KEY = "api_key";
public static final String LABEL = "label";
public static final String LABELS = "labels";
public static final String ADDRS = "addresses";
public static final String FROM_LABELS = "from_labels";
public static final String TO_LABELS = "to_labels";
public static final String FROM_ADDRS = "from_addresses";
public static final String TO_ADDRS = "to_addresses";
public static final String FROM_USERIDS = "from_user_ids";
public static final String TO_USERIDS = "to_user_ids";
public static final String AMOUNTS = "amounts";
public static final String PIN = "pin";
public static final String SIG_DATA = "signature_data";
public static final String PRICE_BASE = "price_base";
public static final String TX_IDS = "transaction_ids";
public static final String TYPE = "type";
public static final String BEFORE_TX = "before_tx";
public static final String USER_IDS = "user_ids";
}
public static class Values {
public static final String TYPE_SENT = "sent";
public static final String TYPE_RECEIVED = "received";
}
public static String buildUri(String method) {
return buildUri(method, false);
}
public static String buildUri(String method, boolean removeTrailingSlash) {
String s = BASE_URL + API_VERSION + "/" + method;
return removeTrailingSlash ? s : s + "/";
}
}
| mit |
artsy/force-public | src/lib/volley.ts | 1654 | import { data as sd } from "sharify"
import request from "superagent"
import {
getDomComplete,
getDomContentLoadedEnd,
getDomContentLoadedStart,
getFirstContentfulPaint,
getFirstPaint,
getLoadEventEnd,
getTTI,
} from "./userPerformanceMetrics"
interface MetricMap {
[metricName: string]: () => Promise<number> | number | null
}
const defaultMetrics: MetricMap = {
"dom-complete": getDomComplete,
"dom-content-loaded-start": getDomContentLoadedStart,
"dom-content-loaded-end": getDomContentLoadedEnd,
"load-event-end": getLoadEventEnd,
"first-paint": getFirstPaint,
"first-contentful-paint": getFirstContentfulPaint,
// @ts-expect-error STRICT_NULL_CHECK
"time-to-interactive": getTTI,
}
export const metricPayload = (pageType, deviceType, name, duration) => {
return !duration
? null
: {
type: "timing",
name: "load-time",
timing: duration,
tags: [
`page-type:${pageType}`,
`device-type:${deviceType}`,
`mark:${name}`,
],
}
}
export async function reportLoadTimeToVolley(
pageType,
deviceType,
metricsMap: MetricMap = defaultMetrics
) {
if (sd.VOLLEY_ENDPOINT) {
const metrics = (
await Promise.all(
Object.keys(metricsMap).map(async metricName =>
metricPayload(
pageType,
deviceType,
metricName,
await metricsMap[metricName]()
)
)
)
).filter(metric => metric != null)
if (metrics.length > 0) {
return request.post(sd.VOLLEY_ENDPOINT).send({
serviceName: "force",
metrics,
})
}
}
}
| mit |
TimeDoctorLLC/td-html-app | public/js/app.js | 1230 | "use strict";
var App = angular.module("todo", ["ui.sortable", "LocalStorageModule", 'js-data'])
.config(function (DSProvider) {
DSProvider.defaults.basePath = "https://td-rest-api.herokuapp.com:443/api/1.0"; // etc.
})
.run(function (DS, DSHttpAdapter) {
// @todo: add proper auth
DSHttpAdapter.defaults.httpConfig.headers = {
Authorization: 'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IlZYTWc5SWhsRWhNQU9ZRnMiLCJyZXYiOjAsImV4cCI6IjIwMTUtMDctMTNUMTc6MzA6MzIrMDA6MDAiLCJkZXYiOiJpVHJhc2gifQ.xmBfGl1P9YMqwoXokIOD-yv7oFvd4gyBz-BPykRRjT8',
'X-Company-ID': 'VXMhSIhlEhMAOYFt'
};
// @todo: refactor
DSHttpAdapter.defaults.deserialize = function (cfg, res) {
var data = res.data;
return (data && data.data) || data;
};
})
// This code won't execute unless you actually
// inject "Comment" somewhere in your code.
// Thanks Angular...
// Some like injecting actual Resource
// definitions, instead of just "DS"
.factory('Task', function (DS) {
return DS.defineResource('tasks');
})
.factory('Project', function (DS) {
return DS.defineResource('projects');
})
.factory('Folder', function (DS) {
return DS.defineResource('folders');
});
| mit |
ozthekoder/chatter | public/modules/core/controllers/right.client.controller.js | 283 | 'use strict';
angular.module('core').controller('RightController', ['$scope', 'Authentication', 'Navigation',
function($scope, Authentication, Menus) {
$scope.authentication = Authentication;
$scope.$on('$stateChangeSuccess', function() {
});
}
]);
| mit |
mithrandi/txspinneret | txspinneret/util.py | 2722 | import cgi
import datetime
from collections import OrderedDict
from functools import wraps
from itertools import chain
# Why does Python not have this built-in?
identity = lambda x: x
def _parseAccept(headers):
"""
Parse and sort an ``Accept`` header.
The header is sorted according to the ``q`` parameter for each header value.
@rtype: `OrderedDict` mapping `bytes` to `dict`
@return: Mapping of media types to header parameters.
"""
def sort(value):
return float(value[1].get('q', 1))
return OrderedDict(sorted(_splitHeaders(headers), key=sort, reverse=True))
def _splitHeaders(headers):
"""
Split an HTTP header whose components are separated with commas.
Each component is then split on semicolons and the component arguments
converted into a `dict`.
@return: `list` of 2-`tuple` of `bytes`, `dict`
@return: List of header arguments and mapping of component argument names
to values.
"""
return [cgi.parse_header(value)
for value in chain.from_iterable(
s.split(',') for s in headers
if s)]
def contentEncoding(requestHeaders, encoding=None):
"""
Extract an encoding from a ``Content-Type`` header.
@type requestHeaders: `twisted.web.http_headers.Headers`
@param requestHeaders: Request headers.
@type encoding: `bytes`
@param encoding: Default encoding to assume if the ``Content-Type``
header is lacking one. Defaults to ``UTF-8``.
@rtype: `bytes`
@return: Content encoding.
"""
if encoding is None:
encoding = b'utf-8'
headers = _splitHeaders(
requestHeaders.getRawHeaders(b'Content-Type', []))
if headers:
return headers[0][1].get(b'charset', encoding)
return encoding
def maybe(f, default=None):
"""
Create a nil-safe callable decorator.
If the wrapped callable receives ``None`` as its argument, it will return
``None`` immediately.
"""
@wraps(f)
def _maybe(x, *a, **kw):
if x is None:
return default
return f(x, *a, **kw)
return _maybe
# Thank you epsilon.extime.
class FixedOffset(datetime.tzinfo):
"""
Fixed offset timezone.
"""
_zeroOffset = datetime.timedelta()
def __init__(self, hours, minutes):
self._hours = hours
self._minutes = minutes
self.offset = datetime.timedelta(minutes=hours * 60 + minutes)
def utcoffset(self, dt):
return self.offset
def dst(self, tz):
return self._zeroOffset
def __repr__(self):
return b'%s(%d, %d)' % (
type(self).__name__, self._hours, self._minutes)
UTC = FixedOffset(0, 0)
| mit |
hfcjweinstock/EncompassREST | src/EncompassRest/Services/Verification/EV4506TTaxReturnFor.cs | 585 | using System.Runtime.Serialization;
namespace EncompassRest.Services.Verification
{
/// <summary>
/// EV4506TTaxReturnFor
/// </summary>
public enum EV4506TTaxReturnFor
{
/// <summary>
/// borrower
/// </summary>
[EnumMember(Value = "borrower")]
Borrower = 0,
/// <summary>
/// coBorrower
/// </summary>
[EnumMember(Value = "coBorrower")]
CoBorrower = 1,
/// <summary>
/// joint
/// </summary>
[EnumMember(Value = "joint")]
Joint = 2
}
} | mit |
junedomingo/react-native-navigation | src/deprecated/platformSpecificDeprecated.ios.js | 20774 | /*eslint-disable*/
import Navigation from './../Navigation';
import Controllers, {Modal, Notification, ScreenUtils} from './controllers';
const React = Controllers.hijackReact();
const {
ControllerRegistry,
TabBarControllerIOS,
NavigationControllerIOS,
DrawerControllerIOS
} = React;
import _ from 'lodash';
import PropRegistry from '../PropRegistry';
function startTabBasedApp(params) {
if (!params.tabs) {
console.error('startTabBasedApp(params): params.tabs is required');
return;
}
const controllerID = _.uniqueId('controllerID');
params.tabs.map(function(tab, index) {
const navigatorID = controllerID + '_nav' + index;
const screenInstanceID = _.uniqueId('screenInstanceID');
if (!tab.screen) {
console.error('startTabBasedApp(params): every tab must include a screen property, take a look at tab#' + (index + 1));
return;
}
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(tab.screen, screenInstanceID, tab);
tab.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID
};
});
const Controller = Controllers.createClass({
render: function() {
if (!params.drawer || (!params.drawer.left && !params.drawer.right)) {
return this.renderBody();
} else {
const navigatorID = controllerID + '_drawer';
return (
<DrawerControllerIOS id={navigatorID}
componentLeft={params.drawer.left ? params.drawer.left.screen : undefined}
passPropsLeft={{navigatorID: navigatorID}}
componentRight={params.drawer.right ? params.drawer.right.screen : undefined}
passPropsRight={{navigatorID: navigatorID}}
disableOpenGesture={params.drawer.disableOpenGesture}
type={params.drawer.type ? params.drawer.type : 'MMDrawer'}
animationType={params.drawer.animationType ? params.drawer.animationType : 'slide'}
style={params.drawer.style}
appStyle={params.appStyle}
>
{this.renderBody()}
</DrawerControllerIOS>
);
}
},
renderBody: function() {
return (
<TabBarControllerIOS
id={controllerID + '_tabs'}
style={params.tabsStyle}
appStyle={params.appStyle}
initialTabIndex={params.initialTabIndex}>
{
params.tabs.map(function(tab, index) {
return (
<TabBarControllerIOS.Item {...tab} title={tab.label}>
<NavigationControllerIOS
id={tab.navigationParams.navigatorID}
title={tab.title}
subtitle={tab.subtitle}
titleImage={tab.titleImage}
component={tab.screen}
passProps={{
navigatorID: tab.navigationParams.navigatorID,
screenInstanceID: tab.navigationParams.screenInstanceID,
navigatorEventID: tab.navigationParams.navigatorEventID,
}}
style={tab.navigationParams.navigatorStyle}
leftButtons={tab.navigationParams.navigatorButtons.leftButtons}
rightButtons={tab.navigationParams.navigatorButtons.rightButtons}
/>
</TabBarControllerIOS.Item>
);
})
}
</TabBarControllerIOS>
);
}
});
savePassProps(params);
_.set(params, 'passProps.timestamp', Date.now());
ControllerRegistry.registerController(controllerID, () => Controller);
ControllerRegistry.setRootController(controllerID, params.animationType, params.passProps || {});
}
function startSingleScreenApp(params) {
if (!params.screen) {
console.error('startSingleScreenApp(params): params.screen is required');
return;
}
const controllerID = _.uniqueId('controllerID');
const screen = params.screen;
if (!screen.screen) {
console.error('startSingleScreenApp(params): screen must include a screen property');
return;
}
const navigatorID = controllerID + '_nav';
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(screen.screen, screenInstanceID, screen);
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID
};
const Controller = Controllers.createClass({
render: function() {
if (!params.drawer || (!params.drawer.left && !params.drawer.right)) {
return this.renderBody();
} else {
const navigatorID = controllerID + '_drawer';
return (
<DrawerControllerIOS id={navigatorID}
componentLeft={params.drawer.left ? params.drawer.left.screen : undefined}
passPropsLeft={{navigatorID: navigatorID}}
componentRight={params.drawer.right ? params.drawer.right.screen : undefined}
passPropsRight={{navigatorID: navigatorID}}
disableOpenGesture={params.drawer.disableOpenGesture}
type={params.drawer.type ? params.drawer.type : 'MMDrawer'}
animationType={params.drawer.animationType ? params.drawer.animationType : 'slide'}
style={params.drawer.style}
appStyle={params.appStyle}
>
{this.renderBody()}
</DrawerControllerIOS>
);
}
},
renderBody: function() {
return (
<NavigationControllerIOS
id={navigatorID}
title={screen.title}
subtitle={params.subtitle}
titleImage={screen.titleImage}
component={screen.screen}
passProps={{
navigatorID: navigatorID,
screenInstanceID: screenInstanceID,
navigatorEventID: navigatorEventID
}}
style={navigatorStyle}
leftButtons={navigatorButtons.leftButtons}
rightButtons={navigatorButtons.rightButtons}
appStyle={params.appStyle}
/>
);
}
});
savePassProps(params);
ControllerRegistry.registerController(controllerID, () => Controller);
ControllerRegistry.setRootController(controllerID, params.animationType, params.passProps || {});
}
function _mergeScreenSpecificSettings(screenID, screenInstanceID, params) {
const screenClass = Navigation.getRegisteredScreen(screenID);
if (!screenClass) {
console.error('Cannot create screen ' + screenID + '. Are you it was registered with Navigation.registerScreen?');
return;
}
const navigatorStyle = Object.assign({}, screenClass.navigatorStyle);
if (params.navigatorStyle) {
Object.assign(navigatorStyle, params.navigatorStyle);
}
let navigatorEventID = screenInstanceID + '_events';
let navigatorButtons = _.cloneDeep(screenClass.navigatorButtons);
if (params.navigatorButtons) {
navigatorButtons = _.cloneDeep(params.navigatorButtons);
}
if (navigatorButtons.leftButtons) {
for (let i = 0; i < navigatorButtons.leftButtons.length; i++) {
navigatorButtons.leftButtons[i].onPress = navigatorEventID;
}
}
if (navigatorButtons.rightButtons) {
for (let i = 0; i < navigatorButtons.rightButtons.length; i++) {
navigatorButtons.rightButtons[i].onPress = navigatorEventID;
}
}
return {navigatorStyle, navigatorButtons, navigatorEventID};
}
function navigatorPush(navigator, params) {
if (!params.screen) {
console.error('Navigator.push(params): params.screen is required');
return;
}
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(params.screen, screenInstanceID, params);
const passProps = Object.assign({}, params.passProps);
passProps.navigatorID = navigator.navigatorID;
passProps.screenInstanceID = screenInstanceID;
passProps.navigatorEventID = navigatorEventID;
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID: navigator.navigatorID
};
savePassProps(params);
Controllers.NavigationControllerIOS(navigator.navigatorID).push({
title: params.title,
subtitle: params.subtitle,
titleImage: params.titleImage,
component: params.screen,
animated: params.animated,
animationType: params.animationType,
passProps: passProps,
style: navigatorStyle,
backButtonTitle: params.backButtonTitle,
backButtonHidden: params.backButtonHidden,
leftButtons: navigatorButtons.leftButtons,
rightButtons: navigatorButtons.rightButtons,
timestamp: Date.now()
});
}
function navigatorPop(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).pop({
animated: params.animated,
animationType: params.animationType,
timestamp: Date.now()
});
}
function navigatorPopToRoot(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).popToRoot({
animated: params.animated,
animationType: params.animationType
});
}
function navigatorResetTo(navigator, params) {
if (!params.screen) {
console.error('Navigator.resetTo(params): params.screen is required');
return;
}
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(params.screen, screenInstanceID, params);
const passProps = Object.assign({}, params.passProps);
passProps.navigatorID = navigator.navigatorID;
passProps.screenInstanceID = screenInstanceID;
passProps.navigatorEventID = navigatorEventID;
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID: navigator.navigatorID
};
savePassProps(params);
Controllers.NavigationControllerIOS(navigator.navigatorID).resetTo({
title: params.title,
subtitle: params.subtitle,
titleImage: params.titleImage,
component: params.screen,
animated: params.animated,
animationType: params.animationType,
passProps: passProps,
style: navigatorStyle,
leftButtons: navigatorButtons.leftButtons,
rightButtons: navigatorButtons.rightButtons
});
}
function navigatorSetDrawerEnabled(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
Controllers.NavigationControllerIOS(controllerID + '_drawer').setDrawerEnabled(params)
}
function navigatorSetTitle(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).setTitle({
title: params.title,
subtitle: params.subtitle,
titleImage: params.titleImage,
style: params.navigatorStyle,
isSetSubtitle: false
});
}
function navigatorSetSubtitle(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).setTitle({
title: params.title,
subtitle: params.subtitle,
titleImage: params.titleImage,
style: params.navigatorStyle,
isSetSubtitle: true
});
}
function navigatorSetTitleImage(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).setTitleImage({
titleImage: params.titleImage
});
}
function navigatorToggleNavBar(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).setHidden({
hidden: ((params.to === 'hidden') ? true : false),
animated: params.animated
});
}
function navigatorSetStyle(navigator, params) {
Controllers.NavigationControllerIOS(navigator.navigatorID).setStyle(params)
}
function navigatorToggleDrawer(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
if (params.to == 'open') {
Controllers.DrawerControllerIOS(controllerID + '_drawer').open({
side: params.side,
animated: params.animated
});
} else if (params.to == 'closed') {
Controllers.DrawerControllerIOS(controllerID + '_drawer').close({
side: params.side,
animated: params.animated
});
} else {
Controllers.DrawerControllerIOS(controllerID + '_drawer').toggle({
side: params.side,
animated: params.animated
});
}
}
function navigatorToggleTabs(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
Controllers.TabBarControllerIOS(controllerID + '_tabs').setHidden({
hidden: params.to == 'hidden',
animated: !(params.animated === false)
});
}
function navigatorSetTabBadge(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
if (params.tabIndex || params.tabIndex === 0) {
Controllers.TabBarControllerIOS(controllerID + '_tabs').setBadge({
tabIndex: params.tabIndex,
badge: params.badge
});
} else {
Controllers.TabBarControllerIOS(controllerID + '_tabs').setBadge({
contentId: navigator.navigatorID,
contentType: 'NavigationControllerIOS',
badge: params.badge
});
}
}
function navigatorSetTabButton(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
if (params.tabIndex || params.tabIndex === 0) {
Controllers.TabBarControllerIOS(controllerID + '_tabs').setTabButton({
tabIndex: params.tabIndex,
icon: params.icon,
selectedIcon: params.selectedIcon
});
} else {
Controllers.TabBarControllerIOS(controllerID + '_tabs').setTabButton({
contentId: navigator.navigatorID,
contentType: 'NavigationControllerIOS',
icon: params.icon,
selectedIcon: params.selectedIcon
});
}
}
function navigatorSwitchToTab(navigator, params) {
const controllerID = navigator.navigatorID.split('_')[0];
if (params.tabIndex || params.tabIndex === 0) {
Controllers.TabBarControllerIOS(controllerID + '_tabs').switchTo({
tabIndex: params.tabIndex
});
} else {
Controllers.TabBarControllerIOS(controllerID + '_tabs').switchTo({
contentId: navigator.navigatorID,
contentType: 'NavigationControllerIOS'
});
}
}
function navigatorSetButtons(navigator, navigatorEventID, params) {
if (params.leftButtons) {
const buttons = params.leftButtons.slice(); // clone
for (let i = 0; i < buttons.length; i++) {
buttons[i].onPress = navigatorEventID;
}
Controllers.NavigationControllerIOS(navigator.navigatorID).setLeftButtons(buttons, params.animated);
}
if (params.rightButtons) {
const buttons = params.rightButtons.slice(); // clone
for (let i = 0; i < buttons.length; i++) {
buttons[i].onPress = navigatorEventID;
}
Controllers.NavigationControllerIOS(navigator.navigatorID).setRightButtons(buttons, params.animated);
}
}
function showModal(params) {
if (!params.screen) {
console.error('showModal(params): params.screen is required');
return;
}
const controllerID = _.uniqueId('controllerID');
const navigatorID = controllerID + '_nav';
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(params.screen, screenInstanceID, params);
const passProps = Object.assign({}, params.passProps);
passProps.navigatorID = navigatorID;
passProps.screenInstanceID = screenInstanceID;
passProps.navigatorEventID = navigatorEventID;
passProps.timestamp = Date.now();
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID: navigator.navigatorID
};
const Controller = Controllers.createClass({
render: function() {
return (
<NavigationControllerIOS
id={navigatorID}
title={params.title}
subtitle={params.subtitle}
titleImage={params.titleImage}
component={params.screen}
passProps={passProps}
style={navigatorStyle}
leftButtons={navigatorButtons.leftButtons}
rightButtons={navigatorButtons.rightButtons}/>
);
}
});
savePassProps(params);
ControllerRegistry.registerController(controllerID, () => Controller);
Modal.showController(controllerID, params.animationType);
}
async function dismissModal(params) {
return await Modal.dismissController(params.animationType);
}
function dismissAllModals(params) {
Modal.dismissAllControllers(params.animationType);
}
function showLightBox(params) {
if (!params.screen) {
console.error('showLightBox(params): params.screen is required');
return;
}
const controllerID = _.uniqueId('controllerID');
const navigatorID = controllerID + '_nav';
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(params.screen, screenInstanceID, params);
const passProps = Object.assign({}, params.passProps);
passProps.navigatorID = navigatorID;
passProps.screenInstanceID = screenInstanceID;
passProps.navigatorEventID = navigatorEventID;
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID
};
savePassProps(params);
Modal.showLightBox({
component: params.screen,
passProps: passProps,
style: params.style
});
}
function dismissLightBox(params) {
Modal.dismissLightBox();
}
function showInAppNotification(params) {
if (!params.screen) {
console.error('showInAppNotification(params): params.screen is required');
return;
}
const controllerID = _.uniqueId('controllerID');
const navigatorID = controllerID + '_nav';
const screenInstanceID = _.uniqueId('screenInstanceID');
const {
navigatorStyle,
navigatorButtons,
navigatorEventID
} = _mergeScreenSpecificSettings(params.screen, screenInstanceID, params);
const passProps = Object.assign({}, params.passProps);
passProps.navigatorID = navigatorID;
passProps.screenInstanceID = screenInstanceID;
passProps.navigatorEventID = navigatorEventID;
params.navigationParams = {
screenInstanceID,
navigatorStyle,
navigatorButtons,
navigatorEventID,
navigatorID
};
savePassProps(params);
let args = {
component: params.screen,
passProps: passProps,
style: params.style,
animation: params.animation || Notification.AnimationPresets.default,
position: params.position,
shadowRadius: params.shadowRadius,
dismissWithSwipe: params.dismissWithSwipe || true,
autoDismissTimerSec: params.autoDismissTimerSec || 5
};
if (params.autoDismiss === false) delete args.autoDismissTimerSec;
Notification.show(args);
}
function dismissInAppNotification(params) {
Notification.dismiss(params);
}
function savePassProps(params) {
//TODO this needs to be handled in a common place,
//TODO also, all global passProps should be handled differently
if (params.navigationParams && params.passProps) {
PropRegistry.save(params.navigationParams.screenInstanceID, params.passProps);
}
if (params.screen && params.screen.passProps) {
PropRegistry.save(params.screen.navigationParams.screenInstanceID, params.screen.passProps);
}
if (_.get(params, 'screen.topTabs')) {
_.forEach(params.screen.topTabs, (tab) => savePassProps(tab));
}
if (params.tabs) {
_.forEach(params.tabs, (tab) => {
if (!tab.passProps) {
tab.passProps = params.passProps;
}
savePassProps(tab);
});
}
}
function showContextualMenu() {
// Android only
}
function dismissContextualMenu() {
// Android only
}
async function getCurrentlyVisibleScreenId() {
return await ScreenUtils.getCurrentlyVisibleScreenId();
}
export default {
startTabBasedApp,
startSingleScreenApp,
navigatorPush,
navigatorPop,
navigatorPopToRoot,
navigatorResetTo,
showModal,
dismissModal,
dismissAllModals,
showLightBox,
dismissLightBox,
showInAppNotification,
dismissInAppNotification,
navigatorSetButtons,
navigatorSetDrawerEnabled,
navigatorSetTitle,
navigatorSetSubtitle,
navigatorSetStyle,
navigatorSetTitleImage,
navigatorToggleDrawer,
navigatorToggleTabs,
navigatorSetTabBadge,
navigatorSetTabButton,
navigatorSwitchToTab,
navigatorToggleNavBar,
showContextualMenu,
dismissContextualMenu,
getCurrentlyVisibleScreenId
};
| mit |
royalwang/youbbs | templates/default/ios_tag.php | 2132 | <?php
if (!defined('IN_SAESPOT')) exit('error: 403 Access Denied');
echo '
<div class="nav-title">
<i class="fa fa-angle-double-right"></i> ',$title;
if($cur_user['notic']){
$notic_n = count(array_unique(explode(',', $cur_user['notic'])))-1;
echo'<span class="nopic"><a href="/notifications"><i class="fa fa-bell"></i> 您有',$notic_n,'条消息</a></span>';
}
echo ' <div class="c"></div>
</div>
<div class="main-box home-box-list">';
foreach($articledb as $article){
echo '
<div class="post-list">
<div class="item-avatar"><a href="/user/',$article['uid'],'">
<img src="/avatar/normal/',$article['uavatar'],'.png" alt="',$article['author'],'" /></a></div>
<div class="item-content count',$article['comments'],'">
<h1><a href="/topics/',$article['id'],'">',$article['title'],'</a></h1>
<span class="item-date"><i class="fa fa-archive"></i> <a href="/nodes/',$article['cid'],'">',$article['cname'],'</a>';
if($article['comments']){
echo '<i class="fa fa-user"></i> <a href="/user/',$article['ruid'],'">',$article['rauthor'],'</a> <i class="fa fa-clock-o"></i> ',$article['edittime'],'回复';
}else{
echo '<i class="fa fa-user"></i> <a href="/user/',$article['uid'],'">',$article['author'],'</a> <i class="fa fa-clock-o"></i> ',$article['addtime'],'发表';
}
echo ' </span>
</div>';
if($article['comments']){
$gotopage = ceil($article['comments']/$options['commentlist_num']);
if($gotopage == 1){
$c_page = '';
}else{
$c_page = '/'.$gotopage;
}
echo '<div class="item-count"><a href="/topics/',$article['id'],$c_page,'#reply',$article['comments'],'">',$article['comments'],'</a></div>';
}
echo ' <div class="c"></div>
</div>';
}
if($tag_obj['articles'] > $options['list_shownum']){
echo '<div class="pagination">';
if($page>1){
echo '<a href="/tag/',$tag,'/',$page-1,'" class="float-left">« 上一页</a>';
}
if($page<$taltol_page){
echo '<a href="/tag/',$tag,'/',$page+1,'" class="float-right">下一页 »</a>';
}
echo '<div class="c"></div>
</div>';
}
echo '</div>';
?>
| mit |
Cylix/cpp_redis | docs/html/search/all_12.js | 2640 | var searchData=
[
['_7earray_5fbuilder',['~array_builder',['../classcpp__redis_1_1builders_1_1array__builder.html#ae6a0cd0743b6b0a21f9c3d44fd31ac17',1,'cpp_redis::builders::array_builder']]],
['_7ebulk_5fstring_5fbuilder',['~bulk_string_builder',['../classcpp__redis_1_1builders_1_1bulk__string__builder.html#a88c7142bab456f70da9f9a6252e2affb',1,'cpp_redis::builders::bulk_string_builder']]],
['_7eclient',['~client',['../classcpp__redis_1_1client.html#aca7030c8bd6856f10314b2862d1bae79',1,'cpp_redis::client']]],
['_7eerror_5fbuilder',['~error_builder',['../classcpp__redis_1_1builders_1_1error__builder.html#a7650c178a457c57c2efb19e7ad256fe7',1,'cpp_redis::builders::error_builder']]],
['_7einteger_5fbuilder',['~integer_builder',['../classcpp__redis_1_1builders_1_1integer__builder.html#ab2b797dd89b1bdec50f8ccf07633162f',1,'cpp_redis::builders::integer_builder']]],
['_7elogger',['~logger',['../classcpp__redis_1_1logger.html#ab5eb02b26c96a6e5cba9a7d30669f625',1,'cpp_redis::logger']]],
['_7elogger_5fiface',['~logger_iface',['../classcpp__redis_1_1logger__iface.html#ac7ed1b828afd2e6589fcdda167d34aa5',1,'cpp_redis::logger_iface']]],
['_7eredis_5fconnection',['~redis_connection',['../classcpp__redis_1_1network_1_1redis__connection.html#a9d392191ce262eddd5570b57e07aa051',1,'cpp_redis::network::redis_connection']]],
['_7ereply',['~reply',['../classcpp__redis_1_1reply.html#a1acfe6cbc763368cc2a9eef25afffe35',1,'cpp_redis::reply']]],
['_7ereply_5fbuilder',['~reply_builder',['../classcpp__redis_1_1builders_1_1reply__builder.html#ac2df7e1ed2f67e01090ad45926c9af1e',1,'cpp_redis::builders::reply_builder']]],
['_7esentinel',['~sentinel',['../classcpp__redis_1_1sentinel.html#af8535e89714db8ddcd7e74337ee5385a',1,'cpp_redis::sentinel']]],
['_7esentinel_5fdef',['~sentinel_def',['../classcpp__redis_1_1sentinel_1_1sentinel__def.html#a5189d8016d9b385099e5ee0828ed7666',1,'cpp_redis::sentinel::sentinel_def']]],
['_7esimple_5fstring_5fbuilder',['~simple_string_builder',['../classcpp__redis_1_1builders_1_1simple__string__builder.html#a7b4f012c532535801f9d5fddbb01d675',1,'cpp_redis::builders::simple_string_builder']]],
['_7esubscriber',['~subscriber',['../classcpp__redis_1_1subscriber.html#a878caeb144b11de30466a380b09abc30',1,'cpp_redis::subscriber']]],
['_7etcp_5fclient',['~tcp_client',['../classcpp__redis_1_1network_1_1tcp__client.html#af859036bbc7e5ec9149c1410a1a66f09',1,'cpp_redis::network::tcp_client']]],
['_7etcp_5fclient_5fiface',['~tcp_client_iface',['../classcpp__redis_1_1network_1_1tcp__client__iface.html#a7381e8921118a13b5994101864906122',1,'cpp_redis::network::tcp_client_iface']]]
];
| mit |
ceolter/ag-grid | charts-packages/ag-charts-community/dist/cjs/chart/themes/solarLight.js | 1545 | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var chartTheme_1 = require("./chartTheme");
var palette = {
fills: [
'#febe76',
'#ff7979',
'#badc58',
'#f9ca23',
'#f0932b',
'#eb4c4b',
'#6ab04c',
'#7ed6df',
'#e056fd',
'#686de0'
],
strokes: [
'#b28553',
'#b35555',
'#829a3e',
'#ae8d19',
'#a8671e',
'#a43535',
'#4a7b35',
'#58969c',
'#9d3cb1',
'#494c9d'
]
};
var SolarLight = /** @class */ (function (_super) {
__extends(SolarLight, _super);
function SolarLight() {
return _super !== null && _super.apply(this, arguments) || this;
}
SolarLight.prototype.getPalette = function () {
return palette;
};
return SolarLight;
}(chartTheme_1.ChartTheme));
exports.SolarLight = SolarLight;
//# sourceMappingURL=solarLight.js.map | mit |
typeorm/typeorm | sample/sample4-many-to-many/entity/PostMetadata.ts | 341 | import {Column, Entity, ManyToMany, PrimaryGeneratedColumn} from "../../../src/index";
import {Post} from "./Post";
@Entity("sample4_post_metadata")
export class PostMetadata {
@PrimaryGeneratedColumn()
id: number;
@Column()
description: string;
@ManyToMany(type => Post, post => post.metadatas)
posts: Post[];
} | mit |
BeetoGuy/BetterWithMods | src/main/java/betterwithmods/module/compat/multipart/MultipartSiding.java | 2494 | package betterwithmods.module.compat.multipart;
import betterwithmods.module.gameplay.miniblocks.ItemMini;
import betterwithmods.module.gameplay.miniblocks.blocks.BlockMini;
import betterwithmods.module.gameplay.miniblocks.blocks.BlockSiding;
import betterwithmods.module.gameplay.miniblocks.orientations.SidingOrientation;
import betterwithmods.module.gameplay.miniblocks.tiles.TileMini;
import mcmultipart.api.container.IPartInfo;
import mcmultipart.api.multipart.IMultipart;
import mcmultipart.api.multipart.IMultipartTile;
import mcmultipart.api.slot.EnumFaceSlot;
import mcmultipart.api.slot.IPartSlot;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class MultipartSiding implements IMultipart {
private BlockSiding siding;
public MultipartSiding(BlockSiding siding) {
this.siding = siding;
}
@Override
public Block getBlock() {
return siding;
}
@Override
public void onPartPlacedBy(IPartInfo part, EntityLivingBase placer, ItemStack stack) {
TileMini tile = (TileMini) part.getTile().getTileEntity();
ItemMini.setNBT(tile, tile.getWorld(), stack);
}
@Override
public IPartSlot getSlotForPlacement(World world, BlockPos pos, IBlockState state, EnumFacing facing, float hitX, float hitY, float hitZ, EntityLivingBase placer) {
SidingOrientation orientation = (SidingOrientation) SidingOrientation.getFromVec(new Vec3d(hitX, hitY, hitZ), facing);
return EnumFaceSlot.fromFace(orientation.getFacing());
}
@Override
public IPartSlot getSlotFromWorld(IBlockAccess world, BlockPos pos, IBlockState state) {
TileEntity tile = world.getTileEntity(pos);
if (tile instanceof TileMini) {
BlockMini mini = (BlockMini) state.getBlock();
SidingOrientation orientation = (SidingOrientation) ((TileMini) tile).getOrientation();
return EnumFaceSlot.fromFace(orientation.getFacing());
}
return EnumFaceSlot.NORTH;
}
@Override
public IMultipartTile convertToMultipartTile(TileEntity tileEntity) {
return new MultipartTileProxy(tileEntity);
}
}
| mit |
postmates/geopy | geopy/geocoders/mapquest.py | 4192 | """
:class:`.MapQuest` geocoder.
"""
from geopy.compat import urlencode
from geopy.geocoders.base import Geocoder, DEFAULT_FORMAT_STRING, \
DEFAULT_TIMEOUT, DEFAULT_SCHEME
from geopy.util import logger, join_filter
from geopy import exc
class MapQuest(Geocoder): # pylint: disable=W0223
"""
MapQuest geocoder, documentation at:
http://www.mapquestapi.com/geocoding/
"""
def __init__(self, api_key, format_string=DEFAULT_FORMAT_STRING, # pylint: disable=R0913
scheme=DEFAULT_SCHEME,
timeout=DEFAULT_TIMEOUT, proxies=None):
"""
Initialize a MapQuest geocoder with address information and
MapQuest API key.
:param string api_key: Key provided by MapQuest.
:param string format_string: String containing '%s' where the
string to geocode should be interpolated before querying the
geocoder. For example: '%s, Mountain View, CA'. The default
is just '%s'.
:param string scheme: Use 'https' or 'http' as the API URL's scheme.
Default is https. Note that SSL connections' certificates are not
verified.
.. versionadded:: 0.97
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception.
.. versionadded:: 0.97
:param dict proxies: If specified, routes this geocoder's requests
through the specified proxy. E.g., {"https": "192.0.2.0"}. For
more information, see documentation on
:class:`urllib2.ProxyHandler`.
"""
super(MapQuest, self).__init__(format_string, scheme, timeout, proxies)
self.api_key = api_key
self.api = "%s://www.mapquestapi.com/geocoding/v1/address" % self.scheme
def geocode(self, query, exactly_one=True, timeout=None): # pylint: disable=W0221
"""
Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call only,
the value set during the geocoder's initialization.
.. versionadded:: 0.97
"""
params = {
'location' : query
}
if exactly_one:
params['maxResults'] = 1
# don't urlencode MapQuest API keys
url = "?".join((
self.api,
"&".join(("=".join(('key', self.api_key)), urlencode(params)))
))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
def _parse_json(self, resources, exactly_one=True):
"""
Parse display name, latitude, and longitude from an JSON response.
"""
if resources.get('info').get('statuscode') == 403:
raise exc.GeocoderAuthenticationFailure()
resources = resources.get('results')[0].get('locations', [])
if not len(resources):
return None
def parse_resource(resource):
"""
Parse each record.
"""
city = resource['adminArea5']
county = resource['adminArea4']
state = resource['adminArea3']
country = resource['adminArea1']
latLng = resource['latLng']
latitude, longitude = latLng.get('lat'), latLng.get('lng')
location = join_filter(", ", [city, county, state, country])
if latitude and longitude:
latitude = float(latitude)
longitude = float(longitude)
return (location, (latitude, longitude))
if exactly_one:
return parse_resource(resources[0])
else:
return [parse_resource(resource) for resource in resources]
| mit |
rtahmasbi/GeneEvolve | Library/libStatGen/bam/test/ValidationTest.cpp | 8169 | /*
* Copyright (C) 2010 Regents of the University of Michigan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SamRecord.h"
#include "SamValidation.h"
#include "ValidationTest.h"
#include <assert.h>
void testSamQNAME()
{
// This method tests:
// QNAME.Length() > 0 and <= 254
// QNAME does not contain [ \t\n\r]
char qname[256];
SamFileHeader samHeader;
SamRecord testRecord(ErrorHandler::RETURN);
// Error list
SamValidationErrors errorList;
// Test Length == 0 by setting qname[0] to 0 (end of char*)
qname[0] = 0;
// It fails, because it is a required field.
assert(testRecord.setReadName(qname) == false);
assert(strcmp(testRecord.getReadName(), "UNKNOWN") == 0);
// It was reset to the default which is valid.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == true);
assert(errorList.numErrors() == 0);
assert(errorList.getNextError() == NULL);
// Test too long of a read name.
memset(qname, '.', 255);
qname[255] = 0;
assert(testRecord.setReadName(qname) == true);
assert(strcmp(testRecord.getReadName(), qname) == 0);
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
// 2 errors - 1 since the qname is longer than 254 (it is 255).
// and the qname length including the null is 256, but the
// read name length is only 8 bits, so that is a 1.
assert(errorList.numErrors() == 2);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_QNAME);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_QNAME);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
// Setup a buffer to set the record to.
int bufferBlockSize = 32;
bamRecordStruct* bufferRecordPtr =
(bamRecordStruct *) malloc(bufferBlockSize + sizeof(int));
bufferRecordPtr->myBlockSize = bufferBlockSize;
bufferRecordPtr->myReferenceID = -1;
bufferRecordPtr->myPosition = 1010;
// Set the read name length to 0.
bufferRecordPtr->myReadNameLength = 0;
bufferRecordPtr->myMapQuality = 0;
bufferRecordPtr->myBin = 4681;
bufferRecordPtr->myCigarLength = 0;
bufferRecordPtr->myFlag = 73;
bufferRecordPtr->myReadLength = 0;
bufferRecordPtr->myMateReferenceID = -1;
bufferRecordPtr->myMatePosition = 1010;
bufferRecordPtr->myInsertSize = 0;
assert(testRecord.setBuffer((const char*)bufferRecordPtr,
bufferBlockSize + sizeof(int),
samHeader) == SamStatus::SUCCESS);
// 1 error - the read name length is 0.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
assert(errorList.numErrors() == 1);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_QNAME);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
// Test a buffer that has a read name, but the length specified is
// longer than the first null.
bufferBlockSize = 40;
bufferRecordPtr->myBlockSize = bufferBlockSize;
// Set the read name length to 8 - longer than 3 - "HI\0".
bufferRecordPtr->myReadNameLength = 8;
bufferRecordPtr->myData[0] = 'H';
bufferRecordPtr->myData[1] = 'I';
bufferRecordPtr->myData[2] = 0;
assert(testRecord.setBuffer((const char*)bufferRecordPtr,
bufferBlockSize + sizeof(int),
samHeader) == SamStatus::SUCCESS);
// 1 error - the read name length in the buffer does not match the
// length of the read name to the first null.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
assert(errorList.numErrors() == 1);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_QNAME);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
// Test a buffer that has a read name, but the length specified is
// shorter than the first null.
bufferBlockSize = 34;
bufferRecordPtr->myBlockSize = bufferBlockSize;
// Set the read name length to 2 - longer than 3 - "HI\0"..
bufferRecordPtr->myReadNameLength = 2;
bufferRecordPtr->myData[0] = 'H';
bufferRecordPtr->myData[1] = 'I';
bufferRecordPtr->myData[2] = 0;
assert(testRecord.setBuffer((const char*)bufferRecordPtr,
bufferBlockSize + sizeof(int),
samHeader) == SamStatus::SUCCESS);
// 1 error - the read name length in the buffer does not match
// the length of the read name to the first null.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
assert(errorList.numErrors() == 1);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_QNAME);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
}
void testBamRID()
{
// BAM
SamRecord testRecord(ErrorHandler::RETURN);
// Error list
SamValidationErrors errorList;
SamFileHeader samHeader;
// Clear the error list
errorList.clear();
// Setup a buffer to set the record to.
int bufferBlockSize = 35;
bamRecordStruct* bufferRecordPtr =
(bamRecordStruct *) malloc(bufferBlockSize + sizeof(int));
bufferRecordPtr->myBlockSize = bufferBlockSize;
bufferRecordPtr->myPosition = 1010;
bufferRecordPtr->myReferenceID = -1;
// Set the read name length to 0.
bufferRecordPtr->myReadNameLength = 3;
bufferRecordPtr->myMapQuality = 0;
bufferRecordPtr->myBin = 4681;
bufferRecordPtr->myCigarLength = 0;
bufferRecordPtr->myFlag = 73;
bufferRecordPtr->myReadLength = 0;
bufferRecordPtr->myMateReferenceID = -1;
bufferRecordPtr->myMatePosition = 1010;
bufferRecordPtr->myInsertSize = 0;
bufferRecordPtr->myData[0] = 'H';
bufferRecordPtr->myData[1] = 'I';
bufferRecordPtr->myData[2] = 0;
////////////////////////////////////////////
// Test out of range reference sequence id.
bufferRecordPtr->myReferenceID = 100;
assert(testRecord.setBuffer((const char*)bufferRecordPtr,
bufferBlockSize + sizeof(int),
samHeader) == SamStatus::SUCCESS);
// 1 error - the read name length is 0.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
assert(errorList.numErrors() == 1);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_REF_ID);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
////////////////////////////////////////////
// Test out of range reference sequence id.
bufferRecordPtr->myReferenceID = -100;
assert(testRecord.setBuffer((const char*)bufferRecordPtr,
bufferBlockSize + sizeof(int),
samHeader) == SamStatus::SUCCESS);
// 1 error - the read name length is 0.
assert(SamValidator::isValid(samHeader, testRecord, errorList) == false);
assert(errorList.numErrors() == 1);
assert(errorList.getNextError()->getType() ==
SamValidationError::INVALID_REF_ID);
assert(errorList.getNextError() == NULL);
// Clear the error list
errorList.clear();
}
void testEmptyQual()
{
}
| mit |
activecollab/monitoring-bundle | src/SupportYard/MonitoringBundle/Tests/Unit/Monolog/QueryExecutionTest.php | 1025 | <?php
namespace SupportYard\MonitoringBundle\Tests\Unit\Monolog;
use SupportYard\FrameworkBundle\Test\TestCase;
use SupportYard\MonitoringBundle\Monolog\QueryExecution;
class QueryExecutionTest extends TestCase
{
/**
* @test
*/
public function checkInitialState()
{
$this->assertSame(0, $this->queryExecution->getTotalTime());
$this->assertSame(0, $this->queryExecution->getCount());
}
/**
* @test
*/
public function timeIsRecorded()
{
$this->queryExecution->recordTime(1);
$this->queryExecution->recordTime(2);
$this->assertSame(3, $this->queryExecution->getTotalTime());
}
/**
* @test
*/
public function counterIsIncremented()
{
$this->queryExecution->incrementCounter();
$this->queryExecution->incrementCounter();
$this->assertSame(2, $this->queryExecution->getCount());
}
protected function setUp()
{
$this->queryExecution = new QueryExecution();
}
}
| mit |
haadcode/orbit-db | src/migrations/0.21-0.22.js | 1337 | const path = require('path')
const fs = require('../fs-shim')
const Cache = require('orbit-db-cache')
const Logger = require('logplease')
const logger = Logger.create('orbit-db')
Logger.setLogLevel('ERROR')
async function migrate (OrbitDB, options, dbAddress) {
let oldCache = OrbitDB.caches[options.directory] ? OrbitDB.caches[options.directory].cache : null
let oldStore
if (!oldCache) {
const addr = (path.posix || path).join(OrbitDB.directory, dbAddress.root, dbAddress.path)
if (fs && fs.existsSync && !fs.existsSync(addr)) return
oldStore = await OrbitDB.storage.createStore(addr)
oldCache = new Cache(oldStore)
}
const _localHeads = await oldCache.get('_localHeads')
if (!_localHeads) return
const keyRoot = dbAddress.toString()
logger.debug('Attempting to migrate from old cache location')
const migrationKeys = [
'_remoteHeads',
'_localHeads',
'snapshot',
'queue'
]
for (const i in migrationKeys) {
try {
const key = path.join(keyRoot, migrationKeys[i])
const val = await oldCache.get(migrationKeys[i])
if (val) await options.cache.set(key, val)
} catch (e) {
logger.debug(e.message)
}
}
await options.cache.set(path.join(keyRoot, '_manifest'), dbAddress.root)
if (oldStore) await oldStore.close()
}
module.exports = migrate
| mit |
moljac/sharpforce | Sharpforce/Extensions.cs | 2419 | using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
namespace Sharpforce
{
public static class Extensions
{
/// <summary>
/// Extends Type class with IsAnonymous method:
/// http://www.liensberger.it/web/blog/?p=191
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is anonymous; otherwise, <c>false</c>.
/// </returns>
public static bool IsAnonymous(this Type type)
{
if (type == null) return false;
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
/// <summary>
/// Serialize this object into JSON.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson(this object obj)
{
if (obj == null) return null;
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
string json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
Debug.WriteLine("Serialization; type={0}; json={1}", obj.GetType(), json);
return json;
}
/// <summary>
/// Deserialize the string into an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ToObject<T>(this string value) where T : new()
{
if (value == null) return default(T);
try
{
return JsonConvert.DeserializeObject<T>(value);
}
catch (Exception e)
{
Debug.WriteLine(e);
return default(T);
}
}
}
} | mit |
MarkEWaite/jenkins | core/src/main/java/hudson/tools/ToolLocationNodeProperty.java | 6165 | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Tom Huybrechts, Seiji Sogabe
*
* 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 hudson.tools;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeSpecific;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* {@link NodeProperty} that allows users to specify different locations for {@link ToolInstallation}s.
*
* @since 1.286
*/
public class ToolLocationNodeProperty extends NodeProperty<Node> {
/**
* Override locations. Never null.
*/
private final List<ToolLocation> locations;
@DataBoundConstructor
public ToolLocationNodeProperty(List<ToolLocation> locations) {
if (locations == null) {
locations = new ArrayList<>();
}
this.locations = locations;
}
public ToolLocationNodeProperty(ToolLocation... locations) {
this(Arrays.asList(locations));
}
public List<ToolLocation> getLocations() {
return Collections.unmodifiableList(locations);
}
public String getHome(ToolInstallation installation) {
for (ToolLocation location : locations) {
if (location.getName().equals(installation.getName()) && location.getType() == installation.getDescriptor()) {
return location.getHome();
}
}
return null;
}
/**
* Checks if the location of the tool is overridden for the given node, and if so,
* return the node-specific home directory. Otherwise return {@code installation.getHome()}
*
* <p>
* This is the core logic behind {@link NodeSpecific#forNode(Node, TaskListener)} for {@link ToolInstallation}.
*
* @return
* never null.
* @deprecated since 2009-04-09.
* Use {@link ToolInstallation#translateFor(Node,TaskListener)}
*/
@Deprecated
public static String getToolHome(Node node, ToolInstallation installation, TaskListener log) throws IOException, InterruptedException {
String result = null;
// node-specific configuration takes precedence
ToolLocationNodeProperty property = node.getNodeProperties().get(ToolLocationNodeProperty.class);
if (property != null) {
result = property.getHome(installation);
}
if (result != null) {
return result;
}
// consult translators
for (ToolLocationTranslator t : ToolLocationTranslator.all()) {
result = t.getToolHome(node, installation, log);
if (result != null) {
return result;
}
}
// fall back is no-op
return installation.getHome();
}
@Extension @Symbol("toolLocation")
public static class DescriptorImpl extends NodePropertyDescriptor {
@Override
public String getDisplayName() {
return Messages.ToolLocationNodeProperty_displayName();
}
public DescriptorExtensionList<ToolInstallation, ToolDescriptor<?>> getToolDescriptors() {
return ToolInstallation.all();
}
public String getKey(ToolInstallation installation) {
return installation.getDescriptor().getClass().getName() + "@" + installation.getName();
}
@Override
public boolean isApplicable(Class<? extends Node> nodeType) {
return nodeType != Jenkins.class;
}
}
public static final class ToolLocation {
private final String type;
private final String name;
private final String home;
private transient volatile ToolDescriptor descriptor;
public ToolLocation(ToolDescriptor type, String name, String home) {
this.descriptor = type;
this.type = type.getClass().getName();
this.name = name;
this.home = home;
}
@DataBoundConstructor
public ToolLocation(String key, String home) {
this.type = key.substring(0, key.indexOf('@'));
this.name = key.substring(key.indexOf('@') + 1);
this.home = home;
}
public String getName() {
return name;
}
public String getHome() {
return home;
}
@SuppressWarnings("deprecation") // TODO this was mistakenly made to be the ToolDescriptor class name, rather than .id as you would expect; now baked into serial form
public ToolDescriptor getType() {
if (descriptor == null) {
descriptor = (ToolDescriptor) Descriptor.find(type);
}
return descriptor;
}
public String getKey() {
return type + "@" + name;
}
}
}
| mit |
terotic/digihel | events/views.py | 611 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
from events.models import EventsIndexPage
# Create your views here.
def event_data(request):
future = request.GET.get('future', 'False')
try:
if future.lower() == 'true':
data = EventsIndexPage.objects.get().events(future=True)
else:
data = EventsIndexPage.objects.get().events()
except EventsIndexPage.DoesNotExist:
return HttpResponseNotFound({'No events index page could be found. Please create one in Wagtail Admin.'})
return HttpResponse(data)
| mit |
stamepicmorg/Easy-ADB-Screenshoter | Sources/Screenshoter/Properties/AssemblyInfo.cs | 2044 | using System.Reflection;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Easy ADB Screenshoter")]
[assembly: AssemblyDescription("Easy ADB Screenshoter")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EpicMorg")]
[assembly: AssemblyProduct("Easy ADB Screenshoter")]
[assembly: AssemblyCopyright("Copyright © EpicMorg 2015")]
[assembly: AssemblyTrademark("EpicMorg")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("fe5ec074-207b-4809-bc39-5a4ae7667af3")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.6")]
[assembly: AssemblyFileVersion("1.0.0.6")]
[assembly: AssemblyInformationalVersion("1.0.0.6")] | mit |
TruDB/tru-type-lib | src/js/common/services/std-operator-lookup.js | 2066 | (function(){
'use strict';
var module = angular.module('std.operator.lookup', []);
module.factory('stdOperatorLookup',
[
function() {
var operatorLookup = {
'equal': {
operator: 'eq',
operatorImage: 'ico-equal',
operatorImageMessage: 'Equal To'
},
'not-equal': {
operator: 'not-eq',
operatorImage: 'ico-not-equal',
operatorImageMessage: 'Not Equal To'
},
'greater-than': {
operator: 'gt',
operatorImage: 'ico-greater-than',
operatorImageMessage: 'Greater Than'
},
'greater-than-or-equal': {
operator: 'ge',
operatorImage: 'ico-greater-than-or-equal',
operatorImageMessage: 'Greater Than Or Equal To'
},
'less-than': {
operator: 'lt',
operatorImage: 'ico-less-than',
operatorImageMessage: 'Less Than'
},
'less-than-or-equal': {
operator: 'le',
operatorImage: 'ico-less-than-or-equal',
operatorImageMessage: 'Less Than Or Equal To'
},
'contains': {
operator: 'contains',
operatorImage: 'ico-contains',
operatorImageMessage: 'Contains'
},
undefined: {
operator: 'eq',
operatorImage: 'ico-equal',
operatorImageMessage: 'Equal To'
}
};
return operatorLookup;
}
]);
})();
| mit |
JustynaStebel/l | lib/generators/l/facebook/templates/routes.rb | 94 | resource :facebook, controller: :facebook, only: [] do
get :index
post :index
end
| mit |
morishitter/postcss-annotation-include | index.js | 5865 | var parse = require('css-annotation').parse
module.exports = function plugin (options) {
options = options || {}
return function (root) {
css = options.css !== undefined ? options.css : root;
removeCheck = options.removeBase !== undefined ? options.removeBase : true;
var matchedRules = []
var annotations = parse(css);
root.walkRules(function (node) {
if (checkInclude(node)) {
annotations.forEach(function (annotation) {
if (node.selector === annotation.rule) {
var res = {}
res.include = node.selector
if (!Array.isArray(annotation.include)) {
annotation.include = [annotation.include]
}
res.base = annotation.include
matchedRules.push(res)
}
})
}
})
var tmpMatched = []
var newMatched = []
matchedRules.forEach(function (matchedRule) {
matchedRule.base.forEach(function (base) {
tmpMatched.push({
include: matchedRule.include,
base: base
})
})
})
tmpMatched.forEach(function (tmp, i) {
var tmpSelectors = []
var count = true
var isOne = true
for (var j = i + 1; j < tmpMatched.length; j++) {
if (tmp.base === tmpMatched[j].base) {
if (count) {
tmpSelectors.push(tmp.include)
}
tmpSelectors.push(tmpMatched[j].include)
count = false
isOne = false
tmpMatched.splice(j, 1)
}
}
var newSelector = tmpSelectors.join(',\n')
if (newSelector) {
newMatched.push({
include: newSelector,
base: tmp.base
})
}
if (isOne) {
newMatched.push({
include: tmp.include,
base: tmp.base
})
}
})
matchedRules = newMatched
includeTmp = []
root.walkRules(function (rule) {
if (checkBase(rule)) {
var decls = []
rule.nodes.forEach(function (child) {
if (child.type === 'decl') {
decls.push({
prop: child.prop,
value: child.value
})
}
})
includeTmp.push({
selector: rule.selector,
decls: decls
})
}
})
matchedRules.forEach(function (matchedRule) {
root.walk(function (rule) {
rule.raws.semicolon = true;
if (rule.type === 'atrule') {
rule.nodes.forEach(function (rule) {
if (checkInclude(rule)) {
if (matchedRule.include === rule.selector) {
includeTmp.forEach(function (tmp) {
if (tmp.selector === matchedRule.base && matchedRule.include === rule.selector) {
if (removeCheck) removeBase(root)
}
})
}
}
})
}
else {
if (checkInclude(rule)) {
includeTmp.forEach(function (tmp) {
if (tmp.selector === matchedRule.base && matchedRule.include === rule.selector) {
tmp.decls.forEach(function (decl) {
rule.append({
prop: decl.prop,
value: decl.value
})
})
if (removeCheck) removeBase(root)
}
})
}
}
})
})
return root
}
}
function removeBase (root) {
root.walk(function (rule) {
if (rule.type === 'rule' && checkBase(rule) && !rule.change) {
rule.remove()
}
if (rule.type === 'atrule') {
rule.walk(function (node) {
if (node.type === 'rule' && checkBase(node)) {
node.remove()
}
})
}
})
}
function checkBase (node) {
if (node.nodes) {
var children = node.nodes
var text = ''
children.forEach(function (child) {
if (child.type === 'comment') text = child.text
})
if (text.match(/\@base/)) return true
}
return false
}
function baseRules (root) {
var baseRules = []
root.walkRules(function (rule) {
if (checkBase(rule)) {
baseRules.push(rule)
}
})
return baseRules
}
function checkInclude (node) {
if (node.nodes) {
var children = node.nodes
var text = ''
children.forEach(function (child) {
if (child.type === 'comment') text = child.text
})
if (text.match(/\@include/)) return true
}
return false
}
function includeRules (root) {
var includeRules = []
root.walkRules(function (rule) {
if (checkInclude(rule)) {
includeRules.push(rule)
}
})
return includeRules
}
| mit |
sleepinglion/sleepinglion | node_modules/@babel/helper-optimise-call-expression/lib/index.js | 1668 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var t = _interopRequireWildcard(require("@babel/types"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _default(callee, thisNode, args, optional) {
if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, {
name: "arguments"
})) {
return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]);
} else {
if (optional) {
return t.optionalCallExpression(t.optionalMemberExpression(callee, t.identifier("call"), false, true), [thisNode, ...args], false);
}
return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode, ...args]);
}
} | mit |
guotao2000/ecmall | temp/caches/0440/6316b14f786e2567eef947ca88078dd1.cache.php | 15769 | <?php
/**
* @Created By ECMall PhpCacheServer
* @Time:2015-01-17 19:40:58
*/
if(filemtime(__FILE__) + 1800 < time())return false;
return array (
'id' => 4012,
'goods' =>
array (
'goods_id' => '4012',
'store_id' => '132',
'type' => 'material',
'goods_name' => '【39元区】羊毛外套 羊绒大衣',
'description' => '<p style="text-align: center;"><img src="http://wap.bqmart.cn/data/files/store_132/goods_15/201501041620158751.jpg" alt="39元_01.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_16/201501041620162903.jpg" alt="39元_02.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_16/201501041620169668.jpg" alt="39元_03.jpg" /></p>',
'cate_id' => '842',
'cate_name' => '洗衣 39元区',
'brand' => '倍全',
'spec_qty' => '0',
'spec_name_1' => '',
'spec_name_2' => '',
'if_show' => '1',
'if_seckill' => '0',
'closed' => '0',
'close_reason' => NULL,
'add_time' => '1420330828',
'last_update' => '1420484439',
'default_spec' => '4016',
'default_image' => 'data/files/store_132/goods_186/small_201501041619467368.jpg',
'recommended' => '0',
'cate_id_1' => '838',
'cate_id_2' => '842',
'cate_id_3' => '0',
'cate_id_4' => '0',
'price' => '39.00',
'tags' =>
array (
0 => '羊毛外套 羊绒大衣 洗衣干洗 干洗',
),
'cuxiao_ids' => NULL,
'from_goods_id' => '0',
'quanzhong' => NULL,
'state' => '1',
'_specs' =>
array (
0 =>
array (
'spec_id' => '4016',
'goods_id' => '4012',
'spec_1' => '',
'spec_2' => '',
'color_rgb' => '',
'price' => '39.00',
'stock' => '995',
'sku' => '',
),
),
'_images' =>
array (
0 =>
array (
'image_id' => '1477',
'goods_id' => '4012',
'image_url' => 'data/files/store_132/goods_186/201501041619467368.jpg',
'thumbnail' => 'data/files/store_132/goods_186/small_201501041619467368.jpg',
'sort_order' => '1',
'file_id' => '5952',
),
1 =>
array (
'image_id' => '1478',
'goods_id' => '4012',
'image_url' => 'data/files/store_132/goods_196/201501041619568452.jpg',
'thumbnail' => 'data/files/store_132/goods_196/small_201501041619568452.jpg',
'sort_order' => '255',
'file_id' => '5953',
),
2 =>
array (
'image_id' => '1479',
'goods_id' => '4012',
'image_url' => 'data/files/store_132/goods_7/201501041620075114.jpg',
'thumbnail' => 'data/files/store_132/goods_7/small_201501041620075114.jpg',
'sort_order' => '255',
'file_id' => '5954',
),
),
'_scates' =>
array (
),
'views' => '24',
'collects' => '0',
'carts' => '9',
'orders' => '4',
'sales' => '1',
'comments' => '0',
'related_info' =>
array (
),
),
'store_data' =>
array (
'store_id' => '132',
'store_name' => '大地锐城店',
'owner_name' => '倍全',
'owner_card' => '370832200104057894',
'region_id' => '2213',
'region_name' => '中国 山东 济南 历下区',
'address' => '',
'zipcode' => '',
'tel' => '15666660007',
'sgrade' => '系统默认',
'apply_remark' => '',
'credit_value' => '0',
'praise_rate' => '0.00',
'domain' => '',
'state' => '1',
'close_reason' => '',
'add_time' => '1418929047',
'end_time' => '0',
'certification' => 'autonym,material',
'sort_order' => '65535',
'recommended' => '0',
'theme' => '',
'store_banner' => NULL,
'store_logo' => 'data/files/store_132/other/store_logo.jpg',
'description' => '',
'image_1' => '',
'image_2' => '',
'image_3' => '',
'im_qq' => '',
'im_ww' => '',
'im_msn' => '',
'hot_search' => '',
'business_scope' => '',
'online_service' =>
array (
),
'hotline' => '',
'pic_slides' => '',
'pic_slides_wap' => '{"1":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_1.jpg","link":"http://wap.bqmart.cn/index.php?app=zhuanti&id=7"},"2":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_2.jpg","link":"http://wap.bqmart.cn/index.php?keyword= %E6%B4%97%E8%A1%A3%E5%B9%B2%E6%B4%97&app=store&act=search&id=132"},"3":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_3.jpg","link":"http://wap.bqmart.cn/index.php?app=search&cate_id=691&id=132"}}',
'enable_groupbuy' => '0',
'enable_radar' => '1',
'waptheme' => '',
'is_open_pay' => '0',
'area_peisong' => NULL,
'power_coupon' => '0',
's_long' => '117.096102',
's_lat' => '36.68974',
'user_name' => 'bq516',
'email' => '111111111@qq.com',
'certifications' =>
array (
0 => 'autonym',
1 => 'material',
),
'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif',
'store_owner' =>
array (
'user_id' => '132',
'user_name' => 'bq516',
'email' => '111111111@qq.com',
'password' => '9cbf8a4dcb8e30682b927f352d6559a0',
'real_name' => '新生活家园',
'gender' => '0',
'birthday' => '',
'phone_tel' => NULL,
'phone_mob' => NULL,
'im_qq' => '',
'im_msn' => '',
'im_skype' => NULL,
'im_yahoo' => NULL,
'im_aliww' => NULL,
'reg_time' => '1418928900',
'last_login' => '1421458851',
'last_ip' => '119.163.95.68',
'logins' => '118',
'ugrade' => '0',
'portrait' => NULL,
'outer_id' => '0',
'activation' => NULL,
'feed_config' => NULL,
'uin' => '0',
'parentid' => '0',
'user_level' => '0',
'from_weixin' => '0',
'wx_openid' => NULL,
'wx_nickname' => NULL,
'wx_city' => NULL,
'wx_country' => NULL,
'wx_province' => NULL,
'wx_language' => NULL,
'wx_headimgurl' => NULL,
'wx_subscribe_time' => '0',
'wx_id' => '0',
'from_public' => '0',
'm_storeid' => '0',
),
'store_navs' =>
array (
),
'kmenus' => false,
'kmenusinfo' =>
array (
),
'radio_new' => 1,
'radio_recommend' => 1,
'radio_hot' => 1,
'goods_count' => '1057',
'store_gcates' =>
array (
),
'functions' =>
array (
'editor_multimedia' => 'editor_multimedia',
'coupon' => 'coupon',
'groupbuy' => 'groupbuy',
'enable_radar' => 'enable_radar',
'seckill' => 'seckill',
),
'hot_saleslist' =>
array (
3459 =>
array (
'goods_id' => '3459',
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'sales' => '7',
),
3043 =>
array (
'goods_id' => '3043',
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'sales' => '7',
),
3650 =>
array (
'goods_id' => '3650',
'goods_name' => '美汁源果粒橙450ml果汁',
'default_image' => 'data/files/store_132/goods_5/small_201412181056459752.jpg',
'price' => '3.00',
'sales' => '5',
),
3457 =>
array (
'goods_id' => '3457',
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'sales' => '4',
),
3666 =>
array (
'goods_id' => '3666',
'goods_name' => '乐百氏脉动水蜜桃600ml',
'default_image' => 'data/files/store_132/goods_101/small_201412181105019926.jpg',
'price' => '4.00',
'sales' => '3',
),
3230 =>
array (
'goods_id' => '3230',
'goods_name' => '圣牧全程有机奶1X12X250ml',
'default_image' => 'data/files/store_132/goods_69/small_201412171617496624.jpg',
'price' => '98.00',
'sales' => '1',
),
3708 =>
array (
'goods_id' => '3708',
'goods_name' => '怡泉+c500ml功能饮料',
'default_image' => 'data/files/store_132/goods_115/small_201412181125154319.jpg',
'price' => '4.00',
'sales' => '1',
),
3660 =>
array (
'goods_id' => '3660',
'goods_name' => '雪碧清爽柠檬味汽水330ml',
'default_image' => 'data/files/store_132/goods_150/small_201412181102308979.jpg',
'price' => '2.00',
'sales' => '1',
),
4012 =>
array (
'goods_id' => '4012',
'goods_name' => '【39元区】羊毛外套 羊绒大衣',
'default_image' => 'data/files/store_132/goods_186/small_201501041619467368.jpg',
'price' => '39.00',
'sales' => '1',
),
3983 =>
array (
'goods_id' => '3983',
'goods_name' => '飘零大叔花生牛轧糖牛奶糖',
'default_image' => 'data/files/store_132/goods_42/small_201412181530423503.jpg',
'price' => '13.50',
'sales' => '0',
),
),
'collect_goodslist' =>
array (
3457 =>
array (
'goods_id' => '3457',
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'collects' => '1',
),
3777 =>
array (
'goods_id' => '3777',
'goods_name' => '海天苹果醋450ml',
'default_image' => 'data/files/store_132/goods_47/small_201412181157271271.jpg',
'price' => '6.50',
'collects' => '1',
),
3570 =>
array (
'goods_id' => '3570',
'goods_name' => '康师傅蜂蜜绿茶490ml',
'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg',
'price' => '3.00',
'collects' => '1',
),
3459 =>
array (
'goods_id' => '3459',
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'collects' => '1',
),
5494 =>
array (
'goods_id' => '5494',
'goods_name' => '青岛啤酒奥古特500ml',
'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg',
'price' => '9.80',
'collects' => '1',
),
3043 =>
array (
'goods_id' => '3043',
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'collects' => '1',
),
3871 =>
array (
'goods_id' => '3871',
'goods_name' => '品食客手抓饼葱香味400g速冻食品',
'default_image' => 'data/files/store_132/goods_103/small_201412181421434694.jpg',
'price' => '11.80',
'collects' => '1',
),
3800 =>
array (
'goods_id' => '3800',
'goods_name' => '蒙牛冠益乳草莓味风味发酵乳450g',
'default_image' => 'data/files/store_132/goods_12/small_201412181310121305.jpg',
'price' => '13.50',
'collects' => '1',
),
3130 =>
array (
'goods_id' => '3130',
'goods_name' => '迪士尼巧克力味心宠杯25g',
'default_image' => 'data/files/store_132/goods_110/small_201412171515106856.jpg',
'price' => '2.50',
'collects' => '1',
),
3771 =>
array (
'goods_id' => '3771',
'goods_name' => '亚太糖水梨罐头450g',
'default_image' => 'data/files/store_132/goods_181/small_201412181153017833.jpg',
'price' => '7.00',
'collects' => '0',
),
),
'left_rec_goods' =>
array (
3043 =>
array (
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'sales' => '7',
'goods_id' => '3043',
),
3457 =>
array (
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'sales' => '4',
'goods_id' => '3457',
),
3459 =>
array (
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'sales' => '7',
'goods_id' => '3459',
),
3570 =>
array (
'goods_name' => '康师傅蜂蜜绿茶490ml',
'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg',
'price' => '3.00',
'sales' => '0',
'goods_id' => '3570',
),
5494 =>
array (
'goods_name' => '青岛啤酒奥古特500ml',
'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg',
'price' => '9.80',
'sales' => '0',
'goods_id' => '5494',
),
),
),
'cur_local' =>
array (
0 =>
array (
'text' => '所有分类',
'url' => 'index.php?app=category',
),
1 =>
array (
'text' => '洗衣',
'url' => 'index.php?app=search&cate_id=838',
),
2 =>
array (
'text' => '39元区',
'url' => 'index.php?app=search&cate_id=842',
),
3 =>
array (
'text' => '商品详情',
),
),
'share' =>
array (
4 =>
array (
'title' => '开心网',
'link' => 'http://www.kaixin001.com/repaste/share.php?rtitle=%E3%80%9039%E5%85%83%E5%8C%BA%E3%80%91%E7%BE%8A%E6%AF%9B%E5%A4%96%E5%A5%97+%E7%BE%8A%E7%BB%92%E5%A4%A7%E8%A1%A3-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E&rurl=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D4012',
'type' => 'share',
'sort_order' => 255,
'logo' => 'data/system/kaixin001.gif',
),
3 =>
array (
'title' => 'QQ书签',
'link' => 'http://shuqian.qq.com/post?from=3&title=%E3%80%9039%E5%85%83%E5%8C%BA%E3%80%91%E7%BE%8A%E6%AF%9B%E5%A4%96%E5%A5%97+%E7%BE%8A%E7%BB%92%E5%A4%A7%E8%A1%A3-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D4012&jumpback=2&noui=1',
'type' => 'collect',
'sort_order' => 255,
'logo' => 'data/system/qqshuqian.gif',
),
2 =>
array (
'title' => '人人网',
'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D4012&title=%E3%80%9039%E5%85%83%E5%8C%BA%E3%80%91%E7%BE%8A%E6%AF%9B%E5%A4%96%E5%A5%97+%E7%BE%8A%E7%BB%92%E5%A4%A7%E8%A1%A3-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E',
'type' => 'share',
'sort_order' => 255,
'logo' => 'data/system/renren.gif',
),
1 =>
array (
'title' => '百度收藏',
'link' => 'http://cang.baidu.com/do/add?it=%E3%80%9039%E5%85%83%E5%8C%BA%E3%80%91%E7%BE%8A%E6%AF%9B%E5%A4%96%E5%A5%97+%E7%BE%8A%E7%BB%92%E5%A4%A7%E8%A1%A3-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D4012&fr=ien#nw=1',
'type' => 'collect',
'sort_order' => 255,
'logo' => 'data/system/baidushoucang.gif',
),
),
);
?> | mit |
z38/postmark-inbound-php | example/with_composer/vendor/composer/autoload_namespaces.php | 207 | <?php
// autoload_namespace.php generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Postmark' => $vendorDir . '/jjaffeux/postmark-inbound-php/lib/',
);
| mit |
imasaru/sabbath-school-android-2 | app/src/main/java/com/cryart/sabbathschool/misc/SSConstants.java | 5633 | /*
* Copyright (c) 2016 Adventech <info@adventech.io>
*
* 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 com.cryart.sabbathschool.misc;
public class SSConstants {
public static final int SS_APP_RATE_INSTALL_DAYS = 7;
public static final int SS_GOOGLE_SIGN_IN_CODE = 9001;
public static final String SS_DATE_FORMAT = "dd/MM/yyyy";
public static final String SS_DATE_FORMAT_OUTPUT = "d MMMM";
public static final String SS_DATE_FORMAT_OUTPUT_DAY = "EEEE. d MMMM";
public static final String SS_FIREBASE_API_PREFIX = "/api/v1";
public static final String SS_FIREBASE_LANGUAGES_DATABASE = SS_FIREBASE_API_PREFIX + "/languages";
public static final String SS_FIREBASE_QUARTERLIES_DATABASE = SS_FIREBASE_API_PREFIX + "/quarterlies";
public static final String SS_FIREBASE_QUARTERLY_INFO_DATABASE = SS_FIREBASE_API_PREFIX + "/quarterly-info";
public static final String SS_FIREBASE_LESSON_INFO_DATABASE = SS_FIREBASE_API_PREFIX + "/lesson-info";
public static final String SS_FIREBASE_READS_DATABASE = SS_FIREBASE_API_PREFIX + "/reads";
public static final String SS_FIREBASE_HIGHLIGHTS_DATABASE = "highlights";
public static final String SS_FIREBASE_COMMENTS_DATABASE = "comments";
public static final String SS_FIREBASE_SUGGESTIONS_DATABASE = "suggestions";
public static final String SS_QUARTERLY_INDEX_EXTRA = "SS_QUARTERLY_INDEX";
public static final String SS_LESSON_INDEX_EXTRA = "SS_LESSON_INDEX";
public static final String SS_READ_INDEX_EXTRA = "SS_READ_INDEX";
public static final String SS_READ_VERSE_EXTRA = "SS_READ_VERSE_EXTRA";
public static final String SS_COLOR_THEME_LAST_PRIMARY = "SS_COLOR_THEME_LAST_PRIMARY";
public static final String SS_COLOR_THEME_LAST_PRIMARY_DARK = "SS_COLOR_THEME_LAST_PRIMARY_DARK";
public static final String SS_REMINDER_TIME_SETTINGS_FORMAT = "HH:mm";
public static final String SS_SETTINGS_REMINDER_ENABLED_KEY = "ss_settings_reminder_enabled";
public static final boolean SS_SETTINGS_REMINDER_ENABLED_DEFAULT_VALUE = true;
public static final String SS_SETTINGS_REMINDER_TIME_KEY = "ss_settings_reminder_time";
public static final String SS_SETTINGS_REMINDER_TIME_DEFAULT_VALUE = "08:00";
public static final String SS_SETTINGS_THEME_KEY = "ss_settings_display_options_theme";
public static final String SS_SETTINGS_FONT_KEY = "ss_settings_display_options_font";
public static final String SS_SETTINGS_SIZE_KEY = "ss_settings_display_options_size";
public static final String SS_LAST_LANGUAGE_INDEX = "ss_last_language_index";
public static final String SS_LAST_QUARTERLY_INDEX = "ss_last_quarterly_index";
public static final String SS_USER_NAME_INDEX = "ss_user_name_index";
public static final String SS_USER_EMAIL_INDEX = "ss_user_email_index";
public static final String SS_USER_PHOTO_INDEX = "ss_user_photo_index";
public static final String SS_LAST_BIBLE_VERSION_USED = "ss_last_bible_version_used";
public static final String SS_LANGUAGE_FILTER_PROMPT_SEEN = "ss_language_filter_prompt_seen";
public static final String SS_READER_APP_BASE_URL = "file:///android_asset/reader/";
public static final String SS_READER_APP_ENTRYPOINT = "reader/index.html";
public static final String SS_EVENT_APP_OPEN = "ss_app_open";
public static final String SS_EVENT_LANGUAGE_FILTER = "ss_language_filter";
public static final String SS_EVENT_READ_OPEN = "ss_read_open";
public static final String SS_EVENT_HIGHLIGHTS_OPEN = "ss_highlights_open";
public static final String SS_EVENT_NOTES_OPEN = "ss_notes_open";
public static final String SS_EVENT_ABOUT_OPEN = "ss_about_open";
public static final String SS_EVENT_BIBLE_OPEN = "ss_bible_open";
public static final String SS_EVENT_SETTINGS_OPEN = "ss_settings_open";
public static final String SS_EVENT_READ_OPTIONS_OPEN = "ss_read_options_open";
public static final String SS_EVENT_TEXT_HIGHLIGHTED = "ss_text_highlighted";
public static final String SS_EVENT_COMMENT_CREATED = "ss_comment_created";
public static final String SS_EVENT_PARAM_USER_ID = "ss_user_id";
public static final String SS_EVENT_PARAM_USER_NAME = "ss_user_name";
public static final String SS_EVENT_PARAM_LESSON_INDEX = "ss_lesson_index";
public static final String SS_EVENT_PARAM_READ_INDEX = "ss_read_index";
public static final String SS_READER_ARTIFACT_NAME = "sabbath-school-reader-latest.zip";
public static final String SS_READER_ARTIFACT_CREATION_TIME = "sabbath-school-reader-creation-time";
}
| mit |
jooorooo/embed | tests/ImagesBlacklistTest.php | 1640 | <?php
class ImagesBlacklistTest extends TestCaseBase
{
public function testPlainText()
{
$this->assertEmbed(
'https://github.com/oscarotero/Embed',
[
'image' => 'https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif',
], [
'adapter' => [
'config' => [
'imagesBlacklist' => [
'https://avatars1.githubusercontent.com/u/377873?v=3&s=400',
],
],
]
]
);
}
public function testPlainUrlMatch()
{
$this->assertEmbed(
'https://github.com/oscarotero/Embed',
[
'image' => 'https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif',
], [
'adapter' => [
'config' => [
'imagesBlacklist' => [
'*.githubusercontent.com*',
],
],
]
]
);
}
public function testAuthorizedImage()
{
$this->assertEmbed(
'https://github.com/oscarotero/Embed',
[
'image' => 'https://avatars1.githubusercontent.com/u/377873?v=3&s=400',
], [
'adapter' => [
'config' => [
'imagesBlacklist' => [
'*/octocat-spinner-*',
],
],
]
]
);
}
}
| mit |
npmweb/community-service | app/config/myconfig.php | 189 | <?php
return array(
'string' => 'This is a config that stays the same!',
'inherited' => 'This is inherited; this is the default version.',
'array' => ['this is','an array']
);
| mit |
lgollut/material-ui | packages/material-ui-icons/src/SportsSoccerRounded.js | 716 | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 3.3l1.35-.95c1.82.56 3.37 1.76 4.38 3.34l-.39 1.34-1.35.46L13 6.7V5.3zm-3.35-.95L11 5.3v1.4L7.01 9.49l-1.35-.46-.39-1.34c1.01-1.57 2.56-2.77 4.38-3.34zM7.08 17.11l-1.14.1C4.73 15.81 4 13.99 4 12c0-.12.01-.23.02-.35l1-.73 1.38.48 1.46 4.34-.78 1.37zm7.42 2.48c-.79.26-1.63.41-2.5.41s-1.71-.15-2.5-.41l-.69-1.49.64-1.1h5.11l.64 1.11-.7 1.48zM14.27 15H9.73l-1.35-4.02L12 8.44l3.63 2.54L14.27 15zm3.79 2.21l-1.14-.1-.79-1.37 1.46-4.34 1.39-.47 1 .73c.01.11.02.22.02.34 0 1.99-.73 3.81-1.94 5.21z" />
, 'SportsSoccerRounded');
| mit |
justinshalom/CD | AngleSharp/AngleSharp/Dom/Html/HtmlParamElement.cs | 920 | namespace AngleSharp.Dom.Html
{
using AngleSharp.Extensions;
using AngleSharp.Html;
using System;
/// <summary>
/// Represents a param element.
/// </summary>
sealed class HtmlParamElement : HtmlElement, IHtmlParamElement
{
#region ctor
public HtmlParamElement(Document owner, String prefix = null)
: base(owner, TagNames.Param, prefix, NodeFlags.Special | NodeFlags.SelfClosing)
{
}
#endregion
#region Properties
public String Value
{
get { return this.GetOwnAttribute(AttributeNames.Value); }
set { this.SetOwnAttribute(AttributeNames.Value, value); }
}
public String Name
{
get { return this.GetOwnAttribute(AttributeNames.Name); }
set { this.SetOwnAttribute(AttributeNames.Name, value); }
}
#endregion
}
}
| mit |
qoobaa/sms | vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb | 48993 | require "date"
require 'action_view/helpers/tag_helper'
module ActionView
module Helpers
# The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the
# select-type methods share a number of common options that are as follows:
#
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
# would give birthday[month] instead of date[month] if passed to the select_month method.
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
# the select_month method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of
# "date[month]".
module DateHelper
# Reports the approximate distance in time between two Time or Date objects or integers as seconds.
# Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs
# Distances are reported based on the following table:
#
# 0 <-> 29 secs # => less than a minute
# 30 secs <-> 1 min, 29 secs # => 1 minute
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
# 89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
# 23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs # => 1 day
# 47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
# 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
# 1 yr <-> 2 yrs minus 1 secs # => about 1 year
# 2 yrs <-> max time or date # => over [2..X] years
#
# With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds:
# 0-4 secs # => less than 5 seconds
# 5-9 secs # => less than 10 seconds
# 10-19 secs # => less than 20 seconds
# 20-39 secs # => half a minute
# 40-59 secs # => less than a minute
# 60-89 secs # => 1 minute
#
# ==== Examples
# from_time = Time.now
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
# distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds
# distance_of_time_in_words(from_time, 3.years.from_now) # => over 3 years
# distance_of_time_in_words(from_time, from_time + 60.hours) # => about 3 days
# distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute
# distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years
#
# to_time = Time.now + 6.years + 19.days
# distance_of_time_in_words(from_time, to_time, true) # => over 6 years
# distance_of_time_in_words(to_time, from_time, true) # => over 6 years
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
#
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale|
case distance_in_minutes
when 0..1
return distance_in_minutes == 0 ?
locale.t(:less_than_x_minutes, :count => 1) :
locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds
case distance_in_seconds
when 0..4 then locale.t :less_than_x_seconds, :count => 5
when 5..9 then locale.t :less_than_x_seconds, :count => 10
when 10..19 then locale.t :less_than_x_seconds, :count => 20
when 20..39 then locale.t :half_a_minute
when 40..59 then locale.t :less_than_x_minutes, :count => 1
else locale.t :x_minutes, :count => 1
end
when 2..44 then locale.t :x_minutes, :count => distance_in_minutes
when 45..89 then locale.t :about_x_hours, :count => 1
when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
when 1440..2879 then locale.t :x_days, :count => 1
when 2880..43199 then locale.t :x_days, :count => (distance_in_minutes / 1440).round
when 43200..86399 then locale.t :about_x_months, :count => 1
when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes / 43200).round
when 525600..1051199 then locale.t :about_x_years, :count => 1
else locale.t :over_x_years, :count => (distance_in_minutes / 525600).round
end
end
end
# Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
#
# ==== Examples
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
# time_ago_in_words(Time.now - 15.hours) # => 15 hours
# time_ago_in_words(Time.now) # => less than a minute
#
# from_time = Time.now - 3.days - 14.minutes - 25.seconds # => 3 days
def time_ago_in_words(from_time, include_seconds = false)
distance_of_time_in_words(from_time, Time.now, include_seconds)
end
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
# attribute (identified by +method+) on an object assigned to the template (identified by +object+). You can
# the output in the +options+ hash.
#
# ==== Options
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
# "2" instead of "February").
# * <tt>:use_short_month</tt> - Set to true if you want to use the abbreviated month name instead of the full
# name (e.g. "Feb" instead of "February").
# * <tt>:add_month_number</tt> - Set to true if you want to show both, the month's number and name (e.g.
# "2 - February" instead of "February").
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
# Note: You can also use Rails' new i18n functionality for this.
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
# first of the given month in order to not create invalid dates like 31 February.
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
# as a hidden field instead of showing a select field.
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> do
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
# dates.
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
# or the given prompt string.
#
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
#
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
#
# ==== Examples
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
# date_select("post", "written_on")
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
# # with the year in the year drop down box starting at 1995.
# date_select("post", "written_on", :start_year => 1995)
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
# # and without a day select box.
# date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true,
# :discard_day => true, :include_blank => true)
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
# # with the fields ordered as day, month, year rather than month, day, year.
# date_select("post", "written_on", :order => [:day, :month, :year])
#
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
# # lacking a year field.
# date_select("user", "birthday", :order => [:month, :day])
#
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
# # which is initially set to the date 3 days from the current date
# date_select("post", "written_on", :default => 3.days.from_now)
#
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
# # that will have a default day of 20.
# date_select("credit_card", "bill_due", :default => { :day => 20 })
#
# # Generates a date select with custom prompts
# date_select("post", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' })
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
#
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
# all month choices are valid.
def date_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_date_select_tag(options, html_options)
end
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
# +object+). You can include the seconds with <tt>:include_seconds</tt>.
#
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
# <tt>:ignore_date</tt> is set to +true+.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute
# time_select("post", "sunrise")
#
# # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted
# # attribute
# time_select("order", "submitted")
#
# # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute
# time_select("mail", "sent_at")
#
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in
# # the sunrise attribute.
# time_select("post", "start_time", :include_seconds => true)
#
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in
# # the submission_time attribute.
# time_select("entry", "submission_time", :include_seconds => true)
#
# # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45.
# time_select 'game', 'game_time', {:minute_step => 15}
#
# # Creates a time select tag with a custom prompt. Use :prompt => true for generic prompts.
# time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
# time_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# time_select("post", "written_on", :prompt => true) # generic prompts for all
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
#
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
# all month choices are valid.
def time_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_time_select_tag(options, html_options)
end
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
# by +object+). Examples:
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on
# # attribute
# datetime_select("post", "written_on")
#
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
# # post variable in the written_on attribute.
# datetime_select("post", "written_on", :start_year => 1995)
#
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
# # be stored in the trip variable in the departing attribute.
# datetime_select("trip", "departing", :default => 3.days.from_now)
#
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the post variable
# # as the written_on attribute.
# datetime_select("post", "written_on", :discard_type => true)
#
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts.
# datetime_select("post", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# datetime_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# datetime_select("post", "written_on", :prompt => true) # generic prompts for all
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
def datetime_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_datetime_select_tag(options, html_options)
end
# Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
# control visual display of the elements.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_date_time = Time.now + 4.days
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# select_datetime(my_date_time)
#
# # Generates a datetime select that defaults to today (no specified datetime)
# select_datetime()
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with the fields ordered year, month, day rather than month, day, year.
# select_datetime(my_date_time, :order => [:year, :month, :day])
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with a '/' between each date field.
# select_datetime(my_date_time, :date_separator => '/')
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
# # separated by a comma (',').
# select_datetime(my_date_time, :date_separator => '/', :time_separator => '', :datetime_separator => ',')
#
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
# # my_date_time (four days after today)
# select_datetime(my_date_time, :discard_type => true)
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # prefixed with 'payday' rather than 'date'
# select_datetime(my_date_time, :prefix => 'payday')
#
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts.
# select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours
# select_datetime(my_date_time, :prompt => true) # generic prompts for all
#
def select_datetime(datetime = Time.current, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_datetime
end
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol,
# it will be appended onto the <tt>:order</tt> passed in.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_date = Time.today + 6.days
#
# # Generates a date select that defaults to the date in my_date (six days after today)
# select_date(my_date)
#
# # Generates a date select that defaults to today (no specified date)
# select_date()
#
# # Generates a date select that defaults to the date in my_date (six days after today)
# # with the fields ordered year, month, day rather than month, day, year.
# select_date(my_date, :order => [:year, :month, :day])
#
# # Generates a date select that discards the type of the field and defaults to the date in
# # my_date (six days after today)
# select_date(my_date, :discard_type => true)
#
# # Generates a date select that defaults to the date in my_date,
# # which has fields separated by '/'
# select_date(my_date, :date_separator => '/')
#
# # Generates a date select that defaults to the datetime in my_date (six days after today)
# # prefixed with 'payday' rather than 'date'
# select_date(my_date, :prefix => 'payday')
#
# # Generates a date select with a custom prompt. Use :prompt=>true for generic prompts.
# select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours
# select_date(my_date, :prompt => true) # generic prompts for all
#
def select_date(date = Date.current, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_date
end
# Returns a set of html select-tags (one for hour and minute)
# You can set <tt>:time_separator</tt> key to format the output, and
# the <tt>:include_seconds</tt> option to include an input for seconds.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
#
# # Generates a time select that defaults to the time in my_time
# select_time(my_time)
#
# # Generates a time select that defaults to the current time (no specified time)
# select_time()
#
# # Generates a time select that defaults to the time in my_time,
# # which has fields separated by ':'
# select_time(my_time, :time_separator => ':')
#
# # Generates a time select that defaults to the time in my_time,
# # that also includes an input for seconds
# select_time(my_time, :include_seconds => true)
#
# # Generates a time select that defaults to the time in my_time, that has fields
# # separated by ':' and includes an input for seconds
# select_time(my_time, :time_separator => ':', :include_seconds => true)
#
# # Generates a time select with a custom prompt. Use :prompt=>true for generic prompts.
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
# select_time(my_time, :prompt => true) # generic prompts for all
#
def select_time(datetime = Time.current, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_time
end
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
# The <tt>second</tt> can also be substituted for a second number.
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
#
# ==== Examples
# my_time = Time.now + 16.minutes
#
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
# select_second(my_time)
#
# # Generates a select field for seconds that defaults to the number given
# select_second(33)
#
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
# # that is named 'interval' rather than 'second'
# select_second(my_time, :field_name => 'interval')
#
# # Generates a select field for seconds with a custom prompt. Use :prompt=>true for a
# # generic prompt.
# select_minute(14, :prompt => 'Choose seconds')
#
def select_second(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_second
end
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
# selected. The <tt>minute</tt> can also be substituted for a minute number.
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
#
# ==== Examples
# my_time = Time.now + 6.hours
#
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
# select_minute(my_time)
#
# # Generates a select field for minutes that defaults to the number given
# select_minute(14)
#
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second'
# select_minute(my_time, :field_name => 'stride')
#
# # Generates a select field for minutes with a custom prompt. Use :prompt=>true for a
# # generic prompt.
# select_minute(14, :prompt => 'Choose minutes')
#
def select_minute(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_minute
end
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
# The <tt>hour</tt> can also be substituted for a hour number.
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
#
# ==== Examples
# my_time = Time.now + 6.hours
#
# # Generates a select field for hours that defaults to the hour for the time in my_time
# select_hour(my_time)
#
# # Generates a select field for hours that defaults to the number given
# select_hour(13)
#
# # Generates a select field for hours that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second'
# select_hour(my_time, :field_name => 'stride')
#
# # Generates a select field for hours with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_hour(13, :prompt =>'Choose hour')
#
def select_hour(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_hour
end
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
# The <tt>date</tt> can also be substituted for a hour number.
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
#
# ==== Examples
# my_date = Time.today + 2.days
#
# # Generates a select field for days that defaults to the day for the date in my_date
# select_day(my_time)
#
# # Generates a select field for days that defaults to the number given
# select_day(5)
#
# # Generates a select field for days that defaults to the day for the date in my_date
# # that is named 'due' rather than 'day'
# select_day(my_time, :field_name => 'due')
#
# # Generates a select field for days with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_day(5, :prompt => 'Choose day')
#
def select_day(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_day
end
# Returns a select tag with options for each of the months January through December with the current month
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
#
# ==== Examples
# # Generates a select field for months that defaults to the current month that
# # will use keys like "January", "March".
# select_month(Date.today)
#
# # Generates a select field for months that defaults to the current month that
# # is named "start" rather than "month"
# select_month(Date.today, :field_name => 'start')
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "1", "3".
# select_month(Date.today, :use_month_numbers => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "1 - January", "3 - March".
# select_month(Date.today, :add_month_numbers => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "Jan", "Mar".
# select_month(Date.today, :use_short_month => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "Januar", "Marts."
# select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
#
# # Generates a select field for months with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_month(14, :prompt => 'Choose month')
#
def select_month(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_month
end
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
#
# ==== Examples
# # Generates a select field for years that defaults to the current year that
# # has ascending year values
# select_year(Date.today, :start_year => 1992, :end_year => 2007)
#
# # Generates a select field for years that defaults to the current year that
# # is named 'birth' rather than 'year'
# select_year(Date.today, :field_name => 'birth')
#
# # Generates a select field for years that defaults to the current year that
# # has descending year values
# select_year(Date.today, :start_year => 2005, :end_year => 1900)
#
# # Generates a select field for years that defaults to the year 2006 that
# # has ascending year values
# select_year(2006, :start_year => 2000, :end_year => 2010)
#
# # Generates a select field for years with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_year(14, :prompt => 'Choose year')
#
def select_year(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_year
end
end
class DateTimeSelector #:nodoc:
extend ActiveSupport::Memoizable
include ActionView::Helpers::TagHelper
DEFAULT_PREFIX = 'date'.freeze unless const_defined?('DEFAULT_PREFIX')
POSITION = {
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
}.freeze unless const_defined?('POSITION')
def initialize(datetime, options = {}, html_options = {})
@options = options.dup
@html_options = html_options.dup
@datetime = datetime
end
def select_datetime
# TODO: Remove tag conditional
# Ideally we could just join select_date and select_date for the tag case
if @options[:tag] && @options[:ignore_date]
select_time
elsif @options[:tag]
order = date_order.dup
order -= [:hour, :minute, :second]
@options[:discard_year] ||= true unless order.include?(:year)
@options[:discard_month] ||= true unless order.include?(:month)
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
@options[:discard_minute] ||= true if @options[:discard_hour]
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
order += [:hour, :minute, :second] unless @options[:discard_hour]
build_selects_from_types(order)
else
"#{select_date}#{@options[:datetime_separator]}#{select_time}"
end
end
def select_date
order = date_order.dup
# TODO: Remove tag conditional
if @options[:tag]
@options[:discard_hour] = true
@options[:discard_minute] = true
@options[:discard_second] = true
@options[:discard_year] ||= true unless order.include?(:year)
@options[:discard_month] ||= true unless order.include?(:month)
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
end
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
build_selects_from_types(order)
end
def select_time
order = []
# TODO: Remove tag conditional
if @options[:tag]
@options[:discard_month] = true
@options[:discard_year] = true
@options[:discard_day] = true
@options[:discard_second] ||= true unless @options[:include_seconds]
order += [:year, :month, :day] unless @options[:ignore_date]
end
order += [:hour, :minute]
order << :second if @options[:include_seconds]
build_selects_from_types(order)
end
def select_second
if @options[:use_hidden] || @options[:discard_second]
build_hidden(:second, sec) if @options[:include_seconds]
else
build_options_and_select(:second, sec)
end
end
def select_minute
if @options[:use_hidden] || @options[:discard_minute]
build_hidden(:minute, min)
else
build_options_and_select(:minute, min, :step => @options[:minute_step])
end
end
def select_hour
if @options[:use_hidden] || @options[:discard_hour]
build_hidden(:hour, hour)
else
build_options_and_select(:hour, hour, :end => 23)
end
end
def select_day
if @options[:use_hidden] || @options[:discard_day]
build_hidden(:day, day)
else
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false)
end
end
def select_month
if @options[:use_hidden] || @options[:discard_month]
build_hidden(:month, month)
else
month_options = []
1.upto(12) do |month_number|
options = { :value => month_number }
options[:selected] = "selected" if month == month_number
month_options << content_tag(:option, month_name(month_number), options) + "\n"
end
build_select(:month, month_options.join)
end
end
def select_year
if !@datetime || @datetime == 0
val = ''
middle_year = Date.today.year
else
val = middle_year = year
end
if @options[:use_hidden] || @options[:discard_year]
build_hidden(:year, val)
else
options = {}
options[:start] = @options[:start_year] || middle_year - 5
options[:end] = @options[:end_year] || middle_year + 5
options[:step] = options[:start] < options[:end] ? 1 : -1
options[:leading_zeros] = false
build_options_and_select(:year, val, options)
end
end
private
%w( sec min hour day month year ).each do |method|
define_method(method) do
@datetime.kind_of?(Fixnum) ? @datetime : @datetime.send(method) if @datetime
end
end
# Returns translated month names, but also ensures that a custom month
# name array has a leading nil element
def month_names
month_names = @options[:use_month_names] || translated_month_names
month_names.unshift(nil) if month_names.size < 13
month_names
end
memoize :month_names
# Returns translated month names
# => [nil, "January", "February", "March",
# "April", "May", "June", "July",
# "August", "September", "October",
# "November", "December"]
#
# If :use_short_month option is set
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def translated_month_names
begin
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
I18n.translate(key, :locale => @options[:locale])
end
end
# Lookup month name for number
# month_name(1) => "January"
#
# If :use_month_numbers option is passed
# month_name(1) => 1
#
# If :add_month_numbers option is passed
# month_name(1) => "1 - January"
def month_name(number)
if @options[:use_month_numbers]
number
elsif @options[:add_month_numbers]
"#{number} - #{month_names[number]}"
else
month_names[number]
end
end
def date_order
@options[:order] || translated_date_order
end
memoize :date_order
def translated_date_order
begin
I18n.translate(:'date.order', :locale => @options[:locale]) || []
end
end
# Build full select tag from date type and options
def build_options_and_select(type, selected, options = {})
build_select(type, build_options(selected, options))
end
# Build select option html from date value and options
# build_options(15, :start => 1, :end => 31)
# => "<option value="1">1</option>
# <option value=\"2\">2</option>
# <option value=\"3\">3</option>..."
def build_options(selected, options = {})
start = options.delete(:start) || 0
stop = options.delete(:end) || 59
step = options.delete(:step) || 1
leading_zeros = options.delete(:leading_zeros).nil? ? true : false
select_options = []
start.step(stop, step) do |i|
value = leading_zeros ? sprintf("%02d", i) : i
tag_options = { :value => value }
tag_options[:selected] = "selected" if selected == i
select_options << content_tag(:option, value, tag_options)
end
select_options.join("\n") + "\n"
end
# Builds select tag from date type and html select options
# build_select(:month, "<option value="1">January</option>...")
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
# <option value="1">January</option>...
# </select>"
def build_select(type, select_options_as_html)
select_options = {
:id => input_id_from_type(type),
:name => input_name_from_type(type)
}.merge(@html_options)
select_options.merge!(:disabled => 'disabled') if @options[:disabled]
select_html = "\n"
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
select_html << select_options_as_html.to_s
content_tag(:select, select_html, select_options) + "\n"
end
# Builds a prompt option tag with supplied options or from default options
# prompt_option_tag(:month, :prompt => 'Select month')
# => "<option value="">Select month</option>"
def prompt_option_tag(type, options)
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
case options
when Hash
prompt = default_options.merge(options)[type.to_sym]
when String
prompt = options
else
prompt = I18n.translate(('datetime.prompts.' + type.to_s).to_sym, :locale => @options[:locale])
end
prompt ? content_tag(:option, prompt, :value => '') : ''
end
# Builds hidden input tag for date part and value
# build_hidden(:year, 2008)
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
def build_hidden(type, value)
tag(:input, {
:type => "hidden",
:id => input_id_from_type(type),
:name => input_name_from_type(type),
:value => value
}) + "\n"
end
# Returns the name attribute for the input tag
# => post[written_on(1i)]
def input_name_from_type(type)
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
field_name = @options[:field_name] || type
if @options[:include_position]
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
end
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
end
# Returns the id attribute for the input tag
# => "post_written_on_1i"
def input_id_from_type(type)
input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
end
# Given an ordering of datetime components, create the selection html
# and join them with their appropriate seperators
def build_selects_from_types(order)
select = ''
order.reverse.each do |type|
separator = separator(type) unless type == order.first # don't add on last field
select.insert(0, separator.to_s + send("select_#{type}").to_s)
end
select
end
# Returns the separator for a given datetime component
def separator(type)
case type
when :month, :day
@options[:date_separator]
when :hour
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
when :minute
@options[:time_separator]
when :second
@options[:include_seconds] ? @options[:time_separator] : ""
end
end
end
class InstanceTag #:nodoc:
def to_date_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_date
end
def to_time_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_time
end
def to_datetime_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_datetime
end
private
def datetime_selector(options, html_options)
datetime = value(object) || default_datetime(options)
options = options.dup
options[:field_name] = @method_name
options[:include_position] = true
options[:prefix] ||= @object_name
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
options[:datetime_separator] ||= ' — '
options[:time_separator] ||= ' : '
DateTimeSelector.new(datetime, options.merge(:tag => true), html_options)
end
def default_datetime(options)
return if options[:include_blank]
case options[:default]
when nil
Time.current
when Date, Time
options[:default]
else
default = options[:default].dup
# Rename :minute and :second to :min and :sec
default[:min] ||= default[:minute]
default[:sec] ||= default[:second]
time = Time.current
[:year, :month, :day, :hour, :min, :sec].each do |key|
default[key] ||= time.send(key)
end
Time.utc_time(
default[:year], default[:month], default[:day],
default[:hour], default[:min], default[:sec]
)
end
end
end
class FormBuilder
def date_select(method, options = {}, html_options = {})
@template.date_select(@object_name, method, objectify_options(options), html_options)
end
def time_select(method, options = {}, html_options = {})
@template.time_select(@object_name, method, objectify_options(options), html_options)
end
def datetime_select(method, options = {}, html_options = {})
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
end
end
end
end
| mit |
akrabat/Twig-View | tests/TwigTest.php | 5637 | <?php
/**
* Slim Framework (http://slimframework.com)
*
* @link https://github.com/codeguy/Slim
* @copyright Copyright (c) 2011-2015 Josh Lockhart
* @license https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
*/
namespace Slim\Tests\Views;
use Slim\Views\Twig;
require dirname(__DIR__) . '/vendor/autoload.php';
class TwigTest extends \PHPUnit_Framework_TestCase
{
public function testFetch()
{
$view = new Twig(dirname(__FILE__) . '/templates');
$output = $view->fetch('example.html', [
'name' => 'Josh'
]);
$this->assertEquals("<p>Hi, my name is Josh.</p>\n", $output);
}
public function testFetchFromString()
{
$view = new Twig(dirname(__FILE__) . '/templates');
$output = $view->fetchFromString("<p>Hi, my name is {{ name }}.</p>", [
'name' => 'Josh'
]);
$this->assertEquals("<p>Hi, my name is Josh.</p>", $output);
}
public function testFetchBlock()
{
$view = new Twig(dirname(__FILE__) . '/templates');
$outputOne = $view->fetchBlock('block_example.html', 'first', [
'name' => 'Josh'
]);
$outputTwo = $view->fetchBlock('block_example.html', 'second', [
'name' => 'Peter'
]);
$this->assertEquals("<p>Hi, my name is Josh.</p>", $outputOne);
$this->assertEquals("<p>My name is not Peter.</p>", $outputTwo);
}
public function testSingleNamespaceAndMultipleDirectories()
{
$weekday = (new \DateTimeImmutable('2016-03-08'))->format('l');
$view = new Twig(
[
'namespace' => [
__DIR__.'/another',
__DIR__.'/templates',
__DIR__.'/multi',
],
]
);
$anotherDirectory = $view->fetch('@namespace/example.html', [
'name' => 'Peter'
]);
$templatesDirectory = $view->fetch('@namespace/another_example.html', [
'name' => 'Peter',
'gender' => 'male',
]);
$outputMulti = $view->fetch('@namespace/directory/template/example.html', [
'weekday' => $weekday,
]);
$this->assertEquals("<p>Hi, my name is Peter.</p>\n", $anotherDirectory);
$this->assertEquals("<p>Hi, my name is Peter and I am male.</p>\n", $templatesDirectory);
$this->assertEquals('Happy Tuesday!', $outputMulti);
}
public function testArrayWithASingleTemplateWithANamespace()
{
$views = new Twig([
'One' => [
__DIR__.'/templates',
],
]);
$output = $views->fetch('@One/example.html', [
'name' => 'Josh'
]);
$this->assertEquals("<p>Hi, my name is Josh.</p>\n", $output);
}
public function testASingleTemplateWithANamespace()
{
$views = new Twig([
'One' => __DIR__.'/templates',
]);
$output = $views->fetch('@One/example.html', [
'name' => 'Josh'
]);
$this->assertEquals("<p>Hi, my name is Josh.</p>\n", $output);
}
public function testMultipleTemplatesWithMultipleNamespace()
{
$weekday = (new \DateTimeImmutable('2016-03-08'))->format('l');
$views = new Twig([
'One' => __DIR__.'/templates',
'Two' => __DIR__.'/another',
'Three' => [
__DIR__.'/multi',
],
]);
$outputOne = $views->fetch('@One/example.html', [
'name' => 'Peter'
]);
$outputTwo = $views->fetch('@Two/another_example.html', [
'name' => 'Peter',
'gender' => 'male'
]);
$outputThree = $views->fetch('@Three/directory/template/example.html', [
'weekday' => $weekday,
]);
$this->assertEquals("<p>Hi, my name is Peter.</p>\n", $outputOne);
$this->assertEquals("<p>Hi, my name is Peter and I am male.</p>\n", $outputTwo);
$this->assertEquals('Happy Tuesday!', $outputThree);
}
public function testMultipleDirectoriesWithoutNamespaces()
{
$weekday = (new \DateTimeImmutable('2016-03-08'))->format('l');
$view = new Twig([__DIR__.'/multi/', __DIR__.'/another/']);
$rootDirectory = $view->fetch('directory/template/example.html', [
'weekday' => $weekday,
]);
$multiDirectory = $view->fetch('another_example.html', [
'name' => 'Peter',
'gender' => 'male',
]);
$this->assertEquals('Happy Tuesday!', $rootDirectory);
$this->assertEquals("<p>Hi, my name is Peter and I am male.</p>\n", $multiDirectory);
}
public function testRender()
{
$view = new Twig(dirname(__FILE__) . '/templates');
$mockBody = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->disableOriginalConstructor()
->getMock();
$mockResponse = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')
->disableOriginalConstructor()
->getMock();
$mockBody->expects($this->once())
->method('write')
->with("<p>Hi, my name is Josh.</p>\n")
->willReturn(28);
$mockResponse->expects($this->once())
->method('getBody')
->willReturn($mockBody);
$response = $view->render($mockResponse, 'example.html', [
'name' => 'Josh'
]);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
}
}
| mit |
laemp/gruschen | gruschen/metrics/dtw_delta.py | 1564 | import numpy as np
# own dynamic time warping - squared
def get_metric(s, t):
return _get_dtw_matrix(s, t, _point_cost_sqr)[-1, -1]
def _get_dtw_matrix(s, t, point_norm):
ds = s[1:] - s[0:-1]
s = s[1:]
dt = t[1:] - t[0:-1]
t = t[1:]
n = len(s)
m = len(t)
dtw = np.empty((n, m))
cost = np.empty(m)
dcost = np.empty(m)
totalcost = np.empty(m)
row = np.empty(m)
_cost_vector(cost, s[0], t, point_norm)
_cost_vector(dcost, ds[0], dt, point_norm)
dtw[0, 0] = cost[0] + dcost[0]
for i in range(1, m):
dtw[0, i] = dtw[0, i-1] + cost[i] + dcost[i]
for i in range(1, n):
dtw[i, 0] = (point_norm(s[i] - t[0]) + point_norm(ds[i] - dt[0]) +
dtw[i-1, 0])
for i in range(1, n):
row = dtw[i, :]
_cost_vector(cost, s[i], t[1:], point_norm)
_cost_vector(dcost, ds[i], dt[1:], point_norm)
totalcost = cost+dcost
_row_prediction(row, totalcost, dtw[i-1, :])
_row_adjustment(row, totalcost)
return dtw
def _point_cost_sqr(v):
return np.inner(v, v)
def _cost_vector(cost, ref, mov, point_norm):
for i in range(len(mov)):
diff = ref - mov[i]
cost[i] = point_norm(diff)
def _row_prediction(row, cost, prev_row):
for i in range(1, len(row)):
row[i] = cost[i-1] + min(prev_row[i-1], prev_row[i])
def _row_adjustment(row, cost):
for j in range(1, len(row)):
if row[j-1] + cost[j-1] < row[j]: # is true more often than not
row[j] = row[j-1] + cost[j-1]
| mit |
abhishekgahlot/kivy | kivy/resources.py | 1557 | '''
Resources management
====================
Resource management can be a pain if you have multiple paths and projects. Kivy
offers 2 functions for searching for specific resources across a list of
paths.
'''
__all__ = ('resource_find', 'resource_add_path', 'resource_remove_path')
from os.path import join, dirname, exists
from kivy import kivy_data_dir
from kivy.utils import platform
from kivy.logger import Logger
import sys
import kivy
resource_paths = ['.', dirname(sys.argv[0])]
if platform == 'ios':
resource_paths += [join(dirname(sys.argv[0]), 'YourApp')]
resource_paths += [dirname(kivy.__file__), join(kivy_data_dir, '..')]
def resource_find(filename):
'''Search for a resource in the list of paths.
Use resource_add_path to add a custom path to the search.
'''
if not filename:
return None
if filename[:8] == 'atlas://':
return filename
if exists(filename):
return filename
for path in reversed(resource_paths):
output = join(path, filename)
if exists(output):
return output
return None
def resource_add_path(path):
'''Add a custom path to search in.
'''
if path in resource_paths:
return
Logger.debug('Resource: add <%s> in path list' % path)
resource_paths.append(path)
def resource_remove_path(path):
'''Remove a search path.
.. versionadded:: 1.0.8
'''
if path not in resource_paths:
return
Logger.debug('Resource: remove <%s> from path list' % path)
resource_paths.remove(path)
| mit |
mohayonao/subcollider | src/lib/bubble.js | 570 | sc.define("bubble", {
Array: function(depth, levels) {
depth = depth === void 0 ? 0 : depth;
levels = levels === void 0 ? 1 : levels;
if (depth <= 0) {
if (levels <= 1) { return [this]; }
return [this.bubble(depth, levels-1)];
}
return this.map(function(item) {
return item.bubble(depth-1, levels);
});
},
Number: function(depth, levels) {
depth = depth === void 0 ? 0 : depth;
levels = levels === void 0 ? 1 : levels;
if (levels <= 1) { return [this]; }
return [this.bubble(depth, levels-1)];
}
});
| mit |
MichaelTheLi/guppies | src/app/models/Document/Field/FieldTypeModel.php | 690 | <?php
namespace models\Document\Field;
use RedBeanPHP\Facade as R;
class FieldTypeModel{
const BEEN_NAME = "fieldtype";
/**
*
*/
static function FindByCode($code){
$bean = R::findOne( self::BEEN_NAME, ' code = ? ', [ $code ]);
if ( !isset($bean["id"]) ) {
return null;
}
return $bean;
}
/**
*
*/
static function Add($code, $human_name, $description){
$bean = R::dispense( self::BEEN_NAME );
$bean['code'] = $code;
$bean['human_name'] = $human_name;
$bean['description'] = $description;
$id = R::store( $bean );
return $bean;
}
}
| mit |
JHKennedy4/nqr-client | jspm_packages/npm/ua-parser-js@0.7.9/package.js | 350 | /* */
"format cjs";
Package.describe({
name: 'faisalman:ua-parser-js',
version: '0.7.9',
summary: 'Lightweight JavaScript-based user-agent string parser',
git: 'https://github.com/faisalman/ua-parser-js.git',
documentation: 'readme.md'
});
Package.on_use(function (api) {
api.export("UAParser");
api.addFiles("src/ua-parser.js");
});
| mit |
oliviertassinari/material-ui | packages/mui-icons-material/lib/CompareArrowsOutlined.js | 549 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z"
}), 'CompareArrowsOutlined');
exports.default = _default; | mit |
tomphp/braintree_ruby | lib/braintree/payment_method_gateway.rb | 4774 | module Braintree
class PaymentMethodGateway # :nodoc:
def initialize(gateway)
@gateway = gateway
@config = gateway.config
@config.assert_has_access_token_or_keys
end
def create(attributes)
Util.verify_keys(PaymentMethodGateway._create_signature, attributes)
_do_create("/payment_methods", :payment_method => attributes)
end
def _do_create(path, params=nil) # :nodoc:
response = @config.http.post("#{@config.base_merchant_path}#{path}", params)
if response[:credit_card]
SuccessfulResult.new(:payment_method => CreditCard._new(@gateway, response[:credit_card]))
elsif response[:paypal_account]
SuccessfulResult.new(:payment_method => PayPalAccount._new(@gateway, response[:paypal_account]))
elsif response[:coinbase_account]
SuccessfulResult.new(:payment_method => CoinbaseAccount._new(@gateway, response[:coinbase_account]))
elsif response[:europe_bank_account]
SuccessfulResult.new(:payment_method => EuropeBankAccount._new(@gateway, response[:europe_bank_account]))
elsif response[:apple_pay_card]
SuccessfulResult.new(:payment_method => ApplePayCard._new(@gateway, response[:apple_pay_card]))
elsif response[:android_pay_card]
SuccessfulResult.new(:payment_method => AndroidPayCard._new(@gateway, response[:android_pay_card]))
elsif response[:api_error_response]
ErrorResult.new(@gateway, response[:api_error_response])
elsif response
SuccessfulResult.new(:payment_method => UnknownPaymentMethod._new(@gateway, response))
else
raise UnexpectedError, "expected :payment_method or :api_error_response"
end
end
def delete(token)
@config.http.delete("#{@config.base_merchant_path}/payment_methods/any/#{token}")
end
def find(token)
raise ArgumentError if token.nil? || token.to_s.strip == ""
response = @config.http.get("#{@config.base_merchant_path}/payment_methods/any/#{token}")
if response.has_key?(:credit_card)
CreditCard._new(@gateway, response[:credit_card])
elsif response.has_key?(:paypal_account)
PayPalAccount._new(@gateway, response[:paypal_account])
elsif response[:coinbase_account]
SuccessfulResult.new(:payment_method => CoinbaseAccount._new(@gateway, response[:coinbase_account]))
elsif response.has_key?(:europe_bank_account)
EuropeBankAccount._new(@gateway, response[:europe_bank_account])
elsif response.has_key?(:apple_pay_card)
ApplePayCard._new(@gateway, response[:apple_pay_card])
elsif response.has_key?(:android_pay_card)
AndroidPayCard._new(@gateway, response[:android_pay_card])
else
UnknownPaymentMethod._new(@gateway, response)
end
rescue NotFoundError
raise NotFoundError, "payment method with token #{token.inspect} not found"
end
def update(token, attributes)
Util.verify_keys(PaymentMethodGateway._update_signature, attributes)
_do_update(:put, "/payment_methods/any/#{token}", :payment_method => attributes)
end
def _do_update(http_verb, path, params) # :nodoc:
response = @config.http.send(http_verb, "#{@config.base_merchant_path}#{path}", params)
if response[:credit_card]
SuccessfulResult.new(:payment_method => CreditCard._new(@gateway, response[:credit_card]))
elsif response[:paypal_account]
SuccessfulResult.new(:payment_method => PayPalAccount._new(@gateway, response[:paypal_account]))
elsif response[:api_error_response]
ErrorResult.new(@gateway, response[:api_error_response])
else
raise UnexpectedError, "expected :payment_method or :api_error_response"
end
end
def self._create_signature # :nodoc:
_signature(:create)
end
def self._update_signature # :nodoc:
_signature(:update)
end
def self._signature(type) # :nodoc:
billing_address_params = AddressGateway._shared_signature
options = [:make_default, :verification_merchant_account_id, :verify_card, :venmo_sdk_session]
signature = [
:billing_address_id, :cardholder_name, :cvv, :device_session_id, :expiration_date,
:expiration_month, :expiration_year, :number, :token, :venmo_sdk_payment_method_code,
:device_data, :fraud_merchant_id, :payment_method_nonce,
{:options => options},
{:billing_address => billing_address_params}
]
case type
when :create
options << :fail_on_duplicate_payment_method
signature << :customer_id
when :update
billing_address_params << {:options => [:update_existing]}
else
raise ArgumentError
end
return signature
end
end
end
| mit |
limafabio/lazycf | tests/Test_LazyCF.py | 1628 | #!/usr/bin/py
import os
import sys
import shutil
import unittest
sys.path.append(os.path.abspath('..'))
from sample.LazyCF import LazyCF
from sample.CodeForces import CodeForces
class TestLazyCF(unittest.TestCase):
def test__init__(self):
lazy_test = LazyCF()
self.assertEqual(str(lazy_test.__class__), "sample.LazyCF.LazyCF")
def test_get_contest(self):
cf = LazyCF()
cf.get_contest(768)
self.assertEqual(cf.contest.id, 768)
def test_create_folder(self):
cf = CodeForces()
contest_test = cf.get_contest(768)
lazy = LazyCF()
lazy.create_folder(contest_test)
path = os.path.abspath('.')
for folder in contest_test.problem_list:
self.assertTrue(os.path.isdir(path + "/" + folder.index))
shutil.rmtree(path + "/" + folder.index)
def test_create_file(self):
cf = CodeForces()
contest_test = cf.get_contest(768)
lazy = LazyCF()
lazy.create_folder(contest_test)
path = os.path.abspath('.')
for folder in contest_test.problem_list:
path_folder = path + "/" + folder.index
self.assertTrue(os.path.isdir(path_folder))
i = 0
for cases in folder.test:
i += 1
name_file = "input_" + str(i)
lazy.create_file(cases.input_text, name_file, path_folder)
name_file = "output_" + str(i)
lazy.create_file(cases.output_text, name_file, path_folder)
shutil.rmtree(path_folder)
if __name__ == "__main__":
unittest.main()
| mit |
TransmediaLab/KsuQuest | app/controllers/admin/reports_controller.rb | 596 | class Admin::ReportsController < ApplicationController
layout "admin"
before_filter :login_required, :admin_required
def player_timelines
@players = User.players
end
def player_details
@players = User.players
render xlsx: "player_details", filename: "player_details_#{Date.today}"
end
def task_details
@tasks = Task.all
render xlsx: "task_details", filename: "task_details_#{Date.today}"
end
def mailing_list
emails = User.pluck(:eid).map{|eid| "#{eid}@k-state.edu"}
send_data emails.join(', '), :filename => "rpo_maling_list.txt"
end
end
| mit |
btcgroup2/bitcoin | src/bitcoin-tx.cpp | 29368 | // Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "base58.h"
#include "clientversion.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "core_io.h"
#include "keystore.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include <univalue.h>
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
static bool fCreateBlank;
static std::map<std::string,UniValue> registers;
static const int CONTINUE_EXECUTION=-1;
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRawTx(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
fCreateBlank = GetBoolArg("-create", false);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help"))
{
// First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" bitcoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded bitcoin transaction") + "\n" +
" bitcoin-tx [options] -create [commands] " + _("Create hex-encoded bitcoin transaction") + "\n" +
"\n";
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
strUsage += HelpMessageOpt("-json", _("Select JSON output"));
strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
AppendParamsHelpMessages(strUsage);
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Commands:"));
strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
strUsage += HelpMessageOpt("rbfoptin(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
_("This command requires JSON registers:") +
_("prevtxs=JSON object") + ", " +
_("privatekeys=JSON object") + ". " +
_("See signrawtransaction docs for format of sighash flags, JSON objects."));
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Register Commands:"));
strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void RegisterSetJson(const std::string& key, const std::string& rawJson)
{
UniValue val;
if (!val.read(rawJson)) {
std::string strErr = "Cannot parse JSON for key " + key;
throw std::runtime_error(strErr);
}
registers[key] = val;
}
static void RegisterSet(const std::string& strInput)
{
// separate NAME:VALUE in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register input requires NAME:VALUE");
std::string key = strInput.substr(0, pos);
std::string valStr = strInput.substr(pos + 1, std::string::npos);
RegisterSetJson(key, valStr);
}
static void RegisterLoad(const std::string& strInput)
{
// separate NAME:FILENAME in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register load requires NAME:FILENAME");
std::string key = strInput.substr(0, pos);
std::string filename = strInput.substr(pos + 1, std::string::npos);
FILE *f = fopen(filename.c_str(), "r");
if (!f) {
std::string strErr = "Cannot open file " + filename;
throw std::runtime_error(strErr);
}
// load file chunks into one big buffer
std::string valStr;
while ((!feof(f)) && (!ferror(f))) {
char buf[4096];
int bread = fread(buf, 1, sizeof(buf), f);
if (bread <= 0)
break;
valStr.insert(valStr.size(), buf, bread);
}
int error = ferror(f);
fclose(f);
if (error) {
std::string strErr = "Error reading file " + filename;
throw std::runtime_error(strErr);
}
// evaluate as JSON buffer register
RegisterSetJson(key, valStr);
}
static CAmount ExtractAndValidateValue(const std::string& strValue)
{
CAmount value;
if (!ParseMoney(strValue, value))
throw std::runtime_error("invalid TX output value");
return value;
}
static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newVersion = atoi64(cmdVal);
if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
throw std::runtime_error("Invalid TX version requested");
tx.nVersion = (int) newVersion;
}
static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newLocktime = atoi64(cmdVal);
if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
throw std::runtime_error("Invalid TX locktime requested");
tx.nLockTime = (unsigned int) newLocktime;
}
static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
}
// set the nSequence to MAX_INT - 2 (= RBF opt in flag)
int cnt = 0;
for (CTxIn& txin : tx.vin) {
if (strInIdx == "" || cnt == inIdx) {
if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
}
}
++cnt;
}
}
static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
{
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// separate TXID:VOUT in string
if (vStrInputParts.size()<2)
throw std::runtime_error("TX input missing separator");
// extract and validate TXID
std::string strTxid = vStrInputParts[0];
if ((strTxid.size() != 64) || !IsHex(strTxid))
throw std::runtime_error("invalid TX input txid");
uint256 txid(uint256S(strTxid));
static const unsigned int minTxOutSz = 9;
static const unsigned int maxVout = MAX_BLOCK_BASE_SIZE / minTxOutSz;
// extract and validate vout
std::string strVout = vStrInputParts[1];
int vout = atoi(strVout);
if ((vout < 0) || (vout > (int)maxVout))
throw std::runtime_error("invalid TX input vout");
// extract the optional sequence number
uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
if (vStrInputParts.size() > 2)
nSequenceIn = std::stoul(vStrInputParts[2]);
// append to transaction input list
CTxIn txin(txid, vout, CScript(), nSequenceIn);
tx.vin.push_back(txin);
}
static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:ADDRESS
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() != 2)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate ADDRESS
std::string strAddr = vStrInputParts[1];
CBitcoinAddress addr(strAddr);
if (!addr.IsValid())
throw std::runtime_error("invalid TX output address");
// build standard output script via GetScriptForDestination()
CScript scriptPubKey = GetScriptForDestination(addr.Get());
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:PUBKEY[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract and validate PUBKEY
CPubKey pubkey(ParseHex(vStrInputParts[1]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
// Extract and validate FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts[2];
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (bSegWit) {
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress redeemScriptAddr(scriptPubKey);
scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// Check that there are enough parameters
if (vStrInputParts.size()<3)
throw std::runtime_error("Not enough multisig parameters");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract REQUIRED
uint32_t required = stoul(vStrInputParts[1]);
// Extract NUMKEYS
uint32_t numkeys = stoul(vStrInputParts[2]);
// Validate there are the correct number of pubkeys
if (vStrInputParts.size() < numkeys + 3)
throw std::runtime_error("incorrect number of multisig pubkeys");
if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
throw std::runtime_error("multisig parameter mismatch. Required " \
+ std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
// extract and validate PUBKEYs
std::vector<CPubKey> pubkeys;
for(int pos = 1; pos <= int(numkeys); pos++) {
CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
pubkeys.push_back(pubkey);
}
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == numkeys + 4) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
else if (vStrInputParts.size() > numkeys + 4) {
// Validate that there were no more parameters passed
throw std::runtime_error("Too many parameters");
}
CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
if (bSegWit) {
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
{
CAmount value = 0;
// separate [VALUE:]DATA in string
size_t pos = strInput.find(':');
if (pos==0)
throw std::runtime_error("TX output value not specified");
if (pos != std::string::npos) {
// Extract and validate VALUE
value = ExtractAndValidateValue(strInput.substr(0, pos));
}
// extract and validate DATA
std::string strData = strInput.substr(pos + 1, std::string::npos);
if (!IsHex(strData))
throw std::runtime_error("invalid TX output data");
std::vector<unsigned char> data = ParseHex(strData);
CTxOut txout(value, CScript() << OP_RETURN << data);
tx.vout.push_back(txout);
}
static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
{
// separate VALUE:SCRIPT[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2)
throw std::runtime_error("TX output missing separator");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate script
std::string strScript = vStrInputParts[1];
CScript scriptPubKey = ParseScript(strScript);
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (bSegWit) {
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested deletion index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
std::string strErr = "Invalid TX input index '" + strInIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete input from transaction
tx.vin.erase(tx.vin.begin() + inIdx);
}
static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
{
// parse requested deletion index
int outIdx = atoi(strOutIdx);
if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete output from transaction
tx.vout.erase(tx.vout.begin() + outIdx);
}
static const unsigned int N_SIGHASH_OPTS = 6;
static const struct {
const char *flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
{"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
{"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
};
static bool findSighashFlags(int& flags, const std::string& flagStr)
{
flags = 0;
for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
if (flagStr == sighashOptions[i].flagStr) {
flags = sighashOptions[i].flags;
return true;
}
}
return false;
}
static CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
throw std::runtime_error("Amount is not a number or string");
CAmount amount;
if (!ParseFixedPoint(value.getValStr(), 8, &amount))
throw std::runtime_error("Invalid amount");
if (!MoneyRange(amount))
throw std::runtime_error("Amount out of range");
return amount;
}
static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
{
int nHashType = SIGHASH_ALL;
if (flagStr.size() > 0)
if (!findSighashFlags(nHashType, flagStr))
throw std::runtime_error("unknown sighash flag/sign option");
std::vector<CTransaction> txVariants;
txVariants.push_back(tx);
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
if (!registers.count("privatekeys"))
throw std::runtime_error("privatekeys register variable must be set.");
CBasicKeyStore tempKeystore;
UniValue keysObj = registers["privatekeys"];
for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
if (!keysObj[kidx].isStr())
throw std::runtime_error("privatekey not a std::string");
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
if (!fGood)
throw std::runtime_error("privatekey not valid");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (!registers.count("prevtxs"))
throw std::runtime_error("prevtxs register variable must be set.");
UniValue prevtxsObj = registers["prevtxs"];
{
for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
UniValue prevOut = prevtxsObj[previdx];
if (!prevOut.isObject())
throw std::runtime_error("expected prevtxs internal object");
std::map<std::string, UniValue::VType> types = {
{"txid", UniValue::VSTR},
{"vout", UniValue::VNUM},
{"scriptPubKey", UniValue::VSTR},
};
if (!prevOut.checkObject(types))
throw std::runtime_error("prevtxs internal object typecheck fail");
uint256 txid = ParseHashUV(prevOut["txid"], "txid");
int nOut = atoi(prevOut["vout"].getValStr());
if (nOut < 0)
throw std::runtime_error("vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw std::runtime_error(err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
if (prevOut.exists("amount")) {
newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
}
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and private keys given,
// add redeemScript to the tempKeystore so it can be signed:
if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
prevOut.exists("redeemScript")) {
UniValue v = prevOut["redeemScript"];
std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
const CKeyStore& keystore = tempKeystore;
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata;
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
for (const CTransaction& txv : txVariants)
sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
UpdateTransaction(mergedTx, i, sigdata);
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
fComplete = false;
}
if (fComplete) {
// do nothing... for now
// perhaps store this for later optional JSON output
}
tx = mergedTx;
}
class Secp256k1Init
{
ECCVerifyHandle globalVerifyHandle;
public:
Secp256k1Init() {
ECC_Start();
}
~Secp256k1Init() {
ECC_Stop();
}
};
static void MutateTx(CMutableTransaction& tx, const std::string& command,
const std::string& commandVal)
{
std::unique_ptr<Secp256k1Init> ecc;
if (command == "nversion")
MutateTxVersion(tx, commandVal);
else if (command == "locktime")
MutateTxLocktime(tx, commandVal);
else if (command == "rbfoptin") {
MutateTxRBFOptIn(tx, commandVal);
}
else if (command == "delin")
MutateTxDelInput(tx, commandVal);
else if (command == "in")
MutateTxAddInput(tx, commandVal);
else if (command == "delout")
MutateTxDelOutput(tx, commandVal);
else if (command == "outaddr")
MutateTxAddOutAddr(tx, commandVal);
else if (command == "outpubkey") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutPubKey(tx, commandVal);
} else if (command == "outmultisig") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutMultiSig(tx, commandVal);
} else if (command == "outscript")
MutateTxAddOutScript(tx, commandVal);
else if (command == "outdata")
MutateTxAddOutData(tx, commandVal);
else if (command == "sign") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxSign(tx, commandVal);
}
else if (command == "load")
RegisterLoad(commandVal);
else if (command == "set")
RegisterSet(commandVal);
else
throw std::runtime_error("unknown command");
}
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
TxToUniv(tx, uint256(), entry);
std::string jsonOutput = entry.write(4);
fprintf(stdout, "%s\n", jsonOutput.c_str());
}
static void OutputTxHash(const CTransaction& tx)
{
std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
fprintf(stdout, "%s\n", strHexHash.c_str());
}
static void OutputTxHex(const CTransaction& tx)
{
std::string strHex = EncodeHexTx(tx);
fprintf(stdout, "%s\n", strHex.c_str());
}
static void OutputTx(const CTransaction& tx)
{
if (GetBoolArg("-json", false))
OutputTxJSON(tx);
else if (GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
}
static std::string readStdin()
{
char buf[4096];
std::string ret;
while (!feof(stdin)) {
size_t bread = fread(buf, 1, sizeof(buf), stdin);
ret.append(buf, bread);
if (bread < sizeof(buf))
break;
}
if (ferror(stdin))
throw std::runtime_error("error reading stdin");
boost::algorithm::trim_right(ret);
return ret;
}
static int CommandLineRawTx(int argc, char* argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches; Permit common stdin convention "-"
while (argc > 1 && IsSwitchChar(argv[1][0]) &&
(argv[1][1] != 0)) {
argc--;
argv++;
}
CMutableTransaction tx;
int startArg;
if (!fCreateBlank) {
// require at least one param
if (argc < 2)
throw std::runtime_error("too few parameters");
// param: hex-encoded bitcoin transaction
std::string strHexTx(argv[1]);
if (strHexTx == "-") // "-" implies standard input
strHexTx = readStdin();
if (!DecodeHexTx(tx, strHexTx, true))
throw std::runtime_error("invalid transaction encoding");
startArg = 2;
} else
startArg = 1;
for (int i = startArg; i < argc; i++) {
std::string arg = argv[i];
std::string key, value;
size_t eqpos = arg.find('=');
if (eqpos == std::string::npos)
key = arg;
else {
key = arg.substr(0, eqpos);
value = arg.substr(eqpos + 1);
}
MutateTx(tx, key, value);
}
OutputTx(tx);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitRawTx(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRawTx()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRawTx(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRawTx()");
}
return ret;
}
| mit |
beafus/Living-Meki-Platform | wordpress/wp-content/plugins/contact-form-7-to-database-extension/contact-form-7-db.php | 3173 | <?php
/*
Plugin Name: Contact Form DB
Plugin URI: http://wordpress.org/extend/plugins/contact-form-7-to-database-extension/
Version: 2.9.7
Author: Michael Simpson
Description: Save form submissions to the database from <a href="http://wordpress.org/extend/plugins/contact-form-7/">Contact Form 7</a>, <a href="http://wordpress.org/extend/plugins/si-contact-form/">Fast Secure Contact Form</a>, <a href="http://wordpress.org/extend/plugins/jetpack/">JetPack Contact Form</a> and <a href="http://www.gravityforms.com">Gravity Forms</a>. Includes exports and short codes. | <a href="admin.php?page=CF7DBPluginSubmissions">Data</a> | <a href="admin.php?page=CF7DBPluginShortCodeBuilder">Short Codes</a> | <a href="admin.php?page=CF7DBPluginSettings">Settings</a> | <a href="http://cfdbplugin.com/">Reference</a>
Text Domain: contact-form-7-to-database-extension
License: GPL3
*/
$CF7DBPlugin_minimalRequiredPhpVersion = '5.0';
/**
* echo error message indicating wrong minimum PHP version required
*/
function CF7DBPlugin_noticePhpVersionWrong() {
global $CF7DBPlugin_minimalRequiredPhpVersion;
echo '<div class="updated fade">' .
__('Error: plugin "Contact Form to DB Extension" requires a newer version of PHP to be running.', 'contact-form-7-to-database-extension').
'<br/>' . __('Minimal version of PHP required: ', 'contact-form-7-to-database-extension') . '<strong>' . $CF7DBPlugin_minimalRequiredPhpVersion . '</strong>' .
'<br/>' . __('Your server\'s PHP version: ', 'contact-form-7-to-database-extension') . '<strong>' . phpversion() . '</strong>' .
'</div>';
}
/**
* Check the PHP version and give a useful error message if the user's version is less than the required version
* @return boolean true if version check passed. If false, triggers an error which WP will handle, by displaying
* an error message on the Admin page
*/
function CF7DBPlugin_PhpVersionCheck() {
global $CF7DBPlugin_minimalRequiredPhpVersion;
if (version_compare(phpversion(), $CF7DBPlugin_minimalRequiredPhpVersion) < 0) {
add_action('admin_notices', 'CF7DBPlugin_noticePhpVersionWrong');
return false;
}
return true;
}
/**
* Initialize internationalization (i18n) for this plugin.
* References:
* http://codex.wordpress.org/I18n_for_WordPress_Developers
* http://www.wdmac.com/how-to-create-a-po-language-translation#more-631
* @return void
*/
function CF7DBPlugin_i18n_init() {
$pluginDir = dirname(plugin_basename(__FILE__));
load_plugin_textdomain('contact-form-7-to-database-extension', false, $pluginDir . '/languages/');
}
//////////////////////////////////
// Run initialization
/////////////////////////////////
// Initialize i18n
add_action('plugins_loaded','CF7DBPlugin_i18n_init');
// Run the version check.
// If it is successful, continue with initialization for this plugin
if (CF7DBPlugin_PhpVersionCheck()) {
// Only load and run the init function if we know PHP version can parse it
include_once('CF7DBPlugin_init.php');
CF7DBPlugin_init(__FILE__);
}
| mit |
demoxu/blog | app/Http/Controllers/Api/ArticleController.php | 2319 | <?php
namespace App\Http\Controllers\Api;
use App\Http\Requests\ArticleRequest;
use App\Repositories\ArticleRepository;
class ArticleController extends ApiController
{
protected $article;
public function __construct(ArticleRepository $article)
{
parent::__construct();
$this->article = $article;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
return $this->response->collection($this->article->page());
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\ArticleRequest $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function store(ArticleRequest $request)
{
$data = array_merge($request->all(), [
'user_id' => \Auth::id(),
'last_user_id' => \Auth::id()
]);
$data['is_draft'] = isset($data['is_draft']);
$data['is_original'] = isset($data['is_original']);
$this->article->store($data);
$this->article->syncTag(json_decode($request->get('tags')));
return $this->response->withNoContent();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
*
* @return \Illuminate\Http\JsonResponse
*/
public function edit($id)
{
return $this->response->item($this->article->getById($id));
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\ArticleRequest $request
* @param int $id
*
* @return \Illuminate\Http\JsonResponse
*/
public function update(ArticleRequest $request, $id)
{
$data = array_merge($request->all(), [
'last_user_id' => \Auth::id()
]);
$this->article->update($id, $data);
$this->article->syncTag(json_decode($request->get('tags')));
return $this->response->withNoContent();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
*
* @return \Illuminate\Http\JsonResponse
*/
public function destroy($id)
{
$this->article->destroy($id);
return $this->response->withNoContent();
}
}
| mit |
pagarme/teleport | action/action.go | 454 | package action
type Action interface {
// Execute the given action
Execute(c *Context) error
// Returns whether current action should be executed
// for a targetExpression
Filter(targetExpression string) bool
// Returns whether the action needs to be batched separately to ensure
// consistency. Some actions cannot run inside transactions, thus must have
// a separate batch to ensure apply order and consistency.
NeedsSeparatedBatch() bool
}
| mit |
rbecheras/challengesplatform | db/migrate/20130520154536_add_image_to_challenges.rb | 120 | class AddImageToChallenges < ActiveRecord::Migration
def change
add_column :challenges, :image, :string
end
end
| mit |
bewallyt/Kalendr | pre_signup/serializers.py | 2785 | '''
Serializer for SignUp objects
Question: If SignUp uses customized manager
'''
from rest_framework import serializers
from pre_signup.models import PrefSignUp, PrefTimeBlock, PrefSignUpSlot, SignUpPreference
from authentication.models import Account
class PrefSignUpSlotSerializer(serializers.ModelSerializer):
requester_list = serializers.SerializerMethodField()
owner = serializers.SerializerMethodField()
def get_requester_list(self, obj):
requester_set = obj.requester_list.all()
username_list = []
tuple_list = []
for requester in requester_set:
pref_link = SignUpPreference.objects.get(slot = obj,
requester = requester)
pref = pref_link.pref
tup = (requester.username, pref)
username_list.append(requester.username)
tuple_list.append(tup)
if self.context['is_owner'] == True:
return tuple_list
else:
requester_name = self.context['requester']
requester = Account.objects.get(username = requester_name)
if requester_name in username_list:
pref_link = SignUpPreference.objects.get(slot = obj,
requester = requester)
pref = pref_link.pref
tup = (requester_name, pref)
return [tup]
else:
return []
def get_owner(self, obj):
if obj.owner is None:
return ''
else:
return obj.owner.username
class Meta:
model = PrefSignUpSlot
fields = ('id', 'owner', 'start_time', 'end_time', 'requester_list')
read_only_fields = ('id', 'start_time', 'end_time')
class PrefTimeBlockSerializer(serializers.ModelSerializer):
def get_context(self,obj):
return self.context
context = serializers.SerializerMethodField()
myslots = PrefSignUpSlotSerializer(many=True, context=context)
class Meta:
model = PrefTimeBlock
field = ('id', 'start_time', 'end_time', 'myslots')
read_only_fields = ('id', 'start_time', 'end_time')
class PrefSignUpSheetSerializer(serializers.ModelSerializer):
def get_type(self, obj):
return 'prefsignup'
def get_is_owner(self,obj):
return self.context
# This really should be part of the PostSerializer!! OH WELL
type = serializers.SerializerMethodField()
is_owner = serializers.SerializerMethodField()
myblocks = PrefTimeBlockSerializer(many=True, context=is_owner)
class Meta:
model = PrefSignUp
field = ('id', 'type', 'name', 'location', 'duration',
'myblocks','is_owner')
| mit |
tmcgee/cmv-wab-widgets | wab/2.13/widgets/Visibility/setting/nls/lt/strings.js | 1476 | define({
"taskUrl": "Matymo lauko paslaugos URL",
"portalURL": "Nurodykite ArcGIS Online organizacijos arba Portal for ArcGIS URL",
"portalURLError": "Sukonfigūruotas jūsų ArcGIS Online organizacijos arba Portal for ArcGIS URL netinkamas.",
"privilegeError": "Jūsų naudotojo rolė negali vykdyti analizės. Kad galėtumėte atlikti analizę, jūsų organizacijos administratorius turi jums suteikti tam tikras <a href=\"http://doc.arcgis.com/en/arcgis-online/reference/roles.htm\" target=\"_blank\">teises</a>.",
"noServiceError": "Aukščių analizės paslauga nepasiekiama. Peržiūrėkite savo ArcGIS Online organizacijos arba Portal for ArcGIS konfigūracijas.",
"serviceURLPlaceholder": "Įveskite matymo lauko geoduomenų apdorojimo užduoties URL",
"setTask": "Taikyti",
"setTaskTitle": "Nustatyti matymo lauko geoduomenų apdorojimo užduotį",
"serviceURLError": "Šiuo valdikliu bandoma sukonfigūruoti geoduomenų apdorojimo užduotis yra netinkama. Pasirinkite tinkamą matymo lauko geoduomenų apdorojimo užduoties URL.",
"defaultMilsForAnglesLabel": "Nustatyti kampų tūkstantąsias kaip numatytąsias",
"defaultObserverHeightLabel": "Numatytieji stebėtojo aukščio vienetai",
"defaultObservableDistanceLabel": "Numatytieji stebimo atstumo vienetai",
"units": {
"miles": "Mylios",
"kilometers": "Kilometrai",
"feet": "Pėdos",
"meters": "Metrai",
"yards": "Jardai",
"nauticalMiles": "Jūrmylės"
}
}); | mit |
hmc-cs-lnorgaard/MLCH | script_editor/config/environments/production.rb | 3586 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "script_editor_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| mit |
eggsandbeer/yfa | src/public/javascripts/controllers.js | 1973 | /* Controllers */
angular.module('myApp.controllers', ['ui.bootstrap']).
controller('MyCtrl1', [function () {
"use strict";
if(console && console.log) {
console.log('My Controller 1');
}
}])
.controller('MyCtrl2', [function () {
"use strict";
if(console && console.log) {
console.log('My Controller 2');
}
}]);
var ButtonsCtrl = function ($scope, $http, $compile) {
"use strict";
$scope.singleModel = 1;
$scope.radioModel = 'Middle';
$scope.checkModel = {
left : false,
middle: true,
right : false
};
$scope.contents = '';
$scope.load = function (location) {
$http.get(location).success(function(data) {
var elm = angular.element(document.getElementById('contact-contents'));
elm.html(data);
$compile(elm)($scope);
});
};
};
ButtonsCtrl.$inject = ['$scope', '$http', '$compile'];
var PagesCtrl = function ($scope, $route) {
"use strict";
$scope.dynamic = ($route.current !== undefined);
$scope.static = !$scope.dynamic;
};
PagesCtrl.$inject = ['$scope', '$route'];
var IndexCtrl = function ($scope, $routeParams) {
"use strict";
var routed = $routeParams.action;
// note samples don't appear asynchronously because dropdown links aren't included within this ng-controller
if(routed) {
$scope.alerts = [{ type: 'success', msg: 'Clicked dropdown link: ' + routed }];
} else {
$scope.alerts = [];
}
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
};
IndexCtrl.$inject = ['$scope', '$routeParams'];
var NavigationCtrl = function ($scope, $location) {
"use strict";
$scope.isCurrent = function (me) {
var currentRoute = $location.path() || '/';
return me === currentRoute ? 'active' : '';
};
};
NavigationCtrl.$inject = ['$scope', '$location'];
| mit |
jhelbig/postman-linux-app | app/resources/app/node_modules/waterline-utils/test/unit/converter/sum.test.js | 845 | var Test = require('../../support/convert-runner');
describe('Converter :: ', function() {
describe('Sums :: ', function() {
it('should generate a sum query', function() {
Test({
criteria: {
model: 'user',
method: 'sum',
criteria: {
where: {
and: [
{
firstName: 'Test'
},
{
lastName: 'User'
}
]
}
},
values: 'age'
},
query: {
sum: 'age',
from: 'user',
where: {
and: [
{
firstName: 'Test'
},
{
lastName: 'User'
}
]
}
}
});
});
});
});
| mit |
regalii/regaliator | test/regaliator/v32/bill_test.rb | 2366 | require 'test_helper'
module Regaliator
module V32
class BillTest < Minitest::Test
def setup
@config = Configuration.new.tap do |config|
config.version = API_VERSION
config.api_key = 'testing'
config.secret_key = 'testing'
config.host = 'apix.regalii.dev'
config.use_ssl = false
end
end
def test_create
VCR.use_cassette('V32/bill/create') do |cassette|
response = Regaliator.new(@config).bill.create(biller_id: 2, account_number: '8081969')
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_update
VCR.use_cassette('V32/bill/update') do |cassette|
response = Regaliator.new(@config).bill.update(695109, name_on_account: 'Test name')
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_show
VCR.use_cassette('V32/bill/show') do |cassette|
response = Regaliator.new(@config).bill.show(695109)
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_xdata
VCR.use_cassette('V32/bill/xdata') do |cassette|
response = Regaliator.new(@config).bill.xdata(695109)
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_refresh
VCR.use_cassette('V32/bill/refresh') do |cassette|
response = Regaliator.new(@config).bill.refresh(695109)
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_pay
VCR.use_cassette('V32/bill/pay') do |cassette|
response = Regaliator.new(@config).bill.pay(695109,
amount: 758.0,
currency: 'RD',
user_id: 12981
)
assert response.success?
assert_equal extract_hsh(cassette), response.data
end
end
def test_list
VCR.use_cassette('V32/bill/list') do
response = Regaliator.new(@config).bill.list
assert response.success?
assert_equal 100, response.data['bills'].size
end
end
end
end
end
| mit |
nota-ja/feedbin | app/models/feed_fetcher.rb | 7587 | class FeedFetcher
attr_accessor :feed, :feed_options
def initialize(url, site_url = nil)
@url = normalize_url(url)
@site_url = normalize_url(site_url) if site_url
@feed = nil
@raw_feed = nil
@parsed_feed = nil
@feed_options = []
end
def create_feed!
unless feed_exists?
create_or_get_options
end
self
end
def feed_exists?
@feed = Feed.where(feed_url: @url).first
@feed.instance_of?(Feed)
end
def normalize_url(url)
url = url.strip
url = url.gsub(/^ht*p(s?):?\/*/, 'http\1://')
url = url.gsub(/^feed:\/\//, 'http://')
if url =~ /^https?:\/\//
return url
else
"http://#{url}"
end
end
def create_or_get_options
@parsed_feed = fetch_and_parse
if is_feed?(@parsed_feed)
create!
else
get_options
end
end
def get_options
content = Feedjira::Feed.fetch_raw(@url, {user_agent: 'Feedbin', ssl_verify_peer: false, timeout: 20, connect_timeout: 10, max_redirects: 5})
if content.is_a?(String)
content = Nokogiri::HTML(content)
# Case insensitive rss link search
links = content.search("//link[translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'application/rss+xml'] |" +
"//link[translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'application/atom+xml']")
links.map do |link|
href = link.get_attribute('href')
title = link.get_attribute('title')
unless href.nil?
href = href.gsub(/^feed:\/\//, 'http://')
href = URI.join(@url, href).to_s unless href.start_with?('http')
if title.nil?
title = href
end
@feed_options << { href: href, title: link['title'], site_url: @url }
end
end
end
if @feed_options.length == 1
@site_url = @url
@url = @feed_options.first[:href]
@parsed_feed = fetch_and_parse
if is_feed?(@parsed_feed)
create!
else
get_options
end
end
end
def create!
# Figure out what the url to the site is
unless @site_url
get_site_url
end
# now that we have a feed url recheck if a feed exists
@feed = Feed.where(feed_url: @parsed_feed.feed_url).first
unless @feed
@feed = Feed.create_from_feedjira(@parsed_feed, @site_url)
if @parsed_feed.respond_to?(:hubs) && !@parsed_feed.hubs.blank?
hub_secret = Push::hub_secret(@feed.id)
push_subscribe(@parsed_feed, @feed.id, Push::callback_url(@feed), hub_secret)
end
end
end
def push_subscribe(feedjira, feed_id, push_callback, hub_secret)
begin
feedjira.hubs.each do |hub|
uri = URI(hub)
uri.scheme = 'https' # force https encrypt request
Curl.post(uri.to_s, {
'hub.mode' => 'subscribe',
'hub.topic' => feedjira.feed_url,
'hub.secret' => hub_secret,
'hub.callback' => push_callback,
'hub.verify' => 'async'
})
end
rescue Exception => e
if defined?(Honeybadger)
Honeybadger.notify(
error_class: "PuSH",
error_message: "PuSH Subscribe Failed",
parameters: {exception: e}
)
end
end
end
def get_site_url
if @site_url
@site_url = @site_url
elsif @parsed_feed.url
@site_url = @parsed_feed.url
elsif @url =~ /feedburner\.com/
begin
@site_url = url_from_link(LongURL.expand(@parsed_feed.entries.first.url))
rescue Exception
@site_url = url_from_link(@url)
end
else
@site_url = url_from_link(@url)
end
end
def url_from_link(link)
uri = URI.parse(link)
URI::HTTP.build(host: uri.host).to_s
end
def is_feed?(feed)
feed.class.name.starts_with?('Feedjira')
end
# Fetch and normalize feed
def fetch_and_parse(options = {}, saved_feed_url = nil)
defaults = {user_agent: 'Feedbin', ssl_verify_peer: false, timeout: 20, connect_timeout: 10, max_redirects: 5}
options = defaults.merge(options)
feedjira = nil
Timeout::timeout(35) do
feedjira = Feedjira::Feed.fetch_and_parse(@url, options)
end
if feedjira.respond_to?(:hubs) && !feedjira.hubs.blank? && options[:push_callback] && options[:feed_id]
if @url == feedjira.feed_url
push_subscribe(feedjira, options[:feed_id], options[:push_callback], options[:hub_secret])
end
end
normalize(feedjira, options, saved_feed_url)
end
def parse(xml_string, saved_feed_url)
feedjira = Feedjira::Feed.parse(xml_string)
normalize(feedjira, {}, saved_feed_url)
end
def normalize(feedjira, options = {}, saved_feed_url = nil)
if feedjira && feedjira.respond_to?(:feed_url)
feedjira.etag = feedjira.etag ? feedjira.etag.strip.gsub(/^"/, '').gsub(/"$/, '') : nil
feedjira.last_modified = feedjira.last_modified
feedjira.title = feedjira.title ? feedjira.title.strip : '(No title)'
feedjira.feed_url = feedjira.feed_url.strip
feedjira.url = feedjira.url ? feedjira.url.strip : nil
feedjira.entries.map do |entry|
if entry.try(:content)
content = entry.content
elsif entry.try(:summary)
content = entry.summary
elsif entry.try(:description)
content = entry.description
else
content = nil
end
if entry.try(:author)
entry.author = entry.author
elsif entry.try(:itunes_author)
entry.author = entry.itunes_author
else
entry.author = nil
end
entry.content = content ? content.strip : nil
entry.title = entry.title ? entry.title.strip : nil
entry.url = entry.url ? entry.url.strip : nil
entry.entry_id = entry.entry_id ? entry.entry_id.strip : nil
entry._public_id_ = build_public_id(entry, feedjira, saved_feed_url)
entry._old_public_id_ = build_public_id(entry, feedjira)
if entry.try(:enclosure_type) && entry.try(:enclosure_url)
data = {}
data[:enclosure_type] = entry.enclosure_type ? entry.enclosure_type : nil
data[:enclosure_url] = entry.enclosure_url ? entry.enclosure_url : nil
data[:enclosure_length] = entry.enclosure_length ? entry.enclosure_length : nil
data[:itunes_duration] = entry.itunes_duration ? entry.itunes_duration : nil
entry._data_ = data
end
end
if feedjira.entries.any?
feedjira.entries = feedjira.entries.uniq { |entry| entry._public_id_ }
end
end
feedjira
end
def log(message)
Rails.logger.info(message)
end
# This is the id strategy
# All values are stripped
# feed url + id
# feed url + link + utc iso 8601 date
# feed url + link + title
# WARNING: changes to this will break how entries are identified
# This can only be changed with backwards compatibility in mind
def build_public_id(entry, feedjira, saved_feed_url = nil)
if saved_feed_url
id_string = saved_feed_url.dup
else
id_string = feedjira.feed_url.dup
end
if entry.entry_id
id_string << entry.entry_id.dup
else
if entry.url
id_string << entry.url.dup
end
if entry.published
id_string << entry.published.iso8601
end
if entry.title
id_string << entry.title.dup
end
end
Digest::SHA1.hexdigest(id_string)
end
end
| mit |
mollstam/UnrealPy | UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/examples_java/src/collections/ship/sentity/Supplier.java | 1956 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: Supplier.java 63573 2008-05-23 21:43:21Z trent.nelson $
*/
package collections.ship.sentity;
import java.io.Serializable;
/**
* A Supplier represents the combined key/data pair for a supplier entity.
*
* <p> In this sample, Supplier is created from the stored key/data entry
* using TupleSerialEntityBinding. See {@link SampleViews.PartBinding} for
* details.
* </p>
*
* <p> The binding is "tricky" in that it uses this class for both the stored
* data entry and the combined entity object. To do this, the key field(s) are
* transient and are set by the binding after the data object has been
* deserialized. This avoids the use of a SupplierData class completely. </p>
*
* <p> Since this class is used directly for data storage, it must be
* Serializable. </p>
*
* @author Mark Hayes
*/
public class Supplier implements Serializable {
private transient String number;
private String name;
private int status;
private String city;
public Supplier(String number, String name, int status, String city) {
this.number = number;
this.name = name;
this.status = status;
this.city = city;
}
/**
* Set the transient key fields after deserializing. This method is only
* called by data bindings.
*/
void setKey(String number) {
this.number = number;
}
public final String getNumber() {
return number;
}
public final String getName() {
return name;
}
public final int getStatus() {
return status;
}
public final String getCity() {
return city;
}
public String toString() {
return "[Supplier: number=" + number +
" name=" + name +
" status=" + status +
" city=" + city + ']';
}
}
| mit |
agray/nunit | src/NUnitFramework/tests/Internal/CallContextTests.cs | 5329 | // ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// 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.
// ***********************************************************************
#if PARALLEL
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Security.Principal;
using NUnit.TestData.TestFixtureTests;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal
{
// TODO: Make this work for .NET 2.0
[TestFixture]
public class CallContextTests
{
const string CONTEXT_DATA = "MyContextData";
// IPrincipal savedPrincipal;
// [SetUp]
// public void SaveCurrentPrincipal()
// {
// savedPrincipal = System.Threading.Thread.CurrentPrincipal;
// }
//
// [TearDown]
// public void RestoreCurrentPrincipal()
// {
// System.Threading.Thread.CurrentPrincipal = savedPrincipal;
// CallContext.FreeNamedDataSlot(CONTEXT_DATA);
// }
[TearDown]
public void FreeCallContextDataSlot()
{
// NOTE: We don't want possible side effects on other cross context tests.
CallContext.FreeNamedDataSlot(CONTEXT_DATA);
}
[Test]
public void ILogicalThreadAffinativeTest()
{
CallContext.SetData( CONTEXT_DATA, new EmptyCallContextData() );
}
[Test]
public void ILogicalThreadAffinativeTestConsole()
{
CallContext.SetData( CONTEXT_DATA, new EmptyCallContextData() );
// TODO: make this Assertable
// Console.WriteLine("ILogicalThreadAffinativeTest");
Console.Out.Flush();
}
[Test]
public void GenericPrincipalTest()
{
GenericIdentity ident = new GenericIdentity("Bob");
GenericPrincipal prpal = new GenericPrincipal(ident,
new string[] {"Level1"});
CallContext.SetData( CONTEXT_DATA, new PrincipalCallContextData( prpal ) );
}
[Test]
public void SetGenericPrincipalOnThread()
{
GenericIdentity ident = new GenericIdentity("Bob");
GenericPrincipal prpal = new GenericPrincipal(ident,
new string[] {"Level1"});
System.Threading.Thread.CurrentPrincipal = prpal;
}
[Test]
public void SetCustomPrincipalOnThread()
{
MyPrincipal prpal = new MyPrincipal();
System.Threading.Thread.CurrentPrincipal = prpal;
}
[Test]
public void UseCustomIdentity()
{
TestIdentity ident = new TestIdentity( "test" );
GenericPrincipal principal = new GenericPrincipal( ident, new string[] { "Level1" } );
System.Threading.Thread.CurrentPrincipal = principal;
}
[Test]
public void ShouldRestoreCurrentPrincipalAfterTestRun()
{
IPrincipal principal = Thread.CurrentPrincipal;
TestBuilder.RunTestFixture( typeof( FixtureThatChangesTheCurrentPrincipal ) );
Assert.That(
Thread.CurrentPrincipal,
Is.SameAs(principal),
"The Thread Principal was not restored after the test was run");
}
}
/// <summary>
/// Helper class that implements ILogicalThreadAffinative
/// but holds no data at all
/// </summary>
[Serializable]
public class EmptyCallContextData : ILogicalThreadAffinative
{
}
[Serializable]
public class PrincipalCallContextData : ILogicalThreadAffinative
{
public PrincipalCallContextData( IPrincipal principal )
{
}
}
[Serializable]
public class MyPrincipal : IPrincipal
{
public IIdentity Identity
{
get
{
// TODO: Add MyPrincipal.Identity getter implementation
return null;
}
}
public bool IsInRole(string role)
{
// TODO: Add MyPrincipal.IsInRole implementation
return false;
}
}
[Serializable]
public class TestIdentity : GenericIdentity
{
public TestIdentity( string name ) : base( name )
{
}
}
}
#endif
| mit |
dynamicguy/gpweb | src/vendor/symfony/src/Symfony/Framework/DoctrineBundle/Command/GenerateProxiesDoctrineCommand.php | 1642 | <?php
namespace Symfony\Framework\DoctrineBundle\Command;
use Symfony\Components\Console\Input\InputArgument;
use Symfony\Components\Console\Input\InputOption;
use Symfony\Components\Console\Input\InputInterface;
use Symfony\Components\Console\Output\OutputInterface;
use Symfony\Components\Console\Output\Output;
use Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Generate the Doctrine ORM entity proxies to your cache directory.
*
* @package Symfony
* @subpackage Framework_DoctrineBundle
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GenerateProxiesDoctrineCommand extends GenerateProxiesCommand
{
protected function configure()
{
parent::configure();
$this
->setName('doctrine:generate:proxies')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to use for this command.')
->setHelp(<<<EOT
The <info>doctrine:generate:proxies</info> command generates proxy classes for your entities:
<info>./symfony doctrine:generate:proxies</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));
return parent::execute($input, $output);
}
} | mit |
adamkammeyer/scrum-roulette | src/App/Helper/RandomEmployee.php | 1299 | <?php
namespace App\Helper;
class RandomEmployee
{
public function __construct()
{
$this->employees = ['Ben', 'Shawn', 'Ryan', 'Nick', 'Morgan', 'Zach', 'Brock'];
$this->number = 1;
}
public function getRandomEmployee()
{
$return = [];
for ($i=0; $i<$this->number; $i++) {
$randomIndex = $this->getRandomIndex();
$return[] = $this->employees[$randomIndex];
$this->cleanUpListOfEmployees($randomIndex);
}
// return $this->employees[$randomIndex];
return implode($return, ",");
// return $this->employees[1];
}
public function setNumberToPick(int $number)
{
$this->number = $number;
}
private function cleanUpListOfEmployees($index)
{
unset($this->employees[$index]);
$this->employees = array_values($this->employees);
}
private function getRandomIndex()
{
$lastIndex = count($this->employees) - 1;
$randomIndex = random_int(0, $lastIndex);
return $randomIndex;
}
public function excludeFromPick(array $exclude)
{
$this->employees = array_diff($this->employees, $exclude);
}
public function getEmployees()
{
return $this->employees;
}
}
| mit |
ezekielthao/mozu-dotnet | Mozu.Api/Contracts/Reference/ContentLocale.cs | 914 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Codezu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
namespace Mozu.Api.Contracts.Reference
{
///
/// Properties of a content locale that determines the language and format used for a site.
///
public class ContentLocale
{
///
///Language used for the entity. Currently, only "en-US" is supported.
///
public string Code { get; set; }
///
///The display name of the source product property. For a product field it will be the display name of the field. For a product attribute it will be the Attribute Name.
///
public string Name { get; set; }
}
} | mit |
gevorg/http-auth | examples/digest.js | 505 | // HTTP module
const http = require("http");
// Authentication module.
const auth = require("../src/http-auth");
const digest = auth.digest({
realm: "Simon Area.",
file: __dirname + "/../data/users.htdigest" // vivi:anna, sona:testpass
});
// Creating new HTTP server.
http
.createServer(
digest.check((req, res) => {
res.end(`Welcome to private area - ${req.user}!`);
})
)
.listen(1337, () => {
// Log URL.
console.log("Server running at http://127.0.0.1:1337/");
});
| mit |
kyleshay/ember-route-alias | app/mixins/rel-link-to.js | 64 | export { default } from 'ember-route-alias/mixins/rel-link-to';
| mit |
unaio/una | modules/boonex/english/updates/11.0.2_11.0.3/source/install/config.php | 1507 | <?php
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup English English language
* @ingroup UnaModules
*
* @{
*/
$aConfig = array(
/**
* Main Section.
*/
'type' => BX_DOL_MODULE_TYPE_LANGUAGE,
'name' => 'bx_en',
'title' => 'English',
'note' => 'Language file',
'version' => '11.0.3',
'vendor' => 'Boonex',
'help_url' => 'http://feed.una.io/?section={module_name}',
'compatible_with' => array(
'11.0.x'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/english/',
'home_uri' => 'en',
'db_prefix' => 'bx_eng_',
'class_prefix' => 'BxEng',
/**
* Category for language keys.
*/
'language_category' => 'BoonEx English',
/**
* Installation/Uninstallation Section.
* NOTE. The sequence of actions is critical. Don't change the order.
*/
'install' => array(
'execute_sql' => 1,
'update_languages' => 1,
'install_language' => 1,
'clear_db_cache' => 1
),
'uninstall' => array (
'update_languages' => 1,
'execute_sql' => 1,
'clear_db_cache' => 1
),
'enable' => array(
'execute_sql' => 1
),
'disable' => array(
'execute_sql' => 1
),
/**
* Dependencies Section
*/
'dependencies' => array(),
);
/** @} */
| mit |
IlfirinIlfirin/shavercoin | src/qt/locale/bitcoin_uk.ts | 123572 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Shavercoin</source>
<translation>Про Shavercoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Shavercoin</b> version</source>
<translation>Версія <b>Shavercoin'a<b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Це програмне забезпечення є експериментальним.
Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http://www.opensource.org/licenses/mit-license.php.
Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http://www.openssl.org/), криптографічне програмне забезпечення, написане Еріком Янгом (eay@cryptsoft.com), та функції для роботи з UPnP, написані Томасом Бернардом.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Авторське право</translation>
</message>
<message>
<location line="+0"/>
<source>The Shavercoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Адресна книга</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Двічі клікніть на адресу чи назву для їх зміни</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Створити нову адресу</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копіювати виділену адресу в буфер обміну</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Створити адресу</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Shavercoin 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>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Скопіювати адресу</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Показати QR-&Код</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Shavercoin address</source>
<translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Підписати повідомлення</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Вилучити вибрані адреси з переліку</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Експортувати дані з поточної вкладки в файл</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Shavercoin address</source>
<translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Shavercoin-адресою</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Перевірити повідомлення</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Видалити</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Shavercoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Скопіювати &мітку</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Редагувати</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Експортувати адресну книгу</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Файли відділені комами (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Помилка при експортуванні</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Неможливо записати у файл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Назва</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(немає назви)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Діалог введення паролю</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Введіть пароль</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Новий пароль</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Повторіть пароль</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>Введіть новий пароль для гаманця.<br/>Будь ласка, використовуйте паролі що містять <b>як мінімум 10 випадкових символів</b>, або <b>як мінімум 8 слів</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Зашифрувати гаманець</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ця операція потребує пароль для розблокування гаманця.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Розблокувати гаманець</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ця операція потребує пароль для дешифрування гаманця.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Дешифрувати гаманець</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Змінити пароль</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Ввести старий та новий паролі для гаманця.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Підтвердити шифрування гаманця</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SHAVERCOINS</b>!</source>
<translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви <b>ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ви дійсно хочете зашифрувати свій гаманець?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Увага: Ввімкнено Caps Lock!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Гаманець зашифровано</translation>
</message>
<message>
<location line="-56"/>
<source>Shavercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your shavercoins from being stolen by malware infecting your computer.</source>
<translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам'ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп'ютер буде інфіковано шкідливими програмами.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Не вдалося зашифрувати гаманець</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Введені паролі не співпадають.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Не вдалося розблокувати гаманець</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Введений пароль є невірним.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Не вдалося розшифрувати гаманець</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Пароль було успішно змінено.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>&Підписати повідомлення...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Синхронізація з мережею...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Огляд</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Показати загальний огляд гаманця</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>Транзакції</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Переглянути історію транзакцій</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Редагувати список збережених адрес та міток</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Показати список адрес для отримання платежів</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Вихід</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Вийти</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Shavercoin</source>
<translation>Показати інформацію про Shavercoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Про Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Показати інформацію про Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Параметри...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Шифрування гаманця...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Резервне копіювання гаманця...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Змінити парол&ь...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Імпорт блоків з диску...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Shavercoin address</source>
<translation>Відправити монети на вказану адресу</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Shavercoin</source>
<translation>Редагувати параметри</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Резервне копіювання гаманця в інше місце</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Змінити пароль, який використовується для шифрування гаманця</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Вікно зневадження</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Відкрити консоль зневадження і діагностики</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>Перевірити повідомлення...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Shavercoin</source>
<translation>Shavercoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Гаманець</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Shavercoin</source>
<translation>&Про Shavercoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Показати / Приховати</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Показує або приховує головне вікно</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Shavercoin addresses to prove you own them</source>
<translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою Shavercoin-адресою </translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Shavercoin addresses</source>
<translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Shavercoin-адресою</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Налаштування</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Довідка</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Панель вкладок</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[тестова мережа]</translation>
</message>
<message>
<location line="+47"/>
<source>Shavercoin client</source>
<translation>Shavercoin-клієнт</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Shavercoin network</source>
<translation><numerusform>%n активне з'єднання з мережею</numerusform><numerusform>%n активні з'єднання з мережею</numerusform><numerusform>%n активних з'єднань з мережею</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Оброблено %1 блоків історії транзакцій.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Помилка</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Увага</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Інформація</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Синхронізовано</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Синхронізується...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Підтвердити комісію</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Надіслані транзакції</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Отримані перекази</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Дата: %1
Кількість: %2
Тип: %3
Адреса: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Обробка URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Shavercoin address or malformed URI parameters.</source>
<translation>Неможливо обробити URI! Це може бути викликано неправильною Shavercoin-адресою, чи невірними параметрами URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation><b>Зашифрований</b> гаманець <b>розблоковано</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation><b>Зашифрований</b> гаманець <b>заблоковано</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Shavercoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Сповіщення мережі</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Редагувати адресу</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Мітка</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Мітка, пов'язана з цим записом адресної книги</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адреса</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Адреса, пов'язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Нова адреса для отримання</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Нова адреса для відправлення</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Редагувати адресу для отримання</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Редагувати адресу для відправлення</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Введена адреса «%1» вже присутня в адресній книзі.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Shavercoin address.</source>
<translation>Введена адреса «%1» не є коректною адресою в мережі Shavercoin.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Неможливо розблокувати гаманець.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Не вдалося згенерувати нові ключі.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Shavercoin-Qt</source>
<translation>Shavercoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>версія</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Використання:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>параметри командного рядка</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Параметри інтерфейсу</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Встановлення мови, наприклад "de_DE" (типово: системна)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Запускати згорнутим</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Показувати заставку під час запуску (типово: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Параметри</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Головні</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Заплатити комісі&ю</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Shavercoin after logging in to the system.</source>
<translation>Автоматично запускати гаманець при вході до системи.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Shavercoin on system login</source>
<translation>&Запускати гаманець при вході в систему</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Скинути всі параметри клієнта на типові.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Скинути параметри</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Мережа</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Shavercoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Відображення порту через &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Shavercoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Підключатись до мережі Shavercoin через SOCKS-проксі (наприклад при використанні Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>Підключатись через &SOCKS-проксі:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP проксі:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Порт:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Порт проксі-сервера (наприклад 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS версії:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Версія SOCKS-проксі (наприклад 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Вікно</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Показувати лише іконку в треї після згортання вікна.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>Мінімізувати &у трей</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Згортати замість закритт&я</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Відображення</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Мова інтерфейсу користувача:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Shavercoin.</source>
<translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску Shavercoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>В&имірювати монети в:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Shavercoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Відображати адресу в списку транзакцій</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Гаразд</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Скасувати</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Застосувати</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>типово</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Підтвердження скидання параметрів</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Продовжувати?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Увага</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Shavercoin.</source>
<translation>Цей параметр набуде чинності після перезапуску Shavercoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Невірно вказано адресу проксі.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Shavercoin network after a connection is established, but this process has not completed yet.</source>
<translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею Shavercoin після встановлення підключення, але цей процес ще не завершено.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Непідтверджені:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Гаманець</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Недавні транзакції</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Ваш поточний баланс</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>не синхронізовано</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start shavercoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Діалог QR-коду</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Запросити Платіж</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Кількість:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Мітка:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Повідомлення:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Зберегти як...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Помилка при кодуванні URI в QR-код.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Невірно введено кількість, будь ласка, перевірте.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Зберегти QR-код</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG-зображення (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Назва клієнту</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Н/Д</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Версія клієнту</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Інформація</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Використовується OpenSSL версії</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Мережа</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Кількість підключень</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>В тестовій мережі</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Поточне число блоків</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>Відкрити</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Параметри командного рядка</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Shavercoin-Qt help message to get a list with possible Shavercoin command-line options.</source>
<translation>Показати довідку Shavercoin-Qt для отримання переліку можливих параметрів командного рядка.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>Показати</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>Консоль</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Дата збирання</translation>
</message>
<message>
<location line="-104"/>
<source>Shavercoin - Debug window</source>
<translation>Shavercoin - Вікно зневадження</translation>
</message>
<message>
<location line="+25"/>
<source>Shavercoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Файл звіту зневадження</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Shavercoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Очистити консоль</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Shavercoin RPC console.</source>
<translation>Вітаємо у консолі Shavercoin RPC.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Використовуйте стрілки вгору вниз для навігації по історії, і <b>Ctrl-L</b> для очищення екрана.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Наберіть <b>help</b> для перегляду доступних команд.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Відправити</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Відправити на декілька адрес</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Дод&ати одержувача</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Видалити всі поля транзакції</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Очистити &все</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Підтвердити відправлення</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Відправити</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> адресату %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Підтвердіть відправлення</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ви впевнені що хочете відправити %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> і </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Адреса отримувача невірна, будь ласка перепровірте.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Кількість монет для відправлення повинна бути більшою 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Кількість монет для відправлення перевищує ваш баланс.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Помилка: Не вдалося створити транзакцію!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Кількість:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Отримувач:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Мітка:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Вибрати адресу з адресної книги</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Вставити адресу</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Видалити цього отримувача</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Shavercoin address (e.g. Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</source>
<translation>Введіть адресу Shavercoin (наприклад Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Підписи - Підпис / Перевірка повідомлення</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Підписати повідомлення</translation>
</message>
<message>
<location line="+6"/>
<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"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</source>
<translation>Введіть адресу Shavercoin (наприклад Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Вибрати адресу з адресної книги</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Вставити адресу</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Введіть повідомлення, яке ви хочете підписати тут</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Підпис</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Копіювати поточну сигнатуру до системного буферу обміну</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Shavercoin address</source>
<translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Підписати повідомлення</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Скинути всі поля підпису повідомлення</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Очистити &все</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>Перевірити повідомлення</translation>
</message>
<message>
<location line="+6"/>
<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"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</source>
<translation>Введіть адресу Shavercoin (наприклад Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Shavercoin address</source>
<translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Shavercoin-адресою</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Перевірити повідомлення</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Скинути всі поля перевірки повідомлення</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Shavercoin address (e.g. Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</source>
<translation>Введіть адресу Shavercoin (наприклад Cc25qmrCnU1nQwNMCwFGtzcQTJh32tMe58)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Shavercoin signature</source>
<translation>Введіть сигнатуру Shavercoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Введена нечинна адреса.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Будь ласка, перевірте адресу та спробуйте ще.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Не вдалося підписати повідомлення.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Повідомлення підписано.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Підпис не можливо декодувати.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Будь ласка, перевірте підпис та спробуйте ще.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Не вдалося перевірити повідомлення.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Повідомлення перевірено.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Shavercoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[тестова мережа]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Відкрити до %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/поза інтернетом</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/не підтверджено</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 підтверджень</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Статус</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Згенеровано</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Відправник</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Отримувач</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>Мітка</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>не прийнято</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Дебет</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Комісія за транзакцію</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Загальна сума</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Повідомлення</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Коментар</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID транзакції</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Після генерації монет, потрібно зачекати 120 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Транзакція</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Кількість</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ще не було успішно розіслано</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>невідомий</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Деталі транзакції</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Даний діалог показує детальну статистику по вибраній транзакції</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Кількість</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Відкрити до %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Поза інтернетом (%1 підтверджень)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Непідтверджено (%1 із %2 підтверджень)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Підтверджено (%1 підтверджень)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Згенеровано, але не підтверджено</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Отримано</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Отримано від</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Відправлено</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Відправлено собі</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Добуто</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(недоступно)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата і час, коли транзакцію було отримано.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Тип транзакції.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Адреса отримувача транзакції.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Сума, додана чи знята з балансу.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Всі</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Сьогодні</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>На цьому тижні</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>На цьому місяці</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Минулого місяця</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Цього року</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Проміжок...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Отримані на</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Відправлені на</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Відправлені собі</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Добуті</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Інше</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Введіть адресу чи мітку для пошуку</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Мінімальна сума</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Скопіювати адресу</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Скопіювати мітку</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Копіювати кількість</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Редагувати мітку</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Показати деталі транзакції</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Експортувати дані транзакцій</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Файли, розділені комою (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Підтверджені</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Мітка</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Кількість</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Ідентифікатор</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Помилка експорту</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Неможливо записати у файл %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Діапазон від:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Відправити</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Експортувати дані з поточної вкладки в файл</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Успішне створення резервної копії</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Данні гаманця успішно збережено в новому місці призначення.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Shavercoin version</source>
<translation>Версія</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Використання:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or shavercoind</source>
<translation>Відправити команду серверу -server чи демону</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Список команд</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Отримати довідку по команді</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Параметри:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: shavercoin.conf)</source>
<translation>Вкажіть файл конфігурації (типово: shavercoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: shavercoind.pid)</source>
<translation>Вкажіть pid-файл (типово: shavercoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Вкажіть робочий каталог</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9448 or testnet: 19448)</source>
<translation>Чекати на з'єднання на <port> (типово: 9448 або тестова мережа: 19448)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Підтримувати не більше <n> зв'язків з колегами (типово: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Поріг відключення неправильно під'єднаних пірів (типово: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Максимальній розмір вхідного буферу на одне з'єднання (типово: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9447 or testnet: 19447)</source>
<translation>Прослуховувати <port> для JSON-RPC-з'єднань (типово: 9447 або тестова мережа: 19447)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Приймати команди із командного рядка та команди JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запустити в фоновому режимі (як демон) та приймати команди</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Використовувати тестову мережу</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=shavercoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Shavercoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Shavercoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation>
</message>
<message>
<location line="+4"/>
<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"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Shavercoin will not work properly.</source>
<translation>Увага: будь ласка, перевірте дату і час на своєму комп'ютері. Якщо ваш годинник йде неправильно, Shavercoin може працювати некоректно.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Підключитись лише до вказаного вузла</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Помилка ініціалізації бази даних блоків</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Помилка завантаження бази даних блоків</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Помилка: Мало вільного місця на диску!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Помилка: системна помилка: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Імпорт блоків з зовнішнього файлу blk000??.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Інформація</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Помилка в адресі -tor: «%s»</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Максимальний буфер, <n>*1000 байт (типово: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Максимальній розмір вихідного буферу на одне з'єднання, <n>*1000 байт (типово: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Доповнювати налагоджувальний вивід відміткою часу</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Shavercoin Wiki for SSL setup instructions)</source>
<translation>Параметри SSL: (див. Shavercoin Wiki для налаштування SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Відсилати налагоджувальну інформацію до налагоджувача</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Системна помилка: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Ім'я користувача для JSON-RPC-з'єднань</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Попередження</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Увага: Поточна версія застаріла, необхідне оновлення!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat пошкоджено, відновлення не вдалося</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для JSON-RPC-з'єднань</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Дозволити JSON-RPC-з'єднання з вказаної IP-адреси</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Відправляти команди на вузол, запущений на <ip> (типово: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Модернізувати гаманець до останнього формату</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Встановити розмір пулу ключів <n> (типово: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Використовувати OpenSSL (https) для JSON-RPC-з'єднань</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Файл сертифіката сервера (типово: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Закритий ключ сервера (типово: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Дана довідка</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Неможливо прив'язати до порту %s на цьому комп'ютері (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Підключитись через SOCKS-проксі</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Завантаження адрес...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Shavercoin</source>
<translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Shavercoin to complete</source>
<translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Помилка при завантаженні wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Помилка в адресі проксі-сервера: «%s»</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Невідома мережа вказана в -onlynet: «%s»</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Помилка у величині комісії -paytxfee=<amount>: «%s»</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Некоректна кількість</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Недостатньо коштів</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Завантаження індексу блоків...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Додати вузол до підключення і лишити його відкритим</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Shavercoin is probably already running.</source>
<translation>Неможливо прив'язати до порту %s на цьому комп'ютері. Можливо гаманець вже запущено.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Комісія за КБ</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Завантаження гаманця...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Неможливо записати типову адресу</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Сканування...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Завантаження завершене</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Помилка</translation>
</message>
<message>
<location line="-31"/>
<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>Ви мусите встановити rpcpassword=<password> в файлі конфігурації:
%s
Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation>
</message>
</context>
</TS> | mit |
andyshao/Design-Patterns-in-CSharp | Bridge/ConcreteImplementor.cs | 653 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bridge
{
public class ConcreteImplementor1 : Impementor
{
public void doPaint(string brush)
{
Console.WriteLine("ConcreteImplementor1");
}
}
public class ConcreteImplementor2 : Impementor
{
public void doPaint(string brush)
{
Console.WriteLine("ConcreteImplementor2");
}
}
public class ConcreteImplementor3 : Impementor
{
public void doPaint(string brush)
{
Console.WriteLine("ConcreteImplementor3");
}
}
}
| mit |
wordsaretoys/4est | rise/com/wordsaretoys/rise/glwrapper/Shader.java | 2821 | package com.wordsaretoys.rise.glwrapper;
import android.opengl.GLES20;
import android.util.Log;
/**
* maintains a shader program consisting of one
* vertex shader function and one fragment shader
* function.
*
* @author chris
*
*/
public class Shader {
private int vobj;
private int fobj;
private int program;
public Shader() {
}
/**
* generates GL shader program from source code
*
* @param vertex source code for vertex shader
* @param fragment source code for fragment shader
* @throws Exception
*/
public boolean build(String vertex, String fragment) {
String error;
int[] status = new int[1];
// compile the vertex shader
vobj = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
GLES20.glShaderSource(vobj, vertex);
GLES20.glCompileShader(vobj);
// check the compilation
GLES20.glGetShaderiv(vobj, GLES20.GL_COMPILE_STATUS, status, 0);
if (status[0] == 0) {
error = GLES20.glGetShaderInfoLog(vobj);
String reason = "vertex shader compile error: " + error;
Log.e("shader", reason);
return false;
}
// compile the fragment shader
fobj = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
GLES20.glShaderSource(fobj, fragment);
GLES20.glCompileShader(fobj);
// check the compilation
GLES20.glGetShaderiv(fobj, GLES20.GL_COMPILE_STATUS, status, 0);
if (status[0] == 0) {
error = GLES20.glGetShaderInfoLog(fobj);
String reason = "fragment shader compile error: " + error;
Log.e("shader", reason);
return false;
}
// create and link the shader program
program = GLES20.glCreateProgram();
GLES20.glAttachShader(program, vobj);
GLES20.glAttachShader(program, fobj);
GLES20.glLinkProgram(program);
// check the linkage
GLES20.glGetShaderiv(program, GLES20.GL_LINK_STATUS, status, 0);
if (status[0] == 0) {
error = GLES20.glGetProgramInfoLog(program);
String reason = "shader program link error: " + error;
Log.e("shader", reason);
return false;
}
return true;
}
/**
* get attribute location id
* @param name attribute variable name
* @return id
*/
public int getAttributeId(String name) {
return GLES20.glGetAttribLocation(program, name);
}
/**
* get uniform/sampler location id
* @param name uniform variable name
* @return id
*/
public int getUniformId(String name) {
return GLES20.glGetUniformLocation(program, name);
}
/**
* activate the shader program
*/
public void activate() {
GLES20.glUseProgram(program);
}
/**
* release the shader program
*/
public void release() {
GLES20.glDeleteShader(vobj);
GLES20.glDeleteShader(fobj);
GLES20.glDeleteProgram(program);
}
/**
* set up a matrix
*/
public void setMatrix(String label, float[] m) {
GLES20.glUniformMatrix4fv(
getUniformId(label), 1, false, m, 0);
}
}
| mit |
BrennanConroy/corefx | src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs | 7892 | // 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.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_MaxResponseHeadersLength_Test(ITestOutputHelper output) : base(output) { }
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void InvalidValue_ThrowsException(int invalidValue)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[Theory]
[InlineData(1)]
[InlineData(65)]
[InlineData(int.MaxValue)]
public void ValidValue_SetGet_Roundtrips(int validValue)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.MaxResponseHeadersLength = validValue;
Assert.Equal(validValue, handler.MaxResponseHeadersLength);
}
}
[Fact]
public async Task SetAfterUse_Throws()
{
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
using HttpClientHandler handler = CreateHttpClientHandler();
using HttpClient client = CreateHttpClient(handler);
handler.MaxResponseHeadersLength = 1;
(await client.GetStreamAsync(uri)).Dispose();
Assert.Throws<InvalidOperationException>(() => handler.MaxResponseHeadersLength = 1);
},
server => server.AcceptConnectionSendResponseAndCloseAsync());
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task InfiniteSingleHeader_ThrowsException()
{
if (IsCurlHandler)
{
// libcurl fails with an out of memory error
return;
}
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
var cts = new CancellationTokenSource();
Task serverTask = Task.Run(async delegate
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nMyInfiniteHeader: ");
try
{
while (!cts.IsCancellationRequested)
{
await connection.Writer.WriteAsync(new string('s', 16000));
await Task.Delay(1);
}
}
catch { }
});
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
cts.Cancel();
if (UseSocketsHttpHandler)
{
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
}
await serverTask;
});
}
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(ResponseWithManyHeadersData))]
public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int? maxResponseHeadersLength, bool shouldSucceed)
{
if (IsCurlHandler)
{
// libcurl often fails with out of memory errors
return;
}
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
if (maxResponseHeadersLength.HasValue)
{
handler.MaxResponseHeadersLength = maxResponseHeadersLength.Value;
}
Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await server.AcceptConnectionAsync(async connection =>
{
Task serverTask = connection.ReadRequestHeaderAndSendCustomResponseAsync(responseHeaders);
if (shouldSucceed)
{
(await getAsync).Dispose();
await serverTask;
}
else
{
Exception e = await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
if (UseSocketsHttpHandler)
{
Assert.Contains((handler.MaxResponseHeadersLength * 1024).ToString(), e.ToString());
}
try { await serverTask; } catch { }
}
});
}
});
}
public static IEnumerable<object[]> ResponseWithManyHeadersData
{
get
{
foreach (int? max in new int?[] { null, 1, 31, 128 })
{
int actualSize = max.HasValue ? max.Value : 64;
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024 - 1), max, true }; // Small enough
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024), max, true }; // Just right
yield return new object[] { GenerateLargeResponseHeaders(actualSize * 1024 + 1), max, false }; // Too big
}
}
}
private static string GenerateLargeResponseHeaders(int responseHeadersSizeInBytes)
{
var buffer = new StringBuilder();
buffer.Append("HTTP/1.1 200 OK\r\n");
buffer.Append("Content-Length: 0\r\n");
for (int i = 0; i < 24; i++)
{
buffer.Append($"Custom-{i:D4}: 1234567890123456789012345\r\n");
}
buffer.Append($"Custom-24: ");
buffer.Append(new string('c', responseHeadersSizeInBytes - (buffer.Length + 4)));
buffer.Append("\r\n\r\n");
string response = buffer.ToString();
Assert.Equal(responseHeadersSizeInBytes, response.Length);
return response;
}
}
}
| mit |
coldume/imagecraft | tests/OptionPass/DebugOptionPassTest.php | 449 | <?php
namespace Imagecraft\OptionPass;
/**
* @covers Imagecraft\OptionPass\DebugOptionPass
*/
class DebugOptionPassTest extends \PHPUnit_Framework_TestCase
{
protected $pass;
public function setUp()
{
$this->pass = $this->getMock('Imagecraft\\OptionPass\\DebugOptionPass', null);
}
public function testProcess()
{
$option = $this->pass->process([]);
$this->assertTrue($option['debug']);
}
}
| mit |
RazvanRotari/iaP | deprecated/iap-rs/src/main/java/ro/infoiasi/sparql/dao/AuthorDAO.java | 2610 | package ro.infoiasi.sparql.dao;
import static ro.infoiasi.dao.entity.metamodel.AuthorMetaModel.*;
import static ro.infoiasi.dao.entity.metamodel.UserMetaModel.ID_VALUE;
import java.util.ArrayList;
import java.util.List;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import ro.infoiasi.dao.entity.Author;
import ro.infoiasi.sparql.insertionPoints.subqueries.AggregatePropertyFunction;
import ro.infoiasi.sparql.insertionPoints.subqueries.AggregateSubQuery;
public class AuthorDAO extends GenericDAO<Author>{
public List<Author> authorList = new ArrayList<Author>();
public AuthorDAO() {
super(Author.class);
}
@Override
protected Author toEntity(QuerySolution solution) throws Exception {
Author a = new Author();
a.setName(solution.getLiteral(NAME_VALUE).getString());
a.setRating(solution.getLiteral(RATING_VALUE).getLong());
return a;
}
public List<Author> getAllAuthors() {
return authorList;
}
public Author getAuthor(int i) {
for(Author a:authorList) {
if(a.getId() == i) {
return a;
}
}
return null;
}
public int updateAuthor(Author updateAuthor) {
List<Author> authorList = getAllAuthors();
for(Author a:authorList) {
if(a.getName().toLowerCase().equals(updateAuthor.getName().toLowerCase())) {
int index = authorList.indexOf(a);
authorList.set(index, updateAuthor);
return 1;
}
}
return 0;
}
public int deleteAuthor(String name) {
List<Author> authorList = getAllAuthors();
for (Author a : authorList) {
if (a.getName().equals(name)) {
int index = authorList.indexOf(a);
authorList.remove(index);
return 1;
}
}
return 0;
}
public long getNextId() throws Exception {
String mapping = "next";
String query = new AggregateSubQuery(clazz, AggregatePropertyFunction.MAX, ID_VALUE, mapping).construct();
if (DEBUG) {
logger.debug(query);
}
ResultSet resultSet = QueryExecutionFactory.sparqlService(HTTP_ENDPOINT, query).execSelect();
if (resultSet.hasNext()) {
QuerySolution solution = resultSet.next();
return getCurrentValue(mapping, solution) + 1;
}
throw new Exception("Could not query for next id");
}
private long getCurrentValue(String mapping, QuerySolution solution) {
Literal literal = solution.getLiteral(mapping);
if(literal == null) {
return 0;
}
return literal.getLong();
}
}
| mit |
brmullikin/BRMFlask | setup.py | 813 | """BRMFlask is a unified website generator."""
from setuptools import setup
from brmflask.settings import BaseConfig
setup(
name='BRMFlask',
version=BaseConfig.VERSION,
url='http://github.com/brmullikin/brmflask',
license='MIT',
author='B. R. Mullikin',
author_email='ben@brmullikin.com',
description='Private Flask App',
long_description=__doc__,
packages=['brmflask'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'Flask-Compress',
'flask_caching',
'coloredlogs',
'htmlmin',
'Markdown',
'smartypants',
'pygments'
],
tests_require=[
'pytest',
'pytest-flask',
'pytest-cov',
'pep8',
'flake8-pep257',
'flask-debugtoolbar'
]
)
| mit |
donnut/typescript-ramda | tests/type.ts | 314 | import * as R from '../ramda/dist/index';
declare const boolean: boolean;
declare const number: number;
declare const object: object;
declare const any: any;
// @dts-jest:pass:snap
R.type(boolean);
// @dts-jest:pass:snap
R.type(number);
// @dts-jest:pass:snap
R.type(object);
// @dts-jest:pass:snap
R.type(any);
| mit |
mcelis13/C-Plus-Plus | UsingDeleteCleanUpPointers/main.cpp | 445 | #include <iostream>
using namespace std;
int main()
{
string *phrase = new string ("All presidents are cool!!!");
cout << *phrase << endl;
(*phrase)[20] = 'r'; /*() and * are used to call the various string functions you can also just use -> to call a string function as seen below*/
phrase -> replace (22, 4, "oked");
cout << *phrase << endl;
delete phrase; /*Deletes object*/
return 0; /*Clears the pointer*/
}
| mit |
chondm/BDD-Code-Test | vendor/gems/nokogiri-1.3.3/test/xml/test_node_encoding.rb | 3270 | require File.expand_path(File.join(File.dirname(__FILE__), '..', "helper"))
module Nokogiri
module XML
if RUBY_VERSION =~ /^1\.9/
class TestNodeEncoding < Nokogiri::TestCase
def setup
super
@html = Nokogiri::HTML(File.read(HTML_FILE), HTML_FILE)
end
def test_get_attribute
node = @html.css('a').first
assert_equal @html.encoding, node['href'].encoding.name
end
def test_text_encoding_is_utf_8
@html = Nokogiri::HTML(File.open(NICH_FILE))
assert_equal 'UTF-8', @html.text.encoding.name
end
def test_serialize_encoding_html
@html = Nokogiri::HTML(File.open(NICH_FILE))
assert_equal @html.encoding.downcase,
@html.serialize.encoding.name.downcase
@doc = Nokogiri::HTML(@html.serialize)
assert_equal @html.serialize, @doc.serialize
end
def test_serialize_encoding_xml
@xml = Nokogiri::XML(File.open(SHIFT_JIS_XML))
assert_equal @xml.encoding.downcase,
@xml.serialize.encoding.name.downcase
@doc = Nokogiri::XML(@xml.serialize)
assert_equal @xml.serialize, @doc.serialize
end
def test_encode_special_chars
foo = @html.css('a').first.encode_special_chars('foo')
assert_equal @html.encoding, foo.encoding.name
end
def test_content
node = @html.css('a').first
assert_equal @html.encoding, node.content.encoding.name
end
def test_name
node = @html.css('a').first
assert_equal @html.encoding, node.name.encoding.name
end
def test_path
node = @html.css('a').first
assert_equal @html.encoding, node.path.encoding.name
end
def test_namespace
xml = <<-eoxml
<root>
<car xmlns:part="http://general-motors.com/">
<part:tire>Michelin Model XGV</part:tire>
</car>
<bicycle xmlns:part="http://schwinn.com/">
<part:tire>I'm a bicycle tire!</part:tire>
</bicycle>
</root>
eoxml
doc = Nokogiri::XML(xml, nil, 'UTF-8')
assert_equal 'UTF-8', doc.encoding
n = doc.xpath('//part:tire', { 'part' => 'http://schwinn.com/' }).first
assert n
assert_equal doc.encoding, n.namespace.href.encoding.name
assert_equal doc.encoding, n.namespace.prefix.encoding.name
end
def test_namespace_as_hash
xml = <<-eoxml
<root>
<car xmlns:part="http://general-motors.com/">
<part:tire>Michelin Model XGV</part:tire>
</car>
<bicycle xmlns:part="http://schwinn.com/">
<part:tire>I'm a bicycle tire!</part:tire>
</bicycle>
</root>
eoxml
doc = Nokogiri::XML(xml, nil, 'UTF-8')
assert_equal 'UTF-8', doc.encoding
assert n = doc.xpath('//car').first
n.namespace_definitions.each do |nd|
assert_equal doc.encoding, nd.href.encoding.name
assert_equal doc.encoding, nd.prefix.encoding.name
end
n.namespaces.each do |k,v|
assert_equal doc.encoding, k.encoding.name
assert_equal doc.encoding, v.encoding.name
end
end
end
end
end
end
| mit |
storybooks/react-storybook | lib/cli/generators/METEOR/index.js | 2572 | import fs from 'fs';
import JSON5 from 'json5';
import {
getVersions,
retrievePackageJson,
writePackageJson,
getBabelDependencies,
installDependencies,
copyTemplate,
} from '../../lib/helpers';
export default async (npmOptions, { storyFormat = 'csf' }) => {
const [
storybookVersion,
actionsVersion,
linksVersion,
addonsVersion,
reactVersion,
reactDomVersion,
presetEnvVersion,
presetReactVersion,
] = await getVersions(
npmOptions,
'@storybook/react',
'@storybook/addon-actions',
'@storybook/addon-links',
'@storybook/addons',
'react',
'react-dom',
'@babel/preset-env',
'@babel/preset-react'
);
copyTemplate(__dirname, storyFormat);
const packageJson = await retrievePackageJson();
packageJson.devDependencies = packageJson.devDependencies || {};
packageJson.scripts = packageJson.scripts || {};
packageJson.dependencies = packageJson.dependencies || {};
const devDependencies = [
`@storybook/react@${storybookVersion}`,
`@storybook/addon-actions@${actionsVersion}`,
`@storybook/addon-links@${linksVersion}`,
`@storybook/addons@${addonsVersion}`,
];
// create or update .babelrc
let babelrc = null;
if (fs.existsSync('.babelrc')) {
const babelrcContent = fs.readFileSync('.babelrc', 'utf8');
babelrc = JSON5.parse(babelrcContent);
babelrc.plugins = babelrc.plugins || [];
} else {
babelrc = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-react',
],
};
devDependencies.push(`@babel/preset-env@${presetEnvVersion}`);
devDependencies.push(`@babel/preset-react@${presetReactVersion}`);
}
fs.writeFileSync('.babelrc', JSON.stringify(babelrc, null, 2), 'utf8');
packageJson.scripts.storybook = 'start-storybook -p 6006';
packageJson.scripts['build-storybook'] = 'build-storybook';
writePackageJson(packageJson);
const babelDependencies = await getBabelDependencies(npmOptions, packageJson);
// add react packages.
const dependencies = [];
if (!packageJson.dependencies.react) {
dependencies.push(`react@${reactVersion}`);
}
if (!packageJson.dependencies['react-dom']) {
dependencies.push(`react-dom@${reactDomVersion}`);
}
if (dependencies.length > 0) {
installDependencies(
{ ...npmOptions, packageJson, installAsDevDependencies: false },
dependencies
);
}
installDependencies({ ...npmOptions, packageJson }, [...devDependencies, ...babelDependencies]);
};
| mit |
uktrade/data-hub-fe-beta2 | src/apps/api/index.js | 88 | const router = require('./router')
module.exports = {
mountpath: '/api',
router,
}
| mit |
shnhrrsn/grind-framework | starters/react/public/Errors/NotFoundErrorHandler.js | 165 | import './GenericErrorHandler'
export function NotFoundErrorHandler() {
return <GenericErrorHandler title="The page you’re looking for could not be found." />
}
| mit |
alexbegt/CodeChickenCore | src/codechicken/core/commands/CoreCommand.java | 2994 | package codechicken.core.commands;
import java.util.List;
import codechicken.core.ServerUtils;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
public abstract class CoreCommand implements ICommand
{
public static void chatT(ICommandSender sender, String s, Object... params) {
sender.addChatMessage(new ChatComponentTranslation(s, params));
}
public static void chatOpsT(String s, Object... params) {
for (EntityPlayerMP player : ServerUtils.getPlayers())
if (MinecraftServer.getServer().getConfigurationManager().canSendCommands(player.getGameProfile()))
player.addChatMessage(new ChatComponentTranslation(s, params));
}
public abstract boolean OPOnly();
@Override
public String getCommandUsage(ICommandSender var1) {
return "/" + getCommandName() + " help";
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length < minimumParameters() ||
args.length == 1 && args[0].equals("help")) {
printHelp(sender);
return;
}
String command = getCommandName();
for (String arg : args)
command += " " + arg;
handleCommand(command, sender.getCommandSenderName(), args, sender);
}
public abstract void handleCommand(String command, String playername, String[] args, ICommandSender listener);
public abstract void printHelp(ICommandSender sender);
public final EntityPlayerMP getPlayer(String name) {
return ServerUtils.getPlayer(name);
}
public WorldServer getWorld(int dimension) {
return DimensionManager.getWorld(dimension);
}
public WorldServer getWorld(EntityPlayer player) {
return (WorldServer) player.worldObj;
}
@Override
public int compareTo(Object o) {
return getCommandName().compareTo(((ICommand) o).getCommandName());
}
@Override
public List<?> getCommandAliases() {
return null;
}
@Override
public List<?> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
return null;
}
@Override
public boolean isUsernameIndex(String[] args, int index) {
return false;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender var1) {
if (OPOnly()) {
if (var1 instanceof EntityPlayer)
return MinecraftServer.getServer().getConfigurationManager().canSendCommands(((EntityPlayer) var1).getGameProfile());
return var1 instanceof MinecraftServer;
}
return true;
}
public abstract int minimumParameters();
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE190_Integer_Overflow/s04/CWE190_Integer_Overflow__short_max_multiply_84_goodB2G.cpp | 1678 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__short_max_multiply_84_goodB2G.cpp
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-84_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: max Set data to the max value for short
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: multiply
* GoodSink: Ensure there will not be an overflow before multiplying data by 2
* BadSink : If data is positive, multiply by 2, which can cause an overflow
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE190_Integer_Overflow__short_max_multiply_84.h"
namespace CWE190_Integer_Overflow__short_max_multiply_84
{
CWE190_Integer_Overflow__short_max_multiply_84_goodB2G::CWE190_Integer_Overflow__short_max_multiply_84_goodB2G(short dataCopy)
{
data = dataCopy;
/* POTENTIAL FLAW: Use the maximum size of the data type */
data = SHRT_MAX;
}
CWE190_Integer_Overflow__short_max_multiply_84_goodB2G::~CWE190_Integer_Overflow__short_max_multiply_84_goodB2G()
{
if(data > 0) /* ensure we won't have an underflow */
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < (SHRT_MAX/2))
{
short result = data * 2;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
}
#endif /* OMITGOOD */
| mit |
viennacl/pyviennacl-dev | examples/sparse-matrices.py | 1492 | #!python
"""
Sparse matrix support is still limited in PyViennaCL. The construction
of spare matrices from host data is supported, as is sparse matrix-vector
multiplication and the use of iterative solvers (see iterative-solvers.py
in this directory). However, no other operations have yet been implemented,
and SciPy support is rudimentary.
Here, we demonstrate the construction of a CompressedMatrix instance, and the
calculation of a matrix-vector product.
Other sparse matrix formats are available, such as the CoordinateMatrix,
ELLMatrix and HybridMatrix. They are constructed and used identically to the
CompressedMatrix type.
"""
import pyviennacl as p
import random
# First, we create an empty 5 x 5 CompressedMatrix:
A = p.CompressedMatrix(5, 5)
# Let's set some random values of A.
#
# Importantly, setting individual elements of a PyViennaCL sparse matrix is
# not nearly as expensive as setting individual elements of a dense matrix or
# vector, since in the sparse matrix case, the elements are cached on the host
# and only transferred to the device when they are needed for some computation.
for i in range(6):
x = random.randrange(0, 4, 1)
y = random.randrange(0, 4, 1)
A[x, y] = random.random()
print("A is:\n%s" % A.value)
# Now, let's construct a simple vector of 5 elements.
b = p.Vector(5, 3.142)
print("b is %s" % b)
# Now, represent the product:
c = A * b
# And the result is only computed when we need to print it:
print("A * b = c is %s" % c)
| mit |
wrxck/mattata | migrate.lua | 777 | local redis = dofile('libs/redis.lua')
local disabled_plugin_keys = redis:keys('chat:*:disabled_plugins')
if next(disabled_plugin_keys) then
for _, v in pairs(disabled_plugin_keys) do
local plugins = redis:hgetall(v)
if #plugins > 2 then
for plugin, value in pairs(plugins) do
if plugin then
if tostring(value) == 'true' then
local chat_id = v:match(':(%-?%d+):')
redis:sadd('disabled_plugins:' .. chat_id, plugin:lower())
print('Migrated disabled plugin "' .. plugin.lower() .. '" for ' .. chat_id)
end
end
end
redis:del(v)
end
end
end
return 'Migration complete!' | mit |
vargose/ng-grid | lib/grunt/utils.js | 9758 | var fs = require('fs');
var path = require('path');
var grunt = require('grunt');
var semver = require('semver');
var shell = require('shelljs');
// Get the list of angular files (angular.js, angular-mocks.js, etc)
var cachedAngularFiles = grunt.file.readJSON('lib/test/angular/files.json');
var util = module.exports = {
testDependencies: {
unit: ['bower_components/jquery/jquery.min.js', 'lib/test/jquery.simulate.js', 'dist/release/ui-grid.css', 'bower_components/lodash/dist/lodash.min.js', 'bower_components/csv-js/csv.js']
},
testFiles: {
unit: ['src/js/core/bootstrap.js', 'src/js/**/*.js', 'test/unit/**/*.spec.js', 'src/features/*/js/**/*.js', 'src/features/*/test/**/*.spec.js', '.tmp/template.js']
},
// Return a list of angular files for a specific version
angularFiles: function (version) {
// Start with our test files
var retFiles = []; //grunt.template.process('<%= karma.options.files %>').split(",");
cachedAngularFiles.forEach(function(f) {
var filePath = path.join('lib', 'test', 'angular', version, f);
if (! fs.existsSync(filePath)) {
grunt.fatal("Angular file " + filePath + " doesn't exist");
}
retFiles.push(filePath);
});
return retFiles;
},
startKarma: function(config, singleRun, done){
var browsers = grunt.option('browsers');
var reporters = grunt.option('reporters');
var noColor = grunt.option('no-colors');
var port = grunt.option('port');
var p = spawn('node', ['node_modules/karma/bin/karma', 'start', config,
singleRun ? '--single-run=true' : '',
reporters ? '--reporters=' + reporters : '',
browsers ? '--browsers=' + browsers : '',
noColor ? '--no-colors' : '',
port ? '--port=' + port : ''
]);
p.stdout.pipe(process.stdout);
p.stderr.pipe(process.stderr);
p.on('exit', function(code){
if(code !== 0) grunt.fail.warn("Karma test(s) failed. Exit code: " + code);
done();
});
},
customLaunchers: function() {
return {
'SL_Chrome': {
base: 'SauceLabs',
browserName: 'chrome'
},
'SL_Firefox': {
base: 'SauceLabs',
browserName: 'firefox'
},
'SL_Safari_5': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'Mac 10.6',
version: '5'
},
'SL_Safari_6': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'Mac 10.8',
version: '6'
},
'SL_Safari_7': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'Mac 10.9',
version: '7'
},
// 'SL_IE_8_XP': {
// base: 'SauceLabs',
// browserName: 'internet explorer',
// platform: 'Windows XP',
// version: '8'
// },
// 'SL_IE_8': {
// base: 'SauceLabs',
// browserName: 'internet explorer',
// platform: 'Windows 7',
// version: '8'
// },
'SL_IE_9': {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '9'
},
'SL_IE_10': {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '10'
},
'SL_IE_11': {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8.1',
version: '11'
},
'SL_Android_4': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.0'
},
'SL_Android_4.3': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.3'
},
'SL_Linux_Opera': {
base: 'SauceLabs',
browserName: 'opera',
platform: 'Linux',
version: '12'
},
// NOTE (c0bra): Currently both iOS 6 and 7 will run (w/ a 45 second activity timeout) and the tests pass, but after that the session just hangs indefinitely -- 20140320
// 'SL_iOS_6': {
// base: 'SauceLabs',
// browserName: 'iphone',
// platform: 'OS X 10.8',
// version: '6.0'
// },
// 'SL_iOS_7': {
// base: 'SauceLabs',
// browserName: 'iphone',
// platform: 'OS X 10.9',
// version: '7.0'
// }
};
},
//
browsers: function() {
},
angulars: function() {
var angularLib = path.join('lib', 'test', 'angular');
// Loop over all the files in the angular testlib directory
var files = fs.readdirSync(angularLib);
// For each file found, make sure it's a directory...
var versions = [];
files.forEach(function(file) {
var dir = path.join(angularLib, file);
if (! fs.lstatSync(dir).isDirectory()) return;
if (! semver.valid(file)) return;
versions.push(file);
});
return versions;
},
latestAngular: function() {
function sortFn(a,b) {
return semver.gt(b, a);
};
// For each file found, make sure it's a directory...
var versions = util.angulars();
return versions.sort(sortFn)[0];
},
/* Read in whatever angular versions are in lib/test/angular and register karma configs for them all! */
createKarmangularConfig: function() {
// For each file found, make sure it's a directory...
var versions = grunt.option('angular') ? grunt.option('angular').split(/,/) : null || util.angulars();
if (grunt.option('angular')) {
grunt.log.writeln("Using angular " + grunt.util.pluralize(versions, "version/versions") + ": " + versions.join(', '));
}
versions.forEach(function (version) {
// .. then create a karma config for it!
var karmaConfigName = 'angular-' + grunt.config.escape(version);
grunt.config('karma.' + karmaConfigName, {
options: {
files: util.testDependencies.unit
.concat(util.angularFiles(version)
.concat(util.testFiles.unit))
}
});
});
},
// Take the SauceLabs browsers from the karma config file and split them into groups of 3
createSauceConfig: function() {
var launchers = util.customLaunchers();
var chunkNames = Object.keys(launchers);
var chunks = [].concat.apply([], chunkNames.map(function (c, i) {
return i % 3 ? [] : [ chunkNames.slice(i, i + 3) ];
}));
// console.log(chunks);
chunks.forEach(function (c, i) {
grunt.config('karma.sauce-' + i, {
background: false,
singleRun: true,
// reporters: ['saucelabs', 'coverage'],
reporters: ['saucelabs'],
browsers: c
// preprocessors: {
// 'src/**/!(*.spec)+(.js)': ['coverage']
// },
// coverageReporter: {
// type: 'lcov',
// dir: 'coverage',
// subdir: '.'
// }
});
});
// console.log('tasks', chunks.map(function(c, i) { return 'karma:sauce-' + i }));
grunt.config('serialsauce', chunks.map(function(c, i) { return 'karma:sauce-' + i }));
},
updateConfig: function() {
grunt.config('customLaunchers', util.customLaunchers());
util.createKarmangularConfig()
util.createSauceConfig();
if (process.env.TRAVIS) {
// Update the config for the gh-pages task for it pushes changes as the user: Grud
grunt.config('gh-pages.ui-grid-site.options.user', {
name: 'grud',
email: 'nggridteam@gmail.com'
});
grunt.config('gh-pages.ui-grid-site.options.repo', 'https://' + process.env.GITHUB_NAME + ':' + process.env.GITHUB_PASS + '@github.com/angular-ui/ui-grid.info.git');
grunt.config('gh-pages.bower.options.user', {
name: 'grud',
email: 'nggridteam@gmail.com'
});
grunt.config('gh-pages.bower.options.repo', 'https://' + process.env.GITHUB_NAME + ':' + process.env.GITHUB_PASS + '@github.com/angular-ui/bower-ui-grid.git');
}
},
// Return the tag for the current commit at HEAD if there is one, null if there isn't
getCurrentTag: function() {
var out = shell.exec('git tag -l --points-at HEAD', {silent:true});
return out.output.trim();
},
// Get the current release version
getVersion: function() {
// Try to get a tag for the current version
var out = shell.exec('git tag -l --points-at HEAD', {silent:true});
var version, tag;
// If there's a tag on this commit, use it as the version
if (out.code === 0 && out.output.trim() !== '' && out.output.trim() !== null) {
version = out.output.trim();
tag = version;
}
// ...otherwise, get the most recent stable tag
else {
var hash;
// If there isn't one then just get the most recent tag, whatever it is
version = shell.exec('git rev-list --tags --max-count=1 | xargs git describe', {silent:true}).output.trim();
// Get the short commit hash from the current commit to append to the most recent tag
hash = shell.exec('git rev-parse --short HEAD', {silent:true}).output.trim();
version = version + '-' + hash;
tag = version;
}
tag = semver.clean(tag);
return tag;
},
getStableVersion: function() {
var cmd = 'git log --date-order --graph --tags --simplify-by-decoration --pretty=format:\"%ai %h %d\"';
// grunt.log.writeln(cmd);
var out = shell.exec(cmd, {silent:true}).output;
// grunt.log.writeln(lines);
var lines = out.split('\n');
for (var i in lines) {
var l = lines[i];
var match = l.match(/\(.*?tag: (.+?)(\)|,)/);
if (! match || match.length < 2 || !match[1]) { continue; }
var tag = match[1];
var v = semver.clean(tag);
if (!v.match(/-.+?$/)) {
return v;
}
}
}
}; | mit |
sanjoydesk/framework | src/Cygnite/Helpers/Str.php | 1063 | <?php
namespace Cygnite\Helpers;
/**
* Class String.
*/
class Str
{
public static $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* Generate random key based on type.
*
* @param string $type
* @param int $length
*
* @return string
*/
public static function random($type = 'alnum', $length = 16)
{
switch ($type) {
case 'normal':
$key = mt_rand();
break;
case 'unique':
$key = md5(uniqid(mt_rand()));
break;
case 'sha1':
$key = sha1(uniqid(mt_rand(), true));
break;
case 'alnum':
$key = '0123456789'.static::$alpha;
break;
case 'alpha':
$key = static::$alpha;
break;
}
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= substr($key, mt_rand(0, strlen($key) - 1), 1);
}
return $random;
}
}
| mit |